Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso.fcm	(revision 9987)
@@ -13,4 +13,6 @@
 # USER_INC    additional include files for the compiler,  e.g. -I<include dir> 
 # USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 
@@ -29,2 +31,4 @@
 %USER_INC            %NCDF_INC
 %USER_LIB            %NCDF_LIB 
+%CC                  xlc
+%CFLAGS              -O -qcpluscmt
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_debug.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_debug.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_debug.fcm	(revision 9987)
@@ -13,4 +13,6 @@
 # USER_INC    additional include files for the compiler,  e.g. -I<include dir> 
 # USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 
@@ -29,2 +31,4 @@
 %USER_INC            %NCDF_INC
 %USER_LIB            %NCDF_LIB 
+%CC                  xlc
+%CFLAGS              -O -qcpluscmt
Index: anches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_tools.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_tools.fcm	(revision 9986)
+++ 	(revision )
@@ -1,30 +1,0 @@
-# vargas IBM POWER6 at french IDRIS, http://www.idris.fr/su/Scalaire/vargas/hw-vargas.html
-# NCDF_INC    netcdf include file
-# NCDF_LIB    netcdf library
-# FC          Fortran compiler command
-# FCFLAGS     Fortran compiler flags
-# FFLAGS      Fortran 77 compiler flags
-# LD          linker
-# LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
-# FPPFLAGS    pre-processing flags
-# AR          assembler
-# ARFLAGS     assembler flags
-# MK          make  
-# USER_INC    additional include files for the compiler,  e.g. -I<include dir> 
-# USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
-
-
-%NCDF_INC            -I/usr/local/netcdf-3.6.3/include
-%NCDF_LIB            -L/usr/local/netcdf-3.6.3/lib -lnetcdf
-%CPP                 cpp
-%FC                  xlf90
-%FCFLAGS             -O3 -qsuffix=f=f90  -qstrict -qsuppress=1501-245 -qarch=pwr6 -q64 -qrealsize=8 -qtune=pwr6 -qextname -qlargepage -qmaxmem=-1
-%FFLAGS              -O3 -qsuffix=f=f90  -qstrict -qsuppress=1501-245 -qarch=pwr6 -q64 -qrealsize=8 -qtune=pwr6 -qextname -qlargepage -qmaxmem=-1
-%LD                  xlf90
-%LDFLAGS             -bloadmap:LinkerErrorMap 
-%FPPFLAGS            -P -C
-%AR                  ar  
-%ARFLAGS             rs
-%MK                  gmake 
-%USER_INC            %NCDF_INC
-%USER_LIB            %NCDF_LIB 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-gfortran_athena_xios.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-gfortran_athena_xios.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-gfortran_athena_xios.fcm	(revision 9987)
@@ -25,4 +25,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -56,2 +58,5 @@
 %USER_INC            %XIOS_INC %NCDF_INC %HDF5_INC
 %USER_LIB            %XIOS_LIB %NCDF_LIB %HDF5_LIB  -lnetcdff -lnetcdf -lstdc++ -lz -lcurl -lgpfs
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena.fcm	(revision 9987)
@@ -13,4 +13,6 @@
 # USER_INC additional include files for the compiler, e.g. -I<include dir>
 # USER_LIB additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 
@@ -29,3 +31,5 @@
 %USER_INC %NCDF_INC
 %USER_LIB %NCDF_LIB
+%CC                  icc
+%CFLAGS              -O0
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_debug.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_debug.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_debug.fcm	(revision 9987)
@@ -13,4 +13,6 @@
 # USER_INC additional include files for the compiler, e.g. -I<include dir>
 # USER_LIB additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 
@@ -29,3 +31,5 @@
 %USER_INC %NCDF_INC
 %USER_LIB %NCDF_LIB
+%CC                  icc
+%CFLAGS              -O0
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_tools.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_tools.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_tools.fcm	(revision 9987)
@@ -13,4 +13,6 @@
 # USER_INC additional include files for the compiler, e.g. -I<include dir>
 # USER_LIB additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 
@@ -29,3 +31,5 @@
 %USER_INC %NCDF_INC
 %USER_LIB %NCDF_LIB
+%CC                  icc
+%CFLAGS              -O0
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_xios.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_xios.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/CMCC/arch-ifort_athena_xios.fcm	(revision 9987)
@@ -25,4 +25,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -32,15 +34,17 @@
 
 # required modules
-# module load  INTEL/intel_xe_2013 NETCDF/netcdf-4.3_parallel NETCDF/parallel-netcdf-1.3.1 HDF5/hdf5-1.8.11_parallel
+# module load  INTEL/intel_xe_2013 NETCDF/netcdf-4.3_parallel NETCDF/parallel-netcdf-1.7.0 HDF5/hdf5-1.8.11_parallel
 
-# Environment variables set by user. Others should automatically define when loading modules.
-# export XIOS=/users/home/models/nemo/xios
+# NETCDF and PNETCDF should be set automatically when loading modules.
+# The following environment variables must be set by the user.
+#export XIOS=/users/home/models/nemo/xios
+#export HDF5=/users/home/opt/hdf5/hdf5-1.8.11_parallel
 
-%NCDF_INC            -I$NETCDF/include -I$PNETCDF/include
-%NCDF_LIB            -L$NETCDF/lib -lnetcdff -lnetcdf -L$PNETCDF/lib -lpnetcdf
-%HDF5_INC            -I$PHDF5/include
-%HDF5_LIB            -L$PHDF5/lib -lhdf5_hl -lhdf5
-%XIOS_INC            -I$XIOS/inc
-%XIOS_LIB            -L$XIOS/lib -lxios
+%NCDF_INC            -I${NETCDF}/include -I${PNETCDF}/include
+%NCDF_LIB            -L${NETCDF}/lib -lnetcdff -lnetcdf -L${PNETCDF}/lib -lpnetcdf
+%HDF5_INC            -I${HDF5}/include
+%HDF5_LIB            -L${HDF5}/lib -lhdf5_hl -lhdf5
+%XIOS_INC            -I${XIOS}/inc
+%XIOS_LIB            -L${XIOS}/lib -lxios
 %CPP                 cpp
 %FC                  mpiifort
@@ -55,2 +59,4 @@
 %USER_INC            %XIOS_INC %NCDF_INC %HDF5_INC
 %USER_LIB            %XIOS_LIB %NCDF_LIB %HDF5_LIB
+%CC                  icc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/INGV/arch-IBM_EKMAN_INGV.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/INGV/arch-IBM_EKMAN_INGV.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/INGV/arch-IBM_EKMAN_INGV.fcm	(revision 9987)
@@ -15,4 +15,6 @@
 # USER_INC    additional include files for the compiler,  e.g. -I<include dir>
 # USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 %NCDF_INC            -I/srv/lib/netcdf-x/include
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-ALTIX_NAUTILUS_MPT.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-ALTIX_NAUTILUS_MPT.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-ALTIX_NAUTILUS_MPT.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -58,2 +60,5 @@
 #FCFLAGS             -g -traceback -r8 -O0 -xT -ip -vec-report0
 #FFLAGS              -g -traceback -r8 -O0 -xT -ip -vec-report0
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_C2A_XIO.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_C2A_XIO.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_C2A_XIO.fcm	(revision 9987)
@@ -17,4 +17,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -48,2 +50,5 @@
 %USER_INC            %XIOS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %NCDF_LIB %XLF90_LIB
+
+%CC                  xlc
+%CFLAGS              -O -qcpluscmt
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_METO.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_METO.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_METO.fcm	(revision 9987)
@@ -15,4 +15,6 @@
 # USER_INC    additional include files for the compiler,  e.g. -I<include dir>
 # USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 
@@ -24,5 +26,5 @@
 %FC                  mpxlf90_r
 %FCFLAGS             -qrealsize=8 -qextname -qsuffix=f=f90 -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF
-%FFLAGS              -qrealsize=8 -qextname -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF -qfixed
+%FFLAGS             -qrealsize=8 -qextname -qsuffix=f=f90 -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF
 %LD                  mpCC_r
 %LDFLAGS             -lxlf90 -L/projects/um1/lib -lsig -O2 -L MASS
@@ -33,2 +35,4 @@
 %USER_INC            %NCDF_INC %XIOS_INC
 %USER_LIB            %NCDF_LIB %XIOS_LIB
+%CC                  xlc
+%CFLAGS              -O -qcpluscmt
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_MONSOON.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_MONSOON.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-PW7_MONSOON.fcm	(revision 9987)
@@ -15,4 +15,6 @@
 # USER_INC    additional include files for the compiler,  e.g. -I<include dir>
 # USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 
 %NCDF_INC            -I/home/dcalve/netcdf/4.1.3_seq/include
@@ -32,2 +34,5 @@
 %USER_INC            %NCDF_INC %XIOS_INC
 %USER_LIB            %NCDF_LIB %XIOS_LIB
+
+%CC                  xlc
+%CFLAGS              -O -qcpluscmt
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_ADA.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_ADA.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_ADA.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -54,2 +56,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  icc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_ADA_O0.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_ADA_O0.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_ADA_O0.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -53,2 +55,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  icc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_CURIE.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_CURIE.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_CURIE.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -58,2 +60,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_MOBILIS.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_MOBILIS.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_MOBILIS.fcm	(revision 9987)
@@ -29,4 +29,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -58,2 +60,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_VAYU.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_VAYU.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_VAYU.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -53,2 +55,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_YELLOWSTONE.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_YELLOWSTONE.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-X64_YELLOWSTONE.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -53,2 +55,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC40_METO.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC40_METO.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC40_METO.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -31,5 +33,5 @@
 %NCDF_HOME           /opt/cray/netcdf-hdf5parallel/4.3.2/CRAY/83
 %HDF5_HOME           /opt/cray/hdf5-parallel/1.8.13/CRAY/83
-%XIOS_HOME           /projects/ocean/nemo/xios/xios_1.0_r618_20150619/XIOS
+%XIOS_HOME           /projects/ocean/nemo/xios/xios_1.0_r629_20150625/XIOS
 
 %NCDF_INC            -I%NCDF_HOME/include -I%HDF5_HOME/include
@@ -51,2 +53,5 @@
 %USER_INC            %XIOS_INC
 %USER_LIB            %XIOS_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC_ARCHER.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC_ARCHER.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC_ARCHER.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -57,2 +59,5 @@
 #USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 #USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC_ARCHER_INTEL.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC_ARCHER_INTEL.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-XC_ARCHER_INTEL.fcm	(revision 9987)
@@ -24,4 +24,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -55,2 +57,5 @@
 #USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 #USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-macport_osx.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-macport_osx.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-macport_osx.fcm	(revision 9987)
@@ -33,4 +33,6 @@
 # USER_INC    complete list of include files
 # USER_LIB    complete list of libraries to pass to the linker
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 #
 # Note that:
@@ -62,2 +64,5 @@
 %USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
 %USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-openmpi_NAVITI_MERCATOR.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-openmpi_NAVITI_MERCATOR.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/ARCH/arch-openmpi_NAVITI_MERCATOR.fcm	(revision 9987)
@@ -13,4 +13,6 @@
 # USER_INC    additional include files for the compiler,  e.g. -I<include dir>
 # USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+# CC          C compiler used to compile conv for AGRIF
+# CFLAGS      compiler flags used with CC
 # debug: -g  -check bounds -check uninit -check pointers -traceback
 
@@ -31,2 +33,5 @@
 %USER_INC            -I$XIOS_INC %NCDF_INC
 %USER_LIB            -L$XIOS_LIB -lxios %NCDF_LIB -lstdc++
+
+%CC                  cc
+%CFLAGS              -O0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/AMM12/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/AMM12/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/AMM12/EXP00/namelist_cfg	(revision 9987)
@@ -200,8 +200,4 @@
 /
 !-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-/
-!-----------------------------------------------------------------------
 &namagrif      !  AGRIF zoom                                            ("key_agrif")
 !-----------------------------------------------------------------------
@@ -369,4 +365,8 @@
 /
 !-----------------------------------------------------------------------
+&namzdf_tmx_new !  new tidal mixing parameterization                    ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namsol        !   elliptic solver / island / free surface
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/C1D_PAPA/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/C1D_PAPA/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/C1D_PAPA/EXP00/namelist_cfg	(revision 9987)
@@ -141,4 +141,7 @@
 &namtra_qsr    !   penetrative solar radiation
 !-----------------------------------------------------------------------
+!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
+!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
+   sn_chl      ='chlorophyll_PAPASTATION', -1    , 'CHLA'    ,   .true.     , .true. , 'yearly'  , ''       , ''       , ''
 /
 !-----------------------------------------------------------------------
@@ -173,8 +176,4 @@
 !-----------------------------------------------------------------------
 &namcla        !   cross land advection
-!-----------------------------------------------------------------------
-/
-!-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
 !-----------------------------------------------------------------------
 /
@@ -304,4 +303,8 @@
 /
 !-----------------------------------------------------------------------
+&namzdf_tmx_new !  new tidal mixing parameterization                    ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namsol        !   elliptic solver / island / free surface
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE/EXP00/namelist_cfg	(revision 9987)
@@ -160,8 +160,4 @@
 /
 !-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-/
-!-----------------------------------------------------------------------
 &namagrif      !  AGRIF zoom                                            ("key_agrif")
 !-----------------------------------------------------------------------
@@ -304,4 +300,8 @@
 /
 !-----------------------------------------------------------------------
+&namzdf_tmx_new !  new tidal mixing parameterization                    ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namsol        !   elliptic solver / island / free surface
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE_BFM/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE_BFM/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE_BFM/EXP00/namelist_cfg	(revision 9987)
@@ -165,8 +165,4 @@
 /
 !-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-/
-!-----------------------------------------------------------------------
 &namagrif      !  AGRIF zoom                                            ("key_agrif")
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE_XIOS/cpp_GYRE_XIOS.fcm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE_XIOS/cpp_GYRE_XIOS.fcm	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/GYRE_XIOS/cpp_GYRE_XIOS.fcm	(revision 9987)
@@ -1,1 +1,1 @@
- bld::tool::fppkeys key_dynspg_flt key_ldfslp key_zdftke key_iomput key_mpp_mpi
+ bld::tool::fppkeys key_dynspg_flt key_ldfslp key_zdftke key_iomput key_mpp_mpi key_xios2
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/1_namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/1_namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/1_namelist_cfg	(revision 9987)
@@ -6,5 +6,5 @@
 !-----------------------------------------------------------------------
    cn_exp      = "Agulhas" !  experience name 
-   nn_itend    =     480   !  last  time step
+   nn_itend    =   10950   !  last  time step
    nn_stock    =   10950   !  frequency of creation of a restart file (modulo referenced to 1)
    nn_write    =   10950   !  frequency of write in the output file   (modulo referenced to nn_it000)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/iodef.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/iodef.xml	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/iodef.xml	(revision 9987)
@@ -153,4 +153,148 @@
   </context>
   
+ <context id="1_nemo" time_origin="1950-01-01 00:00:00" >
+    
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+    <field_definition src="./field_def.xml"/>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE." >  <!-- 5d files -->  
+ 
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="sst"          name="tos"      long_name="sea_surface_temperature"                       />
+	  <field field_ref="sss"          name="sos"      long_name="sea_surface_salinity"                          />
+	  <field field_ref="ssh"          name="zos"      long_name="sea_surface_height_above_geoid"                />
+	  <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"               />
+	  <field field_ref="soce"         name="so"       long_name="sea_water_salinity"                            />
+	  <field field_ref="sst2"         name="tossq"    long_name="square_of_sea_surface_temperature"             />
+	  <field field_ref="ssh2"         name="zossq"    long_name="square_of_sea_surface_height_above_geoid"      />
+	  <field field_ref="mldkz5"       />
+	  <field field_ref="mldr10_1"     />
+	  <field field_ref="empmr"        name="wfo"      long_name="water_flux_into_sea_water"                     />
+	  <field field_ref="qsr"          name="rsntds"   long_name="surface_net_downward_shortwave_flux"           />
+	  <field field_ref="qt"           name="tohfls"   long_name="surface_net_downward_total_heat_flux"          />
+	  <field field_ref="saltflx"      name="sosflxdo"  />
+	  <field field_ref="taum"         name="taum" />
+	  <field field_ref="wspd"         name="sowindsp"  />
+          <field field_ref="precip"       name="soprecip" />
+	</file>
+
+	<file id="file3" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="ssu"          name="uos"     long_name="sea_surface_x_velocity"    />
+	  <field field_ref="uoce"         name="uo"      long_name="sea_water_x_velocity"      />
+	  <field field_ref="utau"         name="tauuo"   long_name="surface_downward_x_stress" />
+          <!-- variables available with MLE
+          <field field_ref="psiu_mle"     name="psiu_mle"  long_name="MLE_streamfunction_along_i-axis" />
+	  -->
+	</file>
+	
+	<file id="file4" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="ssv"          name="vos"     long_name="sea_surface_y_velocity"    />
+	  <field field_ref="voce"         name="vo"      long_name="sea_water_y_velocity"      />
+	  <field field_ref="vtau"         name="tauvo"   long_name="surface_downward_y_stress" />
+          <!-- variables available with MLE
+          <field field_ref="psiv_mle"     name="psiv_mle"  long_name="MLE_streamfunction_along_j-axis" />
+	  -->
+	</file>
+	
+	<file id="file5" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="woce"         name="wo"      long_name="ocean vertical velocity"         />
+	  <field field_ref="avt"          name="difvho"  long_name="ocean_vertical_heat_diffusivity" />
+	</file>
+<!--
+	<file id="file6" name_suffix="_icemod" description="ice variables" >
+	  <field field_ref="ice_pres"                     />
+	  <field field_ref="snowthic_cea" name="snd"     long_name="surface_snow_thickness"   />
+	  <field field_ref="icethic_cea"  name="sit"     long_name="sea_ice_thickness"        />
+	  <field field_ref="iceprod_cea"  name="sip"     long_name="sea_ice_thickness"        />
+	  <field field_ref="ist_ipa"      />
+	  <field field_ref="uice_ipa"     />
+	  <field field_ref="vice_ipa"     />
+	  <field field_ref="utau_ice"     />
+	  <field field_ref="vtau_ice"     />
+	  <field field_ref="qsr_io_cea"   />
+	  <field field_ref="qns_io_cea"   />
+	  <field field_ref="snowpre"      />
+	</file>
+
+	<file id="file8" name_suffix="_Tides" description="tidal harmonics" >
+	  <field field_ref="M2x"          name="M2x"      long_name="M2 Elevation harmonic real part"                       />
+	  <field field_ref="M2y"          name="M2y"      long_name="M2 Elevation harmonic imaginary part"                  />
+	  <field field_ref="M2x_u"        name="M2x_u"    long_name="M2 current barotrope along i-axis harmonic real part "       />
+	  <field field_ref="M2y_u"        name="M2y_u"    long_name="M2 current barotrope along i-axis harmonic imaginary part "  />
+	  <field field_ref="M2x_v"        name="M2x_v"    long_name="M2 current barotrope along j-axis harmonic real part "       />
+	  <field field_ref="M2y_v"        name="M2y_v"    long_name="M2 current barotrope along j-axis harmonic imaginary part "  />
+	</file>
+	-->
+      </file_group>
+
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+
+
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
+    <!-- 
+============================================================================================================
+= grid definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+    
+   <axis_definition>  
+      <axis id="deptht" long_name="Vertical T levels" unit="m" positive="down" />
+      <axis id="depthu" long_name="Vertical U levels" unit="m" positive="down" />
+      <axis id="depthv" long_name="Vertical V levels" unit="m" positive="down" />
+      <axis id="depthw" long_name="Vertical W levels" unit="m" positive="down" />
+      <axis id="nfloat" long_name="Float number"      unit="-"  />
+      <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
+   </axis_definition> 
+    
+   <domain_definition src="./domain_def.xml"/>
+   
+   <grid_definition>    
+     <grid id="grid_T_2D" domain_ref="grid_T"/>
+     <grid id="grid_T_3D" domain_ref="grid_T" axis_ref="deptht"/>
+     <grid id="grid_U_2D" domain_ref="grid_U"/>
+     <grid id="grid_U_3D" domain_ref="grid_U" axis_ref="depthu"/>
+     <grid id="grid_V_2D" domain_ref="grid_V"/>
+     <grid id="grid_V_3D" domain_ref="grid_V" axis_ref="depthv"/>
+     <grid id="grid_W_2D" domain_ref="grid_W"/>
+     <grid id="grid_W_3D" domain_ref="grid_W" axis_ref="depthw"/>
+    </grid_definition>   
+  </context>
 
   <context id="xios">
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/namelist_cfg	(revision 9987)
@@ -165,4 +165,8 @@
 /
 !-----------------------------------------------------------------------
+&namzdf_tmx_new !  new tidal mixing parameterization                    ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namsol        !   elliptic solver / island / free surface
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef.xml	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef.xml	(revision 9987)
@@ -61,4 +61,6 @@
 	<file id="file2" name_suffix="_SBC" description="surface fluxes variables" > <!-- time step automaticaly defined based on nn_fsbc -->
 	  <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="emp_oce"      name="emp_oce"  long_name="Evap minus Precip over ocean"              />
+          <field field_ref="emp_ice"      name="emp_ice"  long_name="Evap minus Precip over ice"                />
 	  <field field_ref="qsr_oce"      name="qsr_oce"  />
 	  <field field_ref="qns_oce"      name="qns_oce"  />
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_cfg	(revision 9987)
@@ -168,4 +168,8 @@
 /
 !-----------------------------------------------------------------------
+&namzdf_tmx_new !  new tidal mixing parameterization                    ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namsol        !   elliptic solver / island / free surface
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_CFC_C14b/EXP00/1_namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_CFC_C14b/EXP00/1_namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_CFC_C14b/EXP00/1_namelist_cfg	(revision 9987)
@@ -5,5 +5,5 @@
 !!                                    namsbc_cpl, namtra_qsr, namsbc_rnf, 
 !!                                    namsbc_apr, namsbc_ssr, namsbc_alb)
-!!              4 - lateral boundary (namlbc, namcla, namobc, namagrif, nambdy, nambdy_tide)
+!!              4 - lateral boundary (namlbc, namcla, namagrif, nambdy, nambdy_tide)
 !!              5 - bottom  boundary (nambfr, nambbc, nambbl)
 !!              6 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_dmp)
@@ -303,5 +303,4 @@
 !!   namlbc        lateral momentum boundary condition
 !!   namcla        cross land advection
-!!   namobc        open boundaries parameters                           ("key_obc")
 !!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif") 
 !!   nambdy        Unstructured open boundaries                         ("key_bdy")
@@ -319,25 +318,4 @@
 !-----------------------------------------------------------------------
    nn_cla      =    0      !  advection between 2 ocean pts separates by land
-/
-!-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-   ln_obc_clim = .false.   !  climatological obc data files (T) or not (F)
-   ln_vol_cst  = .true.    !  impose the total volume conservation (T) or not (F)
-   ln_obc_fla  = .false.   !  Flather open boundary condition 
-   nn_obcdta   =    1      !  = 0 the obc data are equal to the initial state
-                           !  = 1 the obc data are read in 'obc.dta' files
-   cn_obcdta   = 'annual'  !  set to annual if obc datafile hold 1 year of data
-                           !  set to monthly if obc datafile hold 1 month of data
-   rn_dpein    =    1.     !  damping time scale for inflow at east  open boundary
-   rn_dpwin    =    1.     !     -           -         -       west    -      -
-   rn_dpnin    =    1.     !     -           -         -       north   -      -
-   rn_dpsin    =    1.     !     -           -         -       south   -      -
-   rn_dpeob    = 3000.     !  time relaxation (days) for the east  open boundary
-   rn_dpwob    =   15.     !     -           -         -     west    -      -
-   rn_dpnob    = 3000.     !     -           -         -     north   -      -
-   rn_dpsob    =   15.     !     -           -         -     south   -      -
-   rn_volemp   =    1.     !  = 0 the total volume change with the surface flux (E-P-R)
-                           !  = 1 the total volume remains constant
 /
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_CFC_C14b/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_CFC_C14b/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_CFC_C14b/EXP00/namelist_cfg	(revision 9987)
@@ -136,8 +136,4 @@
 /
 !-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-/
-!-----------------------------------------------------------------------
 &namagrif      !  AGRIF zoom                                            ("key_agrif")
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_PISCES/EXP00/namelist_cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_PISCES/EXP00/namelist_cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/ORCA2_LIM_PISCES/EXP00/namelist_cfg	(revision 9987)
@@ -165,4 +165,8 @@
 /
 !-----------------------------------------------------------------------
+&namzdf_tmx_new !  new tidal mixing parameterization                    ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namsol        !   elliptic solver / island / free surface
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/1_cfc1112.atm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/1_cfc1112.atm	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/1_cfc1112.atm	(revision 9987)
@@ -0,0 +1,84 @@
+ % Atmospheric lifetimes are  44.0 for CFC-11 
+ %                       and 125.0 for CFC-12 
+ % rel=  0 
+ %        <-Northern Data-> <-Southern Data->
+ % Year    CFC-11  CFC-12    CFC-11  CFC-12 
+ %         (ppt)   (ppt)      (ppt)   (ppt)
+ 1931.50    0.00    0.00       0.00    0.00   
+ 1932.50    0.00    0.01       0.00    0.01   
+ 1933.50    0.00    0.02       0.00    0.01   
+ 1934.50    0.00    0.03       0.00    0.02   
+ 1935.50    0.00    0.04       0.00    0.03   
+ 1936.50    0.00    0.07       0.00    0.04   
+ 1937.50    0.00    0.11       0.00    0.07   
+ 1938.50    0.00    0.17       0.00    0.11   
+ 1939.50    0.01    0.25       0.00    0.17   
+ 1940.50    0.01    0.37       0.01    0.25   
+ 1941.50    0.02    0.53       0.01    0.36   
+ 1942.50    0.02    0.72       0.02    0.51   
+ 1943.50    0.03    0.94       0.02    0.69   
+ 1944.50    0.04    1.25       0.03    0.91   
+ 1945.50    0.05    1.65       0.04    1.21   
+ 1946.50    0.08    2.33       0.05    1.64   
+ 1947.50    0.14    3.42       0.08    2.33   
+ 1948.50    0.24    4.73       0.14    3.32   
+ 1949.50    0.42    6.10       0.25    4.48   
+ 1950.50    0.67    7.58       0.42    5.77   
+ 1951.50    1.02    9.23       0.66    7.19   
+ 1952.50    1.53   10.94       1.01    8.72   
+ 1953.50    2.21   12.82       1.49   10.37   
+ 1954.50    3.07   14.97       2.13   12.20   
+ 1955.50    4.11   17.40       2.93   14.25   
+ 1956.50    5.39   20.22       3.92   16.59   
+ 1957.50    6.84   23.45       5.11   19.28   
+ 1958.50    8.19   26.86       6.39   22.28   
+ 1959.50    9.47   30.58       7.63   25.52   
+ 1960.50   11.13   35.03       8.96   29.18   
+ 1961.50   13.38   40.12      10.63   33.42   
+ 1962.50   16.23   45.89      12.78   38.25   
+ 1963.50   19.72   52.66      15.47   43.80   
+ 1964.50   23.87   60.57      18.75   50.28   
+ 1965.50   28.57   69.53      22.61   57.76   
+ 1966.50   33.78   79.46      26.99   66.21   
+ 1967.50   39.63   90.60      31.91   75.67   
+ 1968.50   46.27  103.16      37.46   86.31   
+ 1969.50   53.96  117.17      43.80   98.25   
+ 1970.50   62.75  132.52      51.07  111.52   
+ 1971.50   72.36  149.00      59.27  126.02   
+ 1972.50   83.04  166.85      68.34  141.70   
+ 1973.50   95.27  186.59      78.54  158.82   
+ 1974.50  108.81  208.14      90.04  177.62   
+ 1975.50  121.86  229.37     102.29  197.54   
+ 1976.50  134.47  249.51     114.40  217.31   
+ 1977.50  146.47  268.67     126.28  236.49   
+ 1978.50  157.18  286.35     137.45  254.72   
+ 1979.50  166.67  303.74     147.60  272.00   
+ 1980.50  175.11  320.96     158.08  290.34   
+ 1981.50  182.81  337.33     166.54  306.90   
+ 1982.50  189.88  352.01     174.69  323.74   
+ 1983.50  197.72  367.69     183.03  341.15   
+ 1984.50  206.34  383.86     190.95  357.80   
+ 1985.50  216.12  401.25     200.50  376.45   
+ 1986.50  227.48  420.96     209.82  394.00   
+ 1987.50  239.67  441.49     220.60  412.82   
+ 1988.50  251.05  463.22     231.46  433.46   
+ 1989.50  257.28  481.80     240.38  452.97   
+ 1990.50  263.65  493.96     249.23  470.55   
+ 1991.50  266.33  504.64     254.53  484.07   
+ 1992.50  266.00  512.87     258.80  495.65   
+ 1993.50  267.58  520.12     260.56  504.49   
+ 1994.50  267.24  526.58     261.73  512.31   
+ 1995.50  266.38  531.59     261.29  518.39   
+ 1996.50  265.25  534.81     261.08  523.50   
+ 1997.50  263.84  537.67     260.16  528.18   
+ 1998.50  262.24  999.99     258.96  999.99   
+ 1999.50  260.72  999.99     257.75  999.99   
+ 2000.50  259.34  999.99     255.69  999.99   
+ 2001.50  257.13  999.99     253.54  999.99   
+ 2002.50  254.89  999.99     252.93  999.99   
+ 2003.50  251.89  999.99     250.62  999.99   
+ 2004.50  250.67  999.99     249.52  999.99   
+ 2005.50  249.49  999.99     247.45  999.99   
+ 2006.50  248.31  999.99     245.38  999.99
+ 2007.50  247.13  999.99     243.31  999.99
+ 2008.50  245.95  999.99     241.24  999.99
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/field_def_bgc.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/field_def_bgc.xml	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/field_def_bgc.xml	(revision 9987)
@@ -0,0 +1,809 @@
+<!--
+<?xml version="1.0"?>
+       -->
+ 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+   <field_definition level="1" prec="8" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                     Biogeochemistry model variables
+============================================================================================================
+    -->
+
+      <!-- ptrc on T grid -->
+
+     <field_group id="ptrc_T" grid_ref="grid_T_3D">
+       <field id="DIC"          long_name="Dissolved inorganic Concentration"        unit="mmol/m3" />
+       <field id="DIC_E3T"      long_name="DIC * E3T"                                unit="mmol/m2" > DIC * e3t </field >
+       <field id="Alkalini"     long_name="Total Alkalinity Concentration"           unit="mmol/m3" />
+       <field id="Alkalini_E3T" long_name="Alkalini * E3T"                           unit="mmol/m2"  > Alkalini * e3t </field >
+       <field id="O2"           long_name="Oxygen Concentration"                     unit="mmol/m3" />
+       <field id="O2_E3T"       long_name="O2 * E3T"                                 unit="mmol/m2"  > O2 * e3t </field >
+       <field id="CaCO3"        long_name="Calcite Concentration"                    unit="mmol/m3" />
+       <field id="CaCO3_E3T"    long_name="CaCO3 * E3T"                              unit="mmol/m2"  > CaCO3 * e3t </field >
+       <field id="PO4"          long_name="Phosphate Concentration"                  unit="mmol/m3" />
+       <field id="PO4_E3T"      long_name="PO4 * E3T"                                unit="mmol/m2"  > PO4 * e3t </field >
+       <field id="POC"          long_name="Small organic carbon Concentration"       unit="mmol/m3" />
+       <field id="POC_E3T"      long_name="POC * E3T"                                unit="mmol/m2"  > POC * e3t </field >
+       <field id="Si"           long_name="Silicate Concentration"                   unit="mmol/m3" />
+       <field id="Si_E3T"       long_name="Si * E3T"                                 unit="mmol/m2"  > Si * e3t </field >
+       <field id="PHY"          long_name="(Nano)Phytoplankton Concentration"        unit="mmol/m3" />
+       <field id="PHY_E3T"      long_name="PHY * E3T"                                unit="mmol/m2"  > PHY * e3t </field >
+       <field id="ZOO"          long_name="(Micro)Zooplankton Concentration"         unit="mmol/m3" />
+       <field id="ZOO_E3T"      long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO * e3t </field >
+       <field id="DOC"          long_name="Dissolved organic Concentration"          unit="mmol/m3" />
+       <field id="DOC_E3T"      long_name="DOC * E3T"                                unit="mmol/m2"  > DOC * e3t </field >
+       <field id="PHY2"         long_name="Diatoms Concentration"                    unit="mmol/m3" />
+       <field id="PHY2_E3T"     long_name="PHY2 * E3T"                               unit="mmol/m2"  > PHY2 * e3t </field >
+       <field id="ZOO2"         long_name="Mesozooplankton Concentration"            unit="mmol/m3" />
+       <field id="ZOO2_E3T"     long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO2 * e3t </field >
+       <field id="DSi"          long_name="Diatoms Silicate Concentration"           unit="mmol/m3" />
+       <field id="DSi_E3T"      long_name="Dsi * E3T"                                unit="mmol/m2"  > DSi * e3t </field >
+       <field id="Fer"          long_name="Dissolved Iron Concentration"             unit="mmol/m3" />
+       <field id="Fer_E3T"      long_name="Fer * E3T"                                unit="mmol/m2"  > Fer * e3t </field >
+       <field id="BFe"          long_name="Big iron particles Concentration"         unit="mmol/m3" />
+       <field id="BFe_E3T"      long_name="BFe * E3T"                                unit="mmol/m2"  > BFe * e3t </field >
+       <field id="GOC"          long_name="Big organic carbon Concentration"         unit="mmol/m3" />
+       <field id="GOC_E3T"      long_name="GOC * E3T"                                unit="mmol/m2"  > GOC * e3t </field >
+       <field id="SFe"          long_name="Small iron particles Concentration"       unit="mmol/m3" />
+       <field id="SFe_E3T"      long_name="SFe * E3T"                                unit="mmol/m2"  > SFe * e3t </field >
+       <field id="DFe"          long_name="Diatoms iron  Concentration"              unit="mmol/m3" />
+       <field id="DFe_E3T"      long_name="DFe * E3T"                                unit="mmol/m2"  > DFe * e3t </field >
+       <field id="GSi"          long_name="Sinking biogenic Silicate Concentration"  unit="mmol/m3" />
+       <field id="GSi_E3T"      long_name="GSi * E3T"                                unit="mmol/m2"  > GSi * e3t </field >
+       <field id="NFe"          long_name="Nano iron Concentration"                  unit="mmol/m3" />
+       <field id="NFe_E3T"      long_name="NFe * E3T"                                unit="mmol/m2"  > NFe * e3t </field >
+       <field id="NCHL"         long_name="Nano chlorophyl Concentration"            unit="mg/m3"   />
+       <field id="NCHL_E3T"     long_name="NCHL * E3T"                               unit="mmol/m2"  > NCHL * e3t </field >
+       <field id="DCHL"         long_name="Diatoms chlorophyl Concentration"         unit="mg/m3"   />
+       <field id="DCHL_E3T"     long_name="DCHL * E3T"                               unit="mmol/m2"  > DCHL * e3t </field >
+       <field id="NO3"          long_name="Nitrate Concentration"                    unit="mmol/m3" />
+       <field id="NO3_E3T"      long_name="NO3 * E3T"                                unit="mmol/m2"  > NO3 * e3t </field >
+       <field id="NH4"          long_name="Ammonium Concentration"                   unit="mmol/m3" />
+       <field id="NH4_E3T"      long_name="NH4 * E3T"                                unit="mmol/m2"  > NH4 * e3t </field >
+
+      <!-- MEDUSA : variables available with key_medusa -->
+       <field id="CHN"      long_name="Chl-a concentration in non-diatom phytoplankton"   unit="mg Chl/m3" />
+       <field id="CHD"      long_name="Chl-a concentration in     diatom phytoplankton"   unit="mg Chl/m3" />
+       <field id="PHN"      long_name="non-diatom phytoplankton"                          unit="mmol-N/m3" />
+       <field id="PHD"      long_name="diatom     phytoplankton"                          unit="mmol-N/m3" />
+       <field id="ZMI"      long_name="micro zooplankton"                                 unit="mmol-N/m3" />
+       <field id="ZME"      long_name="meso  zooplankton"                                 unit="mmol-N/m3" />
+       <field id="DIN"      long_name="dissolved inorganic nitrogen"                      unit="mmol-N/m3" />
+       <field id="SIL"      long_name="dissolved silicic acid"                            unit="mmolSi/m3" />
+       <field id="FER"      long_name="dissolved iron"                                    unit="mmolFe/m3" />
+       <field id="DET"      long_name="detrital nitrogen"                                 unit="mmol-N/m3" />
+       <field id="PDS"      long_name="biogenic silicon in diatom phytoplankton"          unit="mmolSi/m3" />
+       <field id="DTC"      long_name="detrital carbon"                                   unit="mmol-C/m3" />
+       <field id="DiC"      long_name="dissolved inorganic carbon"                        unit="mmol-C/m3" />
+       <field id="ALK"      long_name="alkalinity"                                        unit="meq/m3"    />
+       <field id="OXY"      long_name="dissolved oxygen"                                  unit="mmolO2/m3" />
+
+      <!-- Ideal traceurs : variables available with key_idtra -->
+       <field id="IDTRA"    long_name="Ideal traceur concentration "                      unit="mmol/m3"    />
+
+       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
+       <field id="Num"         long_name="Number of organic particles"              unit="1" />
+       <field id="Num_E3T"     long_name="Num * E3T"                                unit="m"  > Num * e3t </field >
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="DET"         long_name="Detritus"                                 unit="mmol-N/m3" />
+       <field id="DET_E3T"     long_name="DET * E3T"                                unit="mmol-N/m2"  > DET * e3t </field >
+       <field id="DOM"         long_name="Dissolved Organic Matter"                 unit="mmol-N/m3" />
+       <field id="DOM_E3T"     long_name="DOM * E3T"                                unit="mmol-N/m2"  > DOM * e3t </field >
+
+       <!-- CFC11 : variables available with key_cfc -->
+       <field id="CFC11"       long_name="CFC-11 Concentration"                     unit="umol/m3" />
+       <field id="CFC11_E3T"   long_name="CFC11 * E3T"                              unit="umol/m2"  > CFC11 * e3t </field >
+       <!-- Bomb C14 : variables available with key_c14b -->
+       <field id="C14B"        long_name="Bomb C14 Concentration"                   unit="1"         />
+       <field id="C14B_E3T"    long_name="C14B * E3T"                               unit="m"  > C14B * e3t </field >
+       <!-- AGE : variables available with key_age -->
+       <field id="Age"        long_name="Sea Water Age Since Surface contact" standard_name="sea_water_age_since_surface_contact"  unit="yr"         />
+       <field id="Age_e3t"    long_name="Age * e3t"                                 unit="yr * m"  > Age * e3t </field >
+     </field_group>
+
+     <!-- PISCES additional diagnostics on T grid  -->
+
+     <field_group id="diad_T" grid_ref="grid_T_2D">
+       <field id="PH"          long_name="PH"                                      unit="1"          grid_ref="grid_T_3D" />
+       <field id="CO3"         long_name="Bicarbonates"                            unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="CO3sat"      long_name="CO3 saturation"                          unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="PAR"         long_name="Photosynthetically Available Radiation"  unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PARDM"       long_name="Daily mean PAR"                          unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PPPHY"       long_name="Primary production of nanophyto"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPPHY2"      long_name="Primary production of diatoms"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPNEWN"      long_name="New Primary production of nanophyto"     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPNEWD"      long_name="New Primary production of diatoms"       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PBSi"        long_name="Primary production of Si diatoms"        unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PFeN"        long_name="Primary production of nano iron"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PFeD"        long_name="Primary production of diatoms iron"      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="xfracal"     long_name="Calcifying fraction"                     unit="1"          grid_ref="grid_T_3D" />
+       <field id="PCAL"        long_name="Calcite production"                      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DCAL"        long_name="Calcite dissolution"                     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ1"       long_name="Grazing by microzooplankton"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ2"       long_name="Grazing by mesozooplankton"              unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="REMIN"       long_name="Oxic remineralization of OM"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DENIT"       long_name="Anoxic remineralization of OM"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Nfix"        long_name="Nitrogen fixation"                       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Mumax"       long_name="Maximum growth rate"                     unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuN"         long_name="Realized growth rate for nanophyto"      unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuD"         long_name="Realized growth rate for diatomes"       unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="LNnut"       long_name="Nutrient limitation term in Nanophyto"   unit=""           grid_ref="grid_T_3D" />
+       <field id="LDnut"       long_name="Nutrient limitation term in Diatoms"     unit=""           grid_ref="grid_T_3D" />
+       <field id="LNFe"        long_name="Iron limitation term in Nanophyto"       unit=""           grid_ref="grid_T_3D" />
+       <field id="LDFe"        long_name="Iron limitation term in Diatoms"         unit=""           grid_ref="grid_T_3D" />
+       <field id="LNlight"     long_name="Light limitation term in Nanophyto"      unit=""           grid_ref="grid_T_3D" />
+       <field id="LDlight"     long_name="Light limitation term in Diatoms"        unit=""           grid_ref="grid_T_3D" />
+       <field id="Fe2"         long_name="Iron II concentration"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Fe3"         long_name="Iron III concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL1"        long_name="Complexed Iron concentration with L1"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL2"        long_name="Complexed Iron concentration with L2"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeP"         long_name="Precipitated Iron III"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL1"         long_name="Total L1 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL2"         long_name="Total L2 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="pdust"       long_name="dust concentration"                      unit="g/m3"                            />
+       <field id="Totlig"      long_name="Total ligand concentation"               unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Biron"       long_name="Bioavailable iron"                       unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Sdenit"      long_name="Nitrate reduction in the sediments"      unit="mol/m2/s"                        />
+       <field id="Ironice"     long_name="Iron input/uptake due to sea ice"        unit="mol/m2/s"                        />
+       <field id="HYDR"        long_name="Iron input from hydrothemal vents"       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EPC100"      long_name="Export of carbon particles at 100 m"     unit="mol/m2/s"                        />
+       <field id="EPFE100"     long_name="Export of biogenic iron at 100 m"        unit="mol/m2/s"                        />
+       <field id="EPSI100"     long_name="Export of Silicate at 100 m"             unit="mol/m2/s"                        />
+       <field id="EPCAL100"    long_name="Export of Calcite at 100 m"              unit="mol/m2/s"                        />
+       <field id="EXPC"        long_name="Export of carbon"                        unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPFE"       long_name="Export of biogenic iron"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPSI"       long_name="Export of Silicate"                      unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPCAL"      long_name="Export of Calcite"                       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="Cflx"        long_name="DIC flux"                                unit="mol/m2/s"                        />
+       <field id="Oflx"        long_name="Oxygen flux"                             unit="mol/m2/s"                        />
+       <field id="Kg"          long_name="Gas transfer"                            unit="mol/m2/s/uatm"                   />
+       <field id="Dpco2"       long_name="Delta CO2"                               unit="uatm"                            />
+       <field id="Dpo2"        long_name="Delta O2"                                unit="uatm"                            />
+       <field id="Heup"        long_name="Euphotic layer depth"                    unit="m"                               />
+       <field id="Irondep"     long_name="Iron deposition from dust"               unit="mol/m2/s"                        />
+       <field id="Ironsed"     long_name="Iron deposition from sediment"           unit="mol/m2/s"   grid_ref="grid_T_3D" />
+
+
+       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
+       <field id="EPN100"      long_name="Particulate number flux at 100 m"        unit="mol/m2/s"                        />
+       <field id="EXPN"        long_name="Particulate number flux"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="XNUM"        long_name="Number of particles in aggregats"        unit="1"          grid_ref="grid_T_3D" />
+       <field id="WSC"         long_name="sinking speed of mass flux"              unit="m2/s"       grid_ref="grid_T_3D" />
+       <field id="WSN"         long_name="sinking speed of number flux"            unit="m2/s"       grid_ref="grid_T_3D" />
+
+       <!-- dbio_T on T grid : variables available with key_diaar5 -->
+       <field id="TPP"         long_name="Total Primary production of phyto"                   unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPNEW"       long_name="New Primary production of phyto"                     unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPBFE"       long_name="Total biogenic iron production"                      unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="INTDIC"      long_name="DIC content"                                         unit="kg/m2"                          />
+       <field id="O2MIN"       long_name="Oxygen minimum concentration"                        unit="mol/m3"                          />
+       <field id="ZO2MIN"      long_name="Depth of oxygen minimum concentration"               unit="m"                              />
+       <field id="INTNFIX"     long_name="Nitrogen fixation rate : vert. integrated"           unit="mol/m2/s"                       />
+       <field id="INTPPPHY"    long_name="Vertically integrated primary production by nanophy" unit="mol/m2/s"                       />
+       <field id="INTPPPHY2"   long_name="Vertically integrated primary production by diatom"  unit="mol/m2/s"                       />
+       <field id="INTPP"       long_name="Vertically integrated primary production by phyto"   unit="mol/m2/s"                       />
+       <field id="INTPNEW"     long_name="Vertically integrated new primary production"        unit="mol/m2/s"                       />
+       <field id="INTPBFE"     long_name="Vertically integrated of biogenic iron production"   unit="mol/m2/s"                       />
+       <field id="INTPBSI"     long_name="Vertically integrated of biogenic Si production"     unit="mol/m2/s"                       />
+       <field id="INTPCAL"     long_name="Vertically integrated of calcite production"         unit="mol/m2/s"                       />
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="FNO3PHY"     long_name="FNO3PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4PHY"     long_name="FNH4PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4NO3"     long_name="FNH4NO3"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="TNO3PHY"     long_name="TNO3PHY"                                 unit=""  /> 
+       <field id="TNH4PHY"     long_name="TNH4PHY"                                 unit=""  /> 
+       <field id="TPHYDOM"     long_name="TPHYDOM"                                 unit=""  /> 
+       <field id="TPHYNH4"     long_name="TPHYNH4"                                 unit=""  /> 
+       <field id="TPHYZOO"     long_name="TPHYZOO"                                 unit=""  /> 
+       <field id="TPHYDET"     long_name="TPHYDET"                                 unit=""  /> 
+       <field id="TDETZOO"     long_name="TDETZOO"                                 unit=""  /> 
+       <field id="TZOODET"     long_name="TZOODET"                                 unit=""  /> 
+       <field id="TZOOBOD"     long_name="TZOOBOD"                                 unit=""  /> 
+       <field id="TZOONH4"     long_name="TZOONH4"                                 unit=""  /> 
+       <field id="TZOODOM"     long_name="TZOODOM"                                 unit=""  /> 
+       <field id="TNH4NO3"     long_name="TNH4NO3"                                 unit=""  /> 
+       <field id="TDOMNH4"     long_name="TDOMNH4"                                 unit=""  /> 
+       <field id="TDETNH4"     long_name="TDETNH4"                                 unit=""  /> 
+       <field id="TPHYTOT"     long_name="TPHYTOT"                                 unit=""  /> 
+       <field id="TZOOTOT"     long_name="TZOOTOT"                                 unit=""  /> 
+       <field id="SEDPOC"      long_name="SEDPOC"                                  unit=""  /> 
+       <field id="TDETSED"     long_name="TDETSED"                                 unit=""  /> 
+
+       <!-- CFC11 : variables available with key_cfc -->
+       <field id="qtrCFC11"    long_name="Air-sea flux of CFC-11"                  unit="mol/m2/s"   />
+       <field id="qintCFC11"   long_name="Cumulative air-sea flux of CFC-11"       unit="mol/m2"     />
+
+       <!-- Bomb C14 : variables available with key_c14b -->
+       <field id="qtrC14b"     long_name="Air-sea flux of Bomb C14"                unit="mol/m2/s"   />
+       <field id="qintC14b"    long_name="Cumulative air-sea flux of Bomb C14"     unit="mol/m2"     />
+       <field id="fdecay"      long_name="Radiactive decay of Bomb C14"            unit="mol/m3"  grid_ref="grid_T_3D"  />
+
+       <!-- IDTRA : variables available with key_idtra -->
+       <field id="qtrIDTRA"    long_name="Air-sea flux of Ideal Tracer"             unit="mol/m2/s"   />
+       <field id="qintIDTRA"   long_name="Cumulative air-sea flux of Ideal Tracer"  unit="mol/m2"     />
+       <field id="invIDTRA"    long_name="Vertical inventory"                       unit="mol/m2"     />
+
+       <!-- MEDUSA additional diagnostics on T grid  -->
+       <field id= "INVTN"      long_name="Column N inventory"                        unit="mmolN/m2"    />
+       <field id= "INVTSI"     long_name="Column Si inventory"                       unit="mmolSi/m2"   />
+       <field id= "INVTFE"     long_name="Column Fe inventory"                       unit="mmolFe/m2"   />
+       <field id= "PRN"        long_name="Non-diatom primary production"             unit="mmolN/m2/d"  />
+       <field id= "MPN"        long_name="Non-diatom non-grazing losses"             unit="mmolN/m2/d"  />
+       <field id= "PRD"        long_name="Diatom primary production"                 unit="mmolN/m2/d"  />
+       <field id= "MPD"        long_name="Diatom non-grazing losses"                 unit="mmolN/m2/d"  />
+       <field id= "DSED"       long_name="Gravitational sinking of Detritus"         unit="mmolN/m2/d"  />
+       <field id= "OPAL"       long_name="Diatom biogenic opal production"           unit="mmolSi/m2/d" />
+       <field id= "OPALDISS"   long_name="Diatom biogenic opal dissolution"          unit="mmolSi/m2/d" />
+       <field id= "GMIPn"      long_name="Microzoo grazing on non-diatoms"           unit="mmolN/m2/d"  />
+       <field id= "GMID"       long_name="Microzoo grazing on detritus"              unit="mmolN/m2/d"  />
+       <field id= "MZMI"       long_name="Microzoo non-grazing losses"               unit="mmolN/m2/d"  />
+       <field id= "GMEPN"      long_name="Mesozoo grazing on non-diatoms"            unit="mmolN/m2/d"  />
+       <field id= "GMEPD"      long_name="Mesozoo grazing on non-diatoms"            unit="mmolN/m2/d"  />
+       <field id= "GMEZMI"     long_name="Mesozoo grazing on microzoo"               unit="mmolN/m2/d"  />
+       <field id= "GMED"       long_name="Mesozoo grazing on detritus"               unit="mmolN/m2/d"  />
+       <field id= "MZME"       long_name="Mesozoo non-grazing losses"                unit="mmolN/m2/d"  />
+       <field id= "DEXP"       long_name="Detritus export"                           unit="mmolN/m2/d"  />
+       <field id= "DETN"       long_name="Slow detritus creation"                    unit="mmolN/m2/d"  />
+       <field id= "MDET"       long_name="Detritus non-grazing losses"               unit="MmolN/m2/d"  />
+       <field id= "AEOLIAN"    long_name="Aeolian deposition of iron"                unit="mmolFe/m2/d" />
+       <field id= "BENTHIC"    long_name="Benthic supply of iron"                    unit="mmolFe/m2/d" />
+       <field id= "SCAVENGE"   long_name="Scavenged iron"                            unit="mmolFe/m2/d" />
+       <field id= "PN_JLIM"    long_name="Non-diatom light limitation"               unit="-"           />
+       <field id= "PN_NLIM"    long_name="Non-diatom N limitation"                   unit="-"           />
+       <field id= "PN_FELIM"   long_name="Non-diatom Fe limitation"                  unit="-"           />
+       <field id= "PD_JLIM"    long_name="Diatom light limitation"                   unit="-"           />
+       <field id= "PD_NLIM"    long_name="Diatom N limitation"                       unit="-"           />
+       <field id= "PD_FELIM"   long_name="Diatom Fe limitation"                      unit="-"           />
+       <field id= "PD_SILIM"   long_name="Diatom Si limitation"                      unit="-"           />
+       <field id= "PDSILIM2"   long_name="Diatom Si uptake limitation"               unit="-"           />
+       <field id= "SDT__100"   long_name="Slow detrital flux at  100 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT__200"   long_name="Slow detrital flux at  200 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT__500"   long_name="Slow detrital flux at  500 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT_1000"   long_name="Slow detrital flux at 1000 m"              unit="mmolN/m2/d"  />
+       <field id= "TOTREG_N"   long_name="Full column regenerated N"                 unit="mmolN/m2/d"  />
+       <field id= "TOTRG_SI"   long_name="Full column regenerated Si"                unit="mmolSi/m2/d" />
+       <field id= "REG__100"   long_name="Regenerated N to  100 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG__200"   long_name="Regenerated N to  200 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG__500"   long_name="Regenerated N to  500 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG_1000"   long_name="Regenerated N to 1000 m"                   unit="mmolN/m2/d"  />
+       <field id= "FASTN"      long_name="Fast-sinking flux N"                       unit="mmolN/m2/d"  />
+       <field id= "FASTSI"     long_name="Fast-sinking flux Si"                      unit="mmolSi/m2/d" />
+       <field id= "FASTFE"     long_name="Fast-sinking flux Fe"                      unit="mmolFe/m2/d" />
+       <field id= "FASTC"      long_name="Fast-sinking flux C"                       unit="mmolC/m2/d"  />
+       <field id= "FASTCA"     long_name="Fast-sinking flux CaCO3"                   unit="mmolC/m2/d"  />
+       <field id= "FDT__100"   long_name="Fast detrital N flux at  100 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT__200"   long_name="Fast detrital N flux at  200 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT__500"   long_name="Fast detrital N flux at  500 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT_1000"   long_name="Fast detrital N flux at 1000 m"            unit="mmolN/m2/d"  />
+       <field id= "RG__100F"   long_name="Regenerated fast N to  100 m"              unit="mmolN/m2/d"  />
+       <field id= "RG__200F"   long_name="Regenerated fast N to  200 m"              unit="mmolN/m2/d"  />
+       <field id= "RG__500F"   long_name="Regenerated fast N to  500 m"              unit="mmolN/m2/d"  />
+       <field id= "RG_1000F"   long_name="Regenerated fast N to 1000 m"              unit="mmolN/m2/d"  />
+       <field id= "FDS__100"   long_name="Fast detrital Si flux at  100 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS__200"   long_name="Fast detrital Si flux at  200 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS__500"   long_name="Fast detrital Si flux at  500 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS_1000"   long_name="Fast detrital Si flux at 1000 m"           unit="mmolSi/m2/d" />
+       <field id= "RGS_100F"   long_name="Regenerated fast Si to  100 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS_200F"   long_name="Regenerated fast Si to  200 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS_500F"   long_name="Regenerated fast Si to  500 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS1000F"   long_name="Regenerated fast Si to 1000 m"             unit="mmolSi/m2/d" />
+       <field id= "REMINN"     long_name="Fast-sinking remin flux N"                 unit="mmolN/m2/d"  />
+       <field id= "REMINSI"    long_name="Fast-sinking remin flux Si"                unit="mmolSi/m2/d" />
+       <field id= "REMINFE"    long_name="Fast-sinking remin flux Fe"                unit="mmolFe/m2/d" />
+       <field id= "REMINC"     long_name="Fast-sinking remin flux C"                 unit="mmolC/m2/d"  />
+       <field id= "REMINCA"    long_name="Fast-sinking remin flux CaCO3"             unit="mmolC/m2/d"  />
+       <field id= "SEAFLRN"    long_name="Seafloor flux of N"                        unit="mmolN/m2/d"  />
+       <field id= "SEAFLRSI"   long_name="Seafloor flux of Si"                       unit="mmolSi/m2/d" />
+       <field id= "SEAFLRFE"   long_name="Seafloor flux of Fe"                       unit="mmolFe/m2/d" />
+       <field id= "SEAFLRC"    long_name="Seafloor flux of C"                        unit="mmolC/m2/d"  />
+       <field id= "SEAFLRCA"   long_name="Seafloor flux of CaCO3"                    unit="mmolC/m2/d"  />
+       <field id= "MED_QSR"    long_name="Sea surface radiation"                     unit="W/m2"        />
+       <field id= "MED_XPAR"   long_name="Top level radiation"                       unit="W/m2"        />
+       <field id= "INTFLX_N"   long_name="Integrated N  cycle fluxes"                unit="mmolN/m2/d"  />
+       <field id= "INTFLX_SI"  long_name="Integrated Si cycle fluxes"                unit="mmolSi/m2/d" />
+       <field id= "INTFLX_FE"  long_name="Integrated Fe cycle fluxes"                unit="mmolFe/m2/d" />
+       <field id= "INT_PN"     long_name="Vertically integrated Pn"                  unit="mmolN/m2"    />
+       <field id= "INT_PD"     long_name="Vertically integrated Pd"                  unit="mmolN/m2"    />
+       <field id= "ML_PRN"     long_name="Non-diatom mixed layer PP"                 unit="mmolN/m2/d"  />
+       <field id= "ML_PRD"     long_name="Diatom mixed layer PP"                     unit="mmolN/m2/d"  />
+       <field id= "OCAL_CCD"   long_name="Calcite CCD depth"                         unit="m"           />
+       <field id= "OCAL_LVL"   long_name="Calcite CCD level"                         unit="-"           />
+       <field id= "FE_0000"    long_name="Free iron at    0m"                        unit="-"           />
+       <field id= "FE_0100"    long_name="Free iron at  100m"                        unit="-"           />
+       <field id= "FE_0200"    long_name="Free iron at  200m"                        unit="-"           />
+       <field id= "FE_0500"    long_name="Free iron at  500m"                        unit="-"           />
+       <field id= "FE_1000"    long_name="Free iron at 1000m"                        unit="-"           />
+       <field id= "MED_XZE"    long_name="Euphotic depth"                            unit="m"           />
+       <field id= "WIND"       long_name="Surface scalar wind"                       unit="m/s"         />
+       <field id= "ATM_PCO2"   long_name="Atmospheric pCO2"                          unit="uatm"        />
+       <field id= "OCN_PH"     long_name="Surface ocean pH"                          unit="-"           />
+       <field id= "OCN_PCO2"   long_name="Surface ocean pCO2"                        unit="uatm"        />
+       <field id= "OCNH2CO3"   long_name="Surface ocean H2CO3 conc"                  unit="mmolC/m3"    />
+       <field id= "OCN_HCO3"   long_name="Surface ocean HCO3 conc"                   unit="mmolC/m3"    />
+       <field id= "OCN_CO3"    long_name="Surface ocean CO3 conc"                    unit="mmolC/m3"    />
+       <field id= "CO2FLUX"    long_name="Air-sea CO2 flux"                          unit="mmolC/m2/d"  />
+       <field id= "FGCO2"      long_name="Surface Downward CO2 Flux"                 unit="kg-CO2/m2/s" />
+       <field id= "OM_CAL"     long_name="Omega calcite"                             unit="-"           />
+       <field id= "OM_ARG"     long_name="Omega aragonite"                           unit="-"           />
+       <field id= "TCO2"       long_name="Total CO2"                                 unit="umol/kg"     />
+       <field id= "TALK"       long_name="Total alkalinity"                          unit="ueq/kg"      />
+       <field id= "KW660"      long_name="Piston velocity"                           unit="m/s"         />
+       <field id= "ATM_PP0"    long_name="Atmospheric pressure"                      unit="atm"         />
+       <field id= "O2FLUX"     long_name="Air-sea O2 flux"                           unit="mmolO2/m2/d" />
+       <field id= "O2SAT"      long_name="Surface ocean O2 saturation"               unit="mmolO2/m3"   />
+       <field id= "CAL_CCD"    long_name="Calcite CCD depth"                         unit="m"           />
+       <field id= "ARG_CCD"    long_name="Aragonite CCD depth"                       unit="m"           />
+       <field id= "SFR_OCAL"   long_name="Seafloor omega calcite"                    unit="-"           />
+       <field id= "SFR_OARG"   long_name="Seafloor omega aragonite"                  unit="-"           />
+       <field id= "N_PROD"     long_name="Nitrogen production"                       unit="mmolN/m2/d"  />
+       <field id= "N_CONS"     long_name="Nitrogen consumption"                      unit="mmolN/m2/d"  />
+       <field id= "C_PROD"     long_name="Carbon production"                         unit="mmolC/m2/d"  />
+       <field id= "C_CONS"     long_name="Carbon consumption"                        unit="mmolC/m2/d"  />
+       <field id= "O2_PROD"    long_name="Oxygen production"                         unit="mmolO2/m2/d" />
+       <field id= "O2_CONS"    long_name="Oxygen consumption"                        unit="mmolO2/m2/d" />
+       <field id= "O2_ANOX"    long_name="Unrealised oxygen consumption"             unit="mmolO2/m2/d" />
+       <field id= "RR_0100"    long_name="Rain ratio at  100m"                       unit="molC/molC"   />
+       <field id= "RR_0500"    long_name="Rain ratio at  500m"                       unit="molC/molC"   />
+       <field id= "RR_1000"    long_name="Rain ratio at 1000m"                       unit="molC/molC"   />
+       <field id= "IBEN_N"     long_name="Benthic input nitrogen"                    unit="mmolN/m2/d"  />
+       <field id= "IBEN_FE"    long_name="Benthic input iron"                        unit="mmolFe/m2/d" />
+       <field id= "IBEN_C"     long_name="Benthic input carbon"                      unit="mmolC/m2/d"  />
+       <field id= "IBEN_SI"    long_name="Benthic input silicon"                     unit="mmolSi/m2/d" />
+       <field id= "IBEN_CA"    long_name="Benthic input CaCO3"                       unit="mmolC/m2/d"  />
+       <field id= "OBEN_N"     long_name="Benthic output nitrogen"                   unit="mmolN/m2/d"  />
+       <field id= "OBEN_FE"    long_name="Benthic output iron"                       unit="mmolFe/m2/d" />
+       <field id= "OBEN_C"     long_name="Benthic output carbon"                     unit="mmolC/m2/d"  />
+       <field id= "OBEN_SI"    long_name="Benthic output silicon"                    unit="mmolSi/m2/d" />
+       <field id= "OBEN_CA"    long_name="Benthic output CaCO3"                      unit="mmolC/m2/d"  />
+       <field id= "BEN_N"      long_name="Benthic nitrogen"                          unit="mmolN/m2"    />
+       <field id= "BEN_FE"     long_name="Benthic iron"                              unit="mmolFe/m2"   />
+       <field id= "BEN_C"      long_name="Benthic carbon"                            unit="mmolC/m2"    />
+       <field id= "BEN_SI"     long_name="Benthic silicon"                           unit="mmolSi/m2"   />
+       <field id= "BEN_CA"     long_name="Benthic CaCO3"                             unit="mmolC/m2"    />
+       <field id= "RUNOFF"     long_name="River runoff"                              unit="m/d"         />
+       <field id= "RIV_N"      long_name="Riverine input nitrogen"                   unit="mmolN/m2/d"  />
+       <field id= "RIV_SI"     long_name="Riverine input silicon"                    unit="mmolSi/m2/d" />
+       <field id= "RIV_C"      long_name="Riverine input carbon"                     unit="mmolSi/m2/d" />
+       <field id= "RIV_ALK"    long_name="Riverine input alkalinity"                 unit="meq/m2/d"    />
+       <field id= "DETC"       long_name="Slow detritus C creation"                  unit="mmolC/m2/d"  />
+       <field id= "SDC__100"   long_name="Slow detrital C flux at  100 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC__200"   long_name="Slow detrital C flux at  200 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC__500"   long_name="Slow detrital C flux at  500 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC_1000"   long_name="Slow detrital C flux at 1000 m"            unit="mmolC/m2/d"  />
+       <field id= "INVTC"      long_name="Column C inventory"                        unit="mmolC/m2"    />
+       <field id= "INVTALK"    long_name="Column alkalinity inventory"               unit="meq/m2"      />
+       <field id= "INVTO2"     long_name="Column O2 inventory"                       unit="mmolO2/m2"   />
+       <field id= "LYSO_CA"    long_name="Incorrect benthic output CaCO3"            unit="mmolC/m2/d"  />
+       <field id= "COM_RESP"   long_name="Community respiration"                     unit="mmolC/m2/d"  />
+       <field id= "PN_LLOSS"   long_name="Non-diatom linear losses"                  unit="mmolN/m2/d"  />
+       <field id= "PD_LLOSS"   long_name="Diatom linear losses"                      unit="mmolN/m2/d"  />
+       <field id= "ZI_LLOSS"   long_name="Microzooplankton linear losses"            unit="mmolN/m2/d"  />
+       <field id= "ZE_LLOSS"   long_name="Mesozooplankton linear losses"             unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_N"   long_name="Microzoo messy feeding loss to N"          unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_D"   long_name="Microzoo messy feeding loss to D"          unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_C"   long_name="Microzoo messy feeding loss to C"          unit="mmolC/m2/d"  />
+       <field id= "ZI_MESDC"   long_name="Microzoo messy feeding loss to Dc"         unit="mmolC/m2/d"  />
+       <field id= "ZI_EXCR"    long_name="Microzoo excretion"                        unit="mmolN/m2/d"  />
+       <field id= "ZI_RESP"    long_name="Microzoo respiration"                      unit="mmolC/m2/d"  />
+       <field id= "ZI_GROW"    long_name="Microzoo growth"                           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_N"   long_name="Mesozoo messy feeding loss to N"           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_D"   long_name="Mesozoo messy feeding loss to D"           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_C"   long_name="Mesozoo messy feeding loss to C"           unit="mmolC/m2/d"  />
+       <field id= "ZE_MESDC"   long_name="Mesozoo messy feeding loss to Dc"          unit="mmolC/m2/d"  />
+       <field id= "ZE_EXCR"    long_name="Mesozoo excretion"                         unit="mmolN/m2/d"  />
+       <field id= "ZE_RESP"    long_name="Mesozoo respiration"                       unit="mmolC/m2/d"  />
+       <field id= "ZE_GROW"    long_name="Mesozoo growth"                            unit="mmolN/m2/d"  />
+       <field id= "MDETC"      long_name="Detritus non-grazing losses, carbon"       unit="mmolC/m2/d"  />
+       <field id= "GMIDC"      long_name="Microzoo grazing on detritus, carbon"      unit="mmolC/m2/d"  />
+       <field id= "GMEDC"      long_name="Mesozoo  grazing on detritus, carbon"      unit="mmolC/m2/d"  />
+       <field id= "INT_ZMI"    long_name="Vertically integrated Zmi"                 unit="mmolN/m2"    />
+       <field id= "INT_ZME"    long_name="Vertically integrated Zme"                 unit="mmolN/m2"    />
+       <field id= "INT_DET"    long_name="Vertically integrated Det"                 unit="mmolN/m2"    />
+       <field id= "INT_DTC"    long_name="Vertically integrated Dtc"                 unit="mmolC/m2"    />
+       <field id= "DMS_SURF"   long_name="DMS Surface Concentration"                 unit="nmol/L"      />
+       <field id= "DMS_ANDR"   long_name="DMS Surface Concentration, Anderson"       unit="nmol/L"      />
+       <field id= "DMS_SIMO"   long_name="DMS Surface Concentration, SimoDach"       unit="nmol/L"      />
+       <field id= "DMS_ARAN"   long_name="DMS Surface Concentration, AranamiT"       unit="nmol/L"      />
+       <field id= "DMS_HALL"   long_name="DMS Surface Concentration, Halloran"       unit="nmol/L"      />
+       <field id= "ATM_XCO2"   long_name="Atmospheric xCO2"                          unit="ppm"         />
+       <field id= "OCN_FCO2"   long_name="Surface ocean fCO2"                        unit="uatm"        />
+       <field id= "ATM_FCO2"   long_name="Atmospheric fCO2"                          unit="uatm"        />
+       <field id= "OCN_RHOSW"  long_name="MOCSY rhoSW"                               unit="kg/m3"       />
+       <field id= "OCN_SCHCO2" long_name="MOCSY Schmidt CO2"                         unit="-"           />
+       <field id= "OCN_KWCO2"  long_name="MOCSY kw CO2"                              unit="m/s"         />
+       <field id= "OCN_K0"     long_name="MOCSY k0"                                  unit="(mol/kg)/atm" />
+       <field id= "CO2STARAIR" long_name="MOCSY CO2star air"                         unit="mmol/m3"     />
+       <field id= "OCN_DPCO2"  long_name="MOCSY delta pCO2"                          unit="uatm"        />
+       
+
+       <!-- AXY (08/11/16): add new 2D CMIP6 diagnostics -->
+       <field id= "epC100"     long_name="Downward Flux of Particle Organic Carbon"  unit="mmolC/m2/d"  />
+       <field id= "epCALC100"  long_name="Downward Flux of Calcite"                  unit="mmolC/m2/d"  />
+       <field id= "epN100"     long_name="Downward Flux of Particulate Nitrogen"     unit="mmolN/m2/d"  />
+       <field id= "epSI100"    long_name="Downward Flux of Particulate Silica"       unit="mmolSi/m2/d" />
+       <field id= "INTDISSIC"  long_name="Dissolved Inorganic Carbon Content"        unit="mmolC/m2"    />
+       <field id= "INTDISSIN"  long_name="Dissolved Inorganic Nitrogen Content"      unit="mmolN/m2"    />
+       <field id= "INTDISSISI" long_name="Dissolved Inorganic Silicon Content"       unit="mmolSi/m2"   />
+       <field id= "INTTALK"    long_name="Dissolved Alkalinity Content"              unit="meq/m2"      />
+       <field id= "O2min"      long_name="Oxygen Minimum Concentration"              unit="mmolO2/m3"   />
+       <field id= "ZO2min"     long_name="Depth of Oxygen Minimum Concentration"     unit="m"           />
+       <field id= "FBDDTALK"   long_name="Int. change of Alkalinity due to Biology"  unit="meq/m2/d"    />
+       <field id= "FBDDTDIC"   long_name="Int. change of DI Carbon due to Biology"   unit="mmolC/m2/d"  />
+       <field id= "FBDDTDIFE"  long_name="Int. change of DI Iron due to Biology"     unit="mmolFe/m2/d" />
+       <field id= "FBDDTDIN"   long_name="Int. change of DI Nitrogen due to Biology" unit="mmolN/m2/d"  />
+       <field id= "FBDDTDISI"  long_name="Int. change of DI Silicon due to Biology"  unit="mmolSi/m2/d" />
+       
+
+       <!-- MEDUSA 3D diagnostics -->
+       <field id= "TPP3"       long_name="Total primary production 3D"               unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "DETFLUX3"   long_name="Total detrital flux 3D"                    unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "REMIN3N"    long_name="Total remin flux N 3D"                     unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "PH3"        long_name="Ocean pH 3D"                               unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "OM_CAL3"    long_name="Omega calcite 3D"                          unit="-"             grid_ref="grid_T_3D"  />
+
+       <!-- AXY (08/11/16): add new 3D CMIP6 diagnostics -->
+       <field id= "TPPD3"      long_name="Diatom primary production 3D"              unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTALK3"   long_name="Change of Alkalinity due to Biology"       unit="meq/m3/d"      grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIC3"   long_name="Change of DI Carbon due to Biology"        unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIFE3"  long_name="Change of DI Iron due to Biology"          unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIN3"   long_name="Change of DI Nitrogen due to Biology"      unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTDISI3"  long_name="Change of DI Silicon due to Biology"       unit="mmolSi/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "FD_NIT3"    long_name="Fast sinking detrital nitrogen"            unit="mmolN/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "FD_SIL3"    long_name="Fast sinking detrital silicon"             unit="mmolSi/m2/d"   grid_ref="grid_T_3D"  />
+       <field id= "FD_CAR3"    long_name="Fast sinking detrital carbon"              unit="mmolC/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "FD_CAL3"    long_name="Fast sinking detrital calcium carbonate"   unit="mmolC/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "CO33"       long_name="Carbonate ion concentration"               unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "CO3SATARAG3" long_name="Carbonate aragonite saturation conc"      unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "CO3SATCALC3" long_name="Carbonate calcite saturation conc"        unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "DCALC3"     long_name="Calcite dissolution"                       unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "EXPC3"      long_name="Downward Flux of Particulate Org Carbon"   unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "EXPN3"      long_name="Downward Flux of Particulate Org Nitrogen" unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "FEDISS3"    long_name="Particle Source of Dissolved Iron"         unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "FESCAV3"    long_name="Nonbiogenic Iron Scavenging"               unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "MIGRAZP3"   long_name="Microzooplankton grazing on phytoplankton" unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MIGRAZD3"   long_name="Microzooplankton grazing on detritus"      unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZP3"   long_name="Mesozooplankton grazing on phytoplankton"  unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZD3"   long_name="Mesozooplankton grazing on detritus"       unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZZ3"   long_name="Mesozooplankton grazing on microzoop"      unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "O2SAT3"     long_name="Dissolved Oxygen Saturation Concentration" unit="mmolO2/m3"     grid_ref="grid_T_3D"  />
+       <field id= "PBSI3"      long_name="Biogenic Silica Production"                unit="mmolSi/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "PCAL3"      long_name="Biogenic Calcite Production"               unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "REMOC3"     long_name="Remineralization of Organic Carbon"        unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "PNLIMJ3"    long_name="Irradiance limitation of non-diatoms"      unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PNLIMN3"    long_name="Nitrogen limitation of non-diatoms"        unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PNLIMFE3"   long_name="Iron limitation of non-diatoms"            unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMJ3"    long_name="Irradiance limitation of diatoms"          unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMN3"    long_name="Nitrogen limitation of diatoms"            unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMFE3"   long_name="Iron limitation of diatoms"                unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMSI3"   long_name="Silicon limitation of diatoms"             unit="-"             grid_ref="grid_T_3D"  />
+
+     </field_group>
+
+     <field_group id="PISCES_scalar"  domain_ref="1point" >
+       <field id="pno3tot"         long_name="global mean nitrate concentration"                  unit="mol/m3"   />
+       <field id="ppo4tot"         long_name="global mean phosphorus concentration"               unit="mol/m3"   />
+       <field id="psiltot"         long_name="global mean silicate concentration"                 unit="mol/m3"   />
+       <field id="palktot"         long_name="global mean alkalinity concentration"               unit="mol/m3"   />
+       <field id="pfertot"         long_name="global mean iron concentration"                     unit="mol/m3"   />
+       <field id="tcflx"           long_name="total Flux of Carbon out of the ocean"              unit="mol/s"   />
+       <field id="tcflxcum"        long_name="cumulative total Flux of Carbon out of the ocean"   unit="mol/s"   />
+       <field id="tcexp"           long_name="total Carbon export at 100m"                        unit="mol/s"   />
+       <field id="tintpp"          long_name="global total integrated primary production"         unit="mol/s"   />
+       <field id="tnfix"           long_name="global total nitrogen fixation"                     unit="mol/s"   />
+       <field id="tdenit"          long_name="Total denitrification"                              unit="mol/s"   />
+     </field_group>
+
+    <!-- 
+============================================================================================================
+                                        Definitions for iodef_demo.xml
+============================================================================================================
+    -->
+
+    <field_group id="groupMEDUSA" >
+      <field field_ref="CHN"   name="CHN"   />
+      <field field_ref="CHD"   name="CHD"   />
+      <field field_ref="PHN"   name="PHN"   />
+      <field field_ref="PHD"   name="PHD"   />
+      <field field_ref="ZMI"   name="ZMI"   />
+      <field field_ref="ZME"   name="ZME"   />
+      <field field_ref="DIN"   name="DIN"   />
+      <field field_ref="SIL"   name="SIL"   />
+      <field field_ref="FER"   name="FER"   />
+      <field field_ref="DET"   name="DET"   />
+      <field field_ref="PDS"   name="PDS"   />
+      <field field_ref="DTC"   name="DTC"   />
+      <field field_ref="DiC"   name="DIC"   />
+      <field field_ref="ALK"   name="ALK"   />
+      <field field_ref="OXY"   name="OXY"   />
+      </field_group>
+
+    <field_group id="groupIDTRA" >
+      <field field_ref="IDTRA" name="IDTRA" />
+    </field_group>
+
+    <field_group id="groupIDTRA_dia" >
+      <field field_ref="qtrIDTRA"    name="qtrIDTRA"  />
+      <field field_ref="qintIDTRA"   name="qintIDTRA" />
+      <field field_ref="invIDTRA"    name="invIDTRA"  />
+    </field_group>
+
+    <field_group id="groupCFC" >
+      <field field_ref="CFC11" name="CFC11" />
+    </field_group>
+
+    <field_group id="groupCFC_dia" >
+      <field field_ref="qtrCFC11"    name="qtrCFC11"   />
+      <field field_ref="qintCFC11"   name="qintCFC11"  />
+    </field_group>
+
+    <field_group id="groupAGE" >
+      <field field_ref="Age" name="Age" />
+    </field_group>
+
+    <field_group id="groupMEDUSA_dia" >
+      <field field_ref= "INVTN"      name="INVTN"      />
+      <field field_ref= "INVTSI"     name="INVTSI"     />
+      <field field_ref= "INVTFE"     name="INVTFE"     />
+      <field field_ref= "PRN"        name="PRN"        />
+      <field field_ref= "MPN"        name="MPN"        />
+      <field field_ref= "PRD"        name="PRD"        />
+      <field field_ref= "MPD"        name="MPD"        />
+      <field field_ref= "OPAL"       name="OPAL"       />
+      <field field_ref= "OPALDISS"   name="OPALDISS"   />
+      <field field_ref= "GMIPn"      name="GMIPn"      />
+      <field field_ref= "GMID"       name="GMID"       />
+      <field field_ref= "MZMI"       name="MZMI"       />
+      <field field_ref= "GMEPN"      name="GMEPN"      />
+      <field field_ref= "GMEPD"      name="GMEPD"      />
+      <field field_ref= "GMEZMI"     name="GMEZMI"     />
+      <field field_ref= "GMED"       name="GMED"       />
+      <field field_ref= "MZME"       name="MZME"       />
+      <field field_ref= "DETN"       name="DETN"       />
+      <field field_ref= "MDET"       name="MDET"       />
+      <field field_ref= "AEOLIAN"    name="AEOLIAN"    />
+      <field field_ref= "BENTHIC"    name="BENTHIC"    />
+      <field field_ref= "SCAVENGE"   name="SCAVENGE"   />
+      <field field_ref= "PN_JLIM"    name="PN_JLIM"    />
+      <field field_ref= "PN_NLIM"    name="PN_NLIM"    />
+      <field field_ref= "PN_FELIM"   name="PN_FELIM"   />
+      <field field_ref= "PD_JLIM"    name="PD_JLIM"    />
+      <field field_ref= "PD_NLIM"    name="PD_NLIM"    />
+      <field field_ref= "PD_FELIM"   name="PD_FELIM"   />
+      <field field_ref= "PD_SILIM"   name="PD_SILIM"   />
+      <field field_ref= "PDSILIM2"   name="PDSILIM2"   />
+      <field field_ref= "SDT__100"   name="SDT__100"   />
+      <field field_ref= "SDT__200"   name="SDT__200"   />
+      <field field_ref= "SDT__500"   name="SDT__500"   />
+      <field field_ref= "SDT_1000"   name="SDT_1000"   />
+      <field field_ref= "TOTREG_N"   name="TOTREG_N"   />
+      <field field_ref= "TOTRG_SI"   name="TOTRG_SI"   />
+      <field field_ref= "REG__100"   name="REG__100"   />
+      <field field_ref= "REG__200"   name="REG__200"   />
+      <field field_ref= "REG__500"   name="REG__500"   />
+      <field field_ref= "REG_1000"   name="REG_1000"   />
+      <field field_ref= "FASTN"      name="FASTN"      />
+      <field field_ref= "FASTSI"     name="FASTSI"     />
+      <field field_ref= "FASTFE"     name="FASTFE"     />
+      <field field_ref= "FASTC"      name="FASTC"      />
+      <field field_ref= "FASTCA"     name="FASTCA"     />
+      <field field_ref= "FDT__100"   name="FDT__100"   />
+      <field field_ref= "FDT__200"   name="FDT__200"   />
+      <field field_ref= "FDT__500"   name="FDT__500"   />
+      <field field_ref= "FDT_1000"   name="FDT_1000"   /> 
+      <field field_ref= "RG__100F"   name="RG__100F"   />
+      <field field_ref= "RG__200F"   name="RG__200F"   />
+      <field field_ref= "RG__500F"   name="RG__500F"   />
+      <field field_ref= "RG_1000F"   name="RG_1000F"   />
+      <field field_ref= "FDS__100"   name="FDS__100"   />
+      <field field_ref= "FDS__200"   name="FDS__200"   />
+      <field field_ref= "FDS__500"   name="FDS__500"   />
+      <field field_ref= "FDS_1000"   name="FDS_1000"   />
+      <field field_ref= "RGS_100F"   name="RGS_100F"   />
+      <field field_ref= "RGS_200F"   name="RGS_200F"   />
+      <field field_ref= "RGS_500F"   name="RGS_500F"   />
+      <field field_ref= "RGS1000F"   name="RGS1000F"   />
+      <field field_ref= "REMINN"     name="REMINN"     />
+      <field field_ref= "REMINSI"    name="REMINSI"    />
+      <field field_ref= "REMINFE"    name="REMINFE"    />
+      <field field_ref= "SEAFLRN"    name="SEAFLRN"    /> 
+      <field field_ref= "SEAFLRSI"   name="SEAFLRSI"   />
+      <field field_ref= "SEAFLRFE"   name="SEAFLRFE"   />
+      <field field_ref= "SEAFLRC"    name="SEAFLRC"    />
+      <field field_ref= "SEAFLRCA"   name="SEAFLRCA"   />
+      <field field_ref= "MED_QSR"    name="MED_QSR"    />
+      <field field_ref= "MED_XPAR"   name="MED_XPAR"   />
+      <field field_ref= "INTFLX_N"   name="INTFLX_N"   />
+      <field field_ref= "INTFLX_SI"  name="INTFLX_SI"  />
+      <field field_ref= "INTFLX_FE"  name="INTFLX_FE"  />
+      <field field_ref= "INT_PN"     name="INT_PN"     />
+      <field field_ref= "INT_PD"     name="INT_PD"     />
+      <field field_ref= "ML_PRN"     name="ML_PRN"     />
+      <field field_ref= "ML_PRD"     name="ML_PRD"     />
+      <field field_ref= "OCAL_CCD"   name="OCAL_CCD"   />
+      <field field_ref= "OCAL_LVL"   name="OCAL_LVL"   />
+      <field field_ref= "FE_0000"    name="FE_0000"    />
+      <field field_ref= "FE_0100"    name="FE_0100"    />
+      <field field_ref= "FE_0200"    name="FE_0200"    /> 
+      <field field_ref= "FE_0500"    name="FE_0500"    />
+      <field field_ref= "FE_1000"    name="FE_1000"    />
+      <field field_ref= "MED_XZE"    name="MED_XZE"    />
+      <field field_ref= "WIND"       name="WIND"       />
+      <field field_ref= "ATM_PCO2"   name="ATM_PCO2"   />
+      <field field_ref= "OCN_PH"     name="OCN_PH"     />
+      <field field_ref= "OCN_PCO2"   name="OCN_PCO2"   />
+      <field field_ref= "OCNH2CO3"   name="OCNH2CO3"   />
+      <field field_ref= "OCN_HCO3"   name="OCN_HCO3"   />
+      <field field_ref= "OCN_CO3"    name="OCN_CO3"    />
+      <field field_ref= "CO2FLUX"    name="CO2FLUX"    />
+      <field field_ref= "FGCO2"      name="FGCO2"      />
+      <field field_ref= "OM_CAL"     name="OM_CAL"     />
+      <field field_ref= "OM_ARG"     name="OM_ARG"     />
+      <field field_ref= "TCO2"       name="TCO2"       />
+      <field field_ref= "TALK"       name="TALK"       />
+      <field field_ref= "KW660"      name="KW660"      />
+      <field field_ref= "ATM_PP0"    name="ATM_PP0"    />
+      <field field_ref= "O2FLUX"     name="O2FLUX"     />
+      <field field_ref= "O2SAT"      name="O2SAT"      />
+      <field field_ref= "CAL_CCD"    name="CAL_CCD"    />
+      <field field_ref= "ARG_CCD"    name="ARG_CCD"    />
+      <field field_ref= "SFR_OCAL"   name="SFR_OCAL"   />
+      <field field_ref= "SFR_OARG"   name="SFR_OARG"   />
+      <field field_ref= "N_PROD"     name="N_PROD"     />
+      <field field_ref= "N_CONS"     name="N_CONS"     />
+      <field field_ref= "C_PROD"     name="C_PROD"     />
+      <field field_ref= "C_CONS"     name="C_CONS"     />
+      <field field_ref= "O2_PROD"    name="O2_PROD"    />
+      <field field_ref= "O2_CONS"    name="O2_CONS"    />
+      <field field_ref= "O2_ANOX"    name="O2_ANOX"    />
+      <field field_ref= "RR_0100"    name="RR_0100"    />
+      <field field_ref= "RR_0500"    name="RR_0500"    />
+      <field field_ref= "RR_1000"    name="RR_1000"    />
+      <field field_ref= "IBEN_N"     name="IBEN_N"     />
+      <field field_ref= "IBEN_FE"    name="IBEN_FE"    />
+      <field field_ref= "IBEN_C"     name="IBEN_C"     />
+      <field field_ref= "IBEN_SI"    name="IBEN_SI"    />
+      <field field_ref= "IBEN_CA"    name="IBEN_CA"    />
+      <field field_ref= "OBEN_N"     name="OBEN_N"     />
+      <field field_ref= "OBEN_FE"    name="OBEN_FE"    />
+      <field field_ref= "OBEN_C"     name="OBEN_C"     />
+      <field field_ref= "OBEN_SI"    name="OBEN_SI"    />
+      <field field_ref= "OBEN_CA"    name="OBEN_CA"    />
+      <field field_ref= "BEN_N"      name="BEN_N"      />
+      <field field_ref= "BEN_FE"     name="BEN_FE"     />
+      <field field_ref= "BEN_C"      name="BEN_C"      />
+      <field field_ref= "BEN_SI"     name="BEN_SI"     />
+      <field field_ref= "BEN_CA"     name="BEN_CA"     />
+      <field field_ref= "DETC"       name="DETC"       />
+      <field field_ref= "SDC__100"   name="SDC__100"   />
+      <field field_ref= "SDC__200"   name="SDC__200"   />
+      <field field_ref= "SDC__500"   name="SDC__500"   />
+      <field field_ref= "SDC_1000"   name="SDC_1000"   />
+      <field field_ref= "INVTC"      name="INVTC"      />
+      <field field_ref= "INVTALK"    name="INVTALK"    />
+      <field field_ref= "INVTO2"     name="INVTO2"     />
+      <field field_ref= "LYSO_CA"    name="LYSO_CA"    />
+      <field field_ref= "COM_RESP"   name="COM_RESP"   />
+      <field field_ref= "PN_LLOSS"   name="PN_LLOSS"   />
+      <field field_ref= "PD_LLOSS"   name="PD_LLOSS"   />
+      <field field_ref= "ZI_LLOSS"   name="ZI_LLOSS"   />
+      <field field_ref= "ZE_LLOSS"   name="ZE_LLOSS"   />
+      <field field_ref= "ZI_MES_N"   name="ZI_MES_N"   />
+      <field field_ref= "ZI_MES_D"   name="ZI_MES_D"   />
+      <field field_ref= "ZI_MES_C"   name="ZI_MES_C"   />
+      <field field_ref= "ZI_MESDC"   name="ZI_MESDC"   />
+      <field field_ref= "ZI_EXCR"    name="ZI_EXCR"    />
+      <field field_ref= "ZI_RESP"    name="ZI_RESP"    />
+      <field field_ref= "ZI_GROW"    name="ZI_GROW"    />
+      <field field_ref= "ZE_MES_N"   name="ZE_MES_N"   />
+      <field field_ref= "ZE_MES_D"   name="ZE_MES_D"   />
+      <field field_ref= "ZE_MES_C"   name="ZE_MES_C"   />
+      <field field_ref= "ZE_MESDC"   name="ZE_MESDC"   />
+      <field field_ref= "ZE_EXCR"    name="ZE_EXCR"    />
+      <field field_ref= "ZE_RESP"    name="ZE_RESP"    />
+      <field field_ref= "ZE_GROW"    name="ZE_GROW"    />
+      <field field_ref= "MDETC"      name="MDETC"      />
+      <field field_ref= "GMIDC"      name="GMIDC"      />
+      <field field_ref= "GMEDC"      name="GMEDC"      />
+      <field field_ref= "INT_ZMI"    name="INT_ZMI"    />
+      <field field_ref= "INT_ZME"    name="INT_ZME"    />
+      <field field_ref= "INT_DET"    name="INT_DET"    />
+      <field field_ref= "INT_DTC"    name="INT_DTC"    />
+      <field field_ref= "ATM_XCO2"   name="ATM_XCO2"   />
+      <field field_ref= "OCN_FCO2"   name="OCN_FCO2"   />
+      <field field_ref= "ATM_FCO2"   name="ATM_FCO2"   />
+      <field field_ref= "OCN_RHOSW"  name="OCN_RHOSW"  />
+      <field field_ref= "OCN_SCHCO2" name="OCN_SCHCO2" />
+      <field field_ref= "OCN_KWCO2"  name="OCN_KWCO2"  />
+      <field field_ref= "OCN_K0"     name="OCN_K0"     />
+      <field field_ref= "CO2STARAIR" name="CO2STARAIR" />
+      <field field_ref= "OCN_DPCO2"  name="OCN_DPCO2"  />
+    </field_group>
+
+    <field_group id="groupMEDUSA_3dd" >
+      <field field_ref= "TPP3"       name="TPP3"       />
+      <field field_ref= "DETFLUX3"   name="DETFLUX3"   />
+      <field field_ref= "REMIN3N"    name="REMIN3N"    />
+      <field field_ref= "PH3"        name="PH3"        />
+      <field field_ref= "OM_CAL3"    name="OM_CAL3"    /> 
+    </field_group>
+
+    <field_group id="groupMEDUSA_dms" >
+      <field field_ref= "DMS_SURF"   name="DMS_SURF"   />
+      <field field_ref= "DMS_ANDR"   name="DMS_ANDR"   />
+      <field field_ref= "DMS_SIMO"   name="DMS_SIMO"   />
+      <field field_ref= "DMS_ARAN"   name="DMS_ARAN"   />
+      <field field_ref= "DMS_HALL"   name="DMS_HALL"   />
+    </field_group>
+
+    <field_group id="groupMEDUSA_riv" >
+      <field field_ref= "RUNOFF"     name="RUNOFF"     />
+      <field field_ref= "RIV_N"      name="RIV_N"      />
+      <field field_ref= "RIV_SI"     name="RIV_SI"     />
+      <field field_ref= "RIV_C"      name="RIV_C"      />
+      <field field_ref= "RIV_ALK"    name="RIV_ALK"    />
+    </field_group>
+
+    <field_group id="groupMEDUSA_cmip6" >
+      <field field_ref= "epC100"     name="epC100"     />
+      <field field_ref= "epCALC100"  name="epCALC100"  />
+      <field field_ref= "epN100"     name="epN100"     />
+      <field field_ref= "epSI100"    name="epSI100"    />
+      <field field_ref= "INTDISSIC"  name="INTDISSIC"  />
+      <field field_ref= "INTDISSIN"  name="INTDISSIN"  />
+      <field field_ref= "INTDISSISI" name="INTDISSISI" />
+      <field field_ref= "INTTALK"    name="INTTALK"    />
+      <field field_ref= "O2min"      name="O2min"      />
+      <field field_ref= "ZO2min"     name="ZO2min"     />
+      <field field_ref= "FBDDTALK"   name="FBDDTALK"   />
+      <field field_ref= "FBDDTDIC"   name="FBDDTDIC"   />
+      <field field_ref= "FBDDTDIFE"  name="FBDDTDIFE"  />
+      <field field_ref= "FBDDTDIN"   name="FBDDTDIN"   />
+      <field field_ref= "FBDDTDISI"  name="FBDDTDISI"  />
+      <field field_ref= "TPPD3"      name="TPPD3"      />
+      <field field_ref= "BDDTALK3"   name="BDDTALK3"   />
+      <field field_ref= "BDDTDIC3"   name="BDDTDIC3"   />
+      <field field_ref= "BDDTDIFE3"  name="BDDTDIFE3"  />
+      <field field_ref= "BDDTDIN3"   name="BDDTDIN3"   />
+      <field field_ref= "BDDTDISI3"  name="BDDTDISI3"  />
+      <field field_ref= "FD_NIT3"    name="FD_NIT3"    />
+      <field field_ref= "FD_SIL3"    name="FD_SIL3"    />
+      <field field_ref= "FD_CAR3"    name="FD_CAR3"    />
+      <field field_ref= "FD_CAL3"    name="FD_CAL3"    />
+      <field field_ref= "CO33"       name="CO33"       />
+      <field field_ref= "CO3SATARAG3" name="CO3SATARAG3" />
+      <field field_ref= "CO3SATCALC3" name="CO3SATCALC3" />
+      <field field_ref= "DCALC3"     name="DCALC3"     />
+      <field field_ref= "EXPC3"      name="EXPC3"      />
+      <field field_ref= "EXPN3"      name="EXPN3"      />
+      <field field_ref= "FEDISS3"    name="FEDISS3"    />
+      <field field_ref= "FESCAV3"    name="FESCAV3"    />
+      <field field_ref= "MIGRAZP3"   name="MIGRAZP3"   />
+      <field field_ref= "MIGRAZD3"   name="MIGRAZD3"   />
+      <field field_ref= "MEGRAZP3"   name="MEGRAZP3"   />
+      <field field_ref= "MEGRAZD3"   name="MEGRAZD3"   />
+      <field field_ref= "MEGRAZZ3"   name="MEGRAZZ3"   />
+      <field field_ref= "O2SAT3"     name="O2SAT3"     />
+      <field field_ref= "PBSI3"      name="PBSI3"      />
+      <field field_ref= "PCAL3"      name="PCAL3"      />
+      <field field_ref= "REMOC3"     name="REMOC3"     />
+      <field field_ref= "PNLIMJ3"    name="PNLIMJ3"    />
+      <field field_ref= "PNLIMN3"    name="PNLIMN3"    />
+      <field field_ref= "PNLIMFE3"   name="PNLIMFE3"   />
+      <field field_ref= "PDLIMJ3"    name="PDLIMJ3"    />
+      <field field_ref= "PDLIMN3"    name="PDLIMN3"    />
+      <field field_ref= "PDLIMFE3"   name="PDLIMFE3"   />
+      <field field_ref= "PDLIMSI3"   name="PDLIMSI3"   />
+    </field_group>
+
+</field_definition>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/field_def_bgc_CMIP6.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/field_def_bgc_CMIP6.xml	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/field_def_bgc_CMIP6.xml	(revision 9987)
@@ -0,0 +1,778 @@
+<!--
+<?xml version="1.0"?>
+       -->
+ 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+   <field_definition level="1" prec="8" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                     Biogeochemistry model variables
+============================================================================================================
+    -->
+
+      <!-- ptrc on T grid -->
+
+     <field_group id="ptrc_T" grid_ref="grid_T_3D">
+       <field id="DIC"          long_name="Dissolved inorganic Concentration"        unit="mmol/m3" />
+       <field id="DIC_E3T"      long_name="DIC * E3T"                                unit="mmol/m2" > DIC * e3t </field >
+       <field id="Alkalini"     long_name="Total Alkalinity Concentration"           unit="mmol/m3" />
+       <field id="Alkalini_E3T" long_name="Alkalini * E3T"                           unit="mmol/m2"  > Alkalini * e3t </field >
+       <field id="O2"           long_name="Oxygen Concentration"                     unit="mmol/m3" />
+       <field id="O2_E3T"       long_name="O2 * E3T"                                 unit="mmol/m2"  > O2 * e3t </field >
+       <field id="CaCO3"        long_name="Calcite Concentration"                    unit="mmol/m3" />
+       <field id="CaCO3_E3T"    long_name="CaCO3 * E3T"                              unit="mmol/m2"  > CaCO3 * e3t </field >
+       <field id="PO4"          long_name="Phosphate Concentration"                  unit="mmol/m3" />
+       <field id="PO4_E3T"      long_name="PO4 * E3T"                                unit="mmol/m2"  > PO4 * e3t </field >
+       <field id="POC"          long_name="Small organic carbon Concentration"       unit="mmol/m3" />
+       <field id="POC_E3T"      long_name="POC * E3T"                                unit="mmol/m2"  > POC * e3t </field >
+       <field id="Si"           long_name="Silicate Concentration"                   unit="mmol/m3" />
+       <field id="Si_E3T"       long_name="Si * E3T"                                 unit="mmol/m2"  > Si * e3t </field >
+       <field id="PHY"          long_name="(Nano)Phytoplankton Concentration"        unit="mmol/m3" />
+       <field id="PHY_E3T"      long_name="PHY * E3T"                                unit="mmol/m2"  > PHY * e3t </field >
+       <field id="ZOO"          long_name="(Micro)Zooplankton Concentration"         unit="mmol/m3" />
+       <field id="ZOO_E3T"      long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO * e3t </field >
+       <field id="DOC"          long_name="Dissolved organic Concentration"          unit="mmol/m3" />
+       <field id="DOC_E3T"      long_name="DOC * E3T"                                unit="mmol/m2"  > DOC * e3t </field >
+       <field id="PHY2"         long_name="Diatoms Concentration"                    unit="mmol/m3" />
+       <field id="PHY2_E3T"     long_name="PHY2 * E3T"                               unit="mmol/m2"  > PHY2 * e3t </field >
+       <field id="ZOO2"         long_name="Mesozooplankton Concentration"            unit="mmol/m3" />
+       <field id="ZOO2_E3T"     long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO2 * e3t </field >
+       <field id="DSi"          long_name="Diatoms Silicate Concentration"           unit="mmol/m3" />
+       <field id="DSi_E3T"      long_name="Dsi * E3T"                                unit="mmol/m2"  > DSi * e3t </field >
+       <field id="Fer"          long_name="Dissolved Iron Concentration"             unit="mmol/m3" />
+       <field id="Fer_E3T"      long_name="Fer * E3T"                                unit="mmol/m2"  > Fer * e3t </field >
+       <field id="BFe"          long_name="Big iron particles Concentration"         unit="mmol/m3" />
+       <field id="BFe_E3T"      long_name="BFe * E3T"                                unit="mmol/m2"  > BFe * e3t </field >
+       <field id="GOC"          long_name="Big organic carbon Concentration"         unit="mmol/m3" />
+       <field id="GOC_E3T"      long_name="GOC * E3T"                                unit="mmol/m2"  > GOC * e3t </field >
+       <field id="SFe"          long_name="Small iron particles Concentration"       unit="mmol/m3" />
+       <field id="SFe_E3T"      long_name="SFe * E3T"                                unit="mmol/m2"  > SFe * e3t </field >
+       <field id="DFe"          long_name="Diatoms iron  Concentration"              unit="mmol/m3" />
+       <field id="DFe_E3T"      long_name="DFe * E3T"                                unit="mmol/m2"  > DFe * e3t </field >
+       <field id="GSi"          long_name="Sinking biogenic Silicate Concentration"  unit="mmol/m3" />
+       <field id="GSi_E3T"      long_name="GSi * E3T"                                unit="mmol/m2"  > GSi * e3t </field >
+       <field id="NFe"          long_name="Nano iron Concentration"                  unit="mmol/m3" />
+       <field id="NFe_E3T"      long_name="NFe * E3T"                                unit="mmol/m2"  > NFe * e3t </field >
+       <field id="NCHL"         long_name="Nano chlorophyl Concentration"            unit="mg/m3"   />
+       <field id="NCHL_E3T"     long_name="NCHL * E3T"                               unit="mmol/m2"  > NCHL * e3t </field >
+       <field id="DCHL"         long_name="Diatoms chlorophyl Concentration"         unit="mg/m3"   />
+       <field id="DCHL_E3T"     long_name="DCHL * E3T"                               unit="mmol/m2"  > DCHL * e3t </field >
+       <field id="NO3"          long_name="Nitrate Concentration"                    unit="mmol/m3" />
+       <field id="NO3_E3T"      long_name="NO3 * E3T"                                unit="mmol/m2"  > NO3 * e3t </field >
+       <field id="NH4"          long_name="Ammonium Concentration"                   unit="mmol/m3" />
+       <field id="NH4_E3T"      long_name="NH4 * E3T"                                unit="mmol/m2"  > NH4 * e3t </field >
+
+      <!-- MEDUSA : variables available with key_medusa -->
+       <field id="CHN"      long_name="Chl-a concentration in non-diatom phytoplankton"   unit="mg Chl/m3" />
+       <field id="CHD"      long_name="Chl-a concentration in     diatom phytoplankton"   unit="mg Chl/m3" />
+       <field id="PHN"      long_name="non-diatom phytoplankton"                          unit="mmol-N/m3" />
+       <field id="PHD"      long_name="diatom     phytoplankton"                          unit="mmol-N/m3" />
+       <field id="ZMI"      long_name="micro zooplankton"                                 unit="mmol-N/m3" />
+       <field id="ZME"      long_name="meso  zooplankton"                                 unit="mmol-N/m3" />
+       <field id="DIN"      long_name="dissolved inorganic nitrogen"                      unit="mmol-N/m3" />
+       <field id="SIL"      long_name="dissolved silicic acid"                            unit="mmolSi/m3" />
+       <field id="FER"      long_name="dissolved iron"                                    unit="mmolFe/m3" />
+       <field id="DET"      long_name="detrital nitrogen"                                 unit="mmol-N/m3" />
+       <field id="PDS"      long_name="biogenic silicon in diatom phytoplankton"          unit="mmolSi/m3" />
+       <field id="DTC"      long_name="detrital carbon"                                   unit="mmol-C/m3" />
+       <field id="DiC"      long_name="dissolved inorganic carbon"                        unit="mmol-C/m3" />
+       <field id="ALK"      long_name="alkalinity"                                        unit="meq/m3"    />
+       <field id="OXY"      long_name="dissolved oxygen"                                  unit="mmolO2/m3" />
+
+      <!-- Ideal traceurs : variables available with key_idtra -->
+       <field id="IDTRA"    long_name="Ideal traceur concentration "                      unit="mmol/m3"    />
+
+       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
+       <field id="Num"         long_name="Number of organic particles"              unit="1" />
+       <field id="Num_E3T"     long_name="Num * E3T"                                unit="m"  > Num * e3t </field >
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="DET"         long_name="Detritus"                                 unit="mmol-N/m3" />
+       <field id="DET_E3T"     long_name="DET * E3T"                                unit="mmol-N/m2"  > DET * e3t </field >
+       <field id="DOM"         long_name="Dissolved Organic Matter"                 unit="mmol-N/m3" />
+       <field id="DOM_E3T"     long_name="DOM * E3T"                                unit="mmol-N/m2"  > DOM * e3t </field >
+
+       <!-- CFC11 : variables available with key_cfc -->
+       <field id="CFC11"       long_name="CFC-11 Concentration"                     unit="umol/m3" />
+       <field id="CFC11_E3T"   long_name="CFC11 * E3T"                              unit="umol/m2"  > CFC11 * e3t </field >
+       <!-- Bomb C14 : variables available with key_c14b -->
+       <field id="C14B"        long_name="Bomb C14 Concentration"                   unit="1"         />
+       <field id="C14B_E3T"    long_name="C14B * E3T"                               unit="m"  > C14B * e3t </field >
+       <!-- AGE : variables available with key_age -->
+       <field id="Age"        long_name="Sea Water Age Since Surface contact" standard_name="sea_water_age_since_surface_contact"  unit="yr"         />
+       <field id="Age_e3t"    long_name="Age * e3t"                                 unit="yr * m"  > Age * e3t </field >
+     </field_group>
+
+     <!-- PISCES additional diagnostics on T grid  -->
+
+     <field_group id="diad_T" grid_ref="grid_T_2D">
+       <field id="PH"          long_name="PH"                                      unit="1"          grid_ref="grid_T_3D" />
+       <field id="CO3"         long_name="Bicarbonates"                            unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="CO3sat"      long_name="CO3 saturation"                          unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="PAR"         long_name="Photosynthetically Available Radiation"  unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PARDM"       long_name="Daily mean PAR"                          unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PPPHY"       long_name="Primary production of nanophyto"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPPHY2"      long_name="Primary production of diatoms"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPNEWN"      long_name="New Primary production of nanophyto"     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPNEWD"      long_name="New Primary production of diatoms"       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PBSi"        long_name="Primary production of Si diatoms"        unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PFeN"        long_name="Primary production of nano iron"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PFeD"        long_name="Primary production of diatoms iron"      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="xfracal"     long_name="Calcifying fraction"                     unit="1"          grid_ref="grid_T_3D" />
+       <field id="PCAL"        long_name="Calcite production"                      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DCAL"        long_name="Calcite dissolution"                     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ1"       long_name="Grazing by microzooplankton"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ2"       long_name="Grazing by mesozooplankton"              unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="REMIN"       long_name="Oxic remineralization of OM"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DENIT"       long_name="Anoxic remineralization of OM"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Nfix"        long_name="Nitrogen fixation"                       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Mumax"       long_name="Maximum growth rate"                     unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuN"         long_name="Realized growth rate for nanophyto"      unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuD"         long_name="Realized growth rate for diatomes"       unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="LNnut"       long_name="Nutrient limitation term in Nanophyto"   unit=""           grid_ref="grid_T_3D" />
+       <field id="LDnut"       long_name="Nutrient limitation term in Diatoms"     unit=""           grid_ref="grid_T_3D" />
+       <field id="LNFe"        long_name="Iron limitation term in Nanophyto"       unit=""           grid_ref="grid_T_3D" />
+       <field id="LDFe"        long_name="Iron limitation term in Diatoms"         unit=""           grid_ref="grid_T_3D" />
+       <field id="LNlight"     long_name="Light limitation term in Nanophyto"      unit=""           grid_ref="grid_T_3D" />
+       <field id="LDlight"     long_name="Light limitation term in Diatoms"        unit=""           grid_ref="grid_T_3D" />
+       <field id="Fe2"         long_name="Iron II concentration"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Fe3"         long_name="Iron III concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL1"        long_name="Complexed Iron concentration with L1"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL2"        long_name="Complexed Iron concentration with L2"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeP"         long_name="Precipitated Iron III"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL1"         long_name="Total L1 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL2"         long_name="Total L2 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="pdust"       long_name="dust concentration"                      unit="g/m3"                            />
+       <field id="Totlig"      long_name="Total ligand concentation"               unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Biron"       long_name="Bioavailable iron"                       unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Sdenit"      long_name="Nitrate reduction in the sediments"      unit="mol/m2/s"                        />
+       <field id="Ironice"     long_name="Iron input/uptake due to sea ice"        unit="mol/m2/s"                        />
+       <field id="HYDR"        long_name="Iron input from hydrothemal vents"       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EPC100"      long_name="Export of carbon particles at 100 m"     unit="mol/m2/s"                        />
+       <field id="EPFE100"     long_name="Export of biogenic iron at 100 m"        unit="mol/m2/s"                        />
+       <field id="EPSI100"     long_name="Export of Silicate at 100 m"             unit="mol/m2/s"                        />
+       <field id="EPCAL100"    long_name="Export of Calcite at 100 m"              unit="mol/m2/s"                        />
+       <field id="EXPC"        long_name="Export of carbon"                        unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPFE"       long_name="Export of biogenic iron"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPSI"       long_name="Export of Silicate"                      unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPCAL"      long_name="Export of Calcite"                       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="Cflx"        long_name="DIC flux"                                unit="mol/m2/s"                        />
+       <field id="Oflx"        long_name="Oxygen flux"                             unit="mol/m2/s"                        />
+       <field id="Kg"          long_name="Gas transfer"                            unit="mol/m2/s/uatm"                   />
+       <field id="Dpco2"       long_name="Delta CO2"                               unit="uatm"                            />
+       <field id="Dpo2"        long_name="Delta O2"                                unit="uatm"                            />
+       <field id="Heup"        long_name="Euphotic layer depth"                    unit="m"                               />
+       <field id="Irondep"     long_name="Iron deposition from dust"               unit="mol/m2/s"                        />
+       <field id="Ironsed"     long_name="Iron deposition from sediment"           unit="mol/m2/s"   grid_ref="grid_T_3D" />
+
+
+       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
+       <field id="EPN100"      long_name="Particulate number flux at 100 m"        unit="mol/m2/s"                        />
+       <field id="EXPN"        long_name="Particulate number flux"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="XNUM"        long_name="Number of particles in aggregats"        unit="1"          grid_ref="grid_T_3D" />
+       <field id="WSC"         long_name="sinking speed of mass flux"              unit="m2/s"       grid_ref="grid_T_3D" />
+       <field id="WSN"         long_name="sinking speed of number flux"            unit="m2/s"       grid_ref="grid_T_3D" />
+
+       <!-- dbio_T on T grid : variables available with key_diaar5 -->
+       <field id="TPP"         long_name="Total Primary production of phyto"                   unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPNEW"       long_name="New Primary production of phyto"                     unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPBFE"       long_name="Total biogenic iron production"                      unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="INTDIC"      long_name="DIC content"                                         unit="kg/m2"                          />
+       <field id="O2MIN"       long_name="Oxygen minimum concentration"                        unit="mol/m3"                          />
+       <field id="ZO2MIN"      long_name="Depth of oxygen minimum concentration"               unit="m"                              />
+       <field id="INTNFIX"     long_name="Nitrogen fixation rate : vert. integrated"           unit="mol/m2/s"                       />
+       <field id="INTPPPHY"    long_name="Vertically integrated primary production by nanophy" unit="mol/m2/s"                       />
+       <field id="INTPPPHY2"   long_name="Vertically integrated primary production by diatom"  unit="mol/m2/s"                       />
+       <field id="INTPP"       long_name="Vertically integrated primary production by phyto"   unit="mol/m2/s"                       />
+       <field id="INTPNEW"     long_name="Vertically integrated new primary production"        unit="mol/m2/s"                       />
+       <field id="INTPBFE"     long_name="Vertically integrated of biogenic iron production"   unit="mol/m2/s"                       />
+       <field id="INTPBSI"     long_name="Vertically integrated of biogenic Si production"     unit="mol/m2/s"                       />
+       <field id="INTPCAL"     long_name="Vertically integrated of calcite production"         unit="mol/m2/s"                       />
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="FNO3PHY"     long_name="FNO3PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4PHY"     long_name="FNH4PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4NO3"     long_name="FNH4NO3"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="TNO3PHY"     long_name="TNO3PHY"                                 unit=""  /> 
+       <field id="TNH4PHY"     long_name="TNH4PHY"                                 unit=""  /> 
+       <field id="TPHYDOM"     long_name="TPHYDOM"                                 unit=""  /> 
+       <field id="TPHYNH4"     long_name="TPHYNH4"                                 unit=""  /> 
+       <field id="TPHYZOO"     long_name="TPHYZOO"                                 unit=""  /> 
+       <field id="TPHYDET"     long_name="TPHYDET"                                 unit=""  /> 
+       <field id="TDETZOO"     long_name="TDETZOO"                                 unit=""  /> 
+       <field id="TZOODET"     long_name="TZOODET"                                 unit=""  /> 
+       <field id="TZOOBOD"     long_name="TZOOBOD"                                 unit=""  /> 
+       <field id="TZOONH4"     long_name="TZOONH4"                                 unit=""  /> 
+       <field id="TZOODOM"     long_name="TZOODOM"                                 unit=""  /> 
+       <field id="TNH4NO3"     long_name="TNH4NO3"                                 unit=""  /> 
+       <field id="TDOMNH4"     long_name="TDOMNH4"                                 unit=""  /> 
+       <field id="TDETNH4"     long_name="TDETNH4"                                 unit=""  /> 
+       <field id="TPHYTOT"     long_name="TPHYTOT"                                 unit=""  /> 
+       <field id="TZOOTOT"     long_name="TZOOTOT"                                 unit=""  /> 
+       <field id="SEDPOC"      long_name="SEDPOC"                                  unit=""  /> 
+       <field id="TDETSED"     long_name="TDETSED"                                 unit=""  /> 
+
+       <!-- CFC11 : variables available with key_cfc -->
+       <field id="qtrCFC11"    long_name="Air-sea flux of CFC-11"                  unit="mol/m2/s"   />
+       <field id="qintCFC11"   long_name="Cumulative air-sea flux of CFC-11"       unit="mol/m2"     />
+
+       <!-- Bomb C14 : variables available with key_c14b -->
+       <field id="qtrC14b"     long_name="Air-sea flux of Bomb C14"                unit="mol/m2/s"   />
+       <field id="qintC14b"    long_name="Cumulative air-sea flux of Bomb C14"     unit="mol/m2"     />
+       <field id="fdecay"      long_name="Radiactive decay of Bomb C14"            unit="mol/m3"  grid_ref="grid_T_3D"  />
+
+       <!-- IDTRA : variables available with key_idtra -->
+       <field id="qtrIDTRA"    long_name="Air-sea flux of Ideal Tracer"             unit="mol/m2/s"   />
+       <field id="qintIDTRA"   long_name="Cumulative air-sea flux of Ideal Tracer"  unit="mol/m2"     />
+       <field id="invIDTRA"    long_name="Vertical inventory"                       unit="mol/m2"     />
+
+       <!-- MEDUSA additional diagnostics on T grid  -->
+       <field id= "INVTN"      long_name="Column N inventory"                        unit="mmolN/m2"    />
+       <field id= "INVTSI"     long_name="Column Si inventory"                       unit="mmolSi/m2"   />
+       <field id= "INVTFE"     long_name="Column Fe inventory"                       unit="mmolFe/m2"   />
+       <field id= "PRN"        long_name="Non-diatom primary production"             unit="mmolN/m2/d"  />
+       <field id= "MPN"        long_name="Non-diatom non-grazing losses"             unit="mmolN/m2/d"  />
+       <field id= "PRD"        long_name="Diatom primary production"                 unit="mmolN/m2/d"  />
+       <field id= "MPD"        long_name="Diatom non-grazing losses"                 unit="mmolN/m2/d"  />
+       <field id= "DSED"       long_name="Gravitational sinking of Detritus"         unit="mmolN/m2/d"  />
+       <field id= "OPAL"       long_name="Diatom biogenic opal production"           unit="mmolSi/m2/d" />
+       <field id= "OPALDISS"   long_name="Diatom biogenic opal dissolution"          unit="mmolSi/m2/d" />
+       <field id= "GMIPn"      long_name="Microzoo grazing on non-diatoms"           unit="mmolN/m2/d"  />
+       <field id= "GMID"       long_name="Microzoo grazing on detritus"              unit="mmolN/m2/d"  />
+       <field id= "MZMI"       long_name="Microzoo non-grazing losses"               unit="mmolN/m2/d"  />
+       <field id= "GMEPN"      long_name="Mesozoo grazing on non-diatoms"            unit="mmolN/m2/d"  />
+       <field id= "GMEPD"      long_name="Mesozoo grazing on non-diatoms"            unit="mmolN/m2/d"  />
+       <field id= "GMEZMI"     long_name="Mesozoo grazing on microzoo"               unit="mmolN/m2/d"  />
+       <field id= "GMED"       long_name="Mesozoo grazing on detritus"               unit="mmolN/m2/d"  />
+       <field id= "MZME"       long_name="Mesozoo non-grazing losses"                unit="mmolN/m2/d"  />
+       <field id= "DEXP"       long_name="Detritus export"                           unit="mmolN/m2/d"  />
+       <field id= "DETN"       long_name="Slow detritus creation"                    unit="mmolN/m2/d"  />
+       <field id= "MDET"       long_name="Detritus non-grazing losses"               unit="MmolN/m2/d"  />
+       <field id= "AEOLIAN"    long_name="Aeolian deposition of iron"                unit="mmolFe/m2/d" />
+       <field id= "BENTHIC"    long_name="Benthic supply of iron"                    unit="mmolFe/m2/d" />
+       <field id= "SCAVENGE"   long_name="Scavenged iron"                            unit="mmolFe/m2/d" />
+       <field id= "PN_JLIM"    long_name="Non-diatom light limitation"               unit="-"           />
+       <field id= "PN_NLIM"    long_name="Non-diatom N limitation"                   unit="-"           />
+       <field id= "PN_FELIM"   long_name="Non-diatom Fe limitation"                  unit="-"           />
+       <field id= "PD_JLIM"    long_name="Diatom light limitation"                   unit="-"           />
+       <field id= "PD_NLIM"    long_name="Diatom N limitation"                       unit="-"           />
+       <field id= "PD_FELIM"   long_name="Diatom Fe limitation"                      unit="-"           />
+       <field id= "PD_SILIM"   long_name="Diatom Si limitation"                      unit="-"           />
+       <field id= "PDSILIM2"   long_name="Diatom Si uptake limitation"               unit="-"           />
+       <field id= "SDT__100"   long_name="Slow detrital flux at  100 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT__200"   long_name="Slow detrital flux at  200 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT__500"   long_name="Slow detrital flux at  500 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT_1000"   long_name="Slow detrital flux at 1000 m"              unit="mmolN/m2/d"  />
+       <field id= "TOTREG_N"   long_name="Full column regenerated N"                 unit="mmolN/m2/d"  />
+       <field id= "TOTRG_SI"   long_name="Full column regenerated Si"                unit="mmolSi/m2/d" />
+       <field id= "REG__100"   long_name="Regenerated N to  100 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG__200"   long_name="Regenerated N to  200 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG__500"   long_name="Regenerated N to  500 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG_1000"   long_name="Regenerated N to 1000 m"                   unit="mmolN/m2/d"  />
+       <field id= "FASTN"      long_name="Fast-sinking flux N"                       unit="mmolN/m2/d"  />
+       <field id= "FASTSI"     long_name="Fast-sinking flux Si"                      unit="mmolSi/m2/d" />
+       <field id= "FASTFE"     long_name="Fast-sinking flux Fe"                      unit="mmolFe/m2/d" />
+       <field id= "FASTC"      long_name="Fast-sinking flux C"                       unit="mmolC/m2/d"  />
+       <field id= "FASTCA"     long_name="Fast-sinking flux CaCO3"                   unit="mmolC/m2/d"  />
+       <field id= "FDT__100"   long_name="Fast detrital N flux at  100 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT__200"   long_name="Fast detrital N flux at  200 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT__500"   long_name="Fast detrital N flux at  500 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT_1000"   long_name="Fast detrital N flux at 1000 m"            unit="mmolN/m2/d"  />
+       <field id= "RG__100F"   long_name="Regenerated fast N to  100 m"              unit="mmolN/m2/d"  />
+       <field id= "RG__200F"   long_name="Regenerated fast N to  200 m"              unit="mmolN/m2/d"  />
+       <field id= "RG__500F"   long_name="Regenerated fast N to  500 m"              unit="mmolN/m2/d"  />
+       <field id= "RG_1000F"   long_name="Regenerated fast N to 1000 m"              unit="mmolN/m2/d"  />
+       <field id= "FDS__100"   long_name="Fast detrital Si flux at  100 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS__200"   long_name="Fast detrital Si flux at  200 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS__500"   long_name="Fast detrital Si flux at  500 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS_1000"   long_name="Fast detrital Si flux at 1000 m"           unit="mmolSi/m2/d" />
+       <field id= "RGS_100F"   long_name="Regenerated fast Si to  100 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS_200F"   long_name="Regenerated fast Si to  200 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS_500F"   long_name="Regenerated fast Si to  500 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS1000F"   long_name="Regenerated fast Si to 1000 m"             unit="mmolSi/m2/d" />
+       <field id= "REMINN"     long_name="Fast-sinking remin flux N"                 unit="mmolN/m2/d"  />
+       <field id= "REMINSI"    long_name="Fast-sinking remin flux Si"                unit="mmolSi/m2/d" />
+       <field id= "REMINFE"    long_name="Fast-sinking remin flux Fe"                unit="mmolFe/m2/d" />
+       <field id= "REMINC"     long_name="Fast-sinking remin flux C"                 unit="mmolC/m2/d"  />
+       <field id= "REMINCA"    long_name="Fast-sinking remin flux CaCO3"             unit="mmolC/m2/d"  />
+       <field id= "SEAFLRN"    long_name="Seafloor flux of N"                        unit="mmolN/m2/d"  />
+       <field id= "SEAFLRSI"   long_name="Seafloor flux of Si"                       unit="mmolSi/m2/d" />
+       <field id= "SEAFLRFE"   long_name="Seafloor flux of Fe"                       unit="mmolFe/m2/d" />
+       <field id= "SEAFLRC"    long_name="Seafloor flux of C"                        unit="mmolC/m2/d"  />
+       <field id= "SEAFLRCA"   long_name="Seafloor flux of CaCO3"                    unit="mmolC/m2/d"  />
+       <field id= "MED_QSR"    long_name="Sea surface radiation"                     unit="W/m2"        />
+       <field id= "MED_XPAR"   long_name="Top level radiation"                       unit="W/m2"        />
+       <field id= "INTFLX_N"   long_name="Integrated N  cycle fluxes"                unit="mmolN/m2/d"  />
+       <field id= "INTFLX_SI"  long_name="Integrated Si cycle fluxes"                unit="mmolSi/m2/d" />
+       <field id= "INTFLX_FE"  long_name="Integrated Fe cycle fluxes"                unit="mmolFe/m2/d" />
+       <field id= "INT_PN"     long_name="Vertically integrated Pn"                  unit="mmolN/m2"    />
+       <field id= "INT_PD"     long_name="Vertically integrated Pd"                  unit="mmolN/m2"    />
+       <field id= "ML_PRN"     long_name="Non-diatom mixed layer PP"                 unit="mmolN/m2/d"  />
+       <field id= "ML_PRD"     long_name="Diatom mixed layer PP"                     unit="mmolN/m2/d"  />
+       <field id= "OCAL_CCD"   long_name="Calcite CCD depth"                         unit="m"           />
+       <field id= "OCAL_LVL"   long_name="Calcite CCD level"                         unit="-"           />
+       <field id= "FE_0000"    long_name="Free iron at    0m"                        unit="-"           />
+       <field id= "FE_0100"    long_name="Free iron at  100m"                        unit="-"           />
+       <field id= "FE_0200"    long_name="Free iron at  200m"                        unit="-"           />
+       <field id= "FE_0500"    long_name="Free iron at  500m"                        unit="-"           />
+       <field id= "FE_1000"    long_name="Free iron at 1000m"                        unit="-"           />
+       <field id= "MED_XZE"    long_name="Euphotic depth"                            unit="m"           />
+       <field id= "WIND"       long_name="Surface scalar wind"                       unit="m/s"         />
+       <field id= "ATM_PCO2"   long_name="Atmospheric pCO2"                          unit="ppmv"        />
+       <field id= "OCN_PH"     long_name="Surface ocean pH"                          unit="-"           />
+       <field id= "OCN_PCO2"   long_name="Surface ocean pCO2"                        unit="ppmv"        />
+       <field id= "OCNH2CO3"   long_name="Surface ocean H2CO3 conc"                  unit="mmolC/m3"    />
+       <field id= "OCN_HCO3"   long_name="Surface ocean HCO3 conc"                   unit="mmolC/m3"    />
+       <field id= "OCN_CO3"    long_name="Surface ocean CO3 conc"                    unit="mmolC/m3"    />
+       <field id= "CO2FLUX"    long_name="Air-sea CO2 flux"                          unit="mmolC/m2/d"  />
+       <field id= "OM_CAL"     long_name="Omega calcite"                             unit="-"           />
+       <field id= "OM_ARG"     long_name="Omega aragonite"                           unit="-"           />
+       <field id= "TCO2"       long_name="Total CO2"                                 unit="umol/kg"     />
+       <field id= "TALK"       long_name="Total alkalinity"                          unit="ueq/kg"      />
+       <field id= "KW660"      long_name="Piston velocity"                           unit="m/s"         />
+       <field id= "ATM_PP0"    long_name="Atmospheric pressure"                      unit="bar"         />
+       <field id= "O2FLUX"     long_name="Air-sea O2 flux"                           unit="mmolO2/m2/d" />
+       <field id= "O2SAT"      long_name="Surface ocean O2 saturation"               unit="mmolO2/m3"   />
+       <field id= "CAL_CCD"    long_name="Calcite CCD depth"                         unit="m"           />
+       <field id= "ARG_CCD"    long_name="Aragonite CCD depth"                       unit="m"           />
+       <field id= "SFR_OCAL"   long_name="Seafloor omega calcite"                    unit="-"           />
+       <field id= "SFR_OARG"   long_name="Seafloor omega aragonite"                  unit="-"           />
+       <field id= "N_PROD"     long_name="Nitrogen production"                       unit="mmolN/m2/d"  />
+       <field id= "N_CONS"     long_name="Nitrogen consumption"                      unit="mmolN/m2/d"  />
+       <field id= "C_PROD"     long_name="Carbon production"                         unit="mmolC/m2/d"  />
+       <field id= "C_CONS"     long_name="Carbon consumption"                        unit="mmolC/m2/d"  />
+       <field id= "O2_PROD"    long_name="Oxygen production"                         unit="mmolO2/m2/d" />
+       <field id= "O2_CONS"    long_name="Oxygen consumption"                        unit="mmolO2/m2/d" />
+       <field id= "O2_ANOX"    long_name="Unrealised oxygen consumption"             unit="mmolO2/m2/d" />
+       <field id= "RR_0100"    long_name="Rain ratio at  100m"                       unit="molC/molC"   />
+       <field id= "RR_0500"    long_name="Rain ratio at  500m"                       unit="molC/molC"   />
+       <field id= "RR_1000"    long_name="Rain ratio at 1000m"                       unit="molC/molC"   />
+       <field id= "IBEN_N"     long_name="Benthic input nitrogen"                    unit="mmolN/m2/d"  />
+       <field id= "IBEN_FE"    long_name="Benthic input iron"                        unit="mmolFe/m2/d" />
+       <field id= "IBEN_C"     long_name="Benthic input carbon"                      unit="mmolC/m2/d"  />
+       <field id= "IBEN_SI"    long_name="Benthic input silicon"                     unit="mmolSi/m2/d" />
+       <field id= "IBEN_CA"    long_name="Benthic input CaCO3"                       unit="mmolC/m2/d"  />
+       <field id= "OBEN_N"     long_name="Benthic output nitrogen"                   unit="mmolN/m2/d"  />
+       <field id= "OBEN_FE"    long_name="Benthic output iron"                       unit="mmolFe/m2/d" />
+       <field id= "OBEN_C"     long_name="Benthic output carbon"                     unit="mmolC/m2/d"  />
+       <field id= "OBEN_SI"    long_name="Benthic output silicon"                    unit="mmolSi/m2/d" />
+       <field id= "OBEN_CA"    long_name="Benthic output CaCO3"                      unit="mmolC/m2/d"  />
+       <field id= "BEN_N"      long_name="Benthic nitrogen"                          unit="mmolN/m2"    />
+       <field id= "BEN_FE"     long_name="Benthic iron"                              unit="mmolFe/m2"   />
+       <field id= "BEN_C"      long_name="Benthic carbon"                            unit="mmolC/m2"    />
+       <field id= "BEN_SI"     long_name="Benthic silicon"                           unit="mmolSi/m2"   />
+       <field id= "BEN_CA"     long_name="Benthic CaCO3"                             unit="mmolC/m2"    />
+       <field id= "RUNOFF"     long_name="River runoff"                              unit="m/d"         />
+       <field id= "RIV_N"      long_name="Riverine input nitrogen"                   unit="mmolN/m2/d"  />
+       <field id= "RIV_SI"     long_name="Riverine input silicon"                    unit="mmolSi/m2/d" />
+       <field id= "RIV_C"      long_name="Riverine input carbon"                     unit="mmolSi/m2/d" />
+       <field id= "RIV_ALK"    long_name="Riverine input alkalinity"                 unit="meq/m2/d"    />
+       <field id= "DETC"       long_name="Slow detritus C creation"                  unit="mmolC/m2/d"  />
+       <field id= "SDC__100"   long_name="Slow detrital C flux at  100 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC__200"   long_name="Slow detrital C flux at  200 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC__500"   long_name="Slow detrital C flux at  500 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC_1000"   long_name="Slow detrital C flux at 1000 m"            unit="mmolC/m2/d"  />
+       <field id= "INVTC"      long_name="Column C inventory"                        unit="mmolC/m2"    />
+       <field id= "INVTALK"    long_name="Column alkalinity inventory"               unit="meq/m2"      />
+       <field id= "INVTO2"     long_name="Column O2 inventory"                       unit="mmolO2/m2"   />
+       <field id= "LYSO_CA"    long_name="Incorrect benthic output CaCO3"            unit="mmolC/m2/d"  />
+       <field id= "COM_RESP"   long_name="Community respiration"                     unit="mmolC/m2/d"  />
+       <field id= "PN_LLOSS"   long_name="Non-diatom linear losses"                  unit="mmolN/m2/d"  />
+       <field id= "PD_LLOSS"   long_name="Diatom linear losses"                      unit="mmolN/m2/d"  />
+       <field id= "ZI_LLOSS"   long_name="Microzooplankton linear losses"            unit="mmolN/m2/d"  />
+       <field id= "ZE_LLOSS"   long_name="Mesozooplankton linear losses"             unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_N"   long_name="Microzoo messy feeding loss to N"          unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_D"   long_name="Microzoo messy feeding loss to D"          unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_C"   long_name="Microzoo messy feeding loss to C"          unit="mmolC/m2/d"  />
+       <field id= "ZI_MESDC"   long_name="Microzoo messy feeding loss to Dc"         unit="mmolC/m2/d"  />
+       <field id= "ZI_EXCR"    long_name="Microzoo excretion"                        unit="mmolN/m2/d"  />
+       <field id= "ZI_RESP"    long_name="Microzoo respiration"                      unit="mmolC/m2/d"  />
+       <field id= "ZI_GROW"    long_name="Microzoo growth"                           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_N"   long_name="Mesozoo messy feeding loss to N"           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_D"   long_name="Mesozoo messy feeding loss to D"           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_C"   long_name="Mesozoo messy feeding loss to C"           unit="mmolC/m2/d"  />
+       <field id= "ZE_MESDC"   long_name="Mesozoo messy feeding loss to Dc"          unit="mmolC/m2/d"  />
+       <field id= "ZE_EXCR"    long_name="Mesozoo excretion"                         unit="mmolN/m2/d"  />
+       <field id= "ZE_RESP"    long_name="Mesozoo respiration"                       unit="mmolC/m2/d"  />
+       <field id= "ZE_GROW"    long_name="Mesozoo growth"                            unit="mmolN/m2/d"  />
+       <field id= "MDETC"      long_name="Detritus non-grazing losses, carbon"       unit="mmolC/m2/d"  />
+       <field id= "GMIDC"      long_name="Microzoo grazing on detritus, carbon"      unit="mmolC/m2/d"  />
+       <field id= "GMEDC"      long_name="Mesozoo  grazing on detritus, carbon"      unit="mmolC/m2/d"  />
+       <field id= "INT_ZMI"    long_name="Vertically integrated Zmi"                 unit="mmolN/m2"    />
+       <field id= "INT_ZME"    long_name="Vertically integrated Zme"                 unit="mmolN/m2"    />
+       <field id= "INT_DET"    long_name="Vertically integrated Det"                 unit="mmolN/m2"    />
+       <field id= "INT_DTC"    long_name="Vertically integrated Dtc"                 unit="mmolC/m2"    />
+       <field id= "DMS_SURF"   long_name="DMS Surface Concentration"                 unit="nmol/L"      />
+       <field id= "DMS_ANDR"   long_name="DMS Surface Concentration, Anderson"       unit="nmol/L"      />
+       <field id= "DMS_SIMO"   long_name="DMS Surface Concentration, SimoDach"       unit="nmol/L"      />
+       <field id= "DMS_ARAN"   long_name="DMS Surface Concentration, AranamiT"       unit="nmol/L"      />
+       <field id= "DMS_HALL"   long_name="DMS Surface Concentration, Halloran"       unit="nmol/L"      />
+
+       <!-- AXY (08/11/16): add new 2D CMIP6 diagnostics -->
+       <field id= "epC100"     long_name="Downward Flux of Particle Organic Carbon"  unit="mmolC/m2/d"  />
+       <field id= "epCALC100"  long_name="Downward Flux of Calcite"                  unit="mmolC/m2/d"  />
+       <field id= "epN100"     long_name="Downward Flux of Particulate Nitrogen"     unit="mmolN/m2/d"  />
+       <field id= "epSI100"    long_name="Downward Flux of Particulate Silica"       unit="mmolSi/m2/d" />
+       <field id= "FGCO2"      long_name="Surface Downward CO2 Flux"                 unit="kg/m2/s"     />
+       <field id= "INTDISSIC"  long_name="Dissolved Inorganic Carbon Content"        unit="mmolC/m2"    />
+       <field id= "INTDISSIN"  long_name="Dissolved Inorganic Nitrogen Content"      unit="mmolN/m2"    />
+       <field id= "INTDISSISI" long_name="Dissolved Inorganic Silicon Content"       unit="mmolSi/m2"   />
+       <field id= "INTALK"     long_name="Dissolved Alkalinity Content"              unit="meq/m2"      />
+       <field id= "O2min"      long_name="Oxygen Minimum Concentration"              unit="mmolO2/m3"   />
+       <field id= "ZO2min"     long_name="Depth of Oxygen Minimum Concentration"     unit="m"           />
+
+       <field id= "TPP3"       long_name="Total primary production 3D"               unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "DETFLUX3"   long_name="Total detrital flux 3D"                    unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "REMIN3N"    long_name="Total remin flux N 3D"                     unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "PH3"        long_name="Ocean pH 3D"                               unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "OM_CAL3"    long_name="Omega calcite 3D"                          unit="-"             grid_ref="grid_T_3D"  />
+
+       <!-- AXY (08/11/16): add new 3D CMIP6 diagnostics -->
+       <field id= "TPPD3"      long_name="Diatom primary production 3D"              unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTALK3"   long_name="Change of Alkalinity due to Biology"       unit="meq/m3/d"      grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIC3"   long_name="Change of DI Carbon due to Biology"        unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTIFE3"   long_name="Change of DI Iron due to Biology"          unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIN3"   long_name="Change of DI Nitrogen due to Biology"      unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTDISI3"  long_name="Change of DI Silicon due to Biology"       unit="mmolSi/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "FD_NIT3"    long_name="Fast sinking detrital nitrogen"            unit="mmolN/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "FD_SIL3"    long_name="Fast sinking detrital silicon"             unit="mmolSi/m2/d"   grid_ref="grid_T_3D"  />
+       <field id= "FD_CAR3"    long_name="Fast sinking detrital carbon"              unit="mmolC/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "FD_CAL3"    long_name="Fast sinking detrital calcium carbonate"   unit="mmolC/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "CO33"       long_name="Carbonate ion concentration"               unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "CO3SATARG3" long_name="Carbonate aragonite saturation conc"       unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "CO3SATCAL3" long_name="Carbonate calcite saturation conc"         unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "DCALC3"     long_name="Calcite dissolution"                       unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "EXPC3"      long_name="Downward Flux of Particulate Org Carbon"   unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "EXPN3"      long_name="Downward Flux of Particulate Org Nitrogen" unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "FEDISS3"    long_name="Particle Source of Dissolved Iron"         unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "FESCAV3"    long_name="Nonbiogenic Iron Scavenging"               unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "MIGRAZP3"   long_name="Microzooplankton grazing on phytoplankton" unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MIGRAZD3"   long_name="Microzooplankton grazing on detritus"      unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZP3"   long_name="Mesozooplankton grazing on phytoplankton"  unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZD3"   long_name="Mesozooplankton grazing on detritus"       unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZZ3"   long_name="Mesozooplankton grazing on microzoop"      unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "O2SAT3"     long_name="Dissolved Oxygen Saturation Concentration" unit="mmolO2/m3"     grid_ref="grid_T_3D"  />
+       <field id= "PBSI3"      long_name="Biogenic Silica Production"                unit="mmolSi/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "PCAL3"      long_name="Biogenic Calcite Production"               unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "REMOC3"     long_name="Remineralization of Organic Carbon"        unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "PNLIMJ3"    long_name="Irradiance limitation of non-diatoms"      unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PNLIMN3"    long_name="Nitrogen limitation of non-diatoms"        unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PNLIMFE3"   long_name="Iron limitation of non-diatoms"            unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMJ3"    long_name="Irradiance limitation of diatoms"          unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMN3"    long_name="Nitrogen limitation of diatoms"            unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMFE3"   long_name="Iron limitation of diatoms"                unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMSI3"   long_name="Silicon limitation of diatoms"             unit="-"             grid_ref="grid_T_3D"  />
+
+     </field_group>
+
+     <field_group id="PISCES_scalar"  domain_ref="1point" >
+       <field id="pno3tot"         long_name="global mean nitrate concentration"                  unit="mol/m3"   />
+       <field id="ppo4tot"         long_name="global mean phosphorus concentration"               unit="mol/m3"   />
+       <field id="psiltot"         long_name="global mean silicate concentration"                 unit="mol/m3"   />
+       <field id="palktot"         long_name="global mean alkalinity concentration"               unit="mol/m3"   />
+       <field id="pfertot"         long_name="global mean iron concentration"                     unit="mol/m3"   />
+       <field id="tcflx"           long_name="total Flux of Carbon out of the ocean"              unit="mol/s"   />
+       <field id="tcflxcum"        long_name="cumulative total Flux of Carbon out of the ocean"   unit="mol/s"   />
+       <field id="tcexp"           long_name="total Carbon export at 100m"                        unit="mol/s"   />
+       <field id="tintpp"          long_name="global total integrated primary production"         unit="mol/s"   />
+       <field id="tnfix"           long_name="global total nitrogen fixation"                     unit="mol/s"   />
+       <field id="tdenit"          long_name="Total denitrification"                              unit="mol/s"   />
+     </field_group>
+
+    <!-- 
+============================================================================================================
+                                        Definitions for iodef_demo.xml
+============================================================================================================
+    -->
+
+    <field_group id="groupMEDUSA" >
+      <field field_ref="CHN"   name="CHN"   />
+      <field field_ref="CHD"   name="CHD"   />
+      <field field_ref="PHN"   name="PHN"   />
+      <field field_ref="PHD"   name="PHD"   />
+      <field field_ref="ZMI"   name="ZMI"   />
+      <field field_ref="ZME"   name="ZME"   />
+      <field field_ref="DIN"   name="DIN"   />
+      <field field_ref="SIL"   name="SIL"   />
+      <field field_ref="FER"   name="FER"   />
+      <field field_ref="DET"   name="DET"   />
+      <field field_ref="PDS"   name="PDS"   />
+      <field field_ref="DTC"   name="DTC"   />
+      <field field_ref="DiC"   name="DIC"   />
+      <field field_ref="ALK"   name="ALK"   />
+      <field field_ref="OXY"   name="OXY"   />
+      </field_group>
+
+    <field_group id="groupIDTRA" >
+      <field field_ref="IDTRA" name="IDTRA" />
+    </field_group>
+
+    <field_group id="groupIDTRA_dia" >
+      <field field_ref="qtrIDTRA"    name="qtrIDTRA"  />
+      <field field_ref="qintIDTRA"   name="qintIDTRA" />
+      <field field_ref="invIDTRA"    name="invIDTRA"  />
+    </field_group>
+
+    <field_group id="groupCFC" >
+      <field field_ref="CFC11" name="CFC11" />
+    </field_group>
+
+    <field_group id="groupCFC_dia" >
+      <field field_ref="qtrCFC11"    name="qtrCFC11"   />
+      <field field_ref="qintCFC11"   name="qintCFC11"  />
+    </field_group>
+
+    <field_group id="groupAGE" >
+      <field field_ref="Age" name="Age" />
+    </field_group>
+
+    <field_group id="groupMEDUSA_dia" >
+      <field field_ref= "INVTN"      name="INVTN"      />
+      <field field_ref= "INVTSI"     name="INVTSI"     />
+      <field field_ref= "INVTFE"     name="INVTFE"     />
+      <field field_ref= "PRN"        name="PRN"        />
+      <field field_ref= "MPN"        name="MPN"        />
+      <field field_ref= "PRD"        name="PRD"        />
+      <field field_ref= "MPD"        name="MPD"        />
+      <field field_ref= "OPAL"       name="OPAL"       />
+      <field field_ref= "OPALDISS"   name="OPALDISS"   />
+      <field field_ref= "GMIPn"      name="GMIPn"      />
+      <field field_ref= "GMID"       name="GMID"       />
+      <field field_ref= "MZMI"       name="MZMI"       />
+      <field field_ref= "GMEPN"      name="GMEPN"      />
+      <field field_ref= "GMEPD"      name="GMEPD"      />
+      <field field_ref= "GMEZMI"     name="GMEZMI"     />
+      <field field_ref= "GMED"       name="GMED"       />
+      <field field_ref= "MZME"       name="MZME"       />
+      <field field_ref= "DETN"       name="DETN"       />
+      <field field_ref= "MDET"       name="MDET"       />
+      <field field_ref= "AEOLIAN"    name="AEOLIAN"    />
+      <field field_ref= "BENTHIC"    name="BENTHIC"    />
+      <field field_ref= "SCAVENGE"   name="SCAVENGE"   />
+      <field field_ref= "PN_JLIM"    name="PN_JLIM"    />
+      <field field_ref= "PN_NLIM"    name="PN_NLIM"    />
+      <field field_ref= "PN_FELIM"   name="PN_FELIM"   />
+      <field field_ref= "PD_JLIM"    name="PD_JLIM"    />
+      <field field_ref= "PD_NLIM"    name="PD_NLIM"    />
+      <field field_ref= "PD_FELIM"   name="PD_FELIM"   />
+      <field field_ref= "PD_SILIM"   name="PD_SILIM"   />
+      <field field_ref= "PDSILIM2"   name="PDSILIM2"   />
+      <field field_ref= "SDT__100"   name="SDT__100"   />
+      <field field_ref= "SDT__200"   name="SDT__200"   />
+      <field field_ref= "SDT__500"   name="SDT__500"   />
+      <field field_ref= "SDT_1000"   name="SDT_1000"   />
+      <field field_ref= "TOTREG_N"   name="TOTREG_N"   />
+      <field field_ref= "TOTRG_SI"   name="TOTRG_SI"   />
+      <field field_ref= "REG__100"   name="REG__100"   />
+      <field field_ref= "REG__200"   name="REG__200"   />
+      <field field_ref= "REG__500"   name="REG__500"   />
+      <field field_ref= "REG_1000"   name="REG_1000"   />
+      <field field_ref= "FASTN"      name="FASTN"      />
+      <field field_ref= "FASTSI"     name="FASTSI"     />
+      <field field_ref= "FASTFE"     name="FASTFE"     />
+      <field field_ref= "FASTC"      name="FASTC"      />
+      <field field_ref= "FASTCA"     name="FASTCA"     />
+      <field field_ref= "FDT__100"   name="FDT__100"   />
+      <field field_ref= "FDT__200"   name="FDT__200"   />
+      <field field_ref= "FDT__500"   name="FDT__500"   />
+      <field field_ref= "FDT_1000"   name="FDT_1000"   /> 
+      <field field_ref= "RG__100F"   name="RG__100F"   />
+      <field field_ref= "RG__200F"   name="RG__200F"   />
+      <field field_ref= "RG__500F"   name="RG__500F"   />
+      <field field_ref= "RG_1000F"   name="RG_1000F"   />
+      <field field_ref= "FDS__100"   name="FDS__100"   />
+      <field field_ref= "FDS__200"   name="FDS__200"   />
+      <field field_ref= "FDS__500"   name="FDS__500"   />
+      <field field_ref= "FDS_1000"   name="FDS_1000"   />
+      <field field_ref= "RGS_100F"   name="RGS_100F"   />
+      <field field_ref= "RGS_200F"   name="RGS_200F"   />
+      <field field_ref= "RGS_500F"   name="RGS_500F"   />
+      <field field_ref= "RGS1000F"   name="RGS1000F"   />
+      <field field_ref= "REMINN"     name="REMINN"     />
+      <field field_ref= "REMINSI"    name="REMINSI"    />
+      <field field_ref= "REMINFE"    name="REMINFE"    />
+      <field field_ref= "SEAFLRN"    name="SEAFLRN"    /> 
+      <field field_ref= "SEAFLRSI"   name="SEAFLRSI"   />
+      <field field_ref= "SEAFLRFE"   name="SEAFLRFE"   />
+      <field field_ref= "SEAFLRC"    name="SEAFLRC"    />
+      <field field_ref= "SEAFLRCA"   name="SEAFLRCA"   />
+      <field field_ref= "MED_QSR"    name="MED_QSR"    />
+      <field field_ref= "MED_XPAR"   name="MED_XPAR"   />
+      <field field_ref= "INTFLX_N"   name="INTFLX_N"   />
+      <field field_ref= "INTFLX_SI"  name="INTFLX_SI"  />
+      <field field_ref= "INTFLX_FE"  name="INTFLX_FE"  />
+      <field field_ref= "INT_PN"     name="INT_PN"     />
+      <field field_ref= "INT_PD"     name="INT_PD"     />
+      <field field_ref= "ML_PRN"     name="ML_PRN"     />
+      <field field_ref= "ML_PRD"     name="ML_PRD"     />
+      <field field_ref= "OCAL_CCD"   name="OCAL_CCD"   />
+      <field field_ref= "OCAL_LVL"   name="OCAL_LVL"   />
+      <field field_ref= "FE_0000"    name="FE_0000"    />
+      <field field_ref= "FE_0100"    name="FE_0100"    />
+      <field field_ref= "FE_0200"    name="FE_0200"    /> 
+      <field field_ref= "FE_0500"    name="FE_0500"    />
+      <field field_ref= "FE_1000"    name="FE_1000"    />
+      <field field_ref= "MED_XZE"    name="MED_XZE"    />
+      <field field_ref= "WIND"       name="WIND"       />
+      <field field_ref= "ATM_PCO2"   name="ATM_PCO2"   />
+      <field field_ref= "OCN_PH"     name="OCN_PH"     />
+      <field field_ref= "OCN_PCO2"   name="OCN_PCO2"   />
+      <field field_ref= "OCNH2CO3"   name="OCNH2CO3"   />
+      <field field_ref= "OCN_HCO3"   name="OCN_HCO3"   />
+      <field field_ref= "OCN_CO3"    name="OCN_CO3"    />
+      <field field_ref= "CO2FLUX"    name="CO2FLUX"    />
+      <field field_ref= "OM_CAL"     name="OM_CAL"     />
+      <field field_ref= "OM_ARG"     name="OM_ARG"     />
+      <field field_ref= "TCO2"       name="TCO2"       />
+      <field field_ref= "TALK"       name="TALK"       />
+      <field field_ref= "KW660"      name="KW660"      />
+      <field field_ref= "ATM_PP0"    name="ATM_PP0"    />
+      <field field_ref= "O2FLUX"     name="O2FLUX"     />
+      <field field_ref= "O2SAT"      name="O2SAT"      />
+      <field field_ref= "CAL_CCD"    name="CAL_CCD"    />
+      <field field_ref= "ARG_CCD"    name="ARG_CCD"    />
+      <field field_ref= "SFR_OCAL"   name="SFR_OCAL"   />
+      <field field_ref= "SFR_OARG"   name="SFR_OARG"   />
+      <field field_ref= "N_PROD"     name="N_PROD"     />
+      <field field_ref= "N_CONS"     name="N_CONS"     />
+      <field field_ref= "C_PROD"     name="C_PROD"     />
+      <field field_ref= "C_CONS"     name="C_CONS"     />
+      <field field_ref= "O2_PROD"    name="O2_PROD"    />
+      <field field_ref= "O2_CONS"    name="O2_CONS"    />
+      <field field_ref= "O2_ANOX"    name="O2_ANOX"    />
+      <field field_ref= "RR_0100"    name="RR_0100"    />
+      <field field_ref= "RR_0500"    name="RR_0500"    />
+      <field field_ref= "RR_1000"    name="RR_1000"    />
+      <field field_ref= "IBEN_N"     name="IBEN_N"     />
+      <field field_ref= "IBEN_FE"    name="IBEN_FE"    />
+      <field field_ref= "IBEN_C"     name="IBEN_C"     />
+      <field field_ref= "IBEN_SI"    name="IBEN_SI"    />
+      <field field_ref= "IBEN_CA"    name="IBEN_CA"    />
+      <field field_ref= "OBEN_N"     name="OBEN_N"     />
+      <field field_ref= "OBEN_FE"    name="OBEN_FE"    />
+      <field field_ref= "OBEN_C"     name="OBEN_C"     />
+      <field field_ref= "OBEN_SI"    name="OBEN_SI"    />
+      <field field_ref= "OBEN_CA"    name="OBEN_CA"    />
+      <field field_ref= "BEN_N"      name="BEN_N"      />
+      <field field_ref= "BEN_FE"     name="BEN_FE"     />
+      <field field_ref= "BEN_C"      name="BEN_C"      />
+      <field field_ref= "BEN_SI"     name="BEN_SI"     />
+      <field field_ref= "BEN_CA"     name="BEN_CA"     />
+      <field field_ref= "DETC"       name="DETC"       />
+      <field field_ref= "SDC__100"   name="SDC__100"   />
+      <field field_ref= "SDC__200"   name="SDC__200"   />
+      <field field_ref= "SDC__500"   name="SDC__500"   />
+      <field field_ref= "SDC_1000"   name="SDC_1000"   />
+      <field field_ref= "INVTC"      name="INVTC"      />
+      <field field_ref= "INVTALK"    name="INVTALK"    />
+      <field field_ref= "INVTO2"     name="INVTO2"     />
+      <field field_ref= "LYSO_CA"    name="LYSO_CA"    />
+      <field field_ref= "COM_RESP"   name="COM_RESP"   />
+      <field field_ref= "PN_LLOSS"   name="PN_LLOSS"   />
+      <field field_ref= "PD_LLOSS"   name="PD_LLOSS"   />
+      <field field_ref= "ZI_LLOSS"   name="ZI_LLOSS"   />
+      <field field_ref= "ZE_LLOSS"   name="ZE_LLOSS"   />
+      <field field_ref= "ZI_MES_N"   name="ZI_MES_N"   />
+      <field field_ref= "ZI_MES_D"   name="ZI_MES_D"   />
+      <field field_ref= "ZI_MES_C"   name="ZI_MES_C"   />
+      <field field_ref= "ZI_MESDC"   name="ZI_MESDC"   />
+      <field field_ref= "ZI_EXCR"    name="ZI_EXCR"    />
+      <field field_ref= "ZI_RESP"    name="ZI_RESP"    />
+      <field field_ref= "ZI_GROW"    name="ZI_GROW"    />
+      <field field_ref= "ZE_MES_N"   name="ZE_MES_N"   />
+      <field field_ref= "ZE_MES_D"   name="ZE_MES_D"   />
+      <field field_ref= "ZE_MES_C"   name="ZE_MES_C"   />
+      <field field_ref= "ZE_MESDC"   name="ZE_MESDC"   />
+      <field field_ref= "ZE_EXCR"    name="ZE_EXCR"    />
+      <field field_ref= "ZE_RESP"    name="ZE_RESP"    />
+      <field field_ref= "ZE_GROW"    name="ZE_GROW"    />
+      <field field_ref= "MDETC"      name="MDETC"      />
+      <field field_ref= "GMIDC"      name="GMIDC"      />
+      <field field_ref= "GMEDC"      name="GMEDC"      />
+      <field field_ref= "INT_ZMI"    name="INT_ZMI"    />
+      <field field_ref= "INT_ZME"    name="INT_ZME"    />
+      <field field_ref= "INT_DET"    name="INT_DET"    />
+      <field field_ref= "INT_DTC"    name="INT_DTC"    />
+    </field_group>
+
+    <field_group id="groupMEDUSA_3dd" >
+      <field field_ref= "TPP3"       name="TPP3"       />
+      <field field_ref= "DETFLUX3"   name="DETFLUX3"   />
+      <field field_ref= "REMIN3N"    name="REMIN3N"    />
+      <field field_ref= "PH3"        name="PH3"        />
+      <field field_ref= "OM_CAL3"    name="OM_CAL3"    /> 
+    </field_group>
+
+    <field_group id="groupMEDUSA_dms" >
+      <field field_ref= "DMS_SURF"   name="DMS_SURF"   />
+      <field field_ref= "DMS_ANDR"   name="DMS_ANDR"   />
+      <field field_ref= "DMS_SIMO"   name="DMS_SIMO"   />
+      <field field_ref= "DMS_ARAN"   name="DMS_ARAN"   />
+      <field field_ref= "DMS_HALL"   name="DMS_HALL"   />
+    </field_group>
+
+    <field_group id="groupMEDUSA_riv" >
+      <field field_ref= "RUNOFF"     name="RUNOFF"     />
+      <field field_ref= "RIV_N"      name="RIV_N"      />
+      <field field_ref= "RIV_SI"     name="RIV_SI"     />
+      <field field_ref= "RIV_C"      name="RIV_C"      />
+      <field field_ref= "RIV_ALK"    name="RIV_ALK"    />
+    </field_group>
+
+    <field_group id="groupMEDUSA_cmip6" >
+      <field field_ref= "epC100"     name="epC100"     />
+      <field field_ref= "epCALC100"  name="epCALC100"  />
+      <field field_ref= "epN100"     name="epN100"     />
+      <field field_ref= "epSI100"    name="epSI100"    />
+      <field field_ref= "FGCO2"      name="FGCO2"      />
+      <field field_ref= "INTDISSIC"  name="INTDISSIC"  />
+      <field field_ref= "INTDISSIN"  name="INTDISSIN"  />
+      <field field_ref= "INTDISSISI" name="INTDISSISI" />
+      <field field_ref= "INTALK"     name="INTALK"     />
+      <field field_ref= "O2min"      name="O2min"      />
+      <field field_ref= "ZO2min"     name="ZO2min"     />
+      <field field_ref= "TPPD3"      name="TPPD3"      />
+      <field field_ref= "BDDTALK3"   name="BDDTALK3"   />
+      <field field_ref= "BDDTDIC3"   name="BDDTDIC3"   />
+      <field field_ref= "BDDTIFE3"   name="BDDTIFE3"   />
+      <field field_ref= "BDDTDIN3"   name="BDDTDIN3"   />
+      <field field_ref= "BDDTDISI3"  name="BDDTDISI3"  />
+      <field field_ref= "FD_NIT3"    name="FD_NIT3"    />
+      <field field_ref= "FD_SIL3"    name="FD_SIL3"    />
+      <field field_ref= "FD_CAR3"    name="FD_CAR3"    />
+      <field field_ref= "FD_CAL3"    name="FD_CAL3"    />
+      <field field_ref= "CO33"       name="CO33"       />
+      <field field_ref= "CO3SATARG3" name="CO3SATARG3" />
+      <field field_ref= "CO3SATCAL3" name="CO3SATCAL3" />
+      <field field_ref= "DCALC3"     name="DCALC3"     />
+      <field field_ref= "EXPC3"      name="EXPC3"      />
+      <field field_ref= "EXPN3"      name="EXPN3"      />
+      <field field_ref= "FEDISS3"    name="FEDISS3"    />
+      <field field_ref= "FESCAV3"    name="FESCAV3"    />
+      <field field_ref= "MIGRAZP3"   name="MIGRAZP3"   />
+      <field field_ref= "MIGRAZD3"   name="MIGRAZD3"   />
+      <field field_ref= "MEGRAZP3"   name="MEGRAZP3"   />
+      <field field_ref= "MEGRAZD3"   name="MEGRAZD3"   />
+      <field field_ref= "MEGRAZZ3"   name="MEGRAZZ3"   />
+      <field field_ref= "O2SAT3"     name="O2SAT3"     />
+      <field field_ref= "PBSI3"      name="PBSI3"      />
+      <field field_ref= "PCAL3"      name="PCAL3"      />
+      <field field_ref= "REMOC3"     name="REMOC3"     />
+      <field field_ref= "PNLIMJ3"    name="PNLIMJ3"    />
+      <field field_ref= "PNLIMN3"    name="PNLIMN3"    />
+      <field field_ref= "PNLIMFE3"   name="PNLIMFE3"   />
+      <field field_ref= "PDLIMJ3"    name="PDLIMJ3"    />
+      <field field_ref= "PDLIMN3"    name="PDLIMN3"    />
+      <field field_ref= "PDLIMFE3"   name="PDLIMFE3"   />
+      <field field_ref= "PDLIMSI3"   name="PDLIMSI3"   />
+    </field_group>
+
+</field_definition>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/iodef_medusa_et_al.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/iodef_medusa_et_al.xml	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/XIOS2/iodef_medusa_et_al.xml	(revision 9987)
@@ -0,0 +1,310 @@
+<!-- GO6.0 version of the XIOS namelist -->
+<!-- XIOS version 2 -->
+<?xml version="1.0"?>
+
+<simulation> 
+
+ <context id="nemo">
+    
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+    <field_definition src="./field_def_bgc.xml"/>
+    <field_definition src="./field_def.xml"/>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->
+     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+
+      <file_group id="10d" output_freq="10d" output_level="10" enabled=".TRUE."/> <!-- 10d files -->
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE.">   <!-- 1m files -->   
+
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"          name="e3t"        standard_name="cell_thickness" />
+          <field field_ref="toce"         name="votemper"        operation="average" freq_op="1mo" > @toce_e3t / @e3t </field>
+          <field field_ref="toce"         name="votemper2"       operation="average" freq_op="1mo" > @toce2_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"        operation="average" freq_op="1mo" > @soce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline2"       operation="average" freq_op="1mo" > @soce2_e3t / @e3t </field>
+          <field field_ref="ttrd_totad"   name="opottempadvect"  operation="average" freq_op="1mo" > @ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_iso"     name="opottemppmdiff"  operation="average" freq_op="1mo" > @ttrd_iso_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_zdfp"    name="opottempdiff"    operation="average" freq_op="1mo" > @ttrd_zdfp_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_evd"     name="ttrd_evd"        operation="average" freq_op="1mo" > @ttrd_evd_e3t / @e3t </field>
+          <field field_ref="ttrd_qns"     name="ttrd_qns"        operation="average" freq_op="1mo" > @ttrd_qns_e3t / @e3t_surf </field>
+          <field field_ref="ttrd_qsr"     name="rsdoabsorb"      operation="average" freq_op="1mo" > @ttrd_qsr_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_bbl"     name="ttrd_bbl"        operation="average" freq_op="1mo" > @ttrd_bbl_e3t / @e3t </field>
+          <field field_ref="ttrd_tot"     name="opottemptend"    operation="average" freq_op="1mo" > @ttrd_tot_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="strd_totad"   name="osaltadvect"     operation="average" freq_op="1mo" > @strd_totad_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_iso"     name="osaltpmdiff"     operation="average" freq_op="1mo" > @strd_iso_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_zdfp"    name="osaltdiff"       operation="average" freq_op="1mo" > @strd_zdfp_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_evd"     name="strd_evd"        operation="average" freq_op="1mo" > @strd_evd_e3t / @e3t </field>
+          <field field_ref="strd_tot"     name="osalttend"       operation="average" freq_op="1mo" > @strd_tot_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_bbl"     name="strd_bbl"        operation="average" freq_op="1mo" > @strd_bbl_e3t / @e3t </field>
+	  <field field_ref="ssh"          name="sossheig"   standard_name="sea_surface_height_above_geoid"                          />
+          <field field_ref="ssh2"         name="zossq"      standard_name="square_of_sea_surface_height_above_geoid"                />
+	  <field field_ref="empmr"        name="sowaflup"   standard_name="water_flux_out_of_sea_ice_and_sea_water"                 />
+	  <field field_ref="saltflx"      name="sosafldo"   standard_name="salt_flux_into_sea_water"                                />
+	  <field field_ref="qt"           name="sohefldo"   standard_name="surface_downward_heat_flux_in_sea_water"                 />
+	  <field field_ref="qsr"          name="soshfldo"   standard_name="downwelling_photosynthetic_radiative_flux_in_sea_water"               />
+          <field field_ref="mldkz5"       name="somixhgt"   standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity"   />
+          <field field_ref="mldr10_1"     name="somxl010"   standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"      />
+          <field field_ref="mldzint_1"    name="sokaraml"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="mldzint_2"    name="somlddbm"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="ice_cover"    name="soicecov"   standard_name="sea_ice_area_fraction"                                   />
+          <field field_ref="wspd"         name="sowindsp"   standard_name="wind_speed"                                              />          
+          <field field_ref="qhcisf"       name="sohflisf"   standard_name="ice_shelf_heat_flux"                                                        />
+          <field field_ref="qlatisf"      name="soqlatisf"  standard_name="ice_shelf_latent_heat_flux"                                                        />
+          <field field_ref="fwfisf"       name="sowflisf"   standard_name="ice_shelf_melting"                                                        />
+          <field field_ref="berg_total_melt"       name="berg_total_melt"          standard_name=""                                 />
+          <field field_ref="berg_total_heat_flux"  name="berg_total_heat_flux"     standard_name=""                                 />
+          <field field_ref="runoffs"       name="sorunoff"    standard_name="water_flux_into_sea_water_from_rivers"                 />
+          <field field_ref="hflx_rain_cea" name="hfrainds"    standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"/>
+          <field field_ref="hflx_evap_cea" name="hfevapds"    standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"/>
+          <field field_ref="evap_ao_cea"   name="evap_ao_cea" standard_name="water_evaporation_flux"                                />
+          <field field_ref="rain"          name="pr"          standard_name="rainfall_flux"                                         />
+          <field field_ref="snowpre"       name="snowpre"     standard_name="snowfall_flux"                                         />
+          <field field_ref="snow_ao_cea"   name="snow_ao_cea" standard_name="snowfall_flux_over_ocean"                              />
+          <field field_ref="snow_ai_cea"   name="snow_ai_cea" standard_name="snowfall_flux_over_sea_ice"                            />
+	</file>
+	
+	<file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="e3u"          name="e3u"        standard_name="cell_thickness" />
+          <field field_ref="uoce"         name="vozocrtx"     operation="average" freq_op="1mo" > @uoce_e3u / @e3u </field>
+          <field field_ref="uoce"         name="vozocrtx2"    operation="average" freq_op="1mo" > @uoce2_e3u / @e3u </field>
+          <field field_ref="ut"           name="ut"           operation="average" freq_op="1mo" > @ut_e3u / @e3u </field>
+          <field field_ref="us"           name="us"           operation="average" freq_op="1mo" > @us_e3u / @e3u </field>
+	  <field field_ref="utau"         name="sozotaux"   standard_name="surface_downward_x_stress" />
+	</file>
+	
+	<file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="e3v"          name="e3v"        standard_name="cell_thickness" />
+          <field field_ref="voce"         name="vomecrty"     operation="average" freq_op="1mo" > @voce_e3v / @e3v </field>
+          <field field_ref="voce"         name="vomecrty2"    operation="average" freq_op="1mo" > @voce2_e3v / @e3v </field>
+          <field field_ref="vt"           name="vt"           operation="average" freq_op="1mo" > @vt_e3v / @e3v </field>
+          <field field_ref="vs"           name="vs"           operation="average" freq_op="1mo" > @vs_e3v / @e3v </field>
+	  <field field_ref="vtau"         name="sometauy"   standard_name="surface_downward_y_stress" />
+	</file>
+	
+	<file id="file4" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="woce"         name="vovecrtz"   standard_name="upward_sea_water_velocity"                         />
+          <field field_ref="wt"           name="wt"         standard_name=""                                                  />
+          <field field_ref="ws"           name="ws"         standard_name=""                                                  />
+	  <field field_ref="avt"          name="votkeavt"   standard_name="ocean_vertical_heat_diffusivity"                   />
+          <field field_ref="avm"          name="votkeavm"   standard_name="ocean_vertical_momentum_diffusivity"               />
+          <field field_ref="aht2d"        name="soleahtw"   standard_name="vertical_component_of_ocean_xy_tracer_diffusivity" />
+	</file>
+        
+        <file id="file5" name_suffix="_diaptr" description="processed diagnostics" >
+	  <field field_ref="zomsfglo"     name="zomsfglo"   standard_name="meridional_streamfunction_global"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemglo"     name="zotemglo"   standard_name="zonal_mean_temperature_global"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfglo"     name="zosrfglo"   standard_name="zonal_mean_surface_global"                  grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalglo"     name="zosalglo"   standard_name="zonal_mean_salinity_global"                 grid_ref="gznl_T_3D"       />          
+          <field field_ref="zomsfatl"     name="zomsfatl"   standard_name="meridional_streamfunction_atlantic"         grid_ref="gznl_W_3D"       />
+          <field field_ref="zotematl"     name="zotematl"   standard_name="zonal_mean_temperature_atlantic"            grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfatl"     name="zosrfatl"   standard_name="zonal_mean_surface_atlantic"                grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalatl"     name="zosalatl"   standard_name="zonal_mean_salinity_atlantic"               grid_ref="gznl_T_3D"       />          
+          <field field_ref="zomsfpac"     name="zomsfpac"   standard_name="meridional_streamfunction_pacific"          grid_ref="gznl_W_3D"       />
+          <field field_ref="zotempac"     name="zotempac"   standard_name="zonal_mean_temperature_pacific"             grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfpac"     name="zosrfpac"   standard_name="zonal_mean_surface_pacific"                 grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalpac"     name="zosalpac"   standard_name="zonal_mean_salinity_pacific"                grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfind"     name="zomsfind"   standard_name="meridional_streamfunction_indian"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemind"     name="zotemind"   standard_name="zonal_mean_temperature_indian"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfind"     name="zosrfind"   standard_name="zonal_mean_surface_indian"                  grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalind"     name="zosalind"   standard_name="zonal_mean_salinity_indian"                 grid_ref="gznl_T_3D"       />          
+          <field field_ref="zomsfipc"     name="zomsfipc"   standard_name="meridional_streamfunction_indian_pacific"   grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemipc"     name="zotemipc"   standard_name="zonal_mean_temperature_indian_pacific"      grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfipc"     name="zosrfipc"   standard_name="zonal_mean_surface_indian_pacific"          grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalipc"     name="zosalipc"   standard_name="zonal_mean_salinity_indian_pacific"         grid_ref="gznl_T_3D"       />          
+          <field field_ref="sophtadv"     name="sophtadv"   standard_name="advective_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv"     name="sopstadv"   standard_name="advective_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf"     name="sophtldf"   standard_name="diffusive_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf"     name="sopstldf"   standard_name="diffusive_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_atl" name="sophtadv_atl"   standard_name="advective_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_atl" name="sopstadv_atl"   standard_name="advective_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_atl" name="sophtldf_atl"   standard_name="diffusive_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_atl" name="sopstldf_atl"   standard_name="diffusive_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_pac" name="sophtadv_pac"   standard_name="advective_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_pac" name="sopstadv_pac"   standard_name="advective_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_pac" name="sophtldf_pac"   standard_name="diffusive_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_pac" name="sopstldf_pac"   standard_name="diffusive_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ind" name="sophtadv_ind"   standard_name="advective_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ind" name="sopstadv_ind"   standard_name="advective_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ind" name="sophtldf_ind"   standard_name="diffusive_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ind" name="sopstldf_ind"   standard_name="diffusive_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ipc" name="sophtadv_ipc"   standard_name="advective_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ipc" name="sopstadv_ipc"   standard_name="advective_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ipc" name="sophtldf_ipc"   standard_name="diffusive_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ipc" name="sopstldf_ipc"   standard_name="diffusive_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+	</file>
+
+        <file id="file6" name_suffix="_ptrc_T" description="Medusa sms variables" >
+          <field_group group_ref="groupMEDUSA" />
+          <field_group group_ref="groupIDTRA" />
+          <field_group group_ref="groupCFC" />
+          <field_group group_ref="groupAGE" />
+        </file>
+
+        <file id="file7" name_suffix="_diad_T" description="Medusa diagnostic variables" >
+          <field_group group_ref="groupMEDUSA_dia" />
+          <field_group group_ref="groupMEDUSA_3dd" />
+          <field_group group_ref="groupMEDUSA_dms" />
+          <field_group group_ref="groupIDTRA_dia" />
+          <field_group group_ref="groupCFC_dia" />
+          <field_group group_ref="groupMEDUSA_cmip6" />
+        </file>
+
+      </file_group>
+
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
+    <!-- 
+============================================================================================================
+= grid definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+    
+   <axis_definition>
+      <axis id="deptht" standard_name="depth" long_name="Vertical T levels" unit="m" positive="down" />
+      <axis id="depthu" standard_name="depth" long_name="Vertical U levels" unit="m" positive="down" />
+      <axis id="depthv" standard_name="depth" long_name="Vertical V levels" unit="m" positive="down" />
+      <axis id="depthw" standard_name="depth" long_name="Vertical W levels" unit="m" positive="down" />
+      <axis id="nfloat" long_name="Float number"      unit="-"  />
+      <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
+      <axis id="ncatice" long_name="Ice category"       unit="1"               />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"            />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"            />
+      <axis id="deptht_surface" axis_ref="deptht" >
+         <zoom_axis begin=" 1 " n=" 1 " />
+      </axis>
+
+   </axis_definition>
+    
+   <domain_definition src="./domain_def.xml"/>
+   
+    <grid_definition>
+        <!--  -->
+       <grid id="grid_T_2D" >
+         <domain id="grid_T" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_3D_ncatice" >
+         <domain id="grid_T" />
+         <axis id="ncatice" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_3D" >
+         <domain id="grid_T" />
+         <axis id="deptht" />
+       </grid>
+        <!--  -->
+       <grid id="grid_U_2D" >
+         <domain id="grid_U" />
+       </grid>
+        <!--  -->
+       <grid id="grid_U_3D" >
+         <domain id="grid_U" />
+         <axis id="depthu" />
+       </grid>
+        <!--  -->
+       <grid id="grid_V_2D" >
+         <domain id="grid_V" />
+       </grid>
+        <!--  -->
+       <grid id="grid_V_3D" >
+         <domain id="grid_V" />
+         <axis id="depthv" />
+       </grid>
+        <!--  -->
+       <grid id="grid_W_2D" >
+         <domain id="grid_W" />
+       </grid>
+        <!--  -->
+       <grid id="grid_W_3D" >
+         <domain id="grid_W" />
+         <axis id="depthw" />
+       </grid>
+        <!--  -->
+       <grid id="grid_1point" >
+         <domain id="1point"/>
+       </grid>
+        <!--  -->
+       <grid id="grid_T_nfloat" >
+         <domain id="grid_T" />
+         <axis id="nfloat" />
+       </grid>
+        <!--  -->
+       <grid id="grid_EqT" >
+         <domain id="EqT" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_T_2D">
+         <domain id="ptr" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_T_3D">
+         <domain id="ptr" />
+         <axis id="deptht" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_W_2D">
+         <domain id="ptr" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_W_3D">
+         <domain id="ptr" />
+         <axis id="depthw" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_surface_extract">
+         <domain domain_ref="grid_T" />
+         <axis   axis_ref="deptht_surface" />
+       </grid>
+
+    </grid_definition>
+  </context>
+  
+
+  <context id="xios">
+
+      <variable_definition>
+	
+	  <variable id="info_level"            type="int">0</variable>
+	  <variable id="using_server"          type="bool">false</variable>
+	  <variable id="using_oasis"           type="bool">true</variable>
+	  <variable id="oasis_codes_id"        type="string" >toyoce</variable>
+	
+      </variable_definition>
+               
+  </context>
+  
+</simulation>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/cfc1112sf6.atm
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/cfc1112sf6.atm	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/cfc1112sf6.atm	(revision 9987)
@@ -0,0 +1,92 @@
+% Atmospheric lifetimes are   44 for CFC-11
+%                       and  125 for CFC-12
+%			and 1278 for SF6    (Kovacs et al., 2017)
+% rel=  0
+%        <-Northern Data->       <-Southern Data->
+% Year  CFC-11  CFC-12  SF6     CFC-11  CFC-12  SF6
+%       (ppt)   (ppt)   (ppt)   (ppt)   (ppt)   (ppt)
+1931.5	 0.00	 0.00	 0.00	 0.00	 0.00	 0.00
+1932.5	 0.00	 0.00	 0.00	 0.00	 0.00	 0.00
+1933.5	 0.00	 0.00	 0.00	 0.00	 0.00	 0.00
+1934.5	 0.00	 0.00	 0.00	 0.00	 0.00	 0.00
+1935.5	 0.00	 0.00	 0.00	 0.00	 0.00	 0.00
+1936.5	 0.00	 0.10	 0.00	 0.00	 0.00	 0.00
+1937.5	 0.00	 0.10	 0.00	 0.00	 0.10	 0.00
+1938.5	 0.00	 0.20	 0.00	 0.00	 0.10	 0.00
+1939.5	 0.00	 0.30	 0.00	 0.00	 0.20	 0.00
+1940.5	 0.00	 0.40	 0.00	 0.00	 0.30	 0.00
+1941.5	 0.00	 0.50	 0.00	 0.00	 0.40	 0.00
+1942.5	 0.00	 0.70	 0.00	 0.00	 0.50	 0.00
+1943.5	 0.00	 0.90	 0.00	 0.00	 0.70	 0.00
+1944.5	 0.00	 1.20	 0.00	 0.00	 0.90	 0.00
+1945.5	 0.10	 1.70	 0.00	 0.00	 1.20	 0.00
+1946.5	 0.10	 2.30	 0.00	 0.10	 1.70	 0.00
+1947.5	 0.10	 3.40	 0.00	 0.10	 2.40	 0.00
+1948.5	 0.20	 4.80	 0.00	 0.10	 3.40	 0.00
+1949.5	 0.40	 6.10	 0.00	 0.20	 4.70	 0.00
+1950.5	 0.70	 7.60	 0.00	 0.40	 6.00	 0.00
+1951.5	 1.01	 9.20	 0.00	 0.70	 7.40	 0.00
+1952.5	 1.51	11.00	 0.00	 1.01	 9.00	 0.00
+1953.5	 2.21	12.80	 0.04	 1.51	10.70	 0.04
+1954.5	 3.02	15.00	 0.04	 2.21	12.60	 0.04
+1955.5	 4.12	17.40	 0.04	 3.02	14.70	 0.04
+1956.5	 5.33	20.20	 0.04	 4.02	17.10	 0.04
+1957.5	 6.83	23.40	 0.05	 5.23	19.90	 0.04
+1958.5	 8.14	26.80	 0.05	 6.53	23.00	 0.04
+1959.5	 9.45	30.50	 0.05	 7.84	26.30	 0.05
+1960.5	11.06	35.00	 0.05	 9.15	30.10	 0.05
+1961.5	13.27	40.00	 0.06	10.85	34.40	 0.06
+1962.5	16.18	45.80	 0.07	13.07	39.40	 0.06
+1963.5	19.60	52.50	 0.08	15.78	45.10	 0.07
+1964.5	23.72	60.40	 0.09	19.20	51.80	 0.08
+1965.5	28.44	69.30	 0.11	23.12	59.50	 0.10
+1966.5	33.67	79.20	 0.13	27.64	68.20	 0.12
+1967.5	39.40	90.30	 0.15	32.66	77.90	 0.14
+1968.5	46.03	102.80	 0.18	38.29	88.80	 0.17
+1969.5	53.77	116.80	 0.21	44.82	101.10	 0.19
+1970.5	62.41	132.00	 0.23	52.26	114.70	 0.22
+1971.5	72.06	148.40	 0.26	60.70	129.60	 0.24
+1972.5	82.71	166.10	 0.30	69.95	145.70	 0.28
+1973.5	94.87	185.80	 0.34	80.40	163.30	 0.31
+1974.5	108.34	207.10	 0.38	92.16	182.50	 0.35
+1975.5	121.41	228.20	 0.44	104.72	202.90	 0.40
+1976.5	133.97	248.10	 0.50	117.09	223.20	 0.46
+1977.5	145.93	266.90	 0.58	129.35	242.70	 0.53
+1978.5	156.58	284.30	 0.66	140.80	261.20	 0.61
+1979.5	168.34	306.10	 0.76	148.74	273.50	 0.70
+1980.5	176.68	323.20	 0.88	159.30	292.30	 0.81
+1981.5	184.32	339.60	 1.00	167.84	308.80	 0.93
+1982.5	191.46	353.40	 1.13	176.08	325.50	 1.04
+1983.5	199.30	369.00	 1.27	184.52	342.60	 1.17
+1984.5	208.04	385.70	 1.40	192.46	359.40	 1.29
+1985.5	217.99	403.40	 1.55	202.01	378.20	 1.43
+1986.5	229.35	424.30	 1.71	211.36	396.50	 1.58
+1987.5	241.61	444.00	 1.88	222.21	416.30	 1.73
+1988.5	252.86	465.40	 2.05	233.27	435.80	 1.89
+1989.5	259.30	483.60	 2.22	242.11	454.40	 2.05
+1990.5	265.83	497.70	 2.41	251.06	472.70	 2.22
+1991.5	268.24	506.00	 2.62	256.68	487.30	 2.42
+1992.5	268.14	516.30	 2.85	260.80	498.30	 2.63
+1993.5	269.55	523.20	 3.09	262.51	507.00	 2.84
+1994.5	269.65	528.50	 3.33	263.72	514.80	 3.07
+1995.5	268.34	533.40	 3.58	263.22	521.00	 3.30
+1996.5	266.93	537.30	 3.86	262.91	526.50	 3.55
+1997.5	265.73	540.10	 4.07	262.01	530.80	 3.81
+1998.5	264.52	542.90	 4.25	261.01	534.30	 4.01
+1999.5	263.12	544.40	 4.48	259.90	537.20	 4.25
+2000.5	261.71	545.90	 4.68	258.29	539.00	 4.46
+2001.5	260.00	546.50	 4.90	256.98	540.60	 4.65
+2002.5	258.19	546.70	 5.14	255.08	541.30	 4.88
+2003.5	256.18	546.70	 5.37	253.27	541.60	 5.07
+2004.5	253.97	545.70	 5.58	251.36	541.50	 5.30
+2005.5	251.96	544.90	 5.80	249.15	540.70	 5.51
+2006.5	249.55	543.10	 6.04	247.34	539.80	 5.75
+2007.5	247.54	541.10	 6.33	245.03	538.10	 6.03
+2008.5	245.63	538.60	 6.62	243.12	536.20	 6.29
+2009.5	243.61	536.12	 6.89	241.05	533.47	 6.58
+2010.5	241.31	533.26	 7.21	239.15	531.03	 6.87
+2011.5	239.40	530.60	 7.46	236.84	528.53	 7.17
+2012.5	236.89	527.20	 7.73	234.77	526.00	 7.43
+2013.5	235.57	525.22	 8.09	232.88	523.25	 7.73
+2014.5	234.97	522.97	 8.40	231.49	521.00	 8.11
+2015.5	234.36	520.71	 8.72	230.09	518.74	 8.50
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/domain_def.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/domain_def.xml	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/domain_def.xml	(revision 9987)
@@ -1,157 +1,163 @@
 
    <domain_definition>
-      <domain_group id="grid_T">
-         <domain id="grid_T" long_name="grid T"/>
-	 <!--   My zoom: example of hand defined zoom   -->
-         <domain id="myzoom" zoom_ibegin="10" zoom_jbegin="10" zoom_ni="5" zoom_nj="5" />
-         <domain id="1point" zoom_ibegin="10" zoom_jbegin="10" zoom_ni="1" zoom_nj="1" />
+     <domain_group id="grid_T">
+       <domain id="grid_T" long_name="grid T"/>
+       <!--   My zoom: example of hand defined zoom   -->
+       <domain id="myzoom" domain_ref="grid_T" >
+	 <zoom_domain id="myzoom"  ibegin="10" jbegin="10" ni="5" nj="5" />
+       </domain>
+       <domain id="1point" domain_ref="grid_T" >
+	 <zoom_domain id="1point" ibegin="10" jbegin="10" ni="1" nj="1" />
+       </domain>
          <!--   Eq section   -->
-         <domain id="EqT" zoom_ibegin="1" zoom_jbegin="0000" zoom_ni="0000" zoom_nj="1" />
+         <domain id="EqT" domain_ref="grid_T" >
+	   <zoom_domain id="EqT" ibegin="1" jbegin="0000" ni="0000" nj="1" />
+	 </domain>
          <!--   TAO   -->
          <!--   137e   -->
-         <domain id="2n137eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n137eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n137eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   147e   -->
-         <domain id="0n147eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n147eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n147eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   156e   -->
-         <domain id="5s156eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s156eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n156eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n156eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n156eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n156eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   165e   -->
-         <domain id="8s165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n165eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   180w   -->
-         <domain id="8s180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n180wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   170w   -->
-         <domain id="8s170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n170wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   155w   -->
-         <domain id="8s155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n155wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   140w   -->
-         <domain id="8s140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n140wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   125w   -->
-         <domain id="8s125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n125wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   110w   -->
-         <domain id="8s110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n110wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   95w   -->
-         <domain id="8s95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2s95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="2n95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5n95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n95wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   RAMA   -->
-         <!--   55e   -->
-         <domain id="16s55eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12s55eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8s55eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4s55eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5s55eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n55eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5n55eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4n55eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-            <!--   65e   -->
-         <domain id="15n65eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-            <!--   67e   -->
-         <domain id="16s67eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12s67eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8s67eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4s67eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5s67eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n67eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5n67eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4n67eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n67eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   80.5e   -->
-         <domain id="16s80.5eT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12s80.5eT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8s80.5eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4s80.5eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5s80.5eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n80.5eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5n80.5eT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4n80.5eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   90e   -->
-         <domain id="1.5s90eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n90eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="1.5n90eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4n90eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n90eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12n90eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="15n90eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   95e   -->
-         <domain id="16s95eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12s95eT"    zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8s95eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="5s95eT"     zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   PIRATA   -->
-         <!--   38w-30w   -->
-         <domain id="19s34wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="14s32wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8s30wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n35wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4n38wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="8n38wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12n38wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="15n38wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="20n38wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   23w   -->
-         <domain id="0n23wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="4n23wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="12n23wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="21n23wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   10w   -->
-         <domain id="10s10wT" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="6s10wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <domain id="0n10wT"  zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
-         <!--   0e   -->
-         <domain id="0n0eT"   zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" />
+         <!-- <domain id="2n137eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n137eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n137eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   147e   -\-> -->
+         <!-- <domain id="0n147eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n147eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n147eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   156e   -\-> -->
+         <!-- <domain id="5s156eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s156eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n156eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n156eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n156eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n156eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   165e   -\-> -->
+         <!-- <domain id="8s165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n165eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   180w   -\-> -->
+         <!-- <domain id="8s180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n180wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   170w   -\-> -->
+         <!-- <domain id="8s170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n170wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   155w   -\-> -->
+         <!-- <domain id="8s155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n155wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   140w   -\-> -->
+         <!-- <domain id="8s140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n140wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   125w   -\-> -->
+         <!-- <domain id="8s125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n125wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   110w   -\-> -->
+         <!-- <domain id="8s110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n110wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   95w   -\-> -->
+         <!-- <domain id="8s95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2s95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="2n95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5n95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n95wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   RAMA   -\-> -->
+         <!-- <\!--   55e   -\-> -->
+         <!-- <domain id="16s55eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12s55eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8s55eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4s55eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5s55eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n55eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5n55eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4n55eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!--    <\!--   65e   -\-> -->
+         <!-- <domain id="15n65eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!--    <\!--   67e   -\-> -->
+         <!-- <domain id="16s67eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12s67eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8s67eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4s67eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5s67eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n67eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5n67eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4n67eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n67eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   80.5e   -\-> -->
+         <!-- <domain id="16s80.5eT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12s80.5eT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8s80.5eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4s80.5eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5s80.5eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n80.5eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5n80.5eT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4n80.5eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   90e   -\-> -->
+         <!-- <domain id="1.5s90eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n90eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="1.5n90eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4n90eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n90eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12n90eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="15n90eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   95e   -\-> -->
+         <!-- <domain id="16s95eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12s95eT"    domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8s95eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="5s95eT"     domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   PIRATA   -\-> -->
+         <!-- <\!--   38w-30w   -\-> -->
+         <!-- <domain id="19s34wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="14s32wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8s30wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n35wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4n38wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="8n38wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12n38wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="15n38wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="20n38wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   23w   -\-> -->
+         <!-- <domain id="0n23wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="4n23wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="12n23wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="21n23wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   10w   -\-> -->
+         <!-- <domain id="10s10wT" domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="6s10wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <domain id="0n10wT"  domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
+         <!-- <\!--   0e   -\-> -->
+         <!-- <domain id="0n0eT"   domain_ref="grid_T" zoom_ibegin="0000" zoom_jbegin="0000" zoom_ni="1" zoom_nj="1" /> -->
       </domain_group>
 
@@ -159,5 +165,7 @@
          <domain id="grid_U" long_name="grid U"/>
          <!--   Eq section   -->
-         <domain id="EqU" zoom_ibegin="1" zoom_jbegin="0000" zoom_ni="0000" zoom_nj="1" />
+         <domain id="EqU" domain_ref="grid_U" >
+	   <zoom_domain id="EqU" ibegin="1" jbegin="0000" ni="0000" nj="1" /> 
+	 </domain>    
       </domain_group>
 
@@ -166,9 +174,11 @@
          <domain id="grid_W" long_name="grid W"/>
          <!--   Eq section   -->
-         <domain id="EqW" zoom_ibegin="1" zoom_jbegin="0000" zoom_ni="0000" zoom_nj="1" />
+         <domain id="EqW" domain_ref="grid_W" >
+	   <zoom_domain id="EqW" ibegin="1" jbegin="0000" ni="0000" nj="1" />
+	 </domain>   
       </domain_group>
 
-      <domain_group id="scalarpoint"> 
-         <domain id="scalarpoint" long_name="scalar"/> 
+      <domain_group id="scalarpoint">
+         <domain id="scalarpoint" long_name="scalar"/>
          <!-- 
          <domain id="1point" zoom_ibegin="1" zoom_jbegin="1" zoom_ni="1" zoom_nj="1" /> 
@@ -177,7 +187,9 @@
 
       <domain_group id="gznl">
-         <domain id="ptr" long_name="zonal mean grid" zoom_ibegin="0000"  zoom_jbegin="1" zoom_ni="1" zoom_nj="0000" />
-      </domain_group>
-
+         <domain id="gznl" long_name="gznl"/>
+         <domain id="ptr" domain_ref="gznl" >
+	   <zoom_domain id="ptr" ibegin="0000" jbegin="0" ni="1" nj="0000" />
+	</domain>  
+        </domain_group>
 
    </domain_definition>    
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def.xml	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def.xml	(revision 9987)
@@ -11,5 +11,5 @@
 ============================================================================================================
     -->
-   <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+   <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" detect_missing_value="true"> <!-- time step automaticaly defined -->
 
     <!-- 
@@ -22,24 +22,41 @@
       
       <field_group id="grid_T" grid_ref="grid_T_2D" >
-         <field id="e3t"          long_name="T-cell thickness"   standard_name="cell_thickness"   unit="m"   grid_ref="grid_T_3D"/>
-
-         <field id="toce"         long_name="temperature"         standard_name="sea_water_potential_temperature"   unit="degC"     grid_ref="grid_T_3D"/>
-         <field id="toce_e3t"     long_name="temperature * e3t"                                                     unit="degC*m"   grid_ref="grid_T_3D" > toce * e3t </field >
-         <field id="soce"         long_name="salinity"            standard_name="sea_water_practical_salinity"      unit="1e-3"     grid_ref="grid_T_3D"/>
-         <field id="soce_e3t"     long_name="salinity * e3t"                                                        unit="1e-3*m"   grid_ref="grid_T_3D" > soce * e3t </field >
-
-         <field id="sst"          long_name="sea surface temperature"             standard_name="sea_surface_temperature"             unit="degC"     />
-         <field id="sst2"         long_name="square of sea surface temperature"   standard_name="square_of_sea_surface_temperature"   unit="degC2"     > sst * sst </field >
+         <field id="e3t"          long_name="Ocean Model cell Thickness"   standard_name="cell_thickness"   unit="m"   grid_ref="grid_T_3D"/>
+         <field id="e3t_surf"     field_ref="e3t"  long_name="T-cell thickness: surface layer"   standard_name="cell_thickness"   unit="m"  grid_ref="grid_T_surface_extract"/>
+         <field id="e3t_0"        long_name="Initial T-cell thickness"   standard_name="ref_cell_thickness"   unit="m"   grid_ref="grid_T_3D"/>
+
+         <field id="tinsitu"      long_name="in situ temperature" standard_name="in_situ_temperature"   unit="degC"     grid_ref="grid_T_3D"/>
+         <field id="sinsitu"      long_name="in situ salinity" standard_name="in_situ_salinity"   unit="1e-3"     grid_ref="grid_T_3D"/>
+         
+         <field id="toce"         long_name="Sea Water Potential Temperature"         standard_name="sea_water_potential_temperature"   unit="degree_C"     grid_ref="grid_T_3D"/>
+         <field id="toce_e3t"     long_name="temperature * e3t"                                                     unit="degree_C*m"   grid_ref="grid_T_3D" > toce * e3t </field >
+         <field id="toce2_e3t"    long_name="temperature squared * e3t"                                             unit="degC*degC*m"   grid_ref="grid_T_3D" > toce * toce * e3t </field >
+         <field id="soce"         long_name="Sea Water Salinity"            standard_name="sea_water_salinity"      unit="0.001"     grid_ref="grid_T_3D"/>
+         <field id="soce_e3t"     long_name="salinity * e3t"                                                        unit="0.001*m"   grid_ref="grid_T_3D" > soce * e3t </field >
+         <field id="soce2_e3t"    long_name="salinity squared * e3t"                                                unit="1e-3*1e-3*m"   grid_ref="grid_T_3D" > soce * soce * e3t </field >
+         <field id="toce_e3t_vsum" field_ref="toce_e3t" grid_ref="vert_sum" />
+         <field id="e3t_vsum" field_ref="e3t" grid_ref="vert_sum" />
+         <field id="toce_vmean" field_ref="toce_e3t_vsum" grid_ref="vert_sum"> toce_e3t_vsum/e3t_vsum </field>
+         <field id="toce_e3t_300" field_ref="toce_e3t"  unit="degree_C*m"   grid_ref="zoom_300" />
+         <field id="e3t_300" field_ref="e3t"  unit="degree_C*m"   grid_ref="zoom_300" />
+         <field id="toce_e3t_vsum300" field_ref="toce_e3t_300" grid_ref="zoom_300_sum" />
+         <field id="e3t_vsum300" field_ref="e3t_300" grid_ref="zoom_300_sum" />
+         <field id="toce_vmean300" field_ref="toce_e3t_vsum300" grid_ref="zoom_300_sum"> toce_e3t_vsum300/e3t_vsum300 </field>
+
+         <field id="sst"          long_name="Sea Surface Temperature"             standard_name="sea_surface_temperature"             unit="degree_C"     />
+         <field id="sst2"         long_name="Square of Sea Surface Temperature"   standard_name="square_of_sea_surface_temperature"   unit="degree_C2"     > sst * sst </field >
          <field id="sstmax"       long_name="max of sea surface temperature"   field_ref="sst"   operation="maximum"                                  />
          <field id="sstmin"       long_name="min of sea surface temperature"   field_ref="sst"   operation="minimum"                                  />
-         <field id="sstgrad"      long_name="module of sst gradient"                                                                  unit="degC/m"   />
-         <field id="sstgrad2"     long_name="square of module of sst gradient"                                                        unit="degC2/m2" />
-         <field id="sbt"          long_name="sea bottom temperature"                                                                  unit="degC"     />
+         <field id="sstgrad"      long_name="module of sst gradient"                                                                  unit="degree_C/m"   />
+         <field id="sstgrad2"     long_name="square of module of sst gradient"                                                        unit="degree_C2/m2" />
+         <field id="sbt"          long_name="sea bottom temperature"                                                                  unit="degree_C"     />
+         <field id="tosmint"      long_name="vertical integral of temperature times density"   standard_name="integral_wrt_depth_of_product_of_density_and_potential_temperature"  unit="(kg m2) degree_C" />
 	 
-         <field id="sss"          long_name="sea surface salinity"             standard_name="sea_surface_salinity"   unit="1e-3" />
+         <field id="sss"          long_name="Sea Surface Salinity"             standard_name="sea_surface_salinity"   unit="0.001" />
          <field id="sss2"         long_name="square of sea surface salinity"                                          unit="1e-6"  > sss * sss </field >
          <field id="sssmax"       long_name="max of sea surface salinity"   field_ref="sss"   operation="maximum"                 />
          <field id="sssmin"       long_name="min of sea surface salinity"   field_ref="sss"   operation="minimum"                 />
-         <field id="sbs"          long_name="sea bottom salinity"                                                     unit="1e-3" />
+         <field id="sbs"          long_name="sea bottom salinity"                                                     unit="0.001" />
+         <field id="somint"       long_name="vertical integral of salinity times density"   standard_name="integral_wrt_depth_of_product_of_density_and_salinity"  unit="(kg m2) x (1e-3)" /> 
 
          <field id="taubot"       long_name="bottom stress module"                                                    unit="N/m2" /> 
@@ -53,11 +70,20 @@
          <field id="mldr10_1max"  long_name="Max of Mixed Layer Depth (dsigma = 0.01 wrt 10m)"   field_ref="mldr10_1"   operation="maximum"                                                                          />
          <field id="mldr10_1min"  long_name="Min of Mixed Layer Depth (dsigma = 0.01 wrt 10m)"   field_ref="mldr10_1"   operation="minimum"                                                                          />
+         <field id="mldzint_1"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_2"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_3"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_4"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_5"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldhtc_1"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_2"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_3"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_4"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_5"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
          <field id="heatc"        long_name="Heat content vertically integrated"                 standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
-         <field id="saltc"        long_name="Salt content vertically integrated"                                                                                                                   unit="1e-3*kg/m2" />
+         <field id="saltc"        long_name="Salt content vertically integrated"                                                                                                                   unit="0.001*kg/m2" />
 
          <!-- EOS -->
-         <field id="alpha"        long_name="thermal expansion"                                                         unit="degC-1" grid_ref="grid_T_3D" />
+         <field id="alpha"        long_name="thermal expansion"                                                         unit="degree_C-1" grid_ref="grid_T_3D" />
          <field id="beta"         long_name="haline contraction"                                                        unit="1e3"    grid_ref="grid_T_3D" />
-         <field id="bn2"          long_name="squared Brunt-Vaisala frequency"                                           unit="s-1"    grid_ref="grid_T_3D" />
          <field id="rhop"         long_name="potential density (sigma0)"        standard_name="sea_water_sigma_theta"   unit="kg/m3"  grid_ref="grid_T_3D" />
 
@@ -78,16 +104,25 @@
          <field id="pycndep"      long_name="Pycnocline Depth (dsigma[dT=-0.2] wrt 10m)"     standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"                         />
          <field id="BLT"          long_name="Barrier Layer Thickness"                                                                                                                          unit="m"                          > topthdep - pycndep </field>
-         <field id="tinv"         long_name="Max of vertical invertion of temperature"                                                                                                         unit="degC"                      />
+         <field id="tinv"         long_name="Max of vertical invertion of temperature"                                                                                                         unit="degree_C"                      />
          <field id="depti"        long_name="Depth of max. vert. inv. of temperature"                                                                                                          unit="m"                         />
-         <field id="20d"          long_name="Depth of 20C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"      axis_ref="iax_20C" />
-         <field id="28d"          long_name="Depth of 28C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"      axis_ref="iax_28C" />
+         <field id="20d"          long_name="Depth of 20C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"       />
+         <field id="28d"          long_name="Depth of 28C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"       />
          <field id="hc300"        long_name="Heat content 0-300m"                            standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"                      />
 
          <!-- variables available with key_diaar5 -->
-         <field id="botpres"      long_name="Pressure at sea floor"   standard_name="sea_water_pressure_at_sea_floor"   unit="dbar" />
+         <field id="botpres"      long_name="Sea Water Pressure at Sea Floor"   standard_name="sea_water_pressure_at_sea_floor"   unit="dbar" />
+         <field id="sshdyn"       long_name="dynamic sea surface height"     standard_name="dynamic_sea_surface_height_above_geoid"     unit="m" />
+         <field id="sshdyn2"      long_name="square of dynamic sea surface height"     standard_name="dynamic_sea_surface_height_above_geoid_squared"     unit="m2" > sshdyn * sshdyn </field>
+         <field id="tnpeo"       long_name="Tendency of ocean potential energy content"          unit="W/m2"                           />
+
 
          <!-- variables available with key_vvl -->
          <field id="tpt_dep"      long_name="T-point depth"                  standard_name="depth_below_geoid"   unit="m"   grid_ref="grid_T_3D" />
+         <field id="wpt_dep"      long_name="W-point depth"                  standard_name="depth_below_geoid"   unit="m"   grid_ref="grid_W_3D" />
          <field id="e3tdef"       long_name="T-cell thickness deformation"                                       unit="%"   grid_ref="grid_T_3D" />
+
+         <!-- AGE : variables available with key_age -->
+         <field id="Age"        long_name="Sea Water Age Since Surface contact" standard_name="sea_water_age_since_surface_contact"  unit="yr" grid_ref="grid_T_3D"   />
+         <field id="Age_e3t"    long_name="Age * e3t"                                 unit="yr * m"  > Age * e3t </field >
       </field_group>
 
@@ -174,8 +209,11 @@
       <field_group id="SBC" grid_ref="grid_T_2D" > <!-- time step automaticaly defined based on nn_fsbc -->
          <field id="empmr"        long_name="Net Upward Water Flux"                standard_name="water_flux_out_of_sea_ice_and_sea_water"                              unit="kg/m2/s"   />
-         <field id="saltflx"      long_name="Downward salt flux"                                                                                                        unit="1e-3/m2/s" />
+         <field id="empbmr"       long_name="Net Upward Water Flux at pre. tstep"  standard_name="water_flux_out_of_sea_ice_and_sea_water"                              unit="kg/m2/s"   />
+         <field id="emp_oce"      long_name="Evap minus Precip over ocean"         standard_name="evap_minus_precip_over_sea_water"                                     unit="kg/m2/s"   />
+         <field id="emp_ice"      long_name="Evap minus Precip over ice"           standard_name="evap_minus_precip_over_sea_ice"                                       unit="kg/m2/s"   />
+         <field id="saltflx"      long_name="Downward salt flux"                                                                                                        unit="0.001/m2/s" />
          <field id="fmmflx"       long_name="Water flux due to freezing/melting"                                                                                        unit="kg/m2/s"   />
          <field id="snowpre"      long_name="Snow precipitation"                   standard_name="snowfall_flux"                                                        unit="kg/m2/s"   />
-         <field id="runoffs"      long_name="River Runoffs"                        standard_name="water_flux_into_sea_water_from_rivers"                                unit="kg/m2/s"   />
+         <field id="runoffs"      long_name="Water Flux into Sea Water From Rivers" standard_name="water_flux_into_sea_water_from_rivers"                                unit="kg/m2/s"   />
          <field id="precip"       long_name="Total precipitation"                  standard_name="precipitation_flux"                                                   unit="kg/m2/s"   />
  
@@ -193,10 +231,15 @@
 
          <!-- * variable related to ice shelf forcing * -->
+         <field id="berg_calve"   long_name="Iceberg calving"                               unit="kg/m2/s"  />
          <field id="fwfisf"       long_name="Ice shelf melting"                             unit="kg/m2/s"  />
-         <field id="qisf"         long_name="Ice Shelf Heat Flux"                           unit="W/m2"     />
+         <field id="fwfisf3d"     long_name="Ice shelf melting"                             unit="kg/m2/s"  grid_ref="grid_T_3D" />
+         <field id="qlatisf"      long_name="Ice shelf latent heat flux"                    unit="W/m2"     />
+         <field id="qlatisf3d"    long_name="Ice shelf latent heat flux"                    unit="W/m2"     grid_ref="grid_T_3D" />
+         <field id="qhcisf"       long_name="Ice shelf heat content flux"                   unit="W/m2"     />
+         <field id="qhcisf3d"     long_name="Ice shelf heat content flux"                   unit="W/m2"     grid_ref="grid_T_3D" />
          <field id="isfgammat"    long_name="transfert coefficient for isf (temperature)"   unit="m/s"      />
          <field id="isfgammas"    long_name="transfert coefficient for isf (salinity)"      unit="m/s"      />
-         <field id="stbl"         long_name="salinity in the Losh tbl"                      unit="1e-3"     />
-         <field id="ttbl"         long_name="temperature in the Losh tbl"                   unit="degC"     />
+         <field id="stbl"         long_name="salinity in the Losh tbl"                      unit="0.001"     />
+         <field id="ttbl"         long_name="temperature in the Losh tbl"                   unit="degree_C"     />
 
          <!-- *_oce variables available with ln_blk_clio or ln_blk_core -->
@@ -216,4 +259,5 @@
          <!-- available if key_oasis3 + conservative method -->
          <field id="rain"          long_name="Liquid precipitation"                                     standard_name="rainfall_flux"                                                                 unit="kg/m2/s"  />
+         <field id="rain_ao_cea"   long_name="Liquid precipitation over ice-free ocean (cell average)"  standard_name="rainfall_flux"                                                                 unit="kg/m2/s"  />
          <field id="evap_ao_cea"   long_name="Evaporation over ice-free ocean (cell average)"           standard_name="water_evaporation_flux"                                                        unit="kg/m2/s"  />
          <field id="isnwmlt_cea"   long_name="Snow over Ice melting (cell average)"                     standard_name="surface_snow_melt_flux"                                                        unit="kg/m2/s"  />
@@ -221,4 +265,5 @@
          <field id="fsal_real_cea" long_name="Real salt flux due to ice formation (cell average)"       standard_name="downward_sea_ice_basal_salt_flux"                                              unit="kg/m2/s"  />
          <field id="hflx_rain_cea" long_name="heat flux due to rainfall"                                standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"        unit="W/m2"     />
+         <field id="hflx_prec_cea" long_name="heat flux due to precipitation"                           standard_name="temperature_flux_due_to_precipitation_expressed_as_heat_flux_into_sea_water"        unit="W/m2"     />
          <field id="hflx_evap_cea" long_name="heat flux due to evaporation"                             standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"   unit="W/m2"     />
          <field id="hflx_snow_cea" long_name="heat flux due to snow falling over ice-free ocean"        standard_name="heat_flux_into_sea_water_due_to_snow_thermodynamics"                           unit="W/m2"     />
@@ -248,6 +293,6 @@
          
          <field id="ice_pres"     long_name="Ice presence"                                                                                                                    unit=""             />
-         <field id="ist_cea"      long_name="Ice surface temperature (cell average)"                       standard_name="surface_temperature"                                unit="degC"         />
-         <field id="ist_ipa"      long_name="Ice surface temperature (ice presence average)"               standard_name="surface_temperature"                                unit="degC"         />      
+         <field id="ist_cea"      long_name="Ice surface temperature (cell average)"                       standard_name="surface_temperature"                                unit="degree_C"         />
+         <field id="ist_ipa"      long_name="Ice surface temperature (ice presence average)"               standard_name="surface_temperature"                                unit="degree_C"         />      
          <field id="uice_ipa"     long_name="Ice velocity along i-axis at I-point (ice presence average)"  standard_name="sea_ice_x_velocity"                                 unit="m/s"          />      
          <field id="vice_ipa"     long_name="Ice velocity along j-axis at I-point (ice presence average)"  standard_name="sea_ice_y_velocity"                                 unit="m/s"          />      
@@ -258,10 +303,12 @@
          <field id="u_imasstr"    long_name="Sea-ice mass transport along i-axis"                          standard_name="sea_ice_x_transport"                                unit="kg/s"         />
          <field id="v_imasstr"    long_name="Sea-ice mass transport along j-axis"                          standard_name="sea_ice_y_transport"                                unit="kg/s"         />
-         <field id="emp_x_sst"    long_name="Concentration/Dilution term on SST"                                                                                              unit="kg*degC/m2/s" />
-         <field id="emp_x_sss"    long_name="Concentration/Dilution term on SSS"                                                                                              unit="kg*1e-3/m2/s" />        
+         <field id="emp_x_sst"    long_name="Concentration/Dilution term on SST"                                                                                              unit="kg*degree_C/m2/s" />
+         <field id="emp_x_sss"    long_name="Concentration/Dilution term on SSS"                                                                                              unit="kg*0.001/m2/s" />        
+         <field id="rnf_x_sst"    long_name="Runoff term on SST"                                                                                                              unit="kg*degC/m2/s" />
+         <field id="rnf_x_sss"    long_name="Runoff term on SSS"                                                                                                              unit="kg*1e-3/m2/s" />
        
          <field id="iceconc"      long_name="ice concentration"                                            standard_name="sea_ice_area_fraction"                              unit="%"            />
-       	 <field id="isst"         long_name="sea surface temperature"                                      standard_name="sea_surface_temperature"                            unit="degC"         />
-         <field id="isss"         long_name="sea surface salinity"                                         standard_name="sea_surface_salinity"                               unit="1e-3"         /> 
+       	 <field id="isst"         long_name="sea surface temperature"                                      standard_name="sea_surface_temperature"                            unit="degree_C"         />
+         <field id="isss"         long_name="sea surface salinity"                                         standard_name="sea_surface_salinity"                               unit="0.001"         /> 
          <field id="qt_oce"       long_name="total flux at ocean surface"                                  standard_name="surface_downward_heat_flux_in_sea_water"            unit="W/m2"         />
          <field id="qsr_oce"      long_name="solar heat flux at ocean surface"                             standard_name="net_downward_shortwave_flux_at_sea_water_surface"   unit="W/m2"         />
@@ -272,6 +319,8 @@
          <field id="qtr_ice"      long_name="solar heat flux transmitted through ice: sum over categories"                                                                    unit="W/m2"         />
          <field id="qemp_ice"     long_name="Downward Heat Flux from E-P over ice"                                                                                            unit="W/m2"         />
-         <field id="micesalt"     long_name="Mean ice salinity"                                                                                                               unit="1e-3"         />
+         <field id="micesalt"     long_name="Mean ice salinity"                                                                                                               unit="0.001"         />
          <field id="miceage"      long_name="Mean ice age"                                                                                                                    unit="years"        />
+         <field id="alb_ice"      long_name="Mean albedo over sea ice"                                                                                                        unit=""             />
+         <field id="albedo"       long_name="Mean albedo over sea ice and ocean"                                                                                              unit=""             />
 
          <field id="iceage_cat"   long_name="Ice age for categories"                                       unit="days"   axis_ref="ncatice" />
@@ -281,11 +330,11 @@
          <field id="salinity_cat" long_name="Sea-Ice Bulk salinity for categories"                         unit="g/kg"   axis_ref="ncatice" />
          <field id="brinevol_cat" long_name="Brine volume for categories"                                  unit="%"      axis_ref="ncatice" />
-         <field id="icetemp_cat"  long_name="Ice temperature for categories"                               unit="degC"   axis_ref="ncatice" />
-         <field id="snwtemp_cat"  long_name="Snow temperature for categories"                              unit="degC"   axis_ref="ncatice" />
-
-         <field id="micet"        long_name="Mean ice temperature"                                         unit="degC"     />
+         <field id="icetemp_cat"  long_name="Ice temperature for categories"                               unit="degree_C"   axis_ref="ncatice" />
+         <field id="snwtemp_cat"  long_name="Snow temperature for categories"                              unit="degree_C"   axis_ref="ncatice" />
+
+         <field id="micet"        long_name="Mean ice temperature"                                         unit="degree_C"     />
          <field id="icehc"        long_name="ice total heat content"                                       unit="10^9J"    /> 
          <field id="isnowhc"      long_name="snow total heat content"                                      unit="10^9J"    />
-         <field id="icest"        long_name="ice surface temperature"                                      unit="degC"     />
+         <field id="icest"        long_name="ice surface temperature"                                      unit="degree_C"     />
          <field id="ibrinv"       long_name="brine volume"                                                 unit="%"        />
          <field id="icecolf"      long_name="frazil ice collection thickness"                              unit="m"        />
@@ -299,17 +348,18 @@
          <field id="icetrp"       long_name="ice volume transport"                                         unit="m/day"          />
          <field id="snwtrp"       long_name="snw volume transport"                                         unit="m/day"          />
-         <field id="saltrp"       long_name="salt content transport"                                       unit="1e-3*kg/m2/day" />
+         <field id="saltrp"       long_name="salt content transport"                                       unit="0.001*kg/m2/day" />
          <field id="deitrp"       long_name="advected ice enthalpy"                                        unit="W/m2"           />
          <field id="destrp"       long_name="advected snw enthalpy"                                        unit="W/m2"           />
 
-         <field id="sfxbri"       long_name="brine salt flux"                                              unit="1e-3*kg/m2/day" />
-         <field id="sfxdyn"       long_name="salt flux from ridging rafting"                               unit="1e-3*kg/m2/day" />
-         <field id="sfxres"       long_name="salt flux from lipupdate (resultant)"                         unit="1e-3*kg/m2/day" />
-         <field id="sfxbog"       long_name="salt flux from bot growth"                                    unit="1e-3*kg/m2/day" />
-         <field id="sfxbom"       long_name="salt flux from bot melt"                                      unit="1e-3*kg/m2/day" />
-         <field id="sfxsum"       long_name="salt flux from surf melt"                                     unit="1e-3*kg/m2/day" />
-         <field id="sfxsni"       long_name="salt flux from snow-ice formation"                            unit="1e-3*kg/m2/day" />
-         <field id="sfxopw"       long_name="salt flux from open water ice formation"                      unit="1e-3*kg/m2/day" />
-         <field id="sfx"          long_name="salt flux total"                                              unit="1e-3*kg/m2/day" />
+         <field id="sfxbri"       long_name="brine salt flux"                                              unit="0.001*kg/m2/day" />
+         <field id="sfxdyn"       long_name="salt flux from ridging rafting"                               unit="0.001*kg/m2/day" />
+         <field id="sfxres"       long_name="salt flux from lipupdate (resultant)"                         unit="0.001*kg/m2/day" />
+         <field id="sfxbog"       long_name="salt flux from bot growth"                                    unit="0.001*kg/m2/day" />
+         <field id="sfxbom"       long_name="salt flux from bot melt"                                      unit="0.001*kg/m2/day" />
+         <field id="sfxsum"       long_name="salt flux from surf melt"                                     unit="0.001*kg/m2/day" />
+         <field id="sfxsni"       long_name="salt flux from snow-ice formation"                            unit="0.001*kg/m2/day" />
+         <field id="sfxopw"       long_name="salt flux from open water ice formation"                      unit="0.001*kg/m2/day" />
+         <field id="sfxsub"       long_name="salt flux from sublimation"                                   unit="0.001*kg/m2/day" />
+         <field id="sfx"          long_name="salt flux total"                                              unit="0.001*kg/m2/day" />
 
          <field id="vfxbog"       long_name="daily bottom thermo ice prod."                                unit="m/day"   />
@@ -324,4 +374,5 @@
          <field id="vfxsub"       long_name="snw sublimation"                                              unit="m/day"   />
          <field id="vfxspr"       long_name="snw precipitation on ice"                                     unit="m/day"   />
+         <field id="vfxthin"      long_name="daily thermo ice prod. for thin ice(<20cm) + open water"      unit="m/day"   />
 
          <field id="afxtot"       long_name="area tendency (total)"                                        unit="day-1"   />
@@ -351,5 +402,5 @@
          <field id="hfxtur"       long_name="turbulent heat flux at the ice base"                          unit="W/m2" />
 	 <!-- sbcssm variables -->
-         <field id="sst_m"    unit="degC" />
+         <field id="sst_m"    unit="degree_C" />
          <field id="sss_m"    unit="psu"  />
          <field id="ssu_m"    unit="m/s"  />
@@ -365,13 +416,15 @@
       <field_group id="grid_U"   grid_ref="grid_U_2D">
          <field id="e3u"          long_name="U-cell thickness"                                       standard_name="cell_thickness"              unit="m"          grid_ref="grid_U_3D" />
-         <field id="utau"         long_name="Wind Stress along i-axis"                               standard_name="surface_downward_x_stress"   unit="N/m2"                            />
-         <field id="uoce"         long_name="ocean current along i-axis"                             standard_name="sea_water_x_velocity"        unit="m/s"        grid_ref="grid_U_3D" />
+         <field id="e3u_0"        long_name="Initial U-cell thickness"                               standard_name="ref_cell_thickness"          unit="m"          grid_ref="grid_U_3D"/>
+         <field id="utau"         long_name="Surface Downward X Stress"                               standard_name="surface_downward_x_stress"   unit="N/m2"                            />
+         <field id="uoce"         long_name="Sea Water X Velocity"                             standard_name="sea_water_x_velocity"        unit="m/s"        grid_ref="grid_U_3D" />
          <field id="uoce_e3u"     long_name="ocean current along i-axis * e3u"                                                                   unit="m2/s"       grid_ref="grid_U_3D"  > uoce * e3u </field>
+         <field id="uoce2_e3u"    long_name="ocean current along i-axis squared * e3u"                                                           unit="m3/s2"      grid_ref="grid_U_3D"  > uoce * uoce * e3u </field>
          <field id="ssu"          long_name="ocean surface current along i-axis"                                                                 unit="m/s"                             />
          <field id="sbu"          long_name="ocean bottom current along i-axis"                                                                  unit="m/s"                             />
          <field id="ubar"         long_name="ocean barotropic current along i-axis"                                                              unit="m/s"                             />
          <field id="uocetr_eff"   long_name="Effective ocean transport along i-axis"                 standard_name="ocean_volume_x_transport"    unit="m3/s"       grid_ref="grid_U_3D" />
-         <field id="uocet"        long_name="ocean transport along i-axis times temperature (CRS)"                                               unit="degC*m/s"   grid_ref="grid_U_3D" />
-         <field id="uoces"        long_name="ocean transport along i-axis times salinity (CRS)"                                                  unit="1e-3*m/s"   grid_ref="grid_U_3D" />
+         <field id="uocet"        long_name="ocean transport along i-axis times temperature (CRS)"                                               unit="degree_C*m/s"   grid_ref="grid_U_3D" />
+         <field id="uoces"        long_name="ocean transport along i-axis times salinity (CRS)"                                                  unit="0.001*m/s"   grid_ref="grid_U_3D" />
 
          <!-- variables available with MLE -->
@@ -379,5 +432,9 @@
 
          <!-- uoce_eiv: available with key_traldf_eiv and key_diaeiv -->
-         <field id="uoce_eiv"     long_name="EIV ocean current along i-axis"   standard_name="bolus_sea_water_x_velocity"   unit="m/s"   grid_ref="grid_U_3D" />
+         <field id="uoce_eiv"      long_name="EIV ocean current along i-axis"   standard_name="bolus_sea_water_x_velocity"   unit="m/s"   grid_ref="grid_U_3D" />
+         <field id="ueiv_masstr"   long_name="EIV Ocean Mass X Transport"    standard_name="bolus_ocean_mass_x_transport"                          unit="kg/s"        grid_ref="grid_U_3D" />
+         <field id="ueiv_heattr3d" long_name="ocean bolus heat transport along i-axis"    standard_name="ocean_heat_x_transport_due_to_bolus_advection"   unit="W"    grid_ref="grid_U_3D" />
+         <field id="ueiv_salttr3d" long_name="ocean bolus salt transport along i-axis"    standard_name="ocean_salt_x_transport_due_to_bolus_advection"   unit="kg"   grid_ref="grid_U_3D" />
+         <field id="ueiv_masstr"  long_name="EIV Ocean Mass X Transport"    standard_name="bolus_ocean_mass_x_transport"                          unit="kg/s"         grid_ref="grid_U_3D" />
 
          <!-- uoce_eiv: available with key_trabbl -->
@@ -389,8 +446,11 @@
 
          <!-- variables available with key_diaar5 -->
-         <field id="u_masstr"     long_name="ocean eulerian mass transport along i-axis"    standard_name="ocean_mass_x_transport"                          unit="kg/s"        grid_ref="grid_U_3D" />
+         <field id="u_masstr"     long_name="Ocean Mass X Transport"    standard_name="ocean_mass_x_transport"                          unit="kg/s"        grid_ref="grid_U_3D" />
+         <field id="u_masstr_vint" long_name="vertical integral of ocean eulerian mass transport along i-axis"    standard_name="vertical_integral_of_ocean_mass_x_transport"  unit="kg/s" />
          <field id="u_heattr"     long_name="ocean eulerian heat transport along i-axis"    standard_name="ocean_heat_x_transport"                          unit="W"                                />
-         <field id="u_salttr"     long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_x_transport"                          unit="1e-3*kg/s"                        />
+         <field id="uadv_heattr"  long_name="ocean advective heat transport along i-axis"    standard_name="advectice_ocean_heat_x_transport"                          unit="W"                                />
+         <field id="u_salttr"     long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_x_transport"                          unit="0.001*kg/s"                        />
          <field id="ueiv_heattr"  long_name="ocean bolus heat transport along i-axis"       standard_name="ocean_heat_x_transport_due_to_bolus_advection"   unit="W"                                />
+         <field id="ueiv_salttr"  long_name="ocean bolus salt transport along i-axis"       standard_name="ocean_salt_x_transport_due_to_bolus_advection"   unit="W"                                />
          <field id="udiff_heattr" long_name="ocean diffusion heat transport along i-axis"   standard_name="ocean_heat_x_transport_due_to_diffusion"         unit="W"                                />
       </field_group>
@@ -400,13 +460,15 @@
       <field_group id="grid_V"   grid_ref="grid_V_2D">
          <field id="e3v"          long_name="V-cell thickness"                                       standard_name="cell_thickness"              unit="m"          grid_ref="grid_V_3D" />
-         <field id="vtau"         long_name="Wind Stress along j-axis"                               standard_name="surface_downward_y_stress"   unit="N/m2"                            />
-         <field id="voce"         long_name="ocean current along j-axis"                             standard_name="sea_water_y_velocity"        unit="m/s"        grid_ref="grid_V_3D" />
+         <field id="e3v_0"        long_name="Initial V-cell thickness"                               standard_name="ref_cell_thickness"          unit="m"          grid_ref="grid_V_3D"/>
+         <field id="vtau"         long_name="Surface Downward Y Stress"                               standard_name="surface_downward_y_stress"   unit="N/m2"                            />
+         <field id="voce"         long_name="Sea Water Y Velocity"                             standard_name="sea_water_y_velocity"        unit="m/s"        grid_ref="grid_V_3D" />
          <field id="voce_e3v"     long_name="ocean current along j-axis * e3v"                                                                   unit="m2/s"       grid_ref="grid_V_3D"  > voce * e3v </field>
+         <field id="voce2_e3v"    long_name="ocean current along j-axis squared * e3v"                                                           unit="m3/s2"      grid_ref="grid_V_3D"  > voce * voce * e3v </field>
          <field id="ssv"          long_name="ocean surface current along j-axis"                                                                 unit="m/s"                             />
          <field id="sbv"          long_name="ocean bottom current along j-axis"                                                                  unit="m/s"                             />
          <field id="vbar"         long_name="ocean barotropic current along j-axis"                                                              unit="m/s"                             />
          <field id="vocetr_eff"   long_name="Effective ocean transport along j-axis"                 standard_name="ocean_volume_y_transport"    unit="m3/s"       grid_ref="grid_V_3D" />
-         <field id="vocet"        long_name="ocean transport along j-axis times temperature (CRS)"                                               unit="degC*m/s"   grid_ref="grid_V_3D" />
-         <field id="voces"        long_name="ocean transport along j-axis times salinity (CRS)"                                                  unit="1e-3*m/s"   grid_ref="grid_V_3D" />
+         <field id="vocet"        long_name="ocean transport along j-axis times temperature (CRS)"                                               unit="degree_C*m/s"   grid_ref="grid_V_3D" />
+         <field id="voces"        long_name="ocean transport along j-axis times salinity (CRS)"                                                  unit="0.001*m/s"   grid_ref="grid_V_3D" />
 
          <!-- variables available with MLE -->
@@ -415,4 +477,7 @@
          <!-- voce_eiv: available with key_traldf_eiv and key_diaeiv -->
          <field id="voce_eiv"     long_name="EIV ocean current along j-axis"   standard_name="bolus_sea_water_y_velocity"   unit="m/s"   grid_ref="grid_V_3D" />
+         <field id="veiv_masstr"   long_name="EIV Ocean Mass Y Transport"    standard_name="bolus_ocean_mass_y_transport"                          unit="kg/s"        grid_ref="grid_V_3D" />
+         <field id="veiv_heattr3d" long_name="ocean bolus heat transport along j-axis"    standard_name="ocean_heat_y_transport_due_to_bolus_advection"   unit="W"    grid_ref="grid_V_3D" />
+         <field id="veiv_salttr3d" long_name="ocean bolus salt transport along j-axis"    standard_name="ocean_salt_y_transport_due_to_bolus_advection"   unit="kg"   grid_ref="grid_V_3D" />
 
          <!-- voce_eiv: available with key_trabbl -->
@@ -424,8 +489,10 @@
 
          <!-- variables available with key_diaar5 -->
-         <field id="v_masstr"     long_name="ocean eulerian mass transport along j-axis"    standard_name="ocean_mass_y_transport"                          unit="kg/s"        grid_ref="grid_V_3D" />
-         <field id="v_heattr"     long_name="ocean eulerian heat transport along j-axis"    standard_name="ocean_heat_y_transport"                          unit="W"                                />
-         <field id="v_salttr"     long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_y_transport"                          unit="1e-3*kg/s"                        />
+         <field id="v_masstr"     long_name="Ocean Mass Y Transport"    standard_name="ocean_mass_y_transport"                          unit="kg/s"        grid_ref="grid_V_3D" />
+         <field id="v_heattr"     long_name="Ocean Heat X Transport"    standard_name="ocean_heat_y_transport"                          unit="W"                                />
+         <field id="vadv_heattr"  long_name="ocean advective heat transport along j-axis"    standard_name="advectice_ocean_heat_y_transport"                          unit="W"                                />
+         <field id="v_salttr"     long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_y_transport"                          unit="0.001*kg/s"                        />
          <field id="veiv_heattr"  long_name="ocean bolus heat transport along j-axis"       standard_name="ocean_heat_y_transport_due_to_bolus_advection"   unit="W"                                />
+         <field id="veiv_salttr"  long_name="ocean bolus salt transport along j-axis"       standard_name="ocean_salt_y_transport_due_to_bolus_advection"   unit="W"                                />
          <field id="vdiff_heattr" long_name="ocean diffusion heat transport along j-axis"   standard_name="ocean_heat_y_transport_due_to_diffusion"         unit="W"                                />
       </field_group>
@@ -440,11 +507,15 @@
         <!-- woce_eiv: available with key_traldf_eiv and key_diaeiv -->
         <field id="woce_eiv"     long_name="EIV ocean vertical velocity"   standard_name="bolus_upward_sea_water_velocity"   unit="m/s" />
-
-        <!-- woce_eiv: available with key_trabbl_adv -->
+        <field id="weiv_masstr"  long_name="EIV Upward Ocean Mass Transport"  standard_name="bolus_upward_ocean_mass_transport"             unit="kg/s"   />
+        <field id="weiv_heattr3d" long_name="ocean bolus heat transport along k-axis"    standard_name="ocean_heat_z_transport_due_to_bolus_advection"   unit="W" />
+        <field id="weiv_salttr3d" long_name="ocean bolus salt transport along k-axis"    standard_name="ocean_salt_z_transport_due_to_bolus_advection"   unit="kg" />
+
         <field id="avt"          long_name="vertical eddy diffusivity"   standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+        <field id="logavt"       long_name="logarithm of vertical eddy diffusivity"   standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
         <field id="avm"          long_name="vertical eddy viscosity"     standard_name="ocean_vertical_momentum_diffusivity"   unit="m2/s" />
 
         <!-- avs: available with key_zdfddm -->
         <field id="avs"          long_name="salt vertical eddy diffusivity"   standard_name="ocean_vertical_salt_diffusivity"   unit="m2/s" />
+        <field id="logavs"       long_name="logarithm of salt vertical eddy diffusivity"   standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
 
         <!-- avt_evd and avm_evd: available with ln_zdfevd -->
@@ -455,6 +526,13 @@
         <field id="av_tide"      long_name="tidal vertical diffusivity"   standard_name="ocean_vertical_tracer_diffusivity_due_to_tides"   unit="m2/s" />
 
+       <!-- variables available with key_zdftmx_new -->
+        <field id="av_ratio"     long_name="S over T diffusivity ratio"            standard_name="salinity_over_temperature_diffusivity_ratio"                     unit="1"    />
+        <field id="av_wave"      long_name="wave-induced vertical diffusivity"     standard_name="ocean_vertical_tracer_diffusivity_due_to_internal_waves"         unit="m2/s" />
+        <field id="bflx_tmx"     long_name="wave-induced buoyancy flux"            standard_name="buoyancy_flux_due_to_internal_waves"                             unit="W/kg" />
+        <field id="pcmap_tmx"    long_name="power consumed by wave-driven mixing"  standard_name="vertically_integrated_power_consumption_by_wave_driven_mixing"   unit="W/m2"      grid_ref="grid_W_2D" />
+        <field id="emix_tmx"     long_name="power density available for mixing"    standard_name="power_available_for_mixing_from_breaking_internal_waves"         unit="W/kg" />
+
         <!-- variables available with key_diaar5 -->   
-        <field id="w_masstr"     long_name="vertical mass transport"             standard_name="upward_ocean_mass_transport"             unit="kg/s"   />
+        <field id="w_masstr"     long_name="Upward Ocean Mass Transport"             standard_name="upward_ocean_mass_transport"             unit="kg/s"   />
         <field id="w_masstr2"    long_name="square of vertical mass transport"   standard_name="square_of_upward_ocean_mass_transport"   unit="kg2/s2" />
 
@@ -462,23 +540,49 @@
         <field id="aht2d"        long_name="lateral eddy diffusivity"       standard_name="ocean_tracer_xy_laplacian_diffusivity"      unit="m2/s"   grid_ref="grid_W_2D" />
         <field id="aht2d_eiv"    long_name="EIV lateral eddy diffusivity"   standard_name="ocean_tracer_bolus_laplacian_diffusivity"   unit="m2/s"   grid_ref="grid_W_2D" />
+        <!-- variables added for nn_etau revision testing -->
+        <field id="htau"         long_name="e-decay length scale of nn_etau TKE"       unit="m"        grid_ref="grid_W_2D" />
+        <field id="tke"          long_name="Turbulent Kinetic Energy"                  unit="m2/s2"    />
+        <field id="tke_niw"      long_name="Turbulent Kinetic Energy due to near-inertial wave breaking"  unit="m2/s2" />
+
+         <!-- Variable from eosbn2 -->
+         <field id="bn2"          long_name="Squared buoyancy frequency measuring ocean vertical stratification"        standard_name="square_of_brunt_vaisala_frequency_in_sea_water"   unit="1/s^2"  />
       </field_group>
           
+      <!-- product fields -->
+      <field_group id="diaprod">
+	<field id="ut"           long_name="product_of_sea_water_x_velocity_and_potential_temperature"      unit="degree_C m/s"      grid_ref="grid_U_3D"   />
+        <field id="ut_e3u"       long_name="product_of_sea_water_x_velocity_and_potential_temperature * e3u"  unit="degree_C m2/s"   grid_ref="grid_U_3D" > ut * e3u </field >
+	<field id="us"           long_name="product_of_sea_water_x_velocity_and_salinity"                   unit="PSU m/s"       grid_ref="grid_U_3D"   />
+        <field id="us_e3u"       long_name="product_of_sea_water_x_velocity_and_salinity * e3u"             unit="PSU m2/s"      grid_ref="grid_U_3D" > us * e3u </field >
+	<field id="urhop"        long_name="product_of_sea_water_x_velocity_and_potential_density"          unit="(kg/m3).(m/s)" grid_ref="grid_U_3D"   />
+        <field id="urhop_e3u"    long_name="product_of_sea_water_x_velocity_and_potential_density * e3u"    unit="(kg/m3).(m2/s)"   grid_ref="grid_U_3D" > urhop * e3u </field >
+	<field id="vt"           long_name="product_of_sea_water_y_velocity_and_potential_temperature"      unit="degree_C m/s"      grid_ref="grid_V_3D"   />
+        <field id="vt_e3v"       long_name="product_of_sea_water_y_velocity_and_potential_temperature * e3v"  unit="degree_C m2/s"   grid_ref="grid_V_3D" > vt * e3v </field >
+	<field id="vs"           long_name="product_of_sea_water_y_velocity_and_salinity"                   unit="PSU m/s"       grid_ref="grid_V_3D"   />
+        <field id="vs_e3v"       long_name="product_of_sea_water_y_velocity_and_salinity * e3t"             unit="PSU m2/s"      grid_ref="grid_V_3D" > vs * e3v </field >
+	<field id="vrhop"        long_name="product_of_sea_water_y_velocity_and_potential_density"          unit="(kg/m3).(m/s)" grid_ref="grid_V_3D"   />
+        <field id="vrhop_e3v"    long_name="product_of_sea_water_y_velocity_and_potential_density * e3t"    unit="(kg/m3).(m2/s)"  grid_ref="grid_V_3D" > vrhop * e3v </field >
+	<field id="wt"           long_name="product_of_upward_sea_water_velocity_and_potential_temperature" unit="degree_C m/s"      grid_ref="grid_W_3D"   />
+	<field id="ws"           long_name="product_of_upward_sea_water_velocity_and_salinity"              unit="PSU m/s"       grid_ref="grid_W_3D"   />
+	<field id="wrhop"        long_name="product_of_upward_sea_water_velocity_and_potential_density"     unit="(kg/m3).(m/s)" grid_ref="grid_W_3D"   />
+      </field_group>
+
       <!-- scalar variables available with key_diaar5 -->
 
-      <field_group id="scalar"  domain_ref="1point" >
-         <field id="voltot"     long_name="global total volume"                          standard_name="sea_water_volume"                               unit="m3"   />
+      <field_group id="scalar"  grid_ref="scalar" >
+         <field id="voltot"     long_name="Sea Water Volume"                             standard_name="sea_water_volume"                               unit="m3"   />
          <field id="sshtot"     long_name="global mean ssh"                              standard_name="global_average_sea_level_change"                unit="m"    />
          <field id="sshsteric"  long_name="global mean ssh steric"                       standard_name="global_average_steric_sea_level_change"         unit="m"    />
-         <field id="sshthster"  long_name="global mean ssh thermosteric"                 standard_name="global_average_thermosteric_sea_level_change"   unit="m"    />
+         <field id="sshthster"  long_name="Global Average Thermosteric Sea Level Change" standard_name="global_average_thermosteric_sea_level_change"   unit="m"    />
          <field id="masstot"    long_name="global total mass"                            standard_name="sea_water_mass"                                 unit="kg"   />
-         <field id="temptot"    long_name="global mean temperature"                      standard_name="sea_water_potential_temperature"                unit="degC" />
-         <field id="saltot"     long_name="global mean salinity"                         standard_name="sea_water_salinity"                             unit="1e-3" />
+         <field id="temptot"    long_name="Global Average Sea Water Potential Temperature"      standard_name="sea_water_potential_temperature"         unit="degree_C" />
+         <field id="saltot"     long_name="Global Average Sea Water Salinity"                   standard_name="sea_water_salinity"                      unit="0.001" />
          <field id="fram_trans" long_name="Sea Ice Mass Transport Through Fram Strait"   standard_name="sea_ice_transport_across_line"                  unit="kg/s" />
 
       	 <!-- available with ln_diahsb -->
-    	 <field id="bgtemper"     long_name="drift in global mean temperature wrt timestep 1"                 standard_name="change_over_time_in_sea_water_potential_temperature"   unit="degC"     />
-    	 <field id="bgsaline"     long_name="drift in global mean salinity wrt timestep 1"                    standard_name="change_over_time_in_sea_water_practical_salinity"      unit="1e-3"     />
+    	 <field id="bgtemper"     long_name="drift in global mean temperature wrt timestep 1"                 standard_name="change_over_time_in_sea_water_potential_temperature"   unit="degree_C"     />
+    	 <field id="bgsaline"     long_name="drift in global mean salinity wrt timestep 1"                    standard_name="change_over_time_in_sea_water_practical_salinity"      unit="0.001"     />
     	 <field id="bgheatco"     long_name="drift in global mean heat content wrt timestep 1"                                                                                      unit="10^9J"    />
-    	 <field id="bgsaltco"     long_name="drift in global mean salt content wrt timestep 1"                                                                                      unit="1e-3*m3"  />
+    	 <field id="bgsaltco"     long_name="drift in global mean salt content wrt timestep 1"                                                                                      unit="0.001*m3"  />
     	 <field id="bgvolssh"     long_name="drift in global mean ssh volume wrt timestep 1"                                                                                        unit="km3"      />
          <field id="bgvole3t"     long_name="drift in global mean volume variation (e3t) wrt timestep 1"                                                                            unit="km3"      />
@@ -488,21 +592,21 @@
     	 <field id="bgfrcvol"     long_name="drift in global mean volume from forcing wrt timestep 1"                                                                               unit="km3"      />
     	 <field id="bgfrctem"     long_name="drift in global mean heat content from forcing wrt timestep 1"                                                                         unit="10^9J"    />
-    	 <field id="bgfrcsal"     long_name="drift in global mean salt content from forcing wrt timestep 1"                                                                         unit="1e-3*km3" />
-    	 <field id="bgmistem"     long_name="global mean temperature error due to free surface"                                                                                     unit="degC"     />
-    	 <field id="bgmissal"     long_name="global mean salinity error due to free surface"                                                                                        unit="1e-3"     />
+    	 <field id="bgfrcsal"     long_name="drift in global mean salt content from forcing wrt timestep 1"                                                                         unit="0.001*km3" />
+    	 <field id="bgmistem"     long_name="global mean temperature error due to free surface"                                                                                     unit="degree_C"     />
+    	 <field id="bgmissal"     long_name="global mean salinity error due to free surface"                                                                                        unit="0.001"     />
       </field_group>
 
       <!-- LIM3 scalar variables -->
 
-      <field_group id="SBC_scalar"  domain_ref="1point" >
+      <field_group id="SBC_scalar"  grid_ref="scalar" >
          <!-- available with ln_limdiaout -->
          <field id="ibgvoltot"    long_name="global mean ice volume"                                 unit="km3"        />
          <field id="sbgvoltot"    long_name="global mean snow volume"                                unit="km3"        />
          <field id="ibgarea"      long_name="global mean ice area"                                   unit="km2"        />
-         <field id="ibgsaline"    long_name="global mean ice salinity"                               unit="1e-3"       />
-         <field id="ibgtemper"    long_name="global mean ice temperature"                            unit="degC"       />
+         <field id="ibgsaline"    long_name="global mean ice salinity"                               unit="0.001"       />
+         <field id="ibgtemper"    long_name="global mean ice temperature"                            unit="degree_C"       />
          <field id="ibgheatco"    long_name="global mean ice heat content"                           unit="10^20J"     />
          <field id="sbgheatco"    long_name="global mean snow heat content"                          unit="10^20J"     />
-         <field id="ibgsaltco"    long_name="global mean ice salt content"                           unit="1e-3*km3"   />
+         <field id="ibgsaltco"    long_name="global mean ice salt content"                           unit="0.001*km3"   />
 
          <field id="ibgvfx"       long_name="global mean volume flux (emp)"                          unit="m/day"      />
@@ -518,13 +622,14 @@
          <field id="ibgvfxsub"    long_name="global mean volume flux (snow sublimation)"             unit="m/day"      />
 
-         <field id="ibgsfx"       long_name="global mean salt flux (total)"                          unit="1e-3*m/day" />
-         <field id="ibgsfxbri"    long_name="global mean salt flux (brines)"                         unit="1e-3*m/day" />
-         <field id="ibgsfxdyn"    long_name="global mean salt flux (dynamic)"                        unit="1e-3*m/day" />
-         <field id="ibgsfxres"    long_name="global mean salt flux (resultant)"                      unit="1e-3*m/day" />
-         <field id="ibgsfxbog"    long_name="global mean salt flux (thermo)"                         unit="1e-3*m/day" />
-         <field id="ibgsfxopw"    long_name="global mean salt flux (thermo)"                         unit="1e-3*m/day" />
-         <field id="ibgsfxsni"    long_name="global mean salt flux (thermo)"                         unit="1e-3*m/day" />
-         <field id="ibgsfxbom"    long_name="global mean salt flux (thermo)"                         unit="1e-3*m/day" />
-         <field id="ibgsfxsum"    long_name="global mean salt flux (thermo)"                         unit="1e-3*m/day" />
+         <field id="ibgsfx"       long_name="global mean salt flux (total)"                          unit="0.001*m/day" />
+         <field id="ibgsfxbri"    long_name="global mean salt flux (brines)"                         unit="0.001*m/day" />
+         <field id="ibgsfxdyn"    long_name="global mean salt flux (dynamic)"                        unit="0.001*m/day" />
+         <field id="ibgsfxres"    long_name="global mean salt flux (resultant)"                      unit="0.001*m/day" />
+         <field id="ibgsfxbog"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxopw"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxsni"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxbom"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxsum"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxsub"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
 
          <field id="ibghfxdhc"    long_name="Heat content variation in snow and ice"                 unit="W"          />
@@ -545,5 +650,5 @@
 
          <field id="ibgfrcvol"    long_name="global mean forcing volume (emp)"                       unit="km3"        />
-         <field id="ibgfrcsfx"    long_name="global mean forcing salt   (sfx)"                       unit="1e-3*km3"   />
+         <field id="ibgfrcsfx"    long_name="global mean forcing salt   (sfx)"                       unit="0.001*km3"   />
          <field id="ibgvolgrm"    long_name="global mean ice growth+melt volume"                     unit="km3"        />
       </field_group>
@@ -551,10 +656,10 @@
       <!-- variables available with key_float -->
 
-      <field_group id="floatvar" domain_ref="1point" axis_ref="nfloat" operation="instant" >
+      <field_group id="floatvar" grid_ref="scalar" axis_ref="nfloat" operation="instant" >
         <field id="traj_lon"      long_name="floats longitude"                                                           unit="degrees_east"  />
         <field id="traj_lat"      long_name="floats latitude"                                                            unit="degrees_north" />
         <field id="traj_dep"      long_name="floats depth"                                                               unit="m"             />
-        <field id="traj_temp"     long_name="floats temperature"       standard_name="sea_water_potential_temperature"   unit="degC"          />
-        <field id="traj_salt"     long_name="floats salinity"          standard_name="sea_water_practical_salinity"      unit="1e-3"          />
+        <field id="traj_temp"     long_name="floats temperature"       standard_name="sea_water_potential_temperature"   unit="degree_C"          />
+        <field id="traj_salt"     long_name="floats salinity"          standard_name="sea_water_practical_salinity"      unit="0.001"          />
         <field id="traj_dens"     long_name="floats in-situ density"   standard_name="sea_water_density"                 unit="kg/m3"         />
         <field id="traj_group"    long_name="floats group"                                                               unit="1"             />
@@ -563,5 +668,7 @@
       <!-- variables available with iceberg trajectories -->
 
-      <field_group id="icbvar" domain_ref="grid_T"  > 
+      <field_group id="icbvar" grid_ref="grid_T_2D"  > 
+        <field id="berg_total_melt"    long_name="icb melt rate 2 of icebergs"                     unit="kg/m2/s"                    />
+        <field id="berg_total_heat_flux"  long_name="icb latent heat of melting of icebergs"          unit="kg/m2/s"                    />
         <field id="berg_melt"          long_name="icb melt rate of icebergs"                       unit="kg/m2/s"                    />
         <field id="berg_buoy_melt"     long_name="icb buoyancy component of iceberg melt rate"     unit="kg/m2/s"                    />
@@ -580,5 +687,5 @@
 
       <!-- Poleward transport : ptr -->     
-      <field_group id="diaptr" domain_ref="ptr" > 
+      <field_group id="diaptr"> 
         <field id="zomsfglo"          long_name="Meridional Stream-Function: Global"           unit="Sv"       grid_ref="gznl_W_3D" />
         <field id="zomsfatl"          long_name="Meridional Stream-Function: Atlantic"         unit="Sv"       grid_ref="gznl_W_3D" />
@@ -586,14 +693,19 @@
         <field id="zomsfind"          long_name="Meridional Stream-Function: Indian"           unit="Sv"       grid_ref="gznl_W_3D" />
         <field id="zomsfipc"          long_name="Meridional Stream-Function: Pacific+Indian"   unit="Sv"       grid_ref="gznl_W_3D" />
-        <field id="zotemglo"          long_name="Zonal Mean Temperature : Global"              unit="degC"     grid_ref="gznl_T_3D" />
-        <field id="zotematl"          long_name="Zonal Mean Temperature : Atlantic"            unit="degC"     grid_ref="gznl_T_3D" />
-        <field id="zotempac"          long_name="Zonal Mean Temperature : Pacific"             unit="degC"     grid_ref="gznl_T_3D" />
-        <field id="zotemind"          long_name="Zonal Mean Temperature : Indian"              unit="degC"     grid_ref="gznl_T_3D" />
-        <field id="zotemipc"          long_name="Zonal Mean Temperature : Pacific+Indian"      unit="degC"     grid_ref="gznl_T_3D" />
-        <field id="zosalglo"          long_name="Zonal Mean Salinity : Global"                 unit="1e-3"     grid_ref="gznl_T_3D" />
-        <field id="zosalatl"          long_name="Zonal Mean Salinity : Atlantic"               unit="1e-3"     grid_ref="gznl_T_3D" />
-        <field id="zosalpac"          long_name="Zonal Mean Salinity : Pacific"                unit="1e-3"     grid_ref="gznl_T_3D" />
-        <field id="zosalind"          long_name="Zonal Mean Salinity : Indian"                 unit="1e-3"     grid_ref="gznl_T_3D" />
-        <field id="zosalipc"          long_name="Zonal Mean Salinity : Pacific+Indian"         unit="1e-3"     grid_ref="gznl_T_3D" />
+        <field id="zomsfeivglo"       long_name="Meridional Stream-Function: Global"           unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfeivatl"       long_name="Meridional Stream-Function: Atlantic"         unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfeivpac"       long_name="Meridional Stream-Function: Pacific"          unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfeivind"       long_name="Meridional Stream-Function: Indian"           unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfeivipc"       long_name="Meridional Stream-Function: Pacific+Indian"   unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zotemglo"          long_name="Zonal Mean Temperature : Global"              unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotematl"          long_name="Zonal Mean Temperature : Atlantic"            unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotempac"          long_name="Zonal Mean Temperature : Pacific"             unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotemind"          long_name="Zonal Mean Temperature : Indian"              unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotemipc"          long_name="Zonal Mean Temperature : Pacific+Indian"      unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zosalglo"          long_name="Zonal Mean Salinity : Global"                 unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalatl"          long_name="Zonal Mean Salinity : Atlantic"               unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalpac"          long_name="Zonal Mean Salinity : Pacific"                unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalind"          long_name="Zonal Mean Salinity : Indian"                 unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalipc"          long_name="Zonal Mean Salinity : Pacific+Indian"         unit="0.001"     grid_ref="gznl_T_3D" />
         <field id="zosrfglo"          long_name="Zonal Mean Surface"                           unit="m2"       grid_ref="gznl_T_3D" />
         <field id="zosrfatl"          long_name="Zonal Mean Surface : Atlantic"                unit="m2"       grid_ref="gznl_T_3D" />
@@ -602,7 +714,66 @@
         <field id="zosrfipc"          long_name="Zonal Mean Surface : Pacific+Indian"          unit="m2"       grid_ref="gznl_T_3D" />
         <field id="sophtadv"          long_name="Advective Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_atl"      long_name="Advective Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_pac"      long_name="Advective Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_ind"      long_name="Advective Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_ipc"      long_name="Advective Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
         <field id="sophtldf"          long_name="Diffusive Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_atl"      long_name="Diffusive Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_pac"      long_name="Diffusive Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_ind"      long_name="Diffusive Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_ipc"      long_name="Diffusive Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove"          long_name="Overturning Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_atl"      long_name="Overturning Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_pac"      long_name="Overturning Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_ind"      long_name="Overturning Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_ipc"      long_name="Overturning Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr"          long_name="Barotropic Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_atl"      long_name="Barotropic Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_pac"      long_name="Barotropic Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_ind"      long_name="Barotropic Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_ipc"      long_name="Barotropic Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv"          long_name="Heat Transport from mesoscale eddy oveection"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_atl"      long_name="Heat Transport from mesoscale eddy advection: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_pac"      long_name="Heat Transport from mesoscale eddy advection: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_ind"      long_name="Heat Transport from mesoscale eddy advection: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_ipc"      long_name="Heat Transport from mesoscale eddy advection: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
         <field id="sopstadv"          long_name="Advective Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_atl"      long_name="Advective Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_pac"      long_name="Advective Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_ind"      long_name="Advective Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_ipc"      long_name="Advective Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove"          long_name="Overturning Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_atl"      long_name="Overturning Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_pac"      long_name="Overturning Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_ind"      long_name="Overturning Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_ipc"      long_name="Overturning Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr"          long_name="Barotropic Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_atl"      long_name="Barotropic Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_pac"      long_name="Barotropic Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_ind"      long_name="Barotropic Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_ipc"      long_name="Barotropic Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
         <field id="sopstldf"          long_name="Diffusive Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_atl"      long_name="Diffusive Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_pac"      long_name="Diffusive Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_ind"      long_name="Diffusive Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_ipc"      long_name="Diffusive Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopsteiv"          long_name="Salt Transport from mesoscale eddy advection"                     unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_atl"      long_name="Salt Transport from mesoscale eddy advection: Atlantic"           unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_pac"      long_name="Salt Transport from mesoscale eddy advection: Pacific"            unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_ind"      long_name="Salt Transport from mesoscale eddy advection: Indian"             unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_ipc"      long_name="Salt Transport from mesoscale eddy advection: Pacific+Indian"     unit="Giga g/s"       grid_ref="gznl_T_2D" />       
+        <field id="sopht_vt"          long_name="Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_atl"      long_name="Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_ind"      long_name="Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_pac"      long_name="Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_ipc"      long_name="Heat Transport: Indo-Pacific"       unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs"          long_name="Salt Transport"                     unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_atl"      long_name="Salt Transport: Atlantic"           unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_ind"      long_name="Salt Transport: Indian"             unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_pac"      long_name="Salt Transport: Pacific"            unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_ipc"      long_name="Salt Transport: Indo-Pacific"       unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="vsum" grid_ref="gznl_T_2D" unit="none" standard_name="none" />
+        <field id="tmean" grid_ref="gznl_T_2D" unit="none" standard_name="none" />
+        <field id="section_area" grid_ref="gznl_T_2D" unit="none" standard_name="none" />
       </field_group>
 
@@ -613,7 +784,21 @@
     -->
 
-    <field_group id="trendT" grid_ref="grid_T_3D">
       <!-- variables available with ln_tra_trd -->
-      <field id="ttrd_xad"      long_name="temperature-trend: i-advection"                                                                                          unit="degC/s"                        />
+ 
+     <!-- Asselin trends  calculated on odd time steps-->
+     <field_group id="trendT_odd"  grid_ref="grid_T_3D">
+      <field id="ttrd_atf"      long_name="temperature-trend: asselin time filter"       unit="degree_C/s" />
+      <field id="strd_atf"      long_name="salinity   -trend: asselin time filter"       unit="0.001/s" />
+      <!-- Thickness weighted versions: -->
+     <field id="ttrd_atf_e3t"      unit="degC/s * m"  >  ttrd_atf * e3t </field>
+      <field id="strd_atf_e3t"      unit="1e-3/s * m"  >  strd_atf * e3t </field>
+      <!-- OMIP  layer-integrated trends -->
+      <field id="ttrd_atf_li"      long_name="layer integrated heat-trend: asselin time filter "       unit="W/m^2" > ttrd_atf_e3t * 1026.0 * 3991.86795711963  </field>
+       <field id="strd_atf_li"      long_name="layer integrated salt   -trend: asselin time filter "       unit="kg/(m^2 s)" > strd_atf_e3t * 1026.0 * 0.001 </field>
+      </field_group>
+
+    <!-- Other trends  calculated on even time steps-->
+  <field_group id="trendT_even" grid_ref="grid_T_3D">
+       <field id="ttrd_xad"      long_name="temperature-trend: i-advection"                                                                                          unit="degC/s"                        />
       <field id="strd_xad"      long_name="salinity   -trend: i-advection"                                                                                          unit="1e-3/s"                        />
       <field id="ttrd_yad"      long_name="temperature-trend: j-advection"                                                                                          unit="degC/s"                        />
@@ -623,4 +808,6 @@
       <field id="ttrd_ad"       long_name="temperature-trend: advection"               standard_name="tendency_of_sea_water_temperature_due_to_advection"           unit="degC/s"                         > sqrt( ttrd_xad^2 + ttrd_yad^2 + ttrd_zad^2 ) </field>
       <field id="strd_ad"       long_name="salinity   -trend: advection"               standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="1e-3/s"                         > sqrt( strd_xad^2 + strd_yad^2 + strd_zad^2 ) </field>
+      <field id="ttrd_totad"    long_name="temperature-trend: total advection"         standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="degC/s"                        />
+      <field id="strd_totad"    long_name="salinity   -trend: total advection"         standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="1e-3/s"                        />
       <field id="ttrd_sad"      long_name="temperature-trend: surface adv. (no-vvl)"                                                                                unit="degC/s"   grid_ref="grid_T_2D" />
       <field id="strd_sad"      long_name="salinity   -trend: surface adv. (no-vvl)"                                                                                unit="1e-3/s"   grid_ref="grid_T_2D" />
@@ -629,23 +816,106 @@
       <field id="ttrd_zdf"      long_name="temperature-trend: vertical diffusion"      standard_name="tendency_of_sea_water_temperature_due_to_vertical_mixing"     unit="degC/s"                        />
       <field id="strd_zdf"      long_name="salinity   -trend: vertical diffusion"      standard_name="tendency_of_sea_water_salinity_due_to_vertical_mixing"        unit="1e-3/s"                        />
+      <field id="ttrd_evd"      long_name="temperature-trend: EVD convection"                                                                                       unit="degC/s"                        />
+      <field id="strd_evd"      long_name="salinity   -trend: EVD convection"                                                                                       unit="1e-3/s"                        />
 
       <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+      <field id="ttrd_iso_x"    long_name="temperature-trend: isopycnal diffusion x-component"                                                                      unit="degC/s"                        />
+      <field id="strd_iso_x"    long_name="salinity   -trend: isopycnal diffusion x-component"                                                                      unit="1e-3/s"                        />
+      <field id="ttrd_iso_y"    long_name="temperature-trend: isopycnal diffusion y-component"                                                                      unit="degC/s"                        />
+      <field id="strd_iso_y"    long_name="salinity   -trend: isopycnal diffusion y-component"                                                                      unit="1e-3/s"                        />
+      <field id="ttrd_iso_z1"   long_name="temperature-trend: isopycnal diffusion z-component part 1"                                                               unit="degC/s"                        />
+      <field id="strd_iso_z1"   long_name="salinity   -trend: isopycnal diffusion z-component part 1"                                                               unit="1e-3/s"                        />
+      <field id="ttrd_iso_z"    long_name="temperature-trend: isopycnal diffusion z-component"                 unit="degC/s" > ttrd_iso_z1 + ttrd_zdf - ttrd_zdfp </field>
+      <field id="strd_iso_z"    long_name="salinity   -trend: isopycnal diffusion z-component"                 unit="1e-3/s" > strd_iso_z1 + strd_zdf - strd_zdfp </field>
+      <field id="ttrd_iso"      long_name="temperature-trend: isopycnal diffusion"                             unit="degC/s" > ttrd_ldf + ttrd_zdf - ttrd_zdfp </field>
+      <field id="strd_iso"      long_name="salinity   -trend: isopycnal diffusion"                             unit="1e-3/s" > strd_ldf + strd_zdf - strd_zdfp </field>
       <field id="ttrd_zdfp"     long_name="temperature-trend: pure vert. diffusion"   unit="degC/s" />
       <field id="strd_zdfp"     long_name="salinity   -trend: pure vert. diffusion"   unit="1e-3/s" />
 
       <!-- -->
-      <field id="ttrd_dmp"      long_name="temperature-trend: interior restoring"        unit="degC/s" />
-      <field id="strd_dmp"      long_name="salinity   -trend: interior restoring"        unit="1e-3/s" />
-      <field id="ttrd_bbl"      long_name="temperature-trend: bottom boundary layer"     unit="degC/s" />
-      <field id="strd_bbl"      long_name="salinity   -trend: bottom boundary layer"     unit="1e-3/s" />
-      <field id="ttrd_npc"      long_name="temperature-trend: non-penetrative conv."     unit="degC/s" />
-      <field id="strd_npc"      long_name="salinity   -trend: non-penetrative conv."     unit="1e-3/s" />
-      <field id="ttrd_qns"      long_name="temperature-trend: non-solar flux + runoff"   unit="degC/s" />
-      <field id="strd_cdt"      long_name="salinity   -trend: C/D term       + runoff"   unit="degC/s" />
-      <field id="ttrd_qsr"      long_name="temperature-trend: solar penetr. heating"     unit="degC/s" />
-      <field id="ttrd_bbc"      long_name="temperature-trend: geothermal heating"        unit="degC/s" />
-      <field id="ttrd_atf"      long_name="temperature-trend: asselin time filter"       unit="degC/s" />
-      <field id="strd_atf"      long_name="salinity   -trend: asselin time filter"       unit="1e-3/s" />
-
+      <field id="ttrd_dmp"      long_name="temperature-trend: interior restoring"        unit="degree_C/s" />
+      <field id="strd_dmp"      long_name="salinity   -trend: interior restoring"        unit="0.001/s" />
+      <field id="ttrd_bbl"      long_name="temperature-trend: bottom boundary layer"     unit="degree_C/s" />
+      <field id="strd_bbl"      long_name="salinity   -trend: bottom boundary layer"     unit="0.001/s" />
+      <field id="ttrd_npc"      long_name="temperature-trend: non-penetrative conv."     unit="degree_C/s" />
+      <field id="strd_npc"      long_name="salinity   -trend: non-penetrative conv."     unit="0.001/s" />
+      <field id="ttrd_qns"      long_name="temperature-trend: non-solar flux + runoff"   unit="degC/s" grid_ref="grid_T_2D"/>
+      <field id="strd_cdt"      long_name="salinity   -trend: C/D term       + runoff"   unit="degC/s" grid_ref="grid_T_2D"/>
+      <field id="ttrd_qsr"      long_name="temperature-trend: solar penetr. heating"     unit="degree_C/s" />
+      <field id="ttrd_bbc"      long_name="temperature-trend: geothermal heating"        unit="degree_C/s" />
+ 
+      <!-- Thickness weighted versions: -->
+      <field id="ttrd_xad_e3t"      unit="degC/s * m" >  ttrd_xad * e3t </field>
+      <field id="strd_xad_e3t"      unit="1e-3/s * m" >  strd_xad * e3t </field>
+      <field id="ttrd_yad_e3t"      unit="degC/s * m" >  ttrd_yad * e3t </field>
+      <field id="strd_yad_e3t"      unit="1e-3/s * m" >  strd_yad * e3t </field>
+      <field id="ttrd_zad_e3t"      unit="degC/s * m" >  ttrd_zad * e3t </field>
+      <field id="strd_zad_e3t"      unit="1e-3/s * m" >  strd_zad * e3t </field>
+      <field id="ttrd_ad_e3t"       unit="degC/s * m" >  ttrd_ad  * e3t </field>
+      <field id="strd_ad_e3t"       unit="1e-3/s * m" >  strd_ad  * e3t </field>
+      <field id="ttrd_totad_e3t"    unit="degC/s * m" >  ttrd_totad  * e3t </field>
+      <field id="strd_totad_e3t"    unit="1e-3/s * m" >  strd_totad  * e3t </field>
+      <field id="ttrd_ldf_e3t"      unit="degC/s * m" >  ttrd_ldf * e3t </field>
+      <field id="strd_ldf_e3t"      unit="1e-3/s * m" >  strd_ldf * e3t </field>
+      <field id="ttrd_zdf_e3t"      unit="degC/s * m" >  ttrd_zdf * e3t </field>
+      <field id="strd_zdf_e3t"      unit="1e-3/s * m" >  strd_zdf * e3t </field>
+      <field id="ttrd_evd_e3t"      unit="degC/s * m" >  ttrd_evd * e3t </field>
+      <field id="strd_evd_e3t"      unit="1e-3/s * m" >  strd_evd * e3t </field>
+
+      <field id="strd_evd_e3t"      unit="1e-3/s * m" >  strd_evd * e3t </field>
+
+      <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+      <field id="ttrd_iso_x_e3t"    unit="degC/s * m"  >  ttrd_iso_x * e3t </field>
+      <field id="strd_iso_x_e3t"    unit="1e-3/s * m"  >  strd_iso_x * e3t </field>
+      <field id="ttrd_iso_y_e3t"    unit="degC/s * m"  >  ttrd_iso_y * e3t </field>
+      <field id="strd_iso_y_e3t"    unit="1e-3/s * m"  >  strd_iso_y * e3t </field>
+      <field id="ttrd_iso_z_e3t"    unit="degC/s * m"  >  ttrd_iso_z * e3t </field>
+      <field id="strd_iso_z_e3t"    unit="1e-3/s * m"  >  strd_iso_z * e3t </field>
+      <field id="ttrd_iso_e3t"      unit="degC/s * m"  >  ttrd_iso * e3t </field>
+      <field id="strd_iso_e3t"      unit="1e-3/s * m"  >  strd_iso * e3t </field>
+      <field id="ttrd_zdfp_e3t"     unit="degC/s * m"  >  ttrd_zdfp * e3t </field>
+      <field id="strd_zdfp_e3t"     unit="1e-3/s * m"  >  strd_zdfp * e3t </field>
+
+      <!-- -->
+      <field id="ttrd_dmp_e3t"      unit="degC/s * m"  >  ttrd_dmp * e3t </field>
+      <field id="strd_dmp_e3t"      unit="1e-3/s * m"  >  strd_dmp * e3t </field>
+      <field id="ttrd_bbl_e3t"      unit="degC/s * m"  >  ttrd_bbl * e3t </field>
+      <field id="strd_bbl_e3t"      unit="1e-3/s * m"  >  strd_bbl * e3t </field>
+      <field id="ttrd_npc_e3t"      unit="degC/s * m"  >  ttrd_npc * e3t </field>
+      <field id="strd_npc_e3t"      unit="1e-3/s * m"  >  strd_npc * e3t </field>
+      <field id="ttrd_qns_e3t"      unit="degC/s * m"  >  ttrd_qns * e3t_surf </field>
+      <field id="strd_cdt_e3t"      unit="degC/s * m"  >  strd_cdt * e3t_surf </field>
+      <field id="ttrd_qsr_e3t"      unit="degC/s * m"  >  ttrd_qsr * e3t </field>
+      <field id="ttrd_bbc_e3t"      unit="degC/s * m"  >  ttrd_bbc * e3t </field>
+
+      <!-- OMIP  layer-integrated trends -->
+      <field id="ttrd_totad_li"    long_name="layer integrated heat-trend : total advection"       unit="W/m^2"     > ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="strd_totad_li"    long_name="layer integrated salt   -trend : total advection"      unit="kg/(m^2 s)"    > strd_totad_e3t * 1026.0 * 0.001  </field>
+      <field id="ttrd_evd_li"      long_name="layer integrated heat-trend : EVD convection"         unit="W/m^2"    > ttrd_evd_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="strd_evd_li"      long_name="layer integrated salt   -trend : EVD convection"      unit="kg/(m^2 s)"  > strd_evd_e3t * 1026.0 * 0.001  </field>
+      <field id="ttrd_iso_li"      long_name="layer integrated heat-trend : isopycnal diffusion"    unit="W/m^2" > ttrd_iso_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="strd_iso_li"      long_name="layer integrated salt   -trend : isopycnal diffusion"   unit="kg/(m^2 s)" > strd_iso_e3t * 1026.0 * 0.001  </field>
+      <field id="ttrd_zdfp_li"     long_name="layer integrated heat-trend : pure vert. diffusion"   unit="W/m^2" > ttrd_zdfp_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="strd_zdfp_li"     long_name="layer integrated salt   -trend : pure vert. diffusion"   unit="kg/(m^2 s)" > strd_zdfp_e3t * 1026.0 * 0.001  </field>
+      <field id="ttrd_qns_li"      long_name="layer integrated heat-trend : non-solar flux + runoff"   unit="W/m^2" grid_ref="grid_T_2D"> ttrd_qns_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="ttrd_qsr_li"      long_name="layer integrated heat-trend : solar flux"   unit="W/m^2"  grid_ref="grid_T_3D"> ttrd_qsr_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="ttrd_bbl_li"      long_name="layer integrated heat-trend: bottom boundary layer "     unit="W/m^2" > ttrd_bbl_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="strd_bbl_li"      long_name="layer integrated salt   -trend: bottom boundary layer "     unit="kg/(m^2 s)" > strd_bbl_e3t * 1026.0 * 0.001  </field>
+      <field id="ttrd_evd_li"      long_name="layer integrated heat -trend: evd convection "       unit="W/m^2" >ttrd_evd_e3t * 1026.0 * 3991.86795711963  </field>
+      <field id="strd_evd_li"      long_name="layer integrated salt -trend: evd convection "       unit="kg/(m^2 s)" > strd_evd_e3t * 1026.0 * 0.001  </field>
+     </field_group>
+   
+     <!--  Total trends calculated every time step-->
+     <field_group id="trendT" grid_ref="grid_T_3D">
+      <field id="ttrd_tot"      long_name="temperature-trend: total model trend"         unit="degC/s" />
+      <field id="strd_tot"      long_name="salinity   -trend: total model trend"         unit="1e-3/s" />
+      <!-- Thickness weighted versions: -->
+      <field id="ttrd_tot_e3t"      unit="degC/s * m"  >  ttrd_tot * e3t </field>
+      <field id="strd_tot_e3t"      unit="1e-3/s * m"  >  strd_tot * e3t </field>
+      <!-- OMIP  layer-integrated total trends -->
+      <field id="ttrd_tot_li"      long_name="layer integrated heat-trend: total model trend :"         unit="W/m^2" > ttrd_tot_e3t * 1026.0 * 3991.86795711963 </field>
+      <field id="strd_tot_li"      long_name="layer integrated salt   -trend: total model trend :"         unit="kg/(m^2 s)" > strd_tot_e3t * 1026.0 * 0.001  </field>
+   
+      <!-- **** these trends have not been apportioned to all/even/odd ts yet **** -->
       <!-- variables available with ln_KE_trd -->
       <field id="ketrd_hpg"     long_name="ke-trend: hydrostatic pressure gradient"          unit="W/s^3"                        />
@@ -662,5 +932,7 @@
       <field id="ketrd_zad"     long_name="ke-trend: vertical  advection"                    unit="W/s^3"                        />
       <field id="ketrd_udx"     long_name="ke-trend: U.dx[U]"                                unit="W/s^3"                        />
-      <field id="ketrd_ldf"     long_name="ke-trend: lateral   diffusion"                    unit="W/s^3"                        />
+      <field id="ketrd_ldf"     long_name="ke-trend: lateral   diffusion"                    unit="W/m^3"                        />
+      <field id="ketrd_ldf_e3t" field_ref="ketrd_ldf" long_name="ke-trend: lateral   diffusion * e3t" unit="W/m^2" >ketrd_ldf*e3t</field>
+      <field id="ketrd_ldf_vsum" field_ref="ketrd_ldf_e3t" long_name="ke-trend: lateral diffusion vertical integral" unit="W/m^2" grid_ref="vert_sum" />
       <field id="ketrd_zdf"     long_name="ke-trend: vertical  diffusion"                    unit="W/s^3"                        />
       <field id="ketrd_tau"     long_name="ke-trend: wind stress "                           unit="W/s^3"   grid_ref="grid_T_2D" />
@@ -670,4 +942,5 @@
       <field id="ketrd_convP2K" long_name="ke-trend: conversion (potential to kinetic)"      unit="W/s^3"                        />
       <field id="KE"            long_name="kinetic energy: u(n)*u(n+1)/2"                    unit="W/s^2"                        />   
+      <field id="ketrd_eiv"     long_name="Kinetic energy trend from mesoscale eddy advection"   unit="W/s^2" grid_ref="grid_T_2D" />   
 
       <!-- variables available with ln_PE_trd -->
@@ -687,6 +960,8 @@
       <field id="petrd_atf"     long_name="pe-trend: asselin time filter"        unit="W/m^3"                        />
       <field id="PEanom"        long_name="potential energy anomaly"             unit="1"                            />   
-      <field id="alphaPE"       long_name="partial deriv. of PEanom wrt T"       unit="degC-1"                       />   
+      <field id="alphaPE"       long_name="partial deriv. of PEanom wrt T"       unit="degree_C-1"                       />   
       <field id="betaPE"        long_name="partial deriv. of PEanom wrt S"       unit="1e3"                          />   
+      <field id="petrd_zdfp_e3t"    unit="W/m^2" grid_ref="grid_T_3D"  > petrd_zdfp * e3t </field>
+      <field id="petrd_2d" field_ref="petrd_zdfp_e3t" grid_ref="vert_sum" />
     </field_group>
 
@@ -731,212 +1006,6 @@
     </field_group>
 
-    <!-- 
-============================================================================================================
-                                     Biogeochemistry model variables
-============================================================================================================
-    -->
-
-      <!-- ptrc on T grid -->
-
-     <field_group id="ptrc_T" grid_ref="grid_T_3D">
-       <field id="DIC"          long_name="Dissolved inorganic Concentration"        unit="mmol/m3" />
-       <field id="DIC_E3T"      long_name="DIC * E3T"                                unit="mmol/m2" > DIC * e3t </field >
-       <field id="Alkalini"     long_name="Total Alkalinity Concentration"           unit="mmol/m3" />
-       <field id="Alkalini_E3T" long_name="Alkalini * E3T"                           unit="mmol/m2"  > Alkalini * e3t </field >
-       <field id="O2"           long_name="Oxygen Concentration"                     unit="mmol/m3" />
-       <field id="O2_E3T"       long_name="O2 * E3T"                                 unit="mmol/m2"  > O2 * e3t </field >
-       <field id="CaCO3"        long_name="Calcite Concentration"                    unit="mmol/m3" />
-       <field id="CaCO3_E3T"    long_name="CaCO3 * E3T"                              unit="mmol/m2"  > CaCO3 * e3t </field >
-       <field id="PO4"          long_name="Phosphate Concentration"                  unit="mmol/m3" />
-       <field id="PO4_E3T"      long_name="PO4 * E3T"                                unit="mmol/m2"  > PO4 * e3t </field >
-       <field id="POC"          long_name="Small organic carbon Concentration"       unit="mmol/m3" />
-       <field id="POC_E3T"      long_name="POC * E3T"                                unit="mmol/m2"  > POC * e3t </field >
-       <field id="Si"           long_name="Silicate Concentration"                   unit="mmol/m3" />
-       <field id="Si_E3T"       long_name="Si * E3T"                                 unit="mmol/m2"  > Si * e3t </field >
-       <field id="PHY"          long_name="(Nano)Phytoplankton Concentration"        unit="mmol/m3" />
-       <field id="PHY_E3T"      long_name="PHY * E3T"                                unit="mmol/m2"  > PHY * e3t </field >
-       <field id="ZOO"          long_name="(Micro)Zooplankton Concentration"         unit="mmol/m3" />
-       <field id="ZOO_E3T"      long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO * e3t </field >
-       <field id="DOC"          long_name="Dissolved organic Concentration"          unit="mmol/m3" />
-       <field id="DOC_E3T"      long_name="DOC * E3T"                                unit="mmol/m2"  > DOC * e3t </field >
-       <field id="PHY2"         long_name="Diatoms Concentration"                    unit="mmol/m3" />
-       <field id="PHY2_E3T"     long_name="PHY2 * E3T"                               unit="mmol/m2"  > PHY2 * e3t </field >
-       <field id="ZOO2"         long_name="Mesozooplankton Concentration"            unit="mmol/m3" />
-       <field id="ZOO2_E3T"     long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO2 * e3t </field >
-       <field id="DSi"          long_name="Diatoms Silicate Concentration"           unit="mmol/m3" />
-       <field id="DSi_E3T"      long_name="Dsi * E3T"                                unit="mmol/m2"  > DSi * e3t </field >
-       <field id="Fer"          long_name="Dissolved Iron Concentration"             unit="mmol/m3" />
-       <field id="Fer_E3T"      long_name="Fer * E3T"                                unit="mmol/m2"  > Fer * e3t </field >
-       <field id="BFe"          long_name="Big iron particles Concentration"         unit="mmol/m3" />
-       <field id="BFe_E3T"      long_name="BFe * E3T"                                unit="mmol/m2"  > BFe * e3t </field >
-       <field id="GOC"          long_name="Big organic carbon Concentration"         unit="mmol/m3" />
-       <field id="GOC_E3T"      long_name="GOC * E3T"                                unit="mmol/m2"  > GOC * e3t </field >
-       <field id="SFe"          long_name="Small iron particles Concentration"       unit="mmol/m3" />
-       <field id="SFe_E3T"      long_name="SFe * E3T"                                unit="mmol/m2"  > SFe * e3t </field >
-       <field id="DFe"          long_name="Diatoms iron  Concentration"              unit="mmol/m3" />
-       <field id="DFe_E3T"      long_name="DFe * E3T"                                unit="mmol/m2"  > DFe * e3t </field >
-       <field id="GSi"          long_name="Sinking biogenic Silicate Concentration"  unit="mmol/m3" />
-       <field id="GSi_E3T"      long_name="GSi * E3T"                                unit="mmol/m2"  > GSi * e3t </field >
-       <field id="NFe"          long_name="Nano iron Concentration"                  unit="mmol/m3" />
-       <field id="NFe_E3T"      long_name="NFe * E3T"                                unit="mmol/m2"  > NFe * e3t </field >
-       <field id="NCHL"         long_name="Nano chlorophyl Concentration"            unit="mg/m3"   />
-       <field id="NCHL_E3T"     long_name="NCHL * E3T"                               unit="mmol/m2"  > NCHL * e3t </field >
-       <field id="DCHL"         long_name="Diatoms chlorophyl Concentration"         unit="mg/m3"   />
-       <field id="DCHL_E3T"     long_name="DCHL * E3T"                               unit="mmol/m2"  > DCHL * e3t </field >
-       <field id="NO3"          long_name="Nitrate Concentration"                    unit="mmol/m3" />
-       <field id="NO3_E3T"      long_name="NO3 * E3T"                                unit="mmol/m2"  > NO3 * e3t </field >
-       <field id="NH4"          long_name="Ammonium Concentration"                   unit="mmol/m3" />
-       <field id="NH4_E3T"      long_name="NH4 * E3T"                                unit="mmol/m2"  > NH4 * e3t </field >
-
-       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
-       <field id="Num"         long_name="Number of organic particles"              unit="1" />
-       <field id="Num_E3T"     long_name="Num * E3T"                                unit="m"  > Num * e3t </field >
-
-       <!-- PISCES light : variables available with key_pisces_reduced -->
-       <field id="DET"         long_name="Detritus"                                 unit="mmol-N/m3" />
-       <field id="DET_E3T"     long_name="DET * E3T"                                unit="mmol-N/m2"  > DET * e3t </field >
-       <field id="DOM"         long_name="Dissolved Organic Matter"                 unit="mmol-N/m3" />
-       <field id="DOM_E3T"     long_name="DOM * E3T"                                unit="mmol-N/m2"  > DOM * e3t </field >
-
-       <!-- CFC11 : variables available with key_cfc -->
-       <field id="CFC11"       long_name="CFC-11 Concentration"                     unit="umol/m3" />
-       <field id="CFC11_E3T"   long_name="CFC11 * E3T"                              unit="umol/m2"  > CFC11 * e3t </field >
-       <!-- Bomb C14 : variables available with key_c14b -->
-       <field id="C14B"     long_name="Bomb C14 Concentration"                      unit="1"         />
-       <field id="C14B_E3T"    long_name="C14B * E3T"                               unit="m"  > C14B * e3t </field >
-     </field_group>
-
-     <!-- PISCES additional diagnostics on T grid  -->
-
-     <field_group id="diad_T" grid_ref="grid_T_2D">
-       <field id="PH"          long_name="PH"                                      unit="1"          grid_ref="grid_T_3D" />
-       <field id="CO3"         long_name="Bicarbonates"                            unit="mol/m3"     grid_ref="grid_T_3D" />
-       <field id="CO3sat"      long_name="CO3 saturation"                          unit="mol/m3"     grid_ref="grid_T_3D" />
-       <field id="PAR"         long_name="Photosynthetically Available Radiation"  unit="W/m2"       grid_ref="grid_T_3D" />
-       <field id="PARDM"       long_name="Daily mean PAR"                          unit="W/m2"       grid_ref="grid_T_3D" />
-       <field id="PPPHY"       long_name="Primary production of nanophyto"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="PPPHY2"      long_name="Primary production of diatoms"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="PPNEWN"      long_name="New Primary production of nanophyto"     unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="PPNEWD"      long_name="New Primary production of diatoms"       unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="PBSi"        long_name="Primary production of Si diatoms"        unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="PFeN"        long_name="Primary production of nano iron"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="PFeD"        long_name="Primary production of diatoms iron"      unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="xfracal"     long_name="Calcifying fraction"                     unit="1"          grid_ref="grid_T_3D" />
-       <field id="PCAL"        long_name="Calcite production"                      unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="DCAL"        long_name="Calcite dissolution"                     unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="GRAZ1"       long_name="Grazing by microzooplankton"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="GRAZ2"       long_name="Grazing by mesozooplankton"              unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="REMIN"       long_name="Oxic remineralization of OM"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="DENIT"       long_name="Anoxic remineralization of OM"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="Nfix"        long_name="Nitrogen fixation"                       unit="mol/m3/s"   grid_ref="grid_T_3D" />
-       <field id="Mumax"       long_name="Maximum growth rate"                     unit="s-1"        grid_ref="grid_T_3D" />
-       <field id="MuN"         long_name="Realized growth rate for nanophyto"      unit="s-1"        grid_ref="grid_T_3D" />
-       <field id="MuD"         long_name="Realized growth rate for diatomes"       unit="s-1"        grid_ref="grid_T_3D" />
-       <field id="LNnut"       long_name="Nutrient limitation term in Nanophyto"   unit=""           grid_ref="grid_T_3D" />
-       <field id="LDnut"       long_name="Nutrient limitation term in Diatoms"     unit=""           grid_ref="grid_T_3D" />
-       <field id="LNFe"        long_name="Iron limitation term in Nanophyto"       unit=""           grid_ref="grid_T_3D" />
-       <field id="LDFe"        long_name="Iron limitation term in Diatoms"         unit=""           grid_ref="grid_T_3D" />
-       <field id="LNlight"     long_name="Light limitation term in Nanophyto"      unit=""           grid_ref="grid_T_3D" />
-       <field id="LDlight"     long_name="Light limitation term in Diatoms"        unit=""           grid_ref="grid_T_3D" />
-       <field id="Fe2"         long_name="Iron II concentration"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="Fe3"         long_name="Iron III concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="FeL1"        long_name="Complexed Iron concentration with L1"    unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="FeL2"        long_name="Complexed Iron concentration with L2"    unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="FeP"         long_name="Precipitated Iron III"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="TL1"         long_name="Total L1 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="TL2"         long_name="Total L2 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="pdust"       long_name="dust concentration"                      unit="g/m3"                            />
-       <field id="Totlig"      long_name="Total ligand concentation"               unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="Biron"       long_name="Bioavailable iron"                       unit="nmol/m3"    grid_ref="grid_T_3D" />
-       <field id="Sdenit"      long_name="Nitrate reduction in the sediments"      unit="mol/m2/s"                        />
-       <field id="Ironice"     long_name="Iron input/uptake due to sea ice"        unit="mol/m2/s"                        />
-       <field id="HYDR"        long_name="Iron input from hydrothemal vents"       unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="EPC100"      long_name="Export of carbon particles at 100 m"     unit="mol/m2/s"                        />
-       <field id="EPFE100"     long_name="Export of biogenic iron at 100 m"        unit="mol/m2/s"                        />
-       <field id="EPSI100"     long_name="Export of Silicate at 100 m"             unit="mol/m2/s"                        />
-       <field id="EPCAL100"    long_name="Export of Calcite at 100 m"              unit="mol/m2/s"                        />
-       <field id="EXPC"        long_name="Export of carbon"                        unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="EXPFE"       long_name="Export of biogenic iron"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="EXPSI"       long_name="Export of Silicate"                      unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="EXPCAL"      long_name="Export of Calcite"                       unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="Cflx"        long_name="DIC flux"                                unit="mol/m2/s"                        />
-       <field id="Oflx"        long_name="Oxygen flux"                             unit="mol/m2/s"                        />
-       <field id="Kg"          long_name="Gas transfer"                            unit="mol/m2/s/uatm"                   />
-       <field id="Dpco2"       long_name="Delta CO2"                               unit="uatm"                            />
-       <field id="Dpo2"        long_name="Delta O2"                                unit="uatm"                            />
-       <field id="Heup"        long_name="Euphotic layer depth"                    unit="m"                               />
-       <field id="Irondep"     long_name="Iron deposition from dust"               unit="mol/m2/s"                        />
-       <field id="Ironsed"     long_name="Iron deposition from sediment"           unit="mol/m2/s"   grid_ref="grid_T_3D" />
-
-
-       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
-       <field id="EPN100"      long_name="Particulate number flux at 100 m"        unit="mol/m2/s"                        />
-       <field id="EXPN"        long_name="Particulate number flux"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="XNUM"        long_name="Number of particles in aggregats"        unit="1"          grid_ref="grid_T_3D" />
-       <field id="WSC"         long_name="sinking speed of mass flux"              unit="m2/s"       grid_ref="grid_T_3D" />
-       <field id="WSN"         long_name="sinking speed of number flux"            unit="m2/s"       grid_ref="grid_T_3D" />
-
-       <!-- dbio_T on T grid : variables available with key_diaar5 -->
-       <field id="TPP"         long_name="Total Primary production of phyto"                   unit="mol/m3/s"  grid_ref="grid_T_3D" />
-       <field id="TPNEW"       long_name="New Primary production of phyto"                     unit="mol/m3/s"  grid_ref="grid_T_3D" />
-       <field id="TPBFE"       long_name="Total biogenic iron production"                      unit="mol/m3/s"  grid_ref="grid_T_3D" />
-       <field id="INTDIC"      long_name="DIC content"                                         unit="kg/m2"                          />
-       <field id="O2MIN"       long_name="Oxygen minimum concentration"                        unit="mol/m3"                          />
-       <field id="ZO2MIN"      long_name="Depth of oxygen minimum concentration"               unit="m"                              />
-       <field id="INTNFIX"     long_name="Nitrogen fixation rate : vert. integrated"           unit="mol/m2/s"                       />
-       <field id="INTPPPHY"    long_name="Vertically integrated primary production by nanophy" unit="mol/m2/s"                       />
-       <field id="INTPPPHY2"   long_name="Vertically integrated primary production by diatom"  unit="mol/m2/s"                       />
-       <field id="INTPP"       long_name="Vertically integrated primary production by phyto"   unit="mol/m2/s"                       />
-       <field id="INTPNEW"     long_name="Vertically integrated new primary production"        unit="mol/m2/s"                       />
-       <field id="INTPBFE"     long_name="Vertically integrated of biogenic iron production"   unit="mol/m2/s"                       />
-       <field id="INTPBSI"     long_name="Vertically integrated of biogenic Si production"     unit="mol/m2/s"                       />
-       <field id="INTPCAL"     long_name="Vertically integrated of calcite production"         unit="mol/m2/s"                       />
-
-       <!-- PISCES light : variables available with key_pisces_reduced -->
-       <field id="FNO3PHY"     long_name="FNO3PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
-       <field id="FNH4PHY"     long_name="FNH4PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
-       <field id="FNH4NO3"     long_name="FNH4NO3"                                 unit=""          grid_ref="grid_T_3D" /> 
-       <field id="TNO3PHY"     long_name="TNO3PHY"                                 unit=""  /> 
-       <field id="TNH4PHY"     long_name="TNH4PHY"                                 unit=""  /> 
-       <field id="TPHYDOM"     long_name="TPHYDOM"                                 unit=""  /> 
-       <field id="TPHYNH4"     long_name="TPHYNH4"                                 unit=""  /> 
-       <field id="TPHYZOO"     long_name="TPHYZOO"                                 unit=""  /> 
-       <field id="TPHYDET"     long_name="TPHYDET"                                 unit=""  /> 
-       <field id="TDETZOO"     long_name="TDETZOO"                                 unit=""  /> 
-       <field id="TZOODET"     long_name="TZOODET"                                 unit=""  /> 
-       <field id="TZOOBOD"     long_name="TZOOBOD"                                 unit=""  /> 
-       <field id="TZOONH4"     long_name="TZOONH4"                                 unit=""  /> 
-       <field id="TZOODOM"     long_name="TZOODOM"                                 unit=""  /> 
-       <field id="TNH4NO3"     long_name="TNH4NO3"                                 unit=""  /> 
-       <field id="TDOMNH4"     long_name="TDOMNH4"                                 unit=""  /> 
-       <field id="TDETNH4"     long_name="TDETNH4"                                 unit=""  /> 
-       <field id="TPHYTOT"     long_name="TPHYTOT"                                 unit=""  /> 
-       <field id="TZOOTOT"     long_name="TZOOTOT"                                 unit=""  /> 
-       <field id="SEDPOC"      long_name="SEDPOC"                                  unit=""  /> 
-       <field id="TDETSED"     long_name="TDETSED"                                 unit=""  /> 
-
-       <!-- CFC11 : variables available with key_cfc -->
-       <field id="qtrCFC11"    long_name="Air-sea flux of CFC-11"                  unit="mol/m2/s"   />
-       <field id="qintCFC11"   long_name="Cumulative air-sea flux of CFC-11"       unit="mol/m2"     />
-
-       <!-- Bomb C14 : variables available with key_c14b -->
-       <field id="qtrC14b"     long_name="Air-sea flux of Bomb C14"                unit="mol/m2/s"   />
-       <field id="qintC14b"    long_name="Cumulative air-sea flux of Bomb C14"     unit="mol/m2"     />
-       <field id="fdecay"      long_name="Radiactive decay of Bomb C14"            unit="mol/m3"  grid_ref="grid_T_3D"  />
-     </field_group>
-
-     <field_group id="PISCES_scalar"  domain_ref="1point" >
-       <field id="pno3tot"         long_name="global mean nitrate concentration"                  unit="mol/m3"   />
-       <field id="ppo4tot"         long_name="global mean phosphorus concentration"               unit="mol/m3"   />
-       <field id="psiltot"         long_name="global mean silicate concentration"                 unit="mol/m3"   />
-       <field id="palktot"         long_name="global mean alkalinity concentration"               unit="mol/m3"   />
-       <field id="pfertot"         long_name="global mean iron concentration"                     unit="mol/m3"   />
-       <field id="tcflx"           long_name="total Flux of Carbon out of the ocean"              unit="mol/s"   />
-       <field id="tcflxcum"        long_name="cumulative total Flux of Carbon out of the ocean"   unit="mol/s"   />
-       <field id="tcexp"           long_name="total Carbon export at 100m"                        unit="mol/s"   />
-       <field id="tintpp"          long_name="global total integrated primary production"         unit="mol/s"   />
-       <field id="tnfix"           long_name="global total nitrogen fixation"                     unit="mol/s"   />
-       <field id="tdenit"          long_name="Total denitrification"                              unit="mol/s"   />
-     </field_group>
+
+
 
     <!-- 
@@ -946,4 +1015,17 @@
     -->
 
+     <field_group id="TRD" >
+          <field field_ref="ttrd_totad_li"   name="opottempadvect"  />
+          <field field_ref="ttrd_iso_li"     name="opottemppmdiff"  />
+          <field field_ref="ttrd_zdfp_li"    name="opottempdiff"  />
+          <field field_ref="ttrd_evd_li"     name="opottempevd" />
+          <field field_ref="strd_evd_li"     name="osaltevd" />
+          <field field_ref="ttrd_qns_li"     name="opottempqns"  />
+          <field field_ref="ttrd_qsr_li"     name="rsdoabsorb" operation="accumulate" />
+          <field field_ref="strd_totad_li"   name="osaltadvect" />
+          <field field_ref="strd_iso_li"     name="osaltpmdiff"  />
+          <field field_ref="strd_zdfp_li"    name="osaltdiff" />
+    </field_group>
+    
     <field_group id="mooring" >
       <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"      />
@@ -1021,2 +1103,4 @@
 
    </field_definition>
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def_bgc.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def_bgc.xml	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def_bgc.xml	(revision 9987)
@@ -0,0 +1,865 @@
+<!--
+< GO6.0 version of the XIOS namelist >
+< XIOS2 version namelist >
+
+<?xml version="1.0"?>
+       -->
+ 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+   <field_definition level="1" prec="8" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                     Biogeochemistry model variables
+============================================================================================================
+    -->
+
+      <!-- ptrc on T grid -->
+
+     <field_group id="ptrc_T" grid_ref="grid_T_3D">
+       <field id="DIC"          long_name="Dissolved inorganic Concentration"        unit="mmol/m3" />
+       <field id="DIC_E3T"      long_name="DIC * E3T"                                unit="mmol/m2" > DIC * e3t </field >
+       <field id="Alkalini"     long_name="Total Alkalinity Concentration"           unit="mmol/m3" />
+       <field id="Alkalini_E3T" long_name="Alkalini * E3T"                           unit="mmol/m2"  > Alkalini * e3t </field >
+       <field id="O2"           long_name="Oxygen Concentration"                     unit="mmol/m3" />
+       <field id="O2_E3T"       long_name="O2 * E3T"                                 unit="mmol/m2"  > O2 * e3t </field >
+       <field id="CaCO3"        long_name="Calcite Concentration"                    unit="mmol/m3" />
+       <field id="CaCO3_E3T"    long_name="CaCO3 * E3T"                              unit="mmol/m2"  > CaCO3 * e3t </field >
+       <field id="PO4"          long_name="Phosphate Concentration"                  unit="mmol/m3" />
+       <field id="PO4_E3T"      long_name="PO4 * E3T"                                unit="mmol/m2"  > PO4 * e3t </field >
+       <field id="POC"          long_name="Small organic carbon Concentration"       unit="mmol/m3" />
+       <field id="POC_E3T"      long_name="POC * E3T"                                unit="mmol/m2"  > POC * e3t </field >
+       <field id="Si"           long_name="Silicate Concentration"                   unit="mmol/m3" />
+       <field id="Si_E3T"       long_name="Si * E3T"                                 unit="mmol/m2"  > Si * e3t </field >
+       <field id="PHY"          long_name="(Nano)Phytoplankton Concentration"        unit="mmol/m3" />
+       <field id="PHY_E3T"      long_name="PHY * E3T"                                unit="mmol/m2"  > PHY * e3t </field >
+       <field id="ZOO"          long_name="(Micro)Zooplankton Concentration"         unit="mmol/m3" />
+       <field id="ZOO_E3T"      long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO * e3t </field >
+       <field id="DOC"          long_name="Dissolved organic Concentration"          unit="mmol/m3" />
+       <field id="DOC_E3T"      long_name="DOC * E3T"                                unit="mmol/m2"  > DOC * e3t </field >
+       <field id="PHY2"         long_name="Diatoms Concentration"                    unit="mmol/m3" />
+       <field id="PHY2_E3T"     long_name="PHY2 * E3T"                               unit="mmol/m2"  > PHY2 * e3t </field >
+       <field id="ZOO2"         long_name="Mesozooplankton Concentration"            unit="mmol/m3" />
+       <field id="ZOO2_E3T"     long_name="ZOO2 * E3T"                               unit="mmol/m2"  > ZOO2 * e3t </field >
+       <field id="DSi"          long_name="Diatoms Silicate Concentration"           unit="mmol/m3" />
+       <field id="DSi_E3T"      long_name="Dsi * E3T"                                unit="mmol/m2"  > DSi * e3t </field >
+       <field id="Fer"          long_name="Dissolved Iron Concentration"             unit="mmol/m3" />
+       <field id="Fer_E3T"      long_name="Fer * E3T"                                unit="mmol/m2"  > Fer * e3t </field >
+       <field id="BFe"          long_name="Big iron particles Concentration"         unit="mmol/m3" />
+       <field id="BFe_E3T"      long_name="BFe * E3T"                                unit="mmol/m2"  > BFe * e3t </field >
+       <field id="GOC"          long_name="Big organic carbon Concentration"         unit="mmol/m3" />
+       <field id="GOC_E3T"      long_name="GOC * E3T"                                unit="mmol/m2"  > GOC * e3t </field >
+       <field id="SFe"          long_name="Small iron particles Concentration"       unit="mmol/m3" />
+       <field id="SFe_E3T"      long_name="SFe * E3T"                                unit="mmol/m2"  > SFe * e3t </field >
+       <field id="DFe"          long_name="Diatoms iron  Concentration"              unit="mmol/m3" />
+       <field id="DFe_E3T"      long_name="DFe * E3T"                                unit="mmol/m2"  > DFe * e3t </field >
+       <field id="GSi"          long_name="Sinking biogenic Silicate Concentration"  unit="mmol/m3" />
+       <field id="GSi_E3T"      long_name="GSi * E3T"                                unit="mmol/m2"  > GSi * e3t </field >
+       <field id="NFe"          long_name="Nano iron Concentration"                  unit="mmol/m3" />
+       <field id="NFe_E3T"      long_name="NFe * E3T"                                unit="mmol/m2"  > NFe * e3t </field >
+       <field id="NCHL"         long_name="Nano chlorophyl Concentration"            unit="mg/m3"   />
+       <field id="NCHL_E3T"     long_name="NCHL * E3T"                               unit="mmol/m2"  > NCHL * e3t </field >
+       <field id="DCHL"         long_name="Diatoms chlorophyl Concentration"         unit="mg/m3"   />
+       <field id="DCHL_E3T"     long_name="DCHL * E3T"                               unit="mmol/m2"  > DCHL * e3t </field >
+       <field id="NO3"          long_name="Nitrate Concentration"                    unit="mmol/m3" />
+       <field id="NO3_E3T"      long_name="NO3 * E3T"                                unit="mmol/m2"  > NO3 * e3t </field >
+       <field id="NH4"          long_name="Ammonium Concentration"                   unit="mmol/m3" />
+       <field id="NH4_E3T"      long_name="NH4 * E3T"                                unit="mmol/m2"  > NH4 * e3t </field >
+
+      <!-- MEDUSA : variables available with key_medusa -->
+       <field id="CHN"      long_name="Chl-a concentration in non-diatom phytoplankton"   unit="mg Chl/m3" />
+       <field id="CHN_E3T"  long_name="CHN * E3T"                                         unit="mg Chl/m2"  > CHN * e3t </field > 
+       <field id="CHD"      long_name="Chl-a concentration in     diatom phytoplankton"   unit="mg Chl/m3" />
+       <field id="CHD_E3T"  long_name="CHD * E3T"                                         unit="mg Chl/m2"  > CHD * e3t </field >
+       <field id="PHN"      long_name="non-diatom phytoplankton"                          unit="mmol-N/m3" />
+       <field id="PHN_E3T"  long_name="PHN * E3T"                                         unit="mmol-N/m2"  > PHN * e3t </field >
+       <field id="PHD"      long_name="diatom     phytoplankton"                          unit="mmol-N/m3" />
+       <field id="PHD_E3T"  long_name="PHD * E3T"                                         unit="mmol-N/m2"  > PHD * e3t </field >
+       <field id="ZMI"      long_name="micro zooplankton"                                 unit="mmol-N/m3" />
+       <field id="ZMI_E3T"  long_name="ZMI * E3T"                                         unit="mmol-N/m2"  > ZMI * e3t </field >
+       <field id="ZME"      long_name="meso  zooplankton"                                 unit="mmol-N/m3" />
+       <field id="ZME_E3T"  long_name="ZME * E3T"                                         unit="mmol-N/m2"  > ZME * e3t </field >
+       <field id="DIN"      long_name="dissolved inorganic nitrogen"                      unit="mmol-N/m3" />
+       <field id="DIN_E3T"  long_name="DIN * E3T"                                         unit="mmol-N/m2"  > DIN * e3t </field >
+       <field id="SIL"      long_name="dissolved silicic acid"                            unit="mmolSi/m3" />
+       <field id="SIL_E3T"  long_name="SIL * E3T"                                         unit="mmolSi/m2"  > SIL * e3t </field >
+       <field id="FER"      long_name="dissolved iron"                                    unit="mmolFe/m3" />
+       <field id="FER_E3T"  long_name="FER * E3T"                                         unit="mmolFe/m2"  > FER * e3t </field >
+       <field id="DET"      long_name="detrital nitrogen"                                 unit="mmol-N/m3" />
+       <field id="DET_E3T"  long_name="DET * E3T"                                         unit="mmol-N/m2"  > DET * e3t </field >
+       <field id="PDS"      long_name="biogenic silicon in diatom phytoplankton"          unit="mmolSi/m3" />
+       <field id="PDS_E3T"  long_name="PDS * E3T"                                         unit="mmolSi/m2"  > PDS * e3t </field >
+       <field id="DTC"      long_name="detrital carbon"                                   unit="mmol-C/m3" />
+       <field id="DTC_E3T"  long_name="DTC * E3T"                                         unit="mmol-C/m2"  > DTC * e3t </field >
+       <field id="DiC"      long_name="dissolved inorganic carbon"                        unit="mmol-C/m3" />
+       <field id="DiC_E3T"  long_name="DiC * E3T"                                         unit="mmol-C/m2"  > DiC * e3t </field >
+       <field id="ALK"      long_name="alkalinity"                                        unit="meq/m3"    />
+       <field id="ALK_E3T"  long_name="ALK * E3T"                                         unit="meq/m2"     > ALK * e3t </field >
+       <field id="OXY"      long_name="dissolved oxygen"                                  unit="mmolO2/m3" />
+       <field id="OXY_E3T"  long_name="OXY * E3T"                                         unit="mmolO2/m2"  > OXY * e3t </field >
+
+      <!-- Ideal traceurs : variables available with key_idtra -->
+       <field id="IDTRA"    long_name="Ideal traceur concentration "                      unit="mmol/m3"    />
+
+       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
+       <field id="Num"         long_name="Number of organic particles"              unit="1" />
+       <field id="Num_E3T"     long_name="Num * E3T"                                unit="m"  > Num * e3t </field >
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="DET"         long_name="Detritus"                                 unit="mmol-N/m3" />
+       <field id="DET_E3T"     long_name="DET * E3T"                                unit="mmol-N/m2"  > DET * e3t </field >
+       <field id="DOM"         long_name="Dissolved Organic Matter"                 unit="mmol-N/m3" />
+       <field id="DOM_E3T"     long_name="DOM * E3T"                                unit="mmol-N/m2"  > DOM * e3t </field >
+
+       <!-- CFC11 : variables available with key_cfc -->
+       <field id="CFC11"       long_name="CFC-11 Concentration"                     unit="umol/m3" />
+       <field id="CFC11_E3T"   long_name="CFC11 * E3T"                              unit="umol/m2"  > CFC11 * e3t </field >
+       <!-- CFC12 : variables available with key_cfc -->
+       <field id="CFC12"       long_name="CFC-12 Concentration"                     unit="umol/m3" />
+       <field id="CFC12_E3T"   long_name="CFC12 * E3T"                              unit="umol/m2"  > CFC12 * e3t </field >
+       <!-- SF6 : variables available with key_cfc -->
+       <field id="SF6"         long_name="SF6 Concentration"                        unit="umol/m3" />
+       <field id="SF6_E3T"     long_name="SF6 * E3T"                                unit="umol/m2"  > SF6 * e3t </field >
+       <!-- Bomb C14 : variables available with key_c14b -->
+       <field id="C14B"        long_name="Bomb C14 Concentration"                   unit="1"         />
+       <field id="C14B_E3T"    long_name="C14B * E3T"                               unit="m"  > C14B * e3t </field >
+       <!-- AGE : variables available with key_age -->
+       <field id="Age"        long_name="Sea Water Age Since Surface contact" standard_name="sea_water_age_since_surface_contact"  unit="yr"         />
+       <field id="Age_e3t"    long_name="Age * e3t"                                 unit="yr * m"  > Age * e3t </field >
+     </field_group>
+
+     <!-- PISCES additional diagnostics on T grid  -->
+
+     <field_group id="diad_T" grid_ref="grid_T_2D">
+       <field id="PH"          long_name="PH"                                      unit="1"          grid_ref="grid_T_3D" />
+       <field id="CO3"         long_name="Bicarbonates"                            unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="CO3sat"      long_name="CO3 saturation"                          unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="PAR"         long_name="Photosynthetically Available Radiation"  unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PARDM"       long_name="Daily mean PAR"                          unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PPPHY"       long_name="Primary production of nanophyto"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPPHY2"      long_name="Primary production of diatoms"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPNEWN"      long_name="New Primary production of nanophyto"     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PPNEWD"      long_name="New Primary production of diatoms"       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PBSi"        long_name="Primary production of Si diatoms"        unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PFeN"        long_name="Primary production of nano iron"         unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="PFeD"        long_name="Primary production of diatoms iron"      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="xfracal"     long_name="Calcifying fraction"                     unit="1"          grid_ref="grid_T_3D" />
+       <field id="PCAL"        long_name="Calcite production"                      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DCAL"        long_name="Calcite dissolution"                     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ1"       long_name="Grazing by microzooplankton"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ2"       long_name="Grazing by mesozooplankton"              unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="REMIN"       long_name="Oxic remineralization of OM"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DENIT"       long_name="Anoxic remineralization of OM"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Nfix"        long_name="Nitrogen fixation"                       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Mumax"       long_name="Maximum growth rate"                     unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuN"         long_name="Realized growth rate for nanophyto"      unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuD"         long_name="Realized growth rate for diatomes"       unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="LNnut"       long_name="Nutrient limitation term in Nanophyto"   unit=""           grid_ref="grid_T_3D" />
+       <field id="LDnut"       long_name="Nutrient limitation term in Diatoms"     unit=""           grid_ref="grid_T_3D" />
+       <field id="LNFe"        long_name="Iron limitation term in Nanophyto"       unit=""           grid_ref="grid_T_3D" />
+       <field id="LDFe"        long_name="Iron limitation term in Diatoms"         unit=""           grid_ref="grid_T_3D" />
+       <field id="LNlight"     long_name="Light limitation term in Nanophyto"      unit=""           grid_ref="grid_T_3D" />
+       <field id="LDlight"     long_name="Light limitation term in Diatoms"        unit=""           grid_ref="grid_T_3D" />
+       <field id="Fe2"         long_name="Iron II concentration"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Fe3"         long_name="Iron III concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL1"        long_name="Complexed Iron concentration with L1"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL2"        long_name="Complexed Iron concentration with L2"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeP"         long_name="Precipitated Iron III"                   unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL1"         long_name="Total L1 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL2"         long_name="Total L2 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="pdust"       long_name="dust concentration"                      unit="g/m3"                            />
+       <field id="Totlig"      long_name="Total ligand concentation"               unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Biron"       long_name="Bioavailable iron"                       unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Sdenit"      long_name="Nitrate reduction in the sediments"      unit="mol/m2/s"                        />
+       <field id="Ironice"     long_name="Iron input/uptake due to sea ice"        unit="mol/m2/s"                        />
+       <field id="HYDR"        long_name="Iron input from hydrothemal vents"       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EPC100"      long_name="Export of carbon particles at 100 m"     unit="mol/m2/s"                        />
+       <field id="EPFE100"     long_name="Export of biogenic iron at 100 m"        unit="mol/m2/s"                        />
+       <field id="EPSI100"     long_name="Export of Silicate at 100 m"             unit="mol/m2/s"                        />
+       <field id="EPCAL100"    long_name="Export of Calcite at 100 m"              unit="mol/m2/s"                        />
+       <field id="EXPC"        long_name="Export of carbon"                        unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPFE"       long_name="Export of biogenic iron"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPSI"       long_name="Export of Silicate"                      unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPCAL"      long_name="Export of Calcite"                       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="Cflx"        long_name="DIC flux"                                unit="mol/m2/s"                        />
+       <field id="Oflx"        long_name="Oxygen flux"                             unit="mol/m2/s"                        />
+       <field id="Kg"          long_name="Gas transfer"                            unit="mol/m2/s/uatm"                   />
+       <field id="Dpco2"       long_name="Delta CO2"                               unit="uatm"                            />
+       <field id="Dpo2"        long_name="Delta O2"                                unit="uatm"                            />
+       <field id="Heup"        long_name="Euphotic layer depth"                    unit="m"                               />
+       <field id="Irondep"     long_name="Iron deposition from dust"               unit="mol/m2/s"                        />
+       <field id="Ironsed"     long_name="Iron deposition from sediment"           unit="mol/m2/s"   grid_ref="grid_T_3D" />
+
+
+       <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
+       <field id="EPN100"      long_name="Particulate number flux at 100 m"        unit="mol/m2/s"                        />
+       <field id="EXPN"        long_name="Particulate number flux"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="XNUM"        long_name="Number of particles in aggregats"        unit="1"          grid_ref="grid_T_3D" />
+       <field id="WSC"         long_name="sinking speed of mass flux"              unit="m2/s"       grid_ref="grid_T_3D" />
+       <field id="WSN"         long_name="sinking speed of number flux"            unit="m2/s"       grid_ref="grid_T_3D" />
+
+       <!-- dbio_T on T grid : variables available with key_diaar5 -->
+       <field id="TPP"         long_name="Total Primary production of phyto"                   unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPNEW"       long_name="New Primary production of phyto"                     unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPBFE"       long_name="Total biogenic iron production"                      unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="INTDIC"      long_name="DIC content"                                         unit="kg/m2"                          />
+       <field id="O2MIN"       long_name="Oxygen minimum concentration"                        unit="mol/m3"                          />
+       <field id="ZO2MIN"      long_name="Depth of oxygen minimum concentration"               unit="m"                              />
+       <field id="INTNFIX"     long_name="Nitrogen fixation rate : vert. integrated"           unit="mol/m2/s"                       />
+       <field id="INTPPPHY"    long_name="Vertically integrated primary production by nanophy" unit="mol/m2/s"                       />
+       <field id="INTPPPHY2"   long_name="Vertically integrated primary production by diatom"  unit="mol/m2/s"                       />
+       <field id="INTPP"       long_name="Vertically integrated primary production by phyto"   unit="mol/m2/s"                       />
+       <field id="INTPNEW"     long_name="Vertically integrated new primary production"        unit="mol/m2/s"                       />
+       <field id="INTPBFE"     long_name="Vertically integrated of biogenic iron production"   unit="mol/m2/s"                       />
+       <field id="INTPBSI"     long_name="Vertically integrated of biogenic Si production"     unit="mol/m2/s"                       />
+       <field id="INTPCAL"     long_name="Vertically integrated of calcite production"         unit="mol/m2/s"                       />
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="FNO3PHY"     long_name="FNO3PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4PHY"     long_name="FNH4PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4NO3"     long_name="FNH4NO3"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="TNO3PHY"     long_name="TNO3PHY"                                 unit=""  /> 
+       <field id="TNH4PHY"     long_name="TNH4PHY"                                 unit=""  /> 
+       <field id="TPHYDOM"     long_name="TPHYDOM"                                 unit=""  /> 
+       <field id="TPHYNH4"     long_name="TPHYNH4"                                 unit=""  /> 
+       <field id="TPHYZOO"     long_name="TPHYZOO"                                 unit=""  /> 
+       <field id="TPHYDET"     long_name="TPHYDET"                                 unit=""  /> 
+       <field id="TDETZOO"     long_name="TDETZOO"                                 unit=""  /> 
+       <field id="TZOODET"     long_name="TZOODET"                                 unit=""  /> 
+       <field id="TZOOBOD"     long_name="TZOOBOD"                                 unit=""  /> 
+       <field id="TZOONH4"     long_name="TZOONH4"                                 unit=""  /> 
+       <field id="TZOODOM"     long_name="TZOODOM"                                 unit=""  /> 
+       <field id="TNH4NO3"     long_name="TNH4NO3"                                 unit=""  /> 
+       <field id="TDOMNH4"     long_name="TDOMNH4"                                 unit=""  /> 
+       <field id="TDETNH4"     long_name="TDETNH4"                                 unit=""  /> 
+       <field id="TPHYTOT"     long_name="TPHYTOT"                                 unit=""  /> 
+       <field id="TZOOTOT"     long_name="TZOOTOT"                                 unit=""  /> 
+       <field id="SEDPOC"      long_name="SEDPOC"                                  unit=""  /> 
+       <field id="TDETSED"     long_name="TDETSED"                                 unit=""  /> 
+
+       <!-- CFC11 : variables available with key_cfc -->
+       <field id="qtrCFC11"    long_name="Air-sea flux of CFC-11"                  unit="mol/m2/s"   />
+       <field id="qintCFC11"   long_name="Cumulative air-sea flux of CFC-11"       unit="mol/m2"     />
+       <!-- CFC12 : variables available with key_cfc -->
+       <field id="qtrCFC12"    long_name="Air-sea flux of CFC-12"                  unit="mol/m2/s"   />
+       <field id="qintCFC12"   long_name="Cumulative air-sea flux of CFC-12"       unit="mol/m2"     />
+       <!-- SF6 : variables available with key_cfc -->
+       <field id="qtrSF6"    long_name="Air-sea flux of SF6"                  unit="mol/m2/s"   />
+       <field id="qintSF6"   long_name="Cumulative air-sea flux of SF6"       unit="mol/m2"     />
+
+       <!-- Bomb C14 : variables available with key_c14b -->
+       <field id="qtrC14b"     long_name="Air-sea flux of Bomb C14"                unit="mol/m2/s"   />
+       <field id="qintC14b"    long_name="Cumulative air-sea flux of Bomb C14"     unit="mol/m2"     />
+       <field id="fdecay"      long_name="Radiactive decay of Bomb C14"            unit="mol/m3"  grid_ref="grid_T_3D"  />
+
+       <!-- IDTRA : variables available with key_idtra -->
+       <field id="qtrIDTRA"    long_name="Air-sea flux of Ideal Tracer"             unit="mol/m2/s"   />
+       <field id="qintIDTRA"   long_name="Cumulative air-sea flux of Ideal Tracer"  unit="mol/m2"     />
+       <field id="invIDTRA"    long_name="Vertical inventory"                       unit="mol/m2"     />
+
+       <!-- MEDUSA additional diagnostics on T grid  -->
+       <field id= "INVTN"      long_name="Column N inventory"                        unit="mmolN/m2"    />
+       <field id= "INVTSI"     long_name="Column Si inventory"                       unit="mmolSi/m2"   />
+       <field id= "INVTFE"     long_name="Column Fe inventory"                       unit="mmolFe/m2"   />
+       <field id= "PRN"        long_name="Non-diatom primary production"             unit="mmolN/m2/d"  />
+       <field id= "MPN"        long_name="Non-diatom non-grazing losses"             unit="mmolN/m2/d"  />
+       <field id= "PRD"        long_name="Diatom primary production"                 unit="mmolN/m2/d"  />
+       <field id= "MPD"        long_name="Diatom non-grazing losses"                 unit="mmolN/m2/d"  />
+       <field id= "DSED"       long_name="Gravitational sinking of Detritus"         unit="mmolN/m2/d"  />
+       <field id= "OPAL"       long_name="Diatom biogenic opal production"           unit="mmolSi/m2/d" />
+       <field id= "OPALDISS"   long_name="Diatom biogenic opal dissolution"          unit="mmolSi/m2/d" />
+       <field id= "GMIPn"      long_name="Microzoo grazing on non-diatoms"           unit="mmolN/m2/d"  />
+       <field id= "GMID"       long_name="Microzoo grazing on detritus"              unit="mmolN/m2/d"  />
+       <field id= "MZMI"       long_name="Microzoo non-grazing losses"               unit="mmolN/m2/d"  />
+       <field id= "GMEPN"      long_name="Mesozoo grazing on non-diatoms"            unit="mmolN/m2/d"  />
+       <field id= "GMEPD"      long_name="Mesozoo grazing on non-diatoms"            unit="mmolN/m2/d"  />
+       <field id= "GMEZMI"     long_name="Mesozoo grazing on microzoo"               unit="mmolN/m2/d"  />
+       <field id= "GMED"       long_name="Mesozoo grazing on detritus"               unit="mmolN/m2/d"  />
+       <field id= "MZME"       long_name="Mesozoo non-grazing losses"                unit="mmolN/m2/d"  />
+       <field id= "DEXP"       long_name="Detritus export"                           unit="mmolN/m2/d"  />
+       <field id= "DETN"       long_name="Slow detritus creation"                    unit="mmolN/m2/d"  />
+       <field id= "MDET"       long_name="Detritus non-grazing losses"               unit="MmolN/m2/d"  />
+       <field id= "AEOLIAN"    long_name="Aeolian deposition of iron"                unit="mmolFe/m2/d" />
+       <field id= "BENTHIC"    long_name="Benthic supply of iron"                    unit="mmolFe/m2/d" />
+       <field id= "SCAVENGE"   long_name="Scavenged iron"                            unit="mmolFe/m2/d" />
+       <field id= "PN_JLIM"    long_name="Non-diatom light limitation"               unit="-"           />
+       <field id= "PN_NLIM"    long_name="Non-diatom N limitation"                   unit="-"           />
+       <field id= "PN_FELIM"   long_name="Non-diatom Fe limitation"                  unit="-"           />
+       <field id= "PD_JLIM"    long_name="Diatom light limitation"                   unit="-"           />
+       <field id= "PD_NLIM"    long_name="Diatom N limitation"                       unit="-"           />
+       <field id= "PD_FELIM"   long_name="Diatom Fe limitation"                      unit="-"           />
+       <field id= "PD_SILIM"   long_name="Diatom Si limitation"                      unit="-"           />
+       <field id= "PDSILIM2"   long_name="Diatom Si uptake limitation"               unit="-"           />
+       <field id= "SDT__100"   long_name="Slow detrital flux at  100 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT__200"   long_name="Slow detrital flux at  200 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT__500"   long_name="Slow detrital flux at  500 m"              unit="mmolN/m2/d"  />
+       <field id= "SDT_1000"   long_name="Slow detrital flux at 1000 m"              unit="mmolN/m2/d"  />
+       <field id= "TOTREG_N"   long_name="Full column regenerated N"                 unit="mmolN/m2/d"  />
+       <field id= "TOTRG_SI"   long_name="Full column regenerated Si"                unit="mmolSi/m2/d" />
+       <field id= "REG__100"   long_name="Regenerated N to  100 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG__200"   long_name="Regenerated N to  200 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG__500"   long_name="Regenerated N to  500 m"                   unit="mmolN/m2/d"  />
+       <field id= "REG_1000"   long_name="Regenerated N to 1000 m"                   unit="mmolN/m2/d"  />
+       <field id= "FASTN"      long_name="Fast-sinking flux N"                       unit="mmolN/m2/d"  />
+       <field id= "FASTSI"     long_name="Fast-sinking flux Si"                      unit="mmolSi/m2/d" />
+       <field id= "FASTFE"     long_name="Fast-sinking flux Fe"                      unit="mmolFe/m2/d" />
+       <field id= "FASTC"      long_name="Fast-sinking flux C"                       unit="mmolC/m2/d"  />
+       <field id= "FASTCA"     long_name="Fast-sinking flux CaCO3"                   unit="mmolC/m2/d"  />
+       <field id= "FDT__100"   long_name="Fast detrital N flux at  100 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT__200"   long_name="Fast detrital N flux at  200 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT__500"   long_name="Fast detrital N flux at  500 m"            unit="mmolN/m2/d"  />
+       <field id= "FDT_1000"   long_name="Fast detrital N flux at 1000 m"            unit="mmolN/m2/d"  />
+       <field id= "RG__100F"   long_name="Regenerated fast N to  100 m"              unit="mmolN/m2/d"  />
+       <field id= "RG__200F"   long_name="Regenerated fast N to  200 m"              unit="mmolN/m2/d"  />
+       <field id= "RG__500F"   long_name="Regenerated fast N to  500 m"              unit="mmolN/m2/d"  />
+       <field id= "RG_1000F"   long_name="Regenerated fast N to 1000 m"              unit="mmolN/m2/d"  />
+       <field id= "FDS__100"   long_name="Fast detrital Si flux at  100 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS__200"   long_name="Fast detrital Si flux at  200 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS__500"   long_name="Fast detrital Si flux at  500 m"           unit="mmolSi/m2/d" />
+       <field id= "FDS_1000"   long_name="Fast detrital Si flux at 1000 m"           unit="mmolSi/m2/d" />
+       <field id= "RGS_100F"   long_name="Regenerated fast Si to  100 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS_200F"   long_name="Regenerated fast Si to  200 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS_500F"   long_name="Regenerated fast Si to  500 m"             unit="mmolSi/m2/d" />
+       <field id= "RGS1000F"   long_name="Regenerated fast Si to 1000 m"             unit="mmolSi/m2/d" />
+       <field id= "REMINN"     long_name="Fast-sinking remin flux N"                 unit="mmolN/m2/d"  />
+       <field id= "REMINSI"    long_name="Fast-sinking remin flux Si"                unit="mmolSi/m2/d" />
+       <field id= "REMINFE"    long_name="Fast-sinking remin flux Fe"                unit="mmolFe/m2/d" />
+       <field id= "REMINC"     long_name="Fast-sinking remin flux C"                 unit="mmolC/m2/d"  />
+       <field id= "REMINCA"    long_name="Fast-sinking remin flux CaCO3"             unit="mmolC/m2/d"  />
+       <field id= "SEAFLRN"    long_name="Seafloor flux of N"                        unit="mmolN/m2/d"  />
+       <field id= "SEAFLRSI"   long_name="Seafloor flux of Si"                       unit="mmolSi/m2/d" />
+       <field id= "SEAFLRFE"   long_name="Seafloor flux of Fe"                       unit="mmolFe/m2/d" />
+       <field id= "SEAFLRC"    long_name="Seafloor flux of C"                        unit="mmolC/m2/d"  />
+       <field id= "SEAFLRCA"   long_name="Seafloor flux of CaCO3"                    unit="mmolC/m2/d"  />
+       <field id= "MED_QSR"    long_name="Sea surface radiation"                     unit="W/m2"        />
+       <field id= "MED_XPAR"   long_name="Top level radiation"                       unit="W/m2"        />
+       <field id= "INTFLX_N"   long_name="Integrated N  cycle fluxes"                unit="mmolN/m2/d"  />
+       <field id= "INTFLX_SI"  long_name="Integrated Si cycle fluxes"                unit="mmolSi/m2/d" />
+       <field id= "INTFLX_FE"  long_name="Integrated Fe cycle fluxes"                unit="mmolFe/m2/d" />
+       <field id= "INT_PN"     long_name="Vertically integrated Pn"                  unit="mmolN/m2"    />
+       <field id= "INT_PD"     long_name="Vertically integrated Pd"                  unit="mmolN/m2"    />
+       <field id= "ML_PRN"     long_name="Non-diatom mixed layer PP"                 unit="mmolN/m2/d"  />
+       <field id= "ML_PRD"     long_name="Diatom mixed layer PP"                     unit="mmolN/m2/d"  />
+       <field id= "OCAL_CCD"   long_name="Calcite CCD depth"                         unit="m"           />
+       <field id= "OCAL_LVL"   long_name="Calcite CCD level"                         unit="-"           />
+       <field id= "FE_0000"    long_name="Free iron at    0m"                        unit="-"           />
+       <field id= "FE_0100"    long_name="Free iron at  100m"                        unit="-"           />
+       <field id= "FE_0200"    long_name="Free iron at  200m"                        unit="-"           />
+       <field id= "FE_0500"    long_name="Free iron at  500m"                        unit="-"           />
+       <field id= "FE_1000"    long_name="Free iron at 1000m"                        unit="-"           />
+       <field id= "MED_XZE"    long_name="Euphotic depth"                            unit="m"           />
+       <field id= "WIND"       long_name="Surface scalar wind"                       unit="m/s"         />
+       <field id= "ATM_PCO2"   long_name="Atmospheric pCO2"                          unit="uatm"        />
+       <field id= "OCN_PH"     long_name="Surface ocean pH"                          unit="-"           />
+       <field id= "OCN_PCO2"   long_name="Surface ocean pCO2"                        unit="uatm"        />
+       <field id= "OCNH2CO3"   long_name="Surface ocean H2CO3 conc"                  unit="mmolC/m3"    />
+       <field id= "OCN_HCO3"   long_name="Surface ocean HCO3 conc"                   unit="mmolC/m3"    />
+       <field id= "OCN_CO3"    long_name="Surface ocean CO3 conc"                    unit="mmolC/m3"    />
+       <field id= "CO2FLUX"    long_name="Air-sea CO2 flux"                          unit="mmolC/m2/d"  />
+       <field id= "FGCO2"      long_name="Surface Downward CO2 Flux"                 unit="kg-CO2/m2/s" />
+       <field id= "OM_CAL"     long_name="Omega calcite"                             unit="-"           />
+       <field id= "OM_ARG"     long_name="Omega aragonite"                           unit="-"           />
+       <field id= "TCO2"       long_name="Total CO2"                                 unit="umol/kg"     />
+       <field id= "TALK"       long_name="Total alkalinity"                          unit="ueq/kg"      />
+       <field id= "KW660"      long_name="Piston velocity"                           unit="m/s"         />
+       <field id= "ATM_PP0"    long_name="Atmospheric pressure"                      unit="atm"         />
+       <field id= "O2FLUX"     long_name="Air-sea O2 flux"                           unit="mmolO2/m2/d" />
+       <field id= "O2SAT"      long_name="Surface ocean O2 saturation"               unit="mmolO2/m3"   />
+       <field id= "CAL_CCD"    long_name="Calcite CCD depth"                         unit="m"           />
+       <field id= "ARG_CCD"    long_name="Aragonite CCD depth"                       unit="m"           />
+       <field id= "SFR_OCAL"   long_name="Seafloor omega calcite"                    unit="-"           />
+       <field id= "SFR_OARG"   long_name="Seafloor omega aragonite"                  unit="-"           />
+       <field id= "N_PROD"     long_name="Nitrogen production"                       unit="mmolN/m2/d"  />
+       <field id= "N_CONS"     long_name="Nitrogen consumption"                      unit="mmolN/m2/d"  />
+       <field id= "C_PROD"     long_name="Carbon production"                         unit="mmolC/m2/d"  />
+       <field id= "C_CONS"     long_name="Carbon consumption"                        unit="mmolC/m2/d"  />
+       <field id= "O2_PROD"    long_name="Oxygen production"                         unit="mmolO2/m2/d" />
+       <field id= "O2_CONS"    long_name="Oxygen consumption"                        unit="mmolO2/m2/d" />
+       <field id= "O2_ANOX"    long_name="Unrealised oxygen consumption"             unit="mmolO2/m2/d" />
+       <field id= "RR_0100"    long_name="Rain ratio at  100m"                       unit="molC/molC"   />
+       <field id= "RR_0500"    long_name="Rain ratio at  500m"                       unit="molC/molC"   />
+       <field id= "RR_1000"    long_name="Rain ratio at 1000m"                       unit="molC/molC"   />
+       <field id= "IBEN_N"     long_name="Benthic input nitrogen"                    unit="mmolN/m2/d"  />
+       <field id= "IBEN_FE"    long_name="Benthic input iron"                        unit="mmolFe/m2/d" />
+       <field id= "IBEN_C"     long_name="Benthic input carbon"                      unit="mmolC/m2/d"  />
+       <field id= "IBEN_SI"    long_name="Benthic input silicon"                     unit="mmolSi/m2/d" />
+       <field id= "IBEN_CA"    long_name="Benthic input CaCO3"                       unit="mmolC/m2/d"  />
+       <field id= "OBEN_N"     long_name="Benthic output nitrogen"                   unit="mmolN/m2/d"  />
+       <field id= "OBEN_FE"    long_name="Benthic output iron"                       unit="mmolFe/m2/d" />
+       <field id= "OBEN_C"     long_name="Benthic output carbon"                     unit="mmolC/m2/d"  />
+       <field id= "OBEN_SI"    long_name="Benthic output silicon"                    unit="mmolSi/m2/d" />
+       <field id= "OBEN_CA"    long_name="Benthic output CaCO3"                      unit="mmolC/m2/d"  />
+       <field id= "BEN_N"      long_name="Benthic nitrogen"                          unit="mmolN/m2"    />
+       <field id= "BEN_FE"     long_name="Benthic iron"                              unit="mmolFe/m2"   />
+       <field id= "BEN_C"      long_name="Benthic carbon"                            unit="mmolC/m2"    />
+       <field id= "BEN_SI"     long_name="Benthic silicon"                           unit="mmolSi/m2"   />
+       <field id= "BEN_CA"     long_name="Benthic CaCO3"                             unit="mmolC/m2"    />
+       <field id= "RUNOFF"     long_name="River runoff"                              unit="m/d"         />
+       <field id= "RIV_N"      long_name="Riverine input nitrogen"                   unit="mmolN/m2/d"  />
+       <field id= "RIV_SI"     long_name="Riverine input silicon"                    unit="mmolSi/m2/d" />
+       <field id= "RIV_C"      long_name="Riverine input carbon"                     unit="mmolSi/m2/d" />
+       <field id= "RIV_ALK"    long_name="Riverine input alkalinity"                 unit="meq/m2/d"    />
+       <field id= "DETC"       long_name="Slow detritus C creation"                  unit="mmolC/m2/d"  />
+       <field id= "SDC__100"   long_name="Slow detrital C flux at  100 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC__200"   long_name="Slow detrital C flux at  200 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC__500"   long_name="Slow detrital C flux at  500 m"            unit="mmolC/m2/d"  />
+       <field id= "SDC_1000"   long_name="Slow detrital C flux at 1000 m"            unit="mmolC/m2/d"  />
+       <field id= "INVTC"      long_name="Column C inventory"                        unit="mmolC/m2"    />
+       <field id= "INVTALK"    long_name="Column alkalinity inventory"               unit="meq/m2"      />
+       <field id= "INVTO2"     long_name="Column O2 inventory"                       unit="mmolO2/m2"   />
+       <field id= "LYSO_CA"    long_name="Incorrect benthic output CaCO3"            unit="mmolC/m2/d"  />
+       <field id= "COM_RESP"   long_name="Community respiration"                     unit="mmolC/m2/d"  />
+       <field id= "PN_LLOSS"   long_name="Non-diatom linear losses"                  unit="mmolN/m2/d"  />
+       <field id= "PD_LLOSS"   long_name="Diatom linear losses"                      unit="mmolN/m2/d"  />
+       <field id= "ZI_LLOSS"   long_name="Microzooplankton linear losses"            unit="mmolN/m2/d"  />
+       <field id= "ZE_LLOSS"   long_name="Mesozooplankton linear losses"             unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_N"   long_name="Microzoo messy feeding loss to N"          unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_D"   long_name="Microzoo messy feeding loss to D"          unit="mmolN/m2/d"  />
+       <field id= "ZI_MES_C"   long_name="Microzoo messy feeding loss to C"          unit="mmolC/m2/d"  />
+       <field id= "ZI_MESDC"   long_name="Microzoo messy feeding loss to Dc"         unit="mmolC/m2/d"  />
+       <field id= "ZI_EXCR"    long_name="Microzoo excretion"                        unit="mmolN/m2/d"  />
+       <field id= "ZI_RESP"    long_name="Microzoo respiration"                      unit="mmolC/m2/d"  />
+       <field id= "ZI_GROW"    long_name="Microzoo growth"                           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_N"   long_name="Mesozoo messy feeding loss to N"           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_D"   long_name="Mesozoo messy feeding loss to D"           unit="mmolN/m2/d"  />
+       <field id= "ZE_MES_C"   long_name="Mesozoo messy feeding loss to C"           unit="mmolC/m2/d"  />
+       <field id= "ZE_MESDC"   long_name="Mesozoo messy feeding loss to Dc"          unit="mmolC/m2/d"  />
+       <field id= "ZE_EXCR"    long_name="Mesozoo excretion"                         unit="mmolN/m2/d"  />
+       <field id= "ZE_RESP"    long_name="Mesozoo respiration"                       unit="mmolC/m2/d"  />
+       <field id= "ZE_GROW"    long_name="Mesozoo growth"                            unit="mmolN/m2/d"  />
+       <field id= "MDETC"      long_name="Detritus non-grazing losses, carbon"       unit="mmolC/m2/d"  />
+       <field id= "GMIDC"      long_name="Microzoo grazing on detritus, carbon"      unit="mmolC/m2/d"  />
+       <field id= "GMEDC"      long_name="Mesozoo  grazing on detritus, carbon"      unit="mmolC/m2/d"  />
+       <field id= "INT_ZMI"    long_name="Vertically integrated Zmi"                 unit="mmolN/m2"    />
+       <field id= "INT_ZME"    long_name="Vertically integrated Zme"                 unit="mmolN/m2"    />
+       <field id= "INT_DET"    long_name="Vertically integrated Det"                 unit="mmolN/m2"    />
+       <field id= "INT_DTC"    long_name="Vertically integrated Dtc"                 unit="mmolC/m2"    />
+       <field id= "DMS_SURF"   long_name="DMS Surface Concentration"                 unit="nmol/L"      />
+       <field id= "DMS_ANDR"   long_name="DMS Surface Concentration, Anderson"       unit="nmol/L"      />
+       <field id= "DMS_SIMO"   long_name="DMS Surface Concentration, SimoDach"       unit="nmol/L"      />
+       <field id= "DMS_ARAN"   long_name="DMS Surface Concentration, AranamiT"       unit="nmol/L"      />
+       <field id= "DMS_HALL"   long_name="DMS Surface Concentration, Halloran"       unit="nmol/L"      />
+       <field id= "DMS_ANDM"   long_name="DMS Surface Concentration, Anderson modif" unit="nmol/L"      />
+       <field id= "ATM_XCO2"   long_name="Atmospheric xCO2"                          unit="ppm"         />
+       <field id= "OCN_FCO2"   long_name="Surface ocean fCO2"                        unit="uatm"        />
+       <field id= "ATM_FCO2"   long_name="Atmospheric fCO2"                          unit="uatm"        />
+       <field id= "OCN_RHOSW"  long_name="MOCSY rhoSW"                               unit="kg/m3"       />
+       <field id= "OCN_SCHCO2" long_name="MOCSY Schmidt CO2"                         unit="-"           />
+       <field id= "OCN_KWCO2"  long_name="MOCSY kw CO2"                              unit="m/s"         />
+       <field id= "OCN_K0"     long_name="MOCSY k0"                                  unit="(mol/kg)/atm" />
+       <field id= "CO2STARAIR" long_name="MOCSY CO2star air"                         unit="mmol/m3"     />
+       <field id= "OCN_DPCO2"  long_name="MOCSY delta pCO2"                          unit="uatm"        />
+       
+
+       <!-- AXY (08/11/16): add new 2D CMIP6 diagnostics -->
+       <field id= "epC100"     long_name="Downward Flux of Particle Organic Carbon"  unit="mmolC/m2/d"  />
+       <field id= "epCALC100"  long_name="Downward Flux of Calcite"                  unit="mmolC/m2/d"  />
+       <field id= "epN100"     long_name="Downward Flux of Particulate Nitrogen"     unit="mmolN/m2/d"  />
+       <field id= "epSI100"    long_name="Downward Flux of Particulate Silica"       unit="mmolSi/m2/d" />
+       <field id= "INTDISSIC"  long_name="Dissolved Inorganic Carbon Content"        unit="mmolC/m2"    />
+       <field id= "INTDISSIN"  long_name="Dissolved Inorganic Nitrogen Content"      unit="mmolN/m2"    />
+       <field id= "INTDISSISI" long_name="Dissolved Inorganic Silicon Content"       unit="mmolSi/m2"   />
+       <field id= "INTTALK"    long_name="Dissolved Alkalinity Content"              unit="meq/m2"      />
+       <field id= "O2min"      long_name="Oxygen Minimum Concentration"              unit="mmolO2/m3"   />
+       <field id= "ZO2min"     long_name="Depth of Oxygen Minimum Concentration"     unit="m"           />
+       <field id= "FBDDTALK"   long_name="Int. change of Alkalinity due to Biology"  unit="meq/m2/d"    />
+       <field id= "FBDDTDIC"   long_name="Int. change of DI Carbon due to Biology"   unit="mmolC/m2/d"  />
+       <field id= "FBDDTDIFE"  long_name="Int. change of DI Iron due to Biology"     unit="mmolFe/m2/d" />
+       <field id= "FBDDTDIN"   long_name="Int. change of DI Nitrogen due to Biology" unit="mmolN/m2/d"  />
+       <field id= "FBDDTDISI"  long_name="Int. change of DI Silicon due to Biology"  unit="mmolSi/m2/d" />
+       
+
+       <!-- MEDUSA 3D diagnostics -->
+       <field id= "TPP3"       long_name="Total primary production 3D"               unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "DETFLUX3"   long_name="Total detrital flux 3D"                    unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "REMIN3N"    long_name="Total remin flux N 3D"                     unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "PH3"        long_name="Ocean pH 3D"                               unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "OM_CAL3"    long_name="Omega calcite 3D"                          unit="-"             grid_ref="grid_T_3D"  />
+
+       <!-- AXY (08/11/16): add new 3D CMIP6 diagnostics -->
+       <field id= "TPPD3"      long_name="Diatom primary production 3D"              unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTALK3"   long_name="Change of Alkalinity due to Biology"       unit="meq/m3/d"      grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIC3"   long_name="Change of DI Carbon due to Biology"        unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIFE3"  long_name="Change of DI Iron due to Biology"          unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "BDDTDIN3"   long_name="Change of DI Nitrogen due to Biology"      unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "BDDTDISI3"  long_name="Change of DI Silicon due to Biology"       unit="mmolSi/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "FD_NIT3"    long_name="Fast sinking detrital nitrogen"            unit="mmolN/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "FD_SIL3"    long_name="Fast sinking detrital silicon"             unit="mmolSi/m2/d"   grid_ref="grid_T_3D"  />
+       <field id= "FD_CAR3"    long_name="Fast sinking detrital carbon"              unit="mmolC/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "FD_CAL3"    long_name="Fast sinking detrital calcium carbonate"   unit="mmolC/m2/d"    grid_ref="grid_T_3D"  />
+       <field id= "CO33"       long_name="Carbonate ion concentration"               unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "CO3SATARAG3" long_name="Carbonate aragonite saturation conc"      unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "CO3SATCALC3" long_name="Carbonate calcite saturation conc"        unit="mmolC/m3"      grid_ref="grid_T_3D"  />
+       <field id= "DCALC3"     long_name="Calcite dissolution"                       unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "EXPC3"      long_name="Downward Flux of Particulate Org Carbon"   unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "EXPN3"      long_name="Downward Flux of Particulate Org Nitrogen" unit="mmolN/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "FEDISS3"    long_name="Particle Source of Dissolved Iron"         unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "FESCAV3"    long_name="Nonbiogenic Iron Scavenging"               unit="mmolFe/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "MIGRAZP3"   long_name="Microzooplankton grazing on phytoplankton" unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MIGRAZD3"   long_name="Microzooplankton grazing on detritus"      unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZP3"   long_name="Mesozooplankton grazing on phytoplankton"  unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZD3"   long_name="Mesozooplankton grazing on detritus"       unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "MEGRAZZ3"   long_name="Mesozooplankton grazing on microzoop"      unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "O2SAT3"     long_name="Dissolved Oxygen Saturation Concentration" unit="mmolO2/m3"     grid_ref="grid_T_3D"  />
+       <field id= "PBSI3"      long_name="Biogenic Silica Production"                unit="mmolSi/m3/d"   grid_ref="grid_T_3D"  />
+       <field id= "PCAL3"      long_name="Biogenic Calcite Production"               unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "REMOC3"     long_name="Remineralization of Organic Carbon"        unit="mmolC/m3/d"    grid_ref="grid_T_3D"  />
+       <field id= "PNLIMJ3"    long_name="Irradiance limitation of non-diatoms"      unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PNLIMN3"    long_name="Nitrogen limitation of non-diatoms"        unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PNLIMFE3"   long_name="Iron limitation of non-diatoms"            unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMJ3"    long_name="Irradiance limitation of diatoms"          unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMN3"    long_name="Nitrogen limitation of diatoms"            unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMFE3"   long_name="Iron limitation of diatoms"                unit="-"             grid_ref="grid_T_3D"  />
+       <field id= "PDLIMSI3"   long_name="Silicon limitation of diatoms"             unit="-"             grid_ref="grid_T_3D"  />
+
+     </field_group>
+
+     <field_group id="PISCES_scalar"  grid_ref="scalar" >
+       <field id="pno3tot"         long_name="global mean nitrate concentration"                  unit="mol/m3"   />
+       <field id="ppo4tot"         long_name="global mean phosphorus concentration"               unit="mol/m3"   />
+       <field id="psiltot"         long_name="global mean silicate concentration"                 unit="mol/m3"   />
+       <field id="palktot"         long_name="global mean alkalinity concentration"               unit="mol/m3"   />
+       <field id="pfertot"         long_name="global mean iron concentration"                     unit="mol/m3"   />
+       <field id="tcflx"           long_name="total Flux of Carbon out of the ocean"              unit="mol/s"   />
+       <field id="tcflxcum"        long_name="cumulative total Flux of Carbon out of the ocean"   unit="mol/s"   />
+       <field id="tcexp"           long_name="total Carbon export at 100m"                        unit="mol/s"   />
+       <field id="tintpp"          long_name="global total integrated primary production"         unit="mol/s"   />
+       <field id="tnfix"           long_name="global total nitrogen fixation"                     unit="mol/s"   />
+       <field id="tdenit"          long_name="Total denitrification"                              unit="mol/s"   />
+     </field_group>
+
+    <!-- 
+============================================================================================================
+                                        Definitions for iodef_demo.xml
+============================================================================================================
+    -->
+
+    <field_group id="groupMEDUSA" >
+      <field field_ref="CHN"     name="CHN"      />
+      <field field_ref="CHN_E3T" name="CHN_E3T"  />
+      <field field_ref="CHD"     name="CHD"      />
+      <field field_ref="CHD_E3T" name="CHD_E3T"  />
+      <field field_ref="PHN"     name="PHN"      />
+      <field field_ref="PHN_E3T" name="PHN_E3T"  />
+      <field field_ref="PHD"     name="PHD"      />
+      <field field_ref="PHD_E3T" name="PHD_E3T"  />
+      <field field_ref="ZMI"     name="ZMI"      />
+      <field field_ref="ZMI_E3T" name="ZMI_E3T"  />
+      <field field_ref="ZME"     name="ZME"      />
+      <field field_ref="ZME_E3T" name="ZME_E3T"  />
+      <field field_ref="DIN"     name="DIN"      />
+      <field field_ref="DIN_E3T" name="DIN_E3T"  />
+      <field field_ref="SIL"     name="SIL"      />
+      <field field_ref="SIL_E3T" name="SIL_E3T"  />
+      <field field_ref="FER"     name="FER"      />
+      <field field_ref="FER_E3T" name="FER_E3T"  />
+      <field field_ref="DET"     name="DET"      />
+      <field field_ref="DET_E3T" name="DET_E3T"  />
+      <field field_ref="PDS"     name="PDS"      />
+      <field field_ref="PDS_E3T" name="PDS_E3T"  />
+      <field field_ref="DTC"     name="DTC"      />
+      <field field_ref="DTC_E3T" name="DTC_E3T"  />
+      <field field_ref="DiC"     name="DIC"      />
+      <field field_ref="DiC_E3T" name="DIC_E3T"  />
+      <field field_ref="ALK"     name="ALK"      />
+      <field field_ref="ALK_E3T" name="ALK_E3T"  />
+      <field field_ref="OXY"     name="OXY"      />
+      <field field_ref="OXY_E3T" name="OXY_E3T"  />
+      </field_group>
+
+    <field_group id="groupIDTRA" >
+      <field field_ref="IDTRA" name="IDTRA" />
+    </field_group>
+
+    <field_group id="groupIDTRA_dia" >
+      <field field_ref="qtrIDTRA"    name="qtrIDTRA"  />
+      <field field_ref="qintIDTRA"   name="qintIDTRA" />
+      <field field_ref="invIDTRA"    name="invIDTRA"  />
+    </field_group>
+
+    <field_group id="groupCFC" >
+      <field field_ref="CFC11"     name="CFC11"     />
+      <field field_ref="CFC11_E3T" name="CFC11_E3T" />
+      <field field_ref="CFC12"     name="CFC12"     />
+      <field field_ref="CFC12_E3T" name="CFC12_E3T" />
+      <field field_ref="SF6"       name="SF6"       />
+      <field field_ref="SF6_E3T"   name="SF6_E3T"   />
+    </field_group>
+
+    <field_group id="groupCFC_dia" >
+      <field field_ref="qtrCFC11"    name="qtrCFC11"   />
+      <field field_ref="qintCFC11"   name="qintCFC11"  />
+      <field field_ref="qtrCFC12"    name="qtrCFC12"   />
+      <field field_ref="qintCFC12"   name="qintCFC12"  />
+      <field field_ref="qtrSF6"      name="qtrSF6"     />
+      <field field_ref="qintSF6"     name="qintSF6"    />
+    </field_group>
+
+    <field_group id="groupAGE" >
+      <field field_ref="Age" name="Age" />
+    </field_group>
+
+    <field_group id="groupMEDUSA_dia" >
+      <field field_ref= "INVTN"      name="INVTN"      />
+      <field field_ref= "INVTSI"     name="INVTSI"     />
+      <field field_ref= "INVTFE"     name="INVTFE"     />
+      <field field_ref= "PRN"        name="PRN"        />
+      <field field_ref= "MPN"        name="MPN"        />
+      <field field_ref= "PRD"        name="PRD"        />
+      <field field_ref= "MPD"        name="MPD"        />
+      <field field_ref= "OPAL"       name="OPAL"       />
+      <field field_ref= "OPALDISS"   name="OPALDISS"   />
+      <field field_ref= "GMIPn"      name="GMIPn"      />
+      <field field_ref= "GMID"       name="GMID"       />
+      <field field_ref= "MZMI"       name="MZMI"       />
+      <field field_ref= "GMEPN"      name="GMEPN"      />
+      <field field_ref= "GMEPD"      name="GMEPD"      />
+      <field field_ref= "GMEZMI"     name="GMEZMI"     />
+      <field field_ref= "GMED"       name="GMED"       />
+      <field field_ref= "MZME"       name="MZME"       />
+      <field field_ref= "DETN"       name="DETN"       />
+      <field field_ref= "MDET"       name="MDET"       />
+      <field field_ref= "AEOLIAN"    name="AEOLIAN"    />
+      <field field_ref= "BENTHIC"    name="BENTHIC"    />
+      <field field_ref= "SCAVENGE"   name="SCAVENGE"   />
+      <field field_ref= "PN_JLIM"    name="PN_JLIM"    />
+      <field field_ref= "PN_NLIM"    name="PN_NLIM"    />
+      <field field_ref= "PN_FELIM"   name="PN_FELIM"   />
+      <field field_ref= "PD_JLIM"    name="PD_JLIM"    />
+      <field field_ref= "PD_NLIM"    name="PD_NLIM"    />
+      <field field_ref= "PD_FELIM"   name="PD_FELIM"   />
+      <field field_ref= "PD_SILIM"   name="PD_SILIM"   />
+      <field field_ref= "PDSILIM2"   name="PDSILIM2"   />
+      <field field_ref= "SDT__100"   name="SDT__100"   />
+      <field field_ref= "SDT__200"   name="SDT__200"   />
+      <field field_ref= "SDT__500"   name="SDT__500"   />
+      <field field_ref= "SDT_1000"   name="SDT_1000"   />
+      <field field_ref= "TOTREG_N"   name="TOTREG_N"   />
+      <field field_ref= "TOTRG_SI"   name="TOTRG_SI"   />
+      <field field_ref= "REG__100"   name="REG__100"   />
+      <field field_ref= "REG__200"   name="REG__200"   />
+      <field field_ref= "REG__500"   name="REG__500"   />
+      <field field_ref= "REG_1000"   name="REG_1000"   />
+      <field field_ref= "FASTN"      name="FASTN"      />
+      <field field_ref= "FASTSI"     name="FASTSI"     />
+      <field field_ref= "FASTFE"     name="FASTFE"     />
+      <field field_ref= "FASTC"      name="FASTC"      />
+      <field field_ref= "FASTCA"     name="FASTCA"     />
+      <field field_ref= "FDT__100"   name="FDT__100"   />
+      <field field_ref= "FDT__200"   name="FDT__200"   />
+      <field field_ref= "FDT__500"   name="FDT__500"   />
+      <field field_ref= "FDT_1000"   name="FDT_1000"   /> 
+      <field field_ref= "RG__100F"   name="RG__100F"   />
+      <field field_ref= "RG__200F"   name="RG__200F"   />
+      <field field_ref= "RG__500F"   name="RG__500F"   />
+      <field field_ref= "RG_1000F"   name="RG_1000F"   />
+      <field field_ref= "FDS__100"   name="FDS__100"   />
+      <field field_ref= "FDS__200"   name="FDS__200"   />
+      <field field_ref= "FDS__500"   name="FDS__500"   />
+      <field field_ref= "FDS_1000"   name="FDS_1000"   />
+      <field field_ref= "RGS_100F"   name="RGS_100F"   />
+      <field field_ref= "RGS_200F"   name="RGS_200F"   />
+      <field field_ref= "RGS_500F"   name="RGS_500F"   />
+      <field field_ref= "RGS1000F"   name="RGS1000F"   />
+      <field field_ref= "REMINN"     name="REMINN"     />
+      <field field_ref= "REMINSI"    name="REMINSI"    />
+      <field field_ref= "REMINFE"    name="REMINFE"    />
+      <field field_ref= "SEAFLRN"    name="SEAFLRN"    /> 
+      <field field_ref= "SEAFLRSI"   name="SEAFLRSI"   />
+      <field field_ref= "SEAFLRFE"   name="SEAFLRFE"   />
+      <field field_ref= "SEAFLRC"    name="SEAFLRC"    />
+      <field field_ref= "SEAFLRCA"   name="SEAFLRCA"   />
+      <field field_ref= "MED_QSR"    name="MED_QSR"    />
+      <field field_ref= "MED_XPAR"   name="MED_XPAR"   />
+      <field field_ref= "INTFLX_N"   name="INTFLX_N"   />
+      <field field_ref= "INTFLX_SI"  name="INTFLX_SI"  />
+      <field field_ref= "INTFLX_FE"  name="INTFLX_FE"  />
+      <field field_ref= "INT_PN"     name="INT_PN"     />
+      <field field_ref= "INT_PD"     name="INT_PD"     />
+      <field field_ref= "ML_PRN"     name="ML_PRN"     />
+      <field field_ref= "ML_PRD"     name="ML_PRD"     />
+      <field field_ref= "OCAL_CCD"   name="OCAL_CCD"   />
+      <field field_ref= "OCAL_LVL"   name="OCAL_LVL"   />
+      <field field_ref= "FE_0000"    name="FE_0000"    />
+      <field field_ref= "FE_0100"    name="FE_0100"    />
+      <field field_ref= "FE_0200"    name="FE_0200"    /> 
+      <field field_ref= "FE_0500"    name="FE_0500"    />
+      <field field_ref= "FE_1000"    name="FE_1000"    />
+      <field field_ref= "MED_XZE"    name="MED_XZE"    />
+      <field field_ref= "WIND"       name="WIND"       />
+      <field field_ref= "ATM_PCO2"   name="ATM_PCO2"   />
+      <field field_ref= "OCN_PH"     name="OCN_PH"     />
+      <field field_ref= "OCN_PCO2"   name="OCN_PCO2"   />
+      <field field_ref= "OCNH2CO3"   name="OCNH2CO3"   />
+      <field field_ref= "OCN_HCO3"   name="OCN_HCO3"   />
+      <field field_ref= "OCN_CO3"    name="OCN_CO3"    />
+      <field field_ref= "CO2FLUX"    name="CO2FLUX"    />
+      <field field_ref= "FGCO2"      name="FGCO2"      />
+      <field field_ref= "OM_CAL"     name="OM_CAL"     />
+      <field field_ref= "OM_ARG"     name="OM_ARG"     />
+      <field field_ref= "TCO2"       name="TCO2"       />
+      <field field_ref= "TALK"       name="TALK"       />
+      <field field_ref= "KW660"      name="KW660"      />
+      <field field_ref= "ATM_PP0"    name="ATM_PP0"    />
+      <field field_ref= "O2FLUX"     name="O2FLUX"     />
+      <field field_ref= "O2SAT"      name="O2SAT"      />
+      <field field_ref= "CAL_CCD"    name="CAL_CCD"    />
+      <field field_ref= "ARG_CCD"    name="ARG_CCD"    />
+      <field field_ref= "SFR_OCAL"   name="SFR_OCAL"   />
+      <field field_ref= "SFR_OARG"   name="SFR_OARG"   />
+      <field field_ref= "N_PROD"     name="N_PROD"     />
+      <field field_ref= "N_CONS"     name="N_CONS"     />
+      <field field_ref= "C_PROD"     name="C_PROD"     />
+      <field field_ref= "C_CONS"     name="C_CONS"     />
+      <field field_ref= "O2_PROD"    name="O2_PROD"    />
+      <field field_ref= "O2_CONS"    name="O2_CONS"    />
+      <field field_ref= "O2_ANOX"    name="O2_ANOX"    />
+      <field field_ref= "RR_0100"    name="RR_0100"    />
+      <field field_ref= "RR_0500"    name="RR_0500"    />
+      <field field_ref= "RR_1000"    name="RR_1000"    />
+      <field field_ref= "IBEN_N"     name="IBEN_N"     />
+      <field field_ref= "IBEN_FE"    name="IBEN_FE"    />
+      <field field_ref= "IBEN_C"     name="IBEN_C"     />
+      <field field_ref= "IBEN_SI"    name="IBEN_SI"    />
+      <field field_ref= "IBEN_CA"    name="IBEN_CA"    />
+      <field field_ref= "OBEN_N"     name="OBEN_N"     />
+      <field field_ref= "OBEN_FE"    name="OBEN_FE"    />
+      <field field_ref= "OBEN_C"     name="OBEN_C"     />
+      <field field_ref= "OBEN_SI"    name="OBEN_SI"    />
+      <field field_ref= "OBEN_CA"    name="OBEN_CA"    />
+      <field field_ref= "BEN_N"      name="BEN_N"      />
+      <field field_ref= "BEN_FE"     name="BEN_FE"     />
+      <field field_ref= "BEN_C"      name="BEN_C"      />
+      <field field_ref= "BEN_SI"     name="BEN_SI"     />
+      <field field_ref= "BEN_CA"     name="BEN_CA"     />
+      <field field_ref= "DETC"       name="DETC"       />
+      <field field_ref= "SDC__100"   name="SDC__100"   />
+      <field field_ref= "SDC__200"   name="SDC__200"   />
+      <field field_ref= "SDC__500"   name="SDC__500"   />
+      <field field_ref= "SDC_1000"   name="SDC_1000"   />
+      <field field_ref= "INVTC"      name="INVTC"      />
+      <field field_ref= "INVTALK"    name="INVTALK"    />
+      <field field_ref= "INVTO2"     name="INVTO2"     />
+      <field field_ref= "LYSO_CA"    name="LYSO_CA"    />
+      <field field_ref= "COM_RESP"   name="COM_RESP"   />
+      <field field_ref= "PN_LLOSS"   name="PN_LLOSS"   />
+      <field field_ref= "PD_LLOSS"   name="PD_LLOSS"   />
+      <field field_ref= "ZI_LLOSS"   name="ZI_LLOSS"   />
+      <field field_ref= "ZE_LLOSS"   name="ZE_LLOSS"   />
+      <field field_ref= "ZI_MES_N"   name="ZI_MES_N"   />
+      <field field_ref= "ZI_MES_D"   name="ZI_MES_D"   />
+      <field field_ref= "ZI_MES_C"   name="ZI_MES_C"   />
+      <field field_ref= "ZI_MESDC"   name="ZI_MESDC"   />
+      <field field_ref= "ZI_EXCR"    name="ZI_EXCR"    />
+      <field field_ref= "ZI_RESP"    name="ZI_RESP"    />
+      <field field_ref= "ZI_GROW"    name="ZI_GROW"    />
+      <field field_ref= "ZE_MES_N"   name="ZE_MES_N"   />
+      <field field_ref= "ZE_MES_D"   name="ZE_MES_D"   />
+      <field field_ref= "ZE_MES_C"   name="ZE_MES_C"   />
+      <field field_ref= "ZE_MESDC"   name="ZE_MESDC"   />
+      <field field_ref= "ZE_EXCR"    name="ZE_EXCR"    />
+      <field field_ref= "ZE_RESP"    name="ZE_RESP"    />
+      <field field_ref= "ZE_GROW"    name="ZE_GROW"    />
+      <field field_ref= "MDETC"      name="MDETC"      />
+      <field field_ref= "GMIDC"      name="GMIDC"      />
+      <field field_ref= "GMEDC"      name="GMEDC"      />
+      <field field_ref= "INT_ZMI"    name="INT_ZMI"    />
+      <field field_ref= "INT_ZME"    name="INT_ZME"    />
+      <field field_ref= "INT_DET"    name="INT_DET"    />
+      <field field_ref= "INT_DTC"    name="INT_DTC"    />
+      <field field_ref= "ATM_XCO2"   name="ATM_XCO2"   />
+      <field field_ref= "OCN_FCO2"   name="OCN_FCO2"   />
+      <field field_ref= "ATM_FCO2"   name="ATM_FCO2"   />
+      <field field_ref= "OCN_RHOSW"  name="OCN_RHOSW"  />
+      <field field_ref= "OCN_SCHCO2" name="OCN_SCHCO2" />
+      <field field_ref= "OCN_KWCO2"  name="OCN_KWCO2"  />
+      <field field_ref= "OCN_K0"     name="OCN_K0"     />
+      <field field_ref= "CO2STARAIR" name="CO2STARAIR" />
+      <field field_ref= "OCN_DPCO2"  name="OCN_DPCO2"  />
+    </field_group>
+
+    <field_group id="groupMEDUSA_3dd" >
+      <field field_ref= "TPP3"       name="TPP3"       />
+      <field field_ref= "DETFLUX3"   name="DETFLUX3"   />
+      <field field_ref= "REMIN3N"    name="REMIN3N"    />
+      <field field_ref= "PH3"        name="PH3"        />
+      <field field_ref= "OM_CAL3"    name="OM_CAL3"    /> 
+    </field_group>
+
+    <field_group id="groupMEDUSA_dms" >
+      <field field_ref= "DMS_SURF"   name="DMS_SURF"   />
+      <field field_ref= "DMS_ANDR"   name="DMS_ANDR"   />
+      <field field_ref= "DMS_SIMO"   name="DMS_SIMO"   />
+      <field field_ref= "DMS_ARAN"   name="DMS_ARAN"   />
+      <field field_ref= "DMS_HALL"   name="DMS_HALL"   />
+      <field field_ref= "DMS_ANDM"   name="DMS_ANDM"   />
+    </field_group>
+
+    <field_group id="groupMEDUSA_riv" >
+      <field field_ref= "RUNOFF"     name="RUNOFF"     />
+      <field field_ref= "RIV_N"      name="RIV_N"      />
+      <field field_ref= "RIV_SI"     name="RIV_SI"     />
+      <field field_ref= "RIV_C"      name="RIV_C"      />
+      <field field_ref= "RIV_ALK"    name="RIV_ALK"    />
+    </field_group>
+
+    <field_group id="groupMEDUSA_cmip6" >
+      <field field_ref= "epC100"     name="epC100"     />
+      <field field_ref= "epCALC100"  name="epCALC100"  />
+      <field field_ref= "epN100"     name="epN100"     />
+      <field field_ref= "epSI100"    name="epSI100"    />
+      <field field_ref= "INTDISSIC"  name="INTDISSIC"  />
+      <field field_ref= "INTDISSIN"  name="INTDISSIN"  />
+      <field field_ref= "INTDISSISI" name="INTDISSISI" />
+      <field field_ref= "INTTALK"    name="INTTALK"    />
+      <field field_ref= "O2min"      name="O2min"      />
+      <field field_ref= "ZO2min"     name="ZO2min"     />
+      <field field_ref= "FBDDTALK"   name="FBDDTALK"   />
+      <field field_ref= "FBDDTDIC"   name="FBDDTDIC"   />
+      <field field_ref= "FBDDTDIFE"  name="FBDDTDIFE"  />
+      <field field_ref= "FBDDTDIN"   name="FBDDTDIN"   />
+      <field field_ref= "FBDDTDISI"  name="FBDDTDISI"  />
+      <field field_ref= "TPPD3"      name="TPPD3"      />
+      <field field_ref= "BDDTALK3"   name="BDDTALK3"   />
+      <field field_ref= "BDDTDIC3"   name="BDDTDIC3"   />
+      <field field_ref= "BDDTDIFE3"  name="BDDTDIFE3"  />
+      <field field_ref= "BDDTDIN3"   name="BDDTDIN3"   />
+      <field field_ref= "BDDTDISI3"  name="BDDTDISI3"  />
+      <field field_ref= "FD_NIT3"    name="FD_NIT3"    />
+      <field field_ref= "FD_SIL3"    name="FD_SIL3"    />
+      <field field_ref= "FD_CAR3"    name="FD_CAR3"    />
+      <field field_ref= "FD_CAL3"    name="FD_CAL3"    />
+      <field field_ref= "CO33"       name="CO33"       />
+      <field field_ref= "CO3SATARAG3" name="CO3SATARAG3" />
+      <field field_ref= "CO3SATCALC3" name="CO3SATCALC3" />
+      <field field_ref= "DCALC3"     name="DCALC3"     />
+      <field field_ref= "EXPC3"      name="EXPC3"      />
+      <field field_ref= "EXPN3"      name="EXPN3"      />
+      <field field_ref= "FEDISS3"    name="FEDISS3"    />
+      <field field_ref= "FESCAV3"    name="FESCAV3"    />
+      <field field_ref= "MIGRAZP3"   name="MIGRAZP3"   />
+      <field field_ref= "MIGRAZD3"   name="MIGRAZD3"   />
+      <field field_ref= "MEGRAZP3"   name="MEGRAZP3"   />
+      <field field_ref= "MEGRAZD3"   name="MEGRAZD3"   />
+      <field field_ref= "MEGRAZZ3"   name="MEGRAZZ3"   />
+      <field field_ref= "O2SAT3"     name="O2SAT3"     />
+      <field field_ref= "PBSI3"      name="PBSI3"      />
+      <field field_ref= "PCAL3"      name="PCAL3"      />
+      <field field_ref= "REMOC3"     name="REMOC3"     />
+      <field field_ref= "PNLIMJ3"    name="PNLIMJ3"    />
+      <field field_ref= "PNLIMN3"    name="PNLIMN3"    />
+      <field field_ref= "PNLIMFE3"   name="PNLIMFE3"   />
+      <field field_ref= "PDLIMJ3"    name="PDLIMJ3"    />
+      <field field_ref= "PDLIMN3"    name="PDLIMN3"    />
+      <field field_ref= "PDLIMFE3"   name="PDLIMFE3"   />
+      <field field_ref= "PDLIMSI3"   name="PDLIMSI3"   />
+    </field_group>
+
+</field_definition>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def_dyn.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def_dyn.xml	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/field_def_dyn.xml	(revision 9987)
@@ -0,0 +1,1208 @@
+<!--
+< GO6.0 version of the XIOS namelist >
+< XIOS2 version namelist >
+
+<?xml version="1.0"?>
+       -->
+ 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+   <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" detect_missing_value="true"> <!-- time step automaticaly defined -->
+
+    <!-- 
+         ============================================================================================================
+                                  Physical ocean and ice model variables
+============================================================================================================
+    -->
+
+      <!-- T grid -->
+
+      <field_group id="grid_T" grid_ref="grid_T_2D" >
+         <field id="e3t"          long_name="Ocean Model cell Thickness"   standard_name="cell_thickness"   unit="m"   grid_ref="grid_T_3D"/>
+         <field id="e3t_surf"     field_ref="e3t"  long_name="T-cell thickness: surface layer"   standard_name="cell_thickness"   unit="m"  grid_ref="grid_T_surface_extract"/>
+         <field id="e3t_0"        long_name="Initial T-cell thickness"   standard_name="ref_cell_thickness"   unit="m"   grid_ref="grid_T_3D"/>
+
+         <field id="toce"         long_name="Sea Water Potential Temperature"         standard_name="sea_water_potential_temperature"   unit="degree_C"     grid_ref="grid_T_3D"/>
+         <field id="toce_e3t"     long_name="temperature * e3t"                                                     unit="degree_C*m"   grid_ref="grid_T_3D" > toce * e3t </field >
+         <field id="toce2_e3t"    long_name="temperature squared * e3t"                                             unit="degC*degC*m"   grid_ref="grid_T_3D" > toce * toce * e3t </field >
+         <field id="soce"         long_name="Sea Water Salinity"            standard_name="sea_water_salinity"      unit="0.001"     grid_ref="grid_T_3D"/>
+         <field id="soce_e3t"     long_name="salinity * e3t"                                                        unit="0.001*m"   grid_ref="grid_T_3D" > soce * e3t </field >
+         <field id="soce2_e3t"    long_name="salinity squared * e3t"                                                unit="1e-3*1e-3*m"   grid_ref="grid_T_3D" > soce * soce * e3t </field >
+         <field id="toce_e3t_vsum" field_ref="toce_e3t" grid_ref="vert_sum" />
+         <field id="e3t_vsum" field_ref="e3t" grid_ref="vert_sum" />
+         <field id="toce_vmean" field_ref="toce_e3t_vsum" grid_ref="vert_sum"> toce_e3t_vsum/e3t_vsum </field>
+         <field id="toce_e3t_300" field_ref="toce_e3t"  unit="degree_C*m"   grid_ref="zoom_300" />
+         <field id="e3t_300" field_ref="e3t"  unit="degree_C*m"   grid_ref="zoom_300" />
+         <field id="toce_e3t_vsum300" field_ref="toce_e3t_300" grid_ref="zoom_300_sum" />
+         <field id="e3t_vsum300" field_ref="e3t_300" grid_ref="zoom_300_sum" />
+         <field id="toce_vmean300" field_ref="toce_e3t_vsum300" grid_ref="zoom_300_sum"> toce_e3t_vsum300/e3t_vsum300 </field>
+
+         <field id="sst"          long_name="Sea Surface Temperature"             standard_name="sea_surface_temperature"             unit="degree_C"     />
+         <field id="sst2"         long_name="Square of Sea Surface Temperature"   standard_name="square_of_sea_surface_temperature"   unit="degree_C2"     > sst * sst </field >
+         <field id="sstmax"       long_name="max of sea surface temperature"   field_ref="sst"   operation="maximum"                                  />
+         <field id="sstmin"       long_name="min of sea surface temperature"   field_ref="sst"   operation="minimum"                                  />
+         <field id="sstgrad"      long_name="module of sst gradient"                                                                  unit="degree_C/m"   />
+         <field id="sstgrad2"     long_name="square of module of sst gradient"                                                        unit="degree_C2/m2" />
+         <field id="sbt"          long_name="sea bottom temperature"                                                                  unit="degree_C"     />
+         <field id="tosmint"      long_name="vertical integral of temperature times density"   standard_name="integral_wrt_depth_of_product_of_density_and_potential_temperature"  unit="(kg m2) degree_C" />
+
+         <field id="sss"          long_name="Sea Surface Salinity"             standard_name="sea_surface_salinity"   unit="0.001" />
+         <field id="sss2"         long_name="square of sea surface salinity"                                          unit="1e-6"  > sss * sss </field >
+         <field id="sssmax"       long_name="max of sea surface salinity"   field_ref="sss"   operation="maximum"                 />
+         <field id="sssmin"       long_name="min of sea surface salinity"   field_ref="sss"   operation="minimum"                 />
+         <field id="sbs"          long_name="sea bottom salinity"                                                     unit="0.001" />
+         <field id="somint"       long_name="vertical integral of salinity times density"   standard_name="integral_wrt_depth_of_product_of_density_and_salinity"  unit="(kg m2) x (1e-3)" />
+
+         <field id="taubot"       long_name="bottom stress module"                                                    unit="N/m2" />              
+
+         <field id="ssh"          long_name="sea surface height"             standard_name="sea_surface_height_above_geoid"             unit="m" />
+         <field id="ssh2"         long_name="square of sea surface height"   standard_name="square_of_sea_surface_height_above_geoid"   unit="m2" > ssh * ssh </field >
+         <field id="sshmax"       long_name="max of sea surface height"   field_ref="ssh"   operation="maximum"                                  />
+
+         <field id="mldkz5"       long_name="Turbocline depth (Kz = 5e-4)"                       standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity"                unit="m"          />
+         <field id="mldr10_1"     long_name="Mixed Layer Depth (dsigma = 0.01 wrt 10m)"          standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"          />
+         <field id="mldr10_1max"  long_name="Max of Mixed Layer Depth (dsigma = 0.01 wrt 10m)"   field_ref="mldr10_1"   operation="maximum"                                                                          />
+         <field id="mldr10_1min"  long_name="Min of Mixed Layer Depth (dsigma = 0.01 wrt 10m)"   field_ref="mldr10_1"   operation="minimum"                                                                          />
+         <field id="mldzint_1"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_2"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_3"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_4"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldzint_5"    long_name="Mixed Layer Depth interpolated"                     standard_name="ocean_mixed_layer_thickness"                                                       unit="m"          />
+         <field id="mldhtc_1"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_2"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_3"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_4"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="mldhtc_5"     long_name="Mixed Layer Depth integrated heat content"          standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="heatc"        long_name="Heat content vertically integrated"                 standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+         <field id="saltc"        long_name="Salt content vertically integrated"                                                                                                                   unit="0.001*kg/m2" />
+
+         <!-- EOS -->
+         <field id="alpha"        long_name="thermal expansion"                                                         unit="degree_C-1" grid_ref="grid_T_3D" />
+         <field id="beta"         long_name="haline contraction"                                                        unit="1e3"    grid_ref="grid_T_3D" />
+         <field id="rhop"         long_name="potential density (sigma0)"        standard_name="sea_water_sigma_theta"   unit="kg/m3"  grid_ref="grid_T_3D" />
+
+         <!-- Energy - horizontal divergence -->
+         <field id="eken"         long_name="kinetic energy"          standard_name="specific_kinetic_energy_of_sea_water"   unit="m2/s2"  grid_ref="grid_T_3D" />
+         <field id="hdiv"         long_name="horizontal divergence"                                                          unit="s-1"    grid_ref="grid_T_3D" />
+
+         <!-- variables available with MLE -->
+         <field id="Lf_NHpf"      long_name="MLE: Lf = N H / f"   unit="m" />
+
+         <!-- next variables available with key_diahth -->
+         <field id="mlddzt"       long_name="Thermocline Depth (depth of max dT/dz)"         standard_name="depth_at_maximum_upward_derivative_of_sea_water_potential_temperature"             unit="m"    />
+         <field id="mldr10_3"     long_name="Mixed Layer Depth (dsigma = 0.03 wrt 10m)"      standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"    />
+         <field id="mldr0_1"      long_name="Mixed Layer Depth (dsigma = 0.01 wrt sfc)"      standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"    />
+         <field id="mldr0_3"      long_name="Mixed Layer Depth (dsigma = 0.03 wrt sfc)"      standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"    />
+         <field id="mld_dt02"     long_name="Mixed Layer Depth (|dT| = 0.2 wrt 10m)"         standard_name="ocean_mixed_layer_thickness_defined_by_temperature"                                unit="m"    />
+         <field id="topthdep"     long_name="Top of Thermocline Depth (dT = -0.2 wrt 10m)"   standard_name="ocean_mixed_layer_thickness_defined_by_temperature"                                unit="m"    />
+         <field id="pycndep"      long_name="Pycnocline Depth (dsigma[dT=-0.2] wrt 10m)"     standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"    />
+         <field id="BLT"          long_name="Barrier Layer Thickness"                                                                                                                          unit="m"    > topthdep - pycndep </field>
+         <field id="tinv"         long_name="Max of vertical invertion of temperature"                                                                                                         unit="degree_C"                      />
+         <field id="depti"        long_name="Depth of max. vert. inv. of temperature"                                                                                                          unit="m"                         />
+         <field id="20d"          long_name="Depth of 20C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"      axis_ref="iax_20C" />
+         <field id="28d"          long_name="Depth of 28C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"      axis_ref="iax_28C" />
+         <field id="hc300"        long_name="Heat content 0-300m"                            standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"                      />
+
+         <!-- variables available with key_diaar5 -->
+         <field id="botpres"      long_name="Sea Water Pressure at Sea Floor"   standard_name="sea_water_pressure_at_sea_floor"   unit="dbar" />
+         <field id="sshdyn"       long_name="dynamic sea surface height"     standard_name="dynamic_sea_surface_height_above_geoid"     unit="m" />
+         <field id="sshdyn2"      long_name="square of dynamic sea surface height"     standard_name="dynamic_sea_surface_height_above_geoid_squared"     unit="m2" > sshdyn * sshdyn </field>
+
+         <!-- variables available with key_vvl -->
+         <field id="tpt_dep"      long_name="T-point depth"                  standard_name="depth_below_geoid"   unit="m"   grid_ref="grid_T_3D" />
+         <field id="e3tdef"       long_name="T-cell thickness deformation"                                       unit="%"   grid_ref="grid_T_3D" />
+      </field_group>
+
+      <!-- Tides -->
+
+      <field_group id="Tides_T" grid_ref="grid_T_2D" operation="once" >
+         <!-- tidal composante -->
+         <field id="M2x"          long_name="M2 Elevation harmonic real part "                             unit="m"        />
+         <field id="M2y"          long_name="M2 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="S2x"          long_name="S2 Elevation harmonic real part "                             unit="m"        />
+         <field id="S2y"          long_name="S2 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="N2x"          long_name="N2 Elevation harmonic real part "                             unit="m"        />
+         <field id="N2y"          long_name="N2 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="K1x"          long_name="K1 Elevation harmonic real part "                             unit="m"        />
+         <field id="K1y"          long_name="K1 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="O1x"          long_name="O1 Elevation harmonic real part "                             unit="m"        />
+         <field id="O1y"          long_name="O1 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="Q1x"          long_name="Q1 Elevation harmonic real part "                             unit="m"        />
+         <field id="Q1y"          long_name="Q1 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="M4x"          long_name="M4 Elevation harmonic real part "                             unit="m"        />
+         <field id="M4y"          long_name="M4 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="K2x"          long_name="K2 Elevation harmonic real part "                             unit="m"        />
+         <field id="K2y"          long_name="K2 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="P1x"          long_name="P1 Elevation harmonic real part "                             unit="m"        />
+         <field id="P1y"          long_name="P1 Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="Mfx"          long_name="Mf Elevation harmonic real part "                             unit="m"        />
+         <field id="Mfy"          long_name="Mf Elevation harmonic imaginary part"                         unit="m"        />
+         <field id="Mmx"          long_name="Mm Elevation harmonic real part "                             unit="m"        />
+         <field id="Mmy"          long_name="Mm Elevation harmonic imaginary part"                         unit="m"        />
+      </field_group>
+
+      <field_group id="Tides_U" grid_ref="grid_U_2D" operation="once" >
+         <field id="M2x_u"        long_name="M2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="M2y_u"        long_name="M2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="S2x_u"        long_name="S2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="S2y_u"        long_name="S2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="N2x_u"        long_name="N2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="N2y_u"        long_name="N2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="K1x_u"        long_name="K1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="K1y_u"        long_name="K1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="O1x_u"        long_name="O1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="O1y_u"        long_name="O1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="Q1x_u"        long_name="Q1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="Q1y_u"        long_name="Q1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="M4x_u"        long_name="M4 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="M4y_u"        long_name="M4 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="K2x_u"        long_name="K2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="K2y_u"        long_name="K2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="P1x_u"        long_name="P1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="P1y_u"        long_name="P1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="Mfx_u"        long_name="Mf current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="Mfy_u"        long_name="Mf current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="Mmx_u"        long_name="Mm current barotrope along i-axis harmonic real part "        unit="m/s"      />
+         <field id="Mmy_u"        long_name="Mm current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+      </field_group>
+
+      <field_group id="Tides_V" grid_ref="grid_V_2D" operation="once" >
+         <field id="M2x_v"        long_name="M2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="M2y_v"        long_name="M2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="S2x_v"        long_name="S2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="S2y_v"        long_name="S2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="N2x_v"        long_name="N2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="N2y_v"        long_name="N2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="K1x_v"        long_name="K1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="K1y_v"        long_name="K1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="O1x_v"        long_name="O1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="O1y_v"        long_name="O1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="Q1x_v"        long_name="Q1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="Q1y_v"        long_name="Q1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="M4x_v"        long_name="M4 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="M4y_v"        long_name="M4 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="K2x_v"        long_name="K2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="K2y_v"        long_name="K2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="P1x_v"        long_name="P1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="P1y_v"        long_name="P1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="Mfx_v"        long_name="Mf current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="Mfy_v"        long_name="Mf current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+         <field id="Mmx_v"        long_name="Mm current barotrope along j-axis harmonic real part "        unit="m/s"      />
+         <field id="Mmy_v"        long_name="Mm current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+      </field_group>
+
+      <!-- SBC -->
+
+      <field_group id="SBC" grid_ref="grid_T_2D" > <!-- time step automaticaly defined based on nn_fsbc -->
+         <field id="empmr"        long_name="Net Upward Water Flux"                standard_name="water_flux_out_of_sea_ice_and_sea_water"                              unit="kg/m2/s"   />
+         <field id="empbmr"       long_name="Net Upward Water Flux at pre. tstep"  standard_name="water_flux_out_of_sea_ice_and_sea_water"                              unit="kg/m2/s"   />
+         <field id="emp_oce"      long_name="Evap minus Precip over ocean"         standard_name="evap_minus_precip_over_sea_water"                                     unit="kg/m2/s"   />
+         <field id="emp_ice"      long_name="Evap minus Precip over ice"           standard_name="evap_minus_precip_over_sea_ice"                                       unit="kg/m2/s"   />
+         <field id="saltflx"      long_name="Downward salt flux"                                                                                                        unit="0.001/m2/s" />
+         <field id="fmmflx"       long_name="Water flux due to freezing/melting"                                                                                        unit="kg/m2/s"   />
+         <field id="snowpre"      long_name="Snow precipitation"                   standard_name="snowfall_flux"                                                        unit="kg/m2/s"   />
+         <field id="runoffs"      long_name="Water Flux into Sea Water From Rivers" standard_name="water_flux_into_sea_water_from_rivers"                                unit="kg/m2/s"   />
+         <field id="precip"       long_name="Total precipitation"                  standard_name="precipitation_flux"                                                   unit="kg/m2/s"   />
+
+         <field id="qt"           long_name="Net Downward Heat Flux"                standard_name="surface_downward_heat_flux_in_sea_water"                              unit="W/m2"                           />
+         <field id="qns"          long_name="non solar Downward Heat Flux"                                                                                               unit="W/m2"                           />
+         <field id="qsr"          long_name="Shortwave Radiation"                   standard_name="net_downward_shortwave_flux_at_sea_water_surface"                     unit="W/m2"                           />
+         <field id="qsr3d"        long_name="Shortwave Radiation 3D distribution"   standard_name="downwelling_shortwave_flux_in_sea_water"                              unit="W/m2"      grid_ref="grid_T_3D" />
+         <field id="qrp"          long_name="Surface Heat Flux: Damping"            standard_name="heat_flux_into_sea_water_due_to_newtonian_relaxation"                 unit="W/m2"                           />
+         <field id="erp"          long_name="Surface Water Flux: Damping"           standard_name="water_flux_out_of_sea_water_due_to_newtonian_relaxation"              unit="kg/m2/s"                        />
+         <field id="taum"         long_name="wind stress module"                    standard_name="magnitude_of_surface_downward_stress"                                 unit="N/m2"                           />
+         <field id="wspd"         long_name="wind speed module"                     standard_name="wind_speed"                                                           unit="m/s"                            />
+
+         <!-- * variable relative to atmospheric pressure forcing : available with ln_apr_dyn -->
+         <field id="ssh_ib"       long_name="Inverse barometer sea surface height"  standard_name="sea_surface_height_correction_due_to_air_pressure_at_low_frequency"   unit="m"        />
+
+         <!-- * variable related to ice shelf forcing * -->
+         <field id="berg_calve"   long_name="Iceberg calving"                               unit="kg/m2/s"  />
+         <field id="fwfisf"       long_name="Ice shelf melting"                             unit="kg/m2/s"  />
+         <field id="fwfisf3d"     long_name="Ice shelf melting"                             unit="kg/m2/s"  grid_ref="grid_T_3D" />
+         <field id="qlatisf"      long_name="Ice shelf latent heat flux"                    unit="W/m2"     />
+         <field id="qlatisf3d"    long_name="Ice shelf latent heat flux"                    unit="W/m2"     grid_ref="grid_T_3D" />
+         <field id="qhcisf"       long_name="Ice shelf heat content flux"                   unit="W/m2"     />
+         <field id="qhcisf3d"     long_name="Ice shelf heat content flux"                   unit="W/m2"     grid_ref="grid_T_3D" />
+         <field id="isfgammat"    long_name="transfert coefficient for isf (temperature)"   unit="m/s"      />
+         <field id="isfgammas"    long_name="transfert coefficient for isf (salinity)"      unit="m/s"      />
+         <field id="stbl"         long_name="salinity in the Losh tbl"                      unit="0.001"     />
+         <field id="ttbl"         long_name="temperature in the Losh tbl"                   unit="degree_C"     />
+
+         <!-- *_oce variables available with ln_blk_clio or ln_blk_core -->
+         <field id="qlw_oce"      long_name="Longwave Downward Heat Flux over open ocean"  standard_name="surface_net_downward_longwave_flux"   unit="W/m2"  />
+         <field id="qsb_oce"      long_name="Sensible Downward Heat Flux over open ocean"  standard_name="surface_downward_sensible_heat_flux"  unit="W/m2"  />
+         <field id="qla_oce"      long_name="Latent Downward Heat Flux over open ocean"    standard_name="surface_downward_latent_heat_flux"    unit="W/m2"  />
+         <field id="qemp_oce"     long_name="Downward Heat Flux from E-P over open ocean"                                                       unit="W/m2"  />
+         <field id="taum_oce"     long_name="wind stress module over open ocean"           standard_name="magnitude_of_surface_downward_stress" unit="N/m2"  />
+
+         <!-- available key_oasis3 -->
+         <field id="snow_ao_cea"  long_name="Snow over ice-free ocean (cell average)"   standard_name="snowfall_flux"                             unit="kg/m2/s"  />
+         <field id="snow_ai_cea"  long_name="Snow over sea-ice (cell average)"          standard_name="snowfall_flux"                             unit="kg/m2/s"  />
+         <field id="subl_ai_cea"  long_name="Sublimation over sea-ice (cell average)"   standard_name="surface_snow_and_ice_sublimation_flux"     unit="kg/m2/s"  />
+         <field id="icealb_cea"   long_name="Ice albedo (cell average)"                 standard_name="sea_ice_albedo"                            unit="1"        />
+         <field id="calving_cea"  long_name="Calving"                                   standard_name="water_flux_into_sea_water_from_icebergs"   unit="kg/m2/s"  />
+
+         <!-- available if key_oasis3 + conservative method -->
+         <field id="rain"          long_name="Liquid precipitation"                                     standard_name="rainfall_flux"                                                                 unit="kg/m2/s"  />
+         <field id="rain_ao_cea"   long_name="Liquid precipitation over ice-free ocean (cell average)"  standard_name="rainfall_flux"                                                                 unit="kg/m2/s"  />
+         <field id="evap_ao_cea"   long_name="Evaporation over ice-free ocean (cell average)"           standard_name="water_evaporation_flux"                                                        unit="kg/m2/s"  />
+         <field id="isnwmlt_cea"   long_name="Snow over Ice melting (cell average)"                     standard_name="surface_snow_melt_flux"                                                        unit="kg/m2/s"  />
+         <field id="fsal_virt_cea" long_name="Virtual salt flux due to ice formation (cell average)"    standard_name="virtual_salt_flux_into_sea_water_due_to_sea_ice_thermodynamics"                unit="kg/m2/s"  />
+         <field id="fsal_real_cea" long_name="Real salt flux due to ice formation (cell average)"       standard_name="downward_sea_ice_basal_salt_flux"                                              unit="kg/m2/s"  />
+         <field id="hflx_rain_cea" long_name="heat flux due to rainfall"                                standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"        unit="W/m2"     />
+         <field id="hflx_prec_cea" long_name="heat flux due to precipitation"                           standard_name="temperature_flux_due_to_precipitation_expressed_as_heat_flux_into_sea_water"        unit="W/m2"     />
+         <field id="hflx_evap_cea" long_name="heat flux due to evaporation"                             standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"   unit="W/m2"     />
+         <field id="hflx_snow_cea" long_name="heat flux due to snow falling over ice-free ocean"        standard_name="heat_flux_into_sea_water_due_to_snow_thermodynamics"                           unit="W/m2"     />
+         <field id="hflx_ice_cea"  long_name="heat flux due to ice thermodynamics"                      standard_name="heat_flux_into_sea_water_due_to_sea_ice_thermodynamics"                        unit="W/m2"     />
+         <field id="hflx_rnf_cea"  long_name="heat flux due to runoffs"                                 standard_name="temperature_flux_due_to_runoff_expressed_as_heat_flux_into_sea_water"          unit="W/m2"     />
+         <field id="hflx_cal_cea"  long_name="heat flux due to calving"                                 standard_name="heat_flux_into_sea_water_due_to_iceberg_thermodynamics"                        unit="W/m2"     />
+         <field id="bicemel_cea"   long_name="Rate of Melt at Sea Ice Base (cell average)"              standard_name="tendency_of_sea_ice_amount_due_to_basal_melting"                               unit="kg/m2/s"  />
+         <field id="licepro_cea"   long_name="Lateral Sea Ice Growth Rate (cell average)"               standard_name="tendency_of_sea_ice_amount_due_to_lateral_growth_of_ice_floes"                 unit="kg/m2/s"  />
+         <field id="snowmel_cea"   long_name="Snow Melt Rate (cell average)"                            standard_name="surface_snow_melt_flux"                                                        unit="kg/m2/s"  />
+         <field id="sntoice_cea"   long_name="Snow-Ice Formation Rate (cell average)"                   standard_name="tendency_of_sea_ice_amount_due_to_snow_conversion"                             unit="kg/m2/s"  />
+         <field id="ticemel_cea"   long_name="Rate of Melt at Upper Surface of Sea Ice (cell average)"  standard_name="tendency_of_sea_ice_amount_due_to_surface_melting"                             unit="kg/m2/s"  />
+
+         <!-- ice fields -->
+         <field id="ice_cover"    long_name="Ice fraction"                                                 standard_name="sea_ice_area_fraction"                              unit="1"            />
+
+         <field id="qsr_ai_cea"   long_name="Air-Ice downward solar heat flux (cell average)"              standard_name="surface_downwelling_shortwave_flux_in_air"          unit="W/m2"         />
+         <field id="qns_ai_cea"   long_name="Air-Ice downward non-solar heat flux (cell average)"                                                                             unit="W/m2"         />
+         <field id="qla_ai_cea"   long_name="Air-Ice downward Latent heat flux (cell average)"             standard_name="surface_downward_latent_heat_flux"                  unit="W/m2"         />
+
+         <field id="qsr_io_cea"   long_name="Ice-Oce downward solar heat flux (cell average)"              standard_name="net_downward_shortwave_flux_at_sea_water_surface"   unit="W/m2"         />
+         <field id="qns_io_cea"   long_name="Ice-Oce downward non-solar heat flux (cell average)"                                                                             unit="W/m2"         />
+
+         <field id="snowthic_cea" long_name="Snow thickness (cell average)"                                standard_name="surface_snow_thickness"                             unit="m"            />
+         <field id="icethic_cea"  long_name="Ice thickness (cell average)"                                 standard_name="sea_ice_thickness"                                  unit="m"            />
+         <field id="iceprod_cea"  long_name="Ice production (cell average)"                                                                                                   unit="m/s"          />
+         <field id="iiceconc"     long_name="Ice concentration"                                            standard_name="sea_ice_area_fraction"                              unit="1"            />
+
+         <field id="ice_pres"     long_name="Ice presence"                                                                                                                    unit=""             />
+         <field id="ist_cea"      long_name="Ice surface temperature (cell average)"                       standard_name="surface_temperature"                                unit="degree_C"         />
+         <field id="ist_ipa"      long_name="Ice surface temperature (ice presence average)"               standard_name="surface_temperature"                                unit="degree_C"         />
+         <field id="uice_ipa"     long_name="Ice velocity along i-axis at I-point (ice presence average)"  standard_name="sea_ice_x_velocity"                                 unit="m/s"          />
+         <field id="vice_ipa"     long_name="Ice velocity along j-axis at I-point (ice presence average)"  standard_name="sea_ice_y_velocity"                                 unit="m/s"          />
+
+         <field id="utau_ice"     long_name="Wind stress along i-axis over the ice at i-point"             standard_name="surface_downward_x_stress"                          unit="N/m2"         />
+         <field id="vtau_ice"     long_name="Wind stress along j-axis over the ice at i-point"             standard_name="surface_downward_y_stress"                          unit="N/m2"         />
+
+         <field id="u_imasstr"    long_name="Sea-ice mass transport along i-axis"                          standard_name="sea_ice_x_transport"                                unit="kg/s"         />
+         <field id="v_imasstr"    long_name="Sea-ice mass transport along j-axis"                          standard_name="sea_ice_y_transport"                                unit="kg/s"         />
+         <field id="emp_x_sst"    long_name="Concentration/Dilution term on SST"                                                                                              unit="kg*degree_C/m2/s" />
+         <field id="emp_x_sss"    long_name="Concentration/Dilution term on SSS"                                                                                              unit="kg*0.001/m2/s" />
+
+         <field id="iceconc"      long_name="ice concentration"                                            standard_name="sea_ice_area_fraction"                              unit="%"            />
+         <field id="isst"         long_name="sea surface temperature"                                      standard_name="sea_surface_temperature"                            unit="degree_C"         />
+         <field id="isss"         long_name="sea surface salinity"                                         standard_name="sea_surface_salinity"                               unit="0.001"         />
+         <field id="qt_oce"       long_name="total flux at ocean surface"                                  standard_name="surface_downward_heat_flux_in_sea_water"            unit="W/m2"         />
+         <field id="qsr_oce"      long_name="solar heat flux at ocean surface"                             standard_name="net_downward_shortwave_flux_at_sea_water_surface"   unit="W/m2"         />
+         <field id="qns_oce"      long_name="non-solar heat flux at ocean surface"                                                                                            unit="W/m2"         />
+         <field id="qt_ice"       long_name="total heat flux at ice surface: sum over categories"          standard_name="surface_downward_heat_flux_in_air"                  unit="W/m2"         />
+         <field id="qsr_ice"      long_name="solar heat flux at ice surface: sum over categories"          standard_name="surface_downwelling_shortwave_flux_in_air"          unit="W/m2"         />
+         <field id="qns_ice"      long_name="non-solar heat flux at ice surface: sum over categories"                                                                         unit="W/m2"         />
+         <field id="qtr_ice"      long_name="solar heat flux transmitted through ice: sum over categories"                                                                    unit="W/m2"         />
+         <field id="qemp_ice"     long_name="Downward Heat Flux from E-P over ice"                                                                                            unit="W/m2"         />
+         <field id="micesalt"     long_name="Mean ice salinity"                                                                                                               unit="0.001"         />
+         <field id="miceage"      long_name="Mean ice age"                                                                                                                    unit="years"        />
+         <field id="alb_ice"      long_name="Mean albedo over sea ice"                                                                                                        unit=""             />
+         <field id="albedo"       long_name="Mean albedo over sea ice and ocean"                                                                                              unit=""             />
+
+         <field id="iceage_cat"   long_name="Ice age for categories"                                       unit="days"   axis_ref="ncatice" />
+         <field id="iceconc_cat"  long_name="Ice concentration for categories"                             unit="%"      axis_ref="ncatice" />
+         <field id="icethic_cat"  long_name="Ice thickness for categories"                                 unit="m"      axis_ref="ncatice" />
+         <field id="snowthic_cat" long_name="Snow thicknessi for categories"                               unit="m"      axis_ref="ncatice" />
+         <field id="salinity_cat" long_name="Sea-Ice Bulk salinity for categories"                         unit="g/kg"   axis_ref="ncatice" />
+         <field id="brinevol_cat" long_name="Brine volume for categories"                                  unit="%"      axis_ref="ncatice" />
+         <field id="icetemp_cat"  long_name="Ice temperature for categories"                               unit="degree_C"   axis_ref="ncatice" />
+         <field id="snwtemp_cat"  long_name="Snow temperature for categories"                              unit="degree_C"   axis_ref="ncatice" />
+
+         <field id="micet"        long_name="Mean ice temperature"                                         unit="degree_C"     />
+         <field id="icehc"        long_name="ice total heat content"                                       unit="10^9J"    />
+         <field id="isnowhc"      long_name="snow total heat content"                                      unit="10^9J"    />
+         <field id="icest"        long_name="ice surface temperature"                                      unit="degree_C"     />
+         <field id="ibrinv"       long_name="brine volume"                                                 unit="%"        />
+         <field id="icecolf"      long_name="frazil ice collection thickness"                              unit="m"        />
+         <field id="icestr"       long_name="ice strength"                                                 unit="N/m"      />
+         <field id="icevel"       long_name="ice velocity"                                                 unit="m/s"      />
+         <field id="idive"        long_name="divergence"                                                   unit="1e-8s-1"  />
+         <field id="ishear"       long_name="shear"                                                        unit="1e-8s-1"  />
+         <field id="icevolu"      long_name="ice volume"                                                   unit="m"        />
+         <field id="snowvol"      long_name="snow volume"                                                  unit="m"        />
+
+         <field id="icetrp"       long_name="ice volume transport"                                         unit="m/day"          />
+         <field id="snwtrp"       long_name="snw volume transport"                                         unit="m/day"          />
+         <field id="saltrp"       long_name="salt content transport"                                       unit="0.001*kg/m2/day" />
+         <field id="deitrp"       long_name="advected ice enthalpy"                                        unit="W/m2"           />
+         <field id="destrp"       long_name="advected snw enthalpy"                                        unit="W/m2"           />
+
+         <field id="sfxbri"       long_name="brine salt flux"                                              unit="0.001*kg/m2/day" />
+         <field id="sfxdyn"       long_name="salt flux from ridging rafting"                               unit="0.001*kg/m2/day" />
+         <field id="sfxres"       long_name="salt flux from lipupdate (resultant)"                         unit="0.001*kg/m2/day" />
+         <field id="sfxbog"       long_name="salt flux from bot growth"                                    unit="0.001*kg/m2/day" />
+         <field id="sfxbom"       long_name="salt flux from bot melt"                                      unit="0.001*kg/m2/day" />
+         <field id="sfxsum"       long_name="salt flux from surf melt"                                     unit="0.001*kg/m2/day" />
+         <field id="sfxsni"       long_name="salt flux from snow-ice formation"                            unit="0.001*kg/m2/day" />
+         <field id="sfxopw"       long_name="salt flux from open water ice formation"                      unit="0.001*kg/m2/day" />
+         <field id="sfxsub"       long_name="salt flux from sublimation"                                   unit="0.001*kg/m2/day" />
+         <field id="sfx"          long_name="salt flux total"                                              unit="0.001*kg/m2/day" />
+
+         <field id="vfxbog"       long_name="daily bottom thermo ice prod."                                unit="m/day"   />
+         <field id="vfxdyn"       long_name="daily  dynamic ice prod."                                     unit="m/day"   />
+         <field id="vfxopw"       long_name="daily lateral thermo ice prod."                               unit="m/day"   />
+         <field id="vfxsni"       long_name="daily snowice ice prod."                                      unit="m/day"   />
+         <field id="vfxsum"       long_name="surface melt"                                                 unit="m/day"   />
+         <field id="vfxbom"       long_name="bottom melt"                                                  unit="m/day"   />
+         <field id="vfxres"       long_name="daily resultant ice prod./melting from limupdate"             unit="m/day"   />
+         <field id="vfxice"       long_name="ice melt/growth"                                              unit="m/day"   />
+         <field id="vfxsnw"       long_name="snw melt/growth"                                              unit="m/day"   />
+         <field id="vfxsub"       long_name="snw sublimation"                                              unit="m/day"   />
+         <field id="vfxspr"       long_name="snw precipitation on ice"                                     unit="m/day"   />
+         <field id="vfxthin"      long_name="daily thermo ice prod. for thin ice(<20cm) + open water"      unit="m/day"   />
+
+         <field id="afxtot"       long_name="area tendency (total)"                                        unit="day-1"   />
+         <field id="afxdyn"       long_name="area tendency (dynamics)"                                     unit="day-1"   />
+         <field id="afxthd"       long_name="area tendency (thermo)"                                       unit="day-1"   />
+
+         <field id="hfxsum"       long_name="heat fluxes causing surface ice melt"                         unit="W/m2"  />
+         <field id="hfxbom"       long_name="heat fluxes causing bottom ice melt"                          unit="W/m2"  />
+         <field id="hfxbog"       long_name="heat fluxes causing bottom ice growth"                        unit="W/m2"  />
+         <field id="hfxdif"       long_name="heat fluxes causing ice temperature change"                   unit="W/m2"  />
+         <field id="hfxopw"       long_name="heat fluxes causing open water ice formation"                 unit="W/m2"  />
+         <field id="hfxsnw"       long_name="heat fluxes causing snow melt"                                unit="W/m2"  />
+         <field id="hfxerr"       long_name="heat fluxes error after heat diffusion"                       unit="W/m2"  />
+         <field id="hfxerr_rem"   long_name="heat fluxes error after remapping"                            unit="W/m2"  />
+         <field id="hfxout"       long_name="total heat fluxes received by the ocean"                      unit="W/m2"  />
+         <field id="hfxin"        long_name="total heat fluxes at the ice/ocean surface"                   unit="W/m2"  />
+
+         <!-- heat flux associated with mass exchange -->
+         <field id="hfxthd"       long_name="heat fluxes from ice-ocean mass exchange during thermo"       unit="W/m2"  />
+         <field id="hfxdyn"       long_name="heat fluxes from ice-ocean mass exchange during dynamic"      unit="W/m2"  />
+         <field id="hfxres"       long_name="heat fluxes from ice-ocean mass exchange during resultant"    unit="W/m2"  />
+         <field id="hfxsub"       long_name="heat fluxes from ice-atm. mass exchange during sublimation"   unit="W/m2"  />
+         <field id="hfxspr"       long_name="heat fluxes from ice-atm. mass exchange during snow precip"   unit="W/m2"  />
+
+         <!-- diags -->
+         <field id="hfxdhc"       long_name="Heat content variation in snow and ice"                       unit="W/m2" />
+         <field id="hfxtur"       long_name="turbulent heat flux at the ice base"                          unit="W/m2" />
+         <!-- sbcssm variables -->
+         <field id="sst_m"    unit="degree_C" />
+         <field id="sss_m"    unit="psu"  />
+         <field id="ssu_m"    unit="m/s"  />
+         <field id="ssv_m"    unit="m/s"  />
+         <field id="ssh_m"    unit="m"    />
+         <field id="e3t_m"    unit="m"    />
+         <field id="frq_m"    unit="-"    />
+
+      </field_group>
+
+      <!-- U grid -->
+
+      <field_group id="grid_U"   grid_ref="grid_U_2D">
+         <field id="e3u"          long_name="U-cell thickness"                                       standard_name="cell_thickness"              unit="m"          grid_ref="grid_U_3D" />
+         <field id="e3u_0"        long_name="Initial U-cell thickness"                               standard_name="ref_cell_thickness"          unit="m"          grid_ref="grid_U_3D"/>
+         <field id="utau"         long_name="Surface Downward X Stress"                               standard_name="surface_downward_x_stress"   unit="N/m2"                            />
+         <field id="uoce"         long_name="Sea Water X Velocity"                             standard_name="sea_water_x_velocity"        unit="m/s"        grid_ref="grid_U_3D" />
+         <field id="uoce_e3u"     long_name="ocean current along i-axis * e3u"                                                                   unit="m2/s"       grid_ref="grid_U_3D"  > uoce * e3u </field>
+         <field id="uoce2_e3u"    long_name="ocean current along i-axis squared * e3u"                                                           unit="m3/s2"      grid_ref="grid_U_3D"  > uoce * uoce * e3u </field>
+         <field id="ssu"          long_name="ocean surface current along i-axis"                                                                 unit="m/s"                             />
+         <field id="sbu"          long_name="ocean bottom current along i-axis"                                                                  unit="m/s"                             />
+         <field id="ubar"         long_name="ocean barotropic current along i-axis"                                                              unit="m/s"                             />
+         <field id="uocetr_eff"   long_name="Effective ocean transport along i-axis"                 standard_name="ocean_volume_x_transport"    unit="m3/s"       grid_ref="grid_U_3D" />
+         <field id="uocet"        long_name="ocean transport along i-axis times temperature (CRS)"                                               unit="degree_C*m/s"   grid_ref="grid_U_3D" />
+         <field id="uoces"        long_name="ocean transport along i-axis times salinity (CRS)"                                                  unit="0.001*m/s"   grid_ref="grid_U_3D" />
+
+         <!-- variables available with MLE -->
+         <field id="psiu_mle"     long_name="MLE streamfunction along i-axis"   unit="m3/s"   grid_ref="grid_U_3D" />
+
+         <!-- uoce_eiv: available with key_traldf_eiv and key_diaeiv -->
+         <field id="uoce_eiv"      long_name="EIV ocean current along i-axis"   standard_name="bolus_sea_water_x_velocity"   unit="m/s"   grid_ref="grid_U_3D" />
+         <field id="ueiv_masstr"   long_name="EIV Ocean Mass X Transport"    standard_name="bolus_ocean_mass_x_transport"                          unit="kg/s"        grid_ref="grid_U_3D" />
+         <field id="ueiv_heattr3d" long_name="ocean bolus heat transport along i-axis"    standard_name="ocean_heat_x_transport_due_to_bolus_advection"   unit="W"    grid_ref="grid_U_3D" />
+         <field id="ueiv_salttr3d" long_name="ocean bolus salt transport along i-axis"    standard_name="ocean_salt_x_transport_due_to_bolus_advection"   unit="kg"   grid_ref="grid_U_3D" />
+         <field id="ueiv_masstr"  long_name="EIV Ocean Mass X Transport"    standard_name="bolus_ocean_mass_x_transport"                          unit="kg/s"        grid_ref="grid_U_3D" />
+
+         <!-- uoce_eiv: available with key_trabbl -->
+         <field id="uoce_bbl"     long_name="BBL ocean current along i-axis"    unit="m/s"  />
+         <field id="ahu_bbl"      long_name="BBL diffusive flux along i-axis"   unit="m3/s" />
+
+         <!-- variable for ice shelves -->
+         <field id="utbl"         long_name="zonal current in the Losh tbl"     unit="m/s" />
+
+         <!-- variables available with key_diaar5 -->
+         <field id="u_masstr"     long_name="Ocean Mass X Transport"    standard_name="ocean_mass_x_transport"                          unit="kg/s"        grid_ref="grid_U_3D" />
+         <field id="u_masstr_vint" long_name="vertical integral of ocean eulerian mass transport along i-axis"    standard_name="vertical_integral_of_ocean_mass_x_transport"  unit="kg/s" />
+         <field id="u_heattr"     long_name="ocean eulerian heat transport along i-axis"    standard_name="ocean_heat_x_transport"                          unit="W"                                />
+         <field id="uadv_heattr"  long_name="ocean advective heat transport along i-axis"    standard_name="advectice_ocean_heat_x_transport"                          unit="W"                                />
+         <field id="u_salttr"     long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_x_transport"                          unit="0.001*kg/s"                        />
+         <field id="ueiv_heattr"  long_name="ocean bolus heat transport along i-axis"       standard_name="ocean_heat_x_transport_due_to_bolus_advection"   unit="W"                                />
+         <field id="ueiv_salttr"  long_name="ocean bolus salt transport along i-axis"       standard_name="ocean_salt_x_transport_due_to_bolus_advection"   unit="W"                                />
+         <field id="udiff_heattr" long_name="ocean diffusion heat transport along i-axis"   standard_name="ocean_heat_x_transport_due_to_diffusion"         unit="W"                                />
+      </field_group>
+
+      <!-- V grid -->
+
+      <field_group id="grid_V"   grid_ref="grid_V_2D">
+         <field id="e3v"          long_name="V-cell thickness"                                       standard_name="cell_thickness"              unit="m"          grid_ref="grid_V_3D" />
+         <field id="e3v_0"        long_name="Initial V-cell thickness"                               standard_name="ref_cell_thickness"          unit="m"          grid_ref="grid_V_3D"/>
+         <field id="vtau"         long_name="Surface Downward Y Stress"                               standard_name="surface_downward_y_stress"   unit="N/m2"                            />
+         <field id="voce"         long_name="Sea Water Y Velocity"                             standard_name="sea_water_y_velocity"        unit="m/s"        grid_ref="grid_V_3D" />
+         <field id="voce_e3v"     long_name="ocean current along j-axis * e3v"                                                                   unit="m2/s"       grid_ref="grid_V_3D"  > voce * e3v </field>
+         <field id="voce2_e3v"    long_name="ocean current along j-axis squared * e3v"                                                           unit="m3/s2"      grid_ref="grid_V_3D"  > voce * voce * e3v </field>
+         <field id="ssv"          long_name="ocean surface current along j-axis"                                                                 unit="m/s"                             />
+         <field id="sbv"          long_name="ocean bottom current along j-axis"                                                                  unit="m/s"                             />
+         <field id="vbar"         long_name="ocean barotropic current along j-axis"                                                              unit="m/s"                             />
+         <field id="vocetr_eff"   long_name="Effective ocean transport along j-axis"                 standard_name="ocean_volume_y_transport"    unit="m3/s"       grid_ref="grid_V_3D" />
+         <field id="vocet"        long_name="ocean transport along j-axis times temperature (CRS)"                                               unit="degree_C*m/s"   grid_ref="grid_V_3D" />
+         <field id="voces"        long_name="ocean transport along j-axis times salinity (CRS)"                                                  unit="0.001*m/s"   grid_ref="grid_V_3D" />
+
+         <!-- variables available with MLE -->
+         <field id="psiv_mle"     long_name="MLE streamfunction along j-axis"   unit="m3/s"   grid_ref="grid_V_3D" />
+
+         <!-- voce_eiv: available with key_traldf_eiv and key_diaeiv -->
+         <field id="voce_eiv"     long_name="EIV ocean current along j-axis"   standard_name="bolus_sea_water_y_velocity"   unit="m/s"   grid_ref="grid_V_3D" />
+         <field id="veiv_masstr"   long_name="EIV Ocean Mass Y Transport"    standard_name="bolus_ocean_mass_y_transport"                          unit="kg/s"        grid_ref="grid_V_3D" />
+         <field id="veiv_heattr3d" long_name="ocean bolus heat transport along j-axis"    standard_name="ocean_heat_y_transport_due_to_bolus_advection"   unit="W"    grid_ref="grid_V_3D" />
+         <field id="veiv_salttr3d" long_name="ocean bolus salt transport along j-axis"    standard_name="ocean_salt_y_transport_due_to_bolus_advection"   unit="kg"   grid_ref="grid_U_3D" />
+
+         <!-- voce_eiv: available with key_trabbl -->
+         <field id="voce_bbl"     long_name="BBL ocean current along j-axis"    unit="m/s"  />
+         <field id="ahv_bbl"      long_name="BBL diffusive flux along j-axis"   unit="m3/s" />
+
+         <!-- variable for ice shelves -->
+         <field id="vtbl"         long_name="meridional current in the Losh tbl"   unit="m/s" />
+
+         <!-- variables available with key_diaar5 -->
+         <field id="v_masstr"     long_name="Ocean Mass Y Transport"    standard_name="ocean_mass_y_transport"                          unit="kg/s"        grid_ref="grid_V_3D" />
+         <field id="v_heattr"     long_name="Ocean Heat X Transport"    standard_name="ocean_heat_y_transport"                          unit="W"                                />
+         <field id="vadv_heattr"  long_name="ocean advective heat transport along j-axis"    standard_name="advectice_ocean_heat_y_transport"                          unit="W"                                />
+         <field id="v_salttr"     long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_y_transport"                          unit="0.001*kg/s"                        />
+         <field id="veiv_heattr"  long_name="ocean bolus heat transport along j-axis"       standard_name="ocean_heat_y_transport_due_to_bolus_advection"   unit="W"                                />
+         <field id="veiv_salttr"  long_name="ocean bolus salt transport along j-axis"       standard_name="ocean_salt_y_transport_due_to_bolus_advection"   unit="W"                                />
+         <field id="vdiff_heattr" long_name="ocean diffusion heat transport along j-axis"   standard_name="ocean_heat_y_transport_due_to_diffusion"         unit="W"                                />
+      </field_group>
+
+      <!-- W grid -->
+
+      <field_group id="grid_W" grid_ref="grid_W_3D">
+        <field id="e3w"          long_name="W-cell thickness"                     standard_name="cell_thickness"              unit="m"    />
+        <field id="woce"         long_name="ocean vertical velocity"              standard_name="upward_sea_water_velocity"   unit="m/s"  />
+        <field id="wocetr_eff"   long_name="effective ocean vertical transport"                                               unit="m3/s" />
+
+        <!-- woce_eiv: available with key_traldf_eiv and key_diaeiv -->
+        <field id="woce_eiv"     long_name="EIV ocean vertical velocity"   standard_name="bolus_upward_sea_water_velocity"   unit="m/s" />
+        <field id="weiv_masstr"  long_name="EIV Upward Ocean Mass Transport"  standard_name="bolus_upward_ocean_mass_transport"             unit="kg/s"   />
+        <field id="weiv_heattr3d" long_name="ocean bolus heat transport along k-axis"    standard_name="ocean_heat_z_transport_due_to_bolus_advection"   unit="W" />
+        <field id="weiv_salttr3d" long_name="ocean bolus salt transport along k-axis"    standard_name="ocean_salt_z_transport_due_to_bolus_advection"   unit="kg"   grid_ref="grid_U_3D" />
+
+        <field id="avt"          long_name="vertical eddy diffusivity"   standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+        <field id="logavt"       long_name="logarithm of vertical eddy diffusivity"   standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+        <field id="avm"          long_name="vertical eddy viscosity"     standard_name="ocean_vertical_momentum_diffusivity"   unit="m2/s" />
+
+        <!-- avs: available with key_zdfddm -->
+        <field id="avs"          long_name="salt vertical eddy diffusivity"   standard_name="ocean_vertical_salt_diffusivity"   unit="m2/s" />
+        <field id="logavs"       long_name="logarithm of salt vertical eddy diffusivity"   standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+
+        <!-- avt_evd and avm_evd: available with ln_zdfevd -->
+        <field id="avt_evd"      long_name="convective enhancement to vertical diffusivity"   standard_name="ocean_vertical_tracer_diffusivity_due_to_convection"     unit="m2/s" />
+        <field id="avm_evd"      long_name="convective enhancement to vertical viscosity"     standard_name="ocean_vertical_momentum_diffusivity_due_to_convection"   unit="m2/s" />
+
+        <!-- avt_tide: available with key_zdftmx -->
+        <field id="av_tide"      long_name="tidal vertical diffusivity"   standard_name="ocean_vertical_tracer_diffusivity_due_to_tides"   unit="m2/s" />
+
+       <!-- variables available with key_zdftmx_new -->
+        <field id="av_ratio"     long_name="S over T diffusivity ratio"            standard_name="salinity_over_temperature_diffusivity_ratio"                     unit="1"    />
+        <field id="av_wave"      long_name="wave-induced vertical diffusivity"     standard_name="ocean_vertical_tracer_diffusivity_due_to_internal_waves"         unit="m2/s" />
+        <field id="bflx_tmx"     long_name="wave-induced buoyancy flux"            standard_name="buoyancy_flux_due_to_internal_waves"                             unit="W/kg" />
+        <field id="pcmap_tmx"    long_name="power consumed by wave-driven mixing"  standard_name="vertically_integrated_power_consumption_by_wave_driven_mixing"   unit="W/m2"      grid_ref="grid_W_2D" />
+        <field id="emix_tmx"     long_name="power density available for mixing"    standard_name="power_available_for_mixing_from_breaking_internal_waves"         unit="W/kg" />
+
+        <!-- variables available with key_diaar5 -->
+        <field id="w_masstr"     long_name="Upward Ocean Mass Transport"             standard_name="upward_ocean_mass_transport"             unit="kg/s"   />
+        <field id="w_masstr2"    long_name="square of vertical mass transport"   standard_name="square_of_upward_ocean_mass_transport"   unit="kg2/s2" />
+
+        <!-- aht2d and  aht2d_eiv: available with key_traldf_eiv and key_traldf_c2d -->
+        <field id="aht2d"        long_name="lateral eddy diffusivity"       standard_name="ocean_tracer_xy_laplacian_diffusivity"      unit="m2/s"   grid_ref="grid_W_2D" />
+        <field id="aht2d_eiv"    long_name="EIV lateral eddy diffusivity"   standard_name="ocean_tracer_bolus_laplacian_diffusivity"   unit="m2/s"   grid_ref="grid_W_2D" />
+        <!-- variables added for nn_etau revision testing -->
+        <field id="htau"         long_name="e-decay length scale of nn_etau TKE"       unit="m"        grid_ref="grid_W_2D" />
+        <field id="tke"          long_name="Turbulent Kinetic Energy"                  unit="m2/s2"    />
+        <field id="tke_niw"      long_name="Turbulent Kinetic Energy due to near-inertial wave breaking"  unit="m2/s2" />
+
+         <!-- Variable from eosbn2 -->
+         <field id="bn2"          long_name="Squared buoyancy frequency measuring ocean vertical stratification"        standard_name="square_of_brunt_vaisala_frequency_in_sea_water"   unit="1/s^2"  />
+      </field_group>
+
+      <!-- product fields -->
+      <field_group id="diaprod">
+        <field id="ut"           long_name="product_of_sea_water_x_velocity_and_potential_temperature"      unit="degree_C m/s"      grid_ref="grid_U_3D"   />
+        <field id="ut_e3u"       long_name="product_of_sea_water_x_velocity_and_potential_temperature * e3u"  unit="degree_C m2/s"   grid_ref="grid_U_3D" > ut * e3u </field >
+        <field id="us"           long_name="product_of_sea_water_x_velocity_and_salinity"                   unit="PSU m/s"       grid_ref="grid_U_3D"   />
+        <field id="us_e3u"       long_name="product_of_sea_water_x_velocity_and_salinity * e3u"             unit="PSU m2/s"      grid_ref="grid_U_3D" > us * e3u </field >
+        <field id="urhop"        long_name="product_of_sea_water_x_velocity_and_potential_density"          unit="(kg/m3).(m/s)" grid_ref="grid_U_3D"   />
+        <field id="urhop_e3u"    long_name="product_of_sea_water_x_velocity_and_potential_density * e3u"    unit="(kg/m3).(m2/s)"   grid_ref="grid_U_3D" > urhop * e3u </field >
+        <field id="vt"           long_name="product_of_sea_water_y_velocity_and_potential_temperature"      unit="degree_C m/s"      grid_ref="grid_V_3D"   />
+        <field id="vt_e3v"       long_name="product_of_sea_water_y_velocity_and_potential_temperature * e3v"  unit="degree_C m2/s"   grid_ref="grid_V_3D" > vt * e3v </field >
+        <field id="vs"           long_name="product_of_sea_water_y_velocity_and_salinity"                   unit="PSU m/s"       grid_ref="grid_V_3D"   />
+        <field id="vs_e3v"       long_name="product_of_sea_water_y_velocity_and_salinity * e3t"             unit="PSU m2/s"      grid_ref="grid_V_3D" > vs * e3v </field >
+        <field id="vrhop"        long_name="product_of_sea_water_y_velocity_and_potential_density"          unit="(kg/m3).(m/s)" grid_ref="grid_V_3D"   />
+        <field id="vrhop_e3v"    long_name="product_of_sea_water_y_velocity_and_potential_density * e3t"    unit="(kg/m3).(m2/s)"  grid_ref="grid_V_3D" > vrhop * e3v </field >
+        <field id="wt"           long_name="product_of_upward_sea_water_velocity_and_potential_temperature" unit="degree_C m/s"      grid_ref="grid_W_3D"   />
+        <field id="ws"           long_name="product_of_upward_sea_water_velocity_and_salinity"              unit="PSU m/s"       grid_ref="grid_W_3D"   />
+        <field id="wrhop"        long_name="product_of_upward_sea_water_velocity_and_potential_density"     unit="(kg/m3).(m/s)" grid_ref="grid_W_3D"   />
+      </field_group>
+
+      <!-- scalar variables available with key_diaar5 -->
+
+      <field_group id="scalar"  grid_ref="scalar" >
+         <field id="voltot"     long_name="Sea Water Volume"                             standard_name="sea_water_volume"                               unit="m3"   />
+         <field id="sshtot"     long_name="global mean ssh"                              standard_name="global_average_sea_level_change"                unit="m"    />
+         <field id="sshsteric"  long_name="global mean ssh steric"                       standard_name="global_average_steric_sea_level_change"         unit="m"    />
+         <field id="sshthster"  long_name="Global Average Thermosteric Sea Level Change" standard_name="global_average_thermosteric_sea_level_change"   unit="m"    />
+         <field id="masstot"    long_name="global total mass"                            standard_name="sea_water_mass"                                 unit="kg"   />
+         <field id="temptot"    long_name="Global Average Sea Water Potential Temperature"      standard_name="sea_water_potential_temperature"         unit="degree_C" />
+         <field id="saltot"     long_name="Global Average Sea Water Salinity"                   standard_name="sea_water_salinity"                      unit="0.001" />
+         <field id="fram_trans" long_name="Sea Ice Mass Transport Through Fram Strait"   standard_name="sea_ice_transport_across_line"                  unit="kg/s" />
+
+         <!-- available with ln_diahsb -->
+         <field id="bgtemper"     long_name="drift in global mean temperature wrt timestep 1"                 standard_name="change_over_time_in_sea_water_potential_temperature"   unit="degree_C"     />
+         <field id="bgsaline"     long_name="drift in global mean salinity wrt timestep 1"                    standard_name="change_over_time_in_sea_water_practical_salinity"      unit="0.001"     />
+         <field id="bgheatco"     long_name="drift in global mean heat content wrt timestep 1"                                                                                      unit="10^9J"    />
+         <field id="bgsaltco"     long_name="drift in global mean salt content wrt timestep 1"                                                                                      unit="0.001*m3"  />
+         <field id="bgvolssh"     long_name="drift in global mean ssh volume wrt timestep 1"                                                                                        unit="km3"      />
+         <field id="bgvole3t"     long_name="drift in global mean volume variation (e3t) wrt timestep 1"                                                                            unit="km3"      />
+         <field id="bgvoltot"     long_name="drift in global mean volume wrt timestep 1"                                                                                            unit="km3"      />
+         <!-- NOTE: No matching iom_put call -->
+         <field id="bgsshtot"     long_name="drift in global mean ssh wrt timestep 1"                         standard_name="global_average_sea_level_change"                       unit="m"        />
+         <field id="bgfrcvol"     long_name="drift in global mean volume from forcing wrt timestep 1"                                                                               unit="km3"      />
+         <field id="bgfrctem"     long_name="drift in global mean heat content from forcing wrt timestep 1"                                                                         unit="10^9J"    />
+         <field id="bgfrcsal"     long_name="drift in global mean salt content from forcing wrt timestep 1"                                                                         unit="0.001*km3" />
+         <field id="bgmistem"     long_name="global mean temperature error due to free surface"                                                                                     unit="degree_C"     />
+         <field id="bgmissal"     long_name="global mean salinity error due to free surface"                                                                                        unit="0.001"     />
+      </field_group>
+
+      <!-- LIM3 scalar variables -->
+
+      <field_group id="SBC_scalar"  grid_ref="scalar" >
+         <!-- available with ln_limdiaout -->
+         <field id="ibgvoltot"    long_name="global mean ice volume"                                 unit="km3"        />
+         <field id="sbgvoltot"    long_name="global mean snow volume"                                unit="km3"        />
+         <field id="ibgarea"      long_name="global mean ice area"                                   unit="km2"        />
+         <field id="ibgsaline"    long_name="global mean ice salinity"                               unit="0.001"       />
+         <field id="ibgtemper"    long_name="global mean ice temperature"                            unit="degree_C"       />
+         <field id="ibgheatco"    long_name="global mean ice heat content"                           unit="10^20J"     />
+         <field id="sbgheatco"    long_name="global mean snow heat content"                          unit="10^20J"     />
+         <field id="ibgsaltco"    long_name="global mean ice salt content"                           unit="0.001*km3"   />
+
+         <field id="ibgvfx"       long_name="global mean volume flux (emp)"                          unit="m/day"      />
+         <field id="ibgvfxbog"    long_name="global mean volume flux (bottom growth)"                unit="m/day"      />
+         <field id="ibgvfxopw"    long_name="global mean volume flux (open water growth)"            unit="m/day"      />
+         <field id="ibgvfxsni"    long_name="global mean volume flux (snow-ice growth)"              unit="m/day"      />
+         <field id="ibgvfxdyn"    long_name="global mean volume flux (dynamic growth)"               unit="m/day"      />
+         <field id="ibgvfxbom"    long_name="global mean volume flux (bottom melt)"                  unit="m/day"      />
+         <field id="ibgvfxsum"    long_name="global mean volume flux (surface melt)"                 unit="m/day"      />
+         <field id="ibgvfxres"    long_name="global mean volume flux (resultant)"                    unit="m/day"      />
+         <field id="ibgvfxspr"    long_name="global mean volume flux (snow precip)"                  unit="m/day"      />
+         <field id="ibgvfxsnw"    long_name="global mean volume flux (snow melt)"                    unit="m/day"      />
+         <field id="ibgvfxsub"    long_name="global mean volume flux (snow sublimation)"             unit="m/day"      />
+
+         <field id="ibgsfx"       long_name="global mean salt flux (total)"                          unit="0.001*m/day" />
+         <field id="ibgsfxbri"    long_name="global mean salt flux (brines)"                         unit="0.001*m/day" />
+         <field id="ibgsfxdyn"    long_name="global mean salt flux (dynamic)"                        unit="0.001*m/day" />
+         <field id="ibgsfxres"    long_name="global mean salt flux (resultant)"                      unit="0.001*m/day" />
+         <field id="ibgsfxbog"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxopw"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxsni"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxbom"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxsum"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+         <field id="ibgsfxsub"    long_name="global mean salt flux (thermo)"                         unit="0.001*m/day" />
+
+         <field id="ibghfxdhc"    long_name="Heat content variation in snow and ice"                 unit="W"          />
+         <field id="ibghfxspr"    long_name="Heat content of snow precip"                            unit="W"          />
+
+         <field id="ibghfxthd"    long_name="heat fluxes from ice-ocean exchange during thermo"      unit="W"          />
+         <field id="ibghfxsum"    long_name="heat fluxes causing surface ice melt"                   unit="W"          />
+         <field id="ibghfxbom"    long_name="heat fluxes causing bottom ice melt"                    unit="W"          />
+         <field id="ibghfxbog"    long_name="heat fluxes causing bottom ice growth"                  unit="W"          />
+         <field id="ibghfxdif"    long_name="heat fluxes causing ice temperature change"             unit="W"          />
+         <field id="ibghfxopw"    long_name="heat fluxes causing open water ice formation"           unit="W"          />
+         <field id="ibghfxdyn"    long_name="heat fluxes from ice-ocean exchange during dynamic"     unit="W"          />
+         <field id="ibghfxres"    long_name="heat fluxes from ice-ocean exchange during resultant"   unit="W"          />
+         <field id="ibghfxsub"    long_name="heat fluxes from sublimation"                           unit="W"          />
+         <field id="ibghfxsnw"    long_name="heat fluxes from snow-ocean exchange"                   unit="W"          />
+         <field id="ibghfxout"    long_name="non solar heat fluxes received by the ocean"            unit="W"          />
+         <field id="ibghfxin"     long_name="total heat fluxes at the ice surface"                   unit="W"          />
+
+         <field id="ibgfrcvol"    long_name="global mean forcing volume (emp)"                       unit="km3"        />
+         <field id="ibgfrcsfx"    long_name="global mean forcing salt   (sfx)"                       unit="0.001*km3"   />
+         <field id="ibgvolgrm"    long_name="global mean ice growth+melt volume"                     unit="km3"        />
+      </field_group>
+
+      <!-- variables available with key_float -->
+
+      <field_group id="floatvar" grid_ref="scalar" axis_ref="nfloat" operation="instant" >
+        <field id="traj_lon"      long_name="floats longitude"                                                           unit="degrees_east"  />
+        <field id="traj_lat"      long_name="floats latitude"                                                            unit="degrees_north" />
+        <field id="traj_dep"      long_name="floats depth"                                                               unit="m"             />
+        <field id="traj_temp"     long_name="floats temperature"       standard_name="sea_water_potential_temperature"   unit="degree_C"          />
+        <field id="traj_salt"     long_name="floats salinity"          standard_name="sea_water_practical_salinity"      unit="0.001"          />
+        <field id="traj_dens"     long_name="floats in-situ density"   standard_name="sea_water_density"                 unit="kg/m3"         />
+        <field id="traj_group"    long_name="floats group"                                                               unit="1"             />
+      </field_group>
+
+      <!-- variables available with iceberg trajectories -->
+
+      <field_group id="icbvar" grid_ref="grid_T_2D"  >
+        <field id="berg_total_melt"    long_name="icb melt rate 2 of icebergs"                     unit="kg/m2/s"                    />
+        <field id="berg_total_heat_flux"  long_name="icb latent heat of melting of icebergs"          unit="kg/m2/s"                    />
+        <field id="berg_melt"          long_name="icb melt rate of icebergs"                       unit="kg/m2/s"                    />
+        <field id="berg_buoy_melt"     long_name="icb buoyancy component of iceberg melt rate"     unit="kg/m2/s"                    />
+        <field id="berg_eros_melt"     long_name="icb erosion component of iceberg melt rate"      unit="kg/m2/s"                    />
+        <field id="berg_conv_melt"     long_name="icb convective component of iceberg melt rate"   unit="kg/m2/s"                    />
+        <field id="berg_virtual_area"  long_name="icb virtual coverage by icebergs"                unit="m2"                         />
+        <field id="bits_src"           long_name="icb mass source of bergy bits"                   unit="kg/m2/s"                    />
+        <field id="bits_melt"          long_name="icb melt rate of bergy bits"                     unit="kg/m2/s"                    />
+        <field id="bits_mass"          long_name="icb bergy bit density field"                     unit="kg/m2"                      />
+        <field id="berg_mass"          long_name="icb iceberg density field"                       unit="kg/m2"                      />
+        <field id="calving"            long_name="icb calving mass input"                          unit="kg/s"                       />
+        <field id="berg_floating_melt" long_name="icb melt rate of icebergs + bits"                unit="kg/m2/s"                    />
+        <field id="berg_real_calving"  long_name="icb calving into iceberg class"                  unit="kg/s"     axis_ref="icbcla" />
+        <field id="berg_stored_ice"    long_name="icb accumulated ice mass by class"               unit="kg"       axis_ref="icbcla" />
+      </field_group>
+
+      <!-- Poleward transport : ptr -->
+      <field_group id="diaptr">
+        <field id="zomsfglo"          long_name="Meridional Stream-Function: Global"           unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfatl"          long_name="Meridional Stream-Function: Atlantic"         unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfpac"          long_name="Meridional Stream-Function: Pacific"          unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfind"          long_name="Meridional Stream-Function: Indian"           unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zomsfipc"          long_name="Meridional Stream-Function: Pacific+Indian"   unit="Sv"       grid_ref="gznl_W_3D" />
+        <field id="zotemglo"          long_name="Zonal Mean Temperature : Global"              unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotematl"          long_name="Zonal Mean Temperature : Atlantic"            unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotempac"          long_name="Zonal Mean Temperature : Pacific"             unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotemind"          long_name="Zonal Mean Temperature : Indian"              unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zotemipc"          long_name="Zonal Mean Temperature : Pacific+Indian"      unit="degree_C"     grid_ref="gznl_T_3D" />
+        <field id="zosalglo"          long_name="Zonal Mean Salinity : Global"                 unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalatl"          long_name="Zonal Mean Salinity : Atlantic"               unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalpac"          long_name="Zonal Mean Salinity : Pacific"                unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalind"          long_name="Zonal Mean Salinity : Indian"                 unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosalipc"          long_name="Zonal Mean Salinity : Pacific+Indian"         unit="0.001"     grid_ref="gznl_T_3D" />
+        <field id="zosrfglo"          long_name="Zonal Mean Surface"                           unit="m2"       grid_ref="gznl_T_3D" />
+        <field id="zosrfatl"          long_name="Zonal Mean Surface : Atlantic"                unit="m2"       grid_ref="gznl_T_3D" />
+        <field id="zosrfpac"          long_name="Zonal Mean Surface : Pacific"                 unit="m2"       grid_ref="gznl_T_3D" />
+        <field id="zosrfind"          long_name="Zonal Mean Surface : Indian"                  unit="m2"       grid_ref="gznl_T_3D" />
+        <field id="zosrfipc"          long_name="Zonal Mean Surface : Pacific+Indian"          unit="m2"       grid_ref="gznl_T_3D" />
+        <field id="sophtadv"          long_name="Advective Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_atl"      long_name="Advective Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_pac"      long_name="Advective Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_ind"      long_name="Advective Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtadv_ipc"      long_name="Advective Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf"          long_name="Diffusive Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_atl"      long_name="Diffusive Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_pac"      long_name="Diffusive Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_ind"      long_name="Diffusive Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtldf_ipc"      long_name="Diffusive Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove"          long_name="Overturning Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_atl"      long_name="Overturning Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_pac"      long_name="Overturning Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_ind"      long_name="Overturning Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtove_ipc"      long_name="Overturning Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr"          long_name="Barotropic Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_atl"      long_name="Barotropic Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_pac"      long_name="Barotropic Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_ind"      long_name="Barotropic Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophtbtr_ipc"      long_name="Barotropic Heat Transport: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv"          long_name="Heat Transport from mesoscale eddy oveection"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_atl"      long_name="Heat Transport from mesoscale eddy advection: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_pac"      long_name="Heat Transport from mesoscale eddy advection: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_ind"      long_name="Heat Transport from mesoscale eddy advection: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sophteiv_ipc"      long_name="Heat Transport from mesoscale eddy advection: Pacific+Indian"     unit="PW"       grid_ref="gznl_T_2D" />
+       <field id="sopstadv"          long_name="Advective Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_atl"      long_name="Advective Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_pac"      long_name="Advective Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_ind"      long_name="Advective Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstadv_ipc"      long_name="Advective Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove"          long_name="Overturning Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_atl"      long_name="Overturning Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_pac"      long_name="Overturning Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_ind"      long_name="Overturning Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstove_ipc"      long_name="Overturning Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr"          long_name="Barotropic Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_atl"      long_name="Barotropic Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_pac"      long_name="Barotropic Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_ind"      long_name="Barotropic Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstbtr_ipc"      long_name="Barotropic Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf"          long_name="Diffusive Salt Transport"                     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_atl"      long_name="Diffusive Salt Transport: Atlantic"           unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_pac"      long_name="Diffusive Salt Transport: Pacific"            unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_ind"      long_name="Diffusive Salt Transport: Indian"             unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopstldf_ipc"      long_name="Diffusive Salt Transport: Pacific+Indian"     unit="Giga g/s" grid_ref="gznl_T_2D" />
+        <field id="sopsteiv"          long_name="Salt Transport from mesoscale eddy advection"                     unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_atl"      long_name="Salt Transport from mesoscale eddy advection: Atlantic"           unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_pac"      long_name="Salt Transport from mesoscale eddy advection: Pacific"            unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_ind"      long_name="Salt Transport from mesoscale eddy advection: Indian"             unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopsteiv_ipc"      long_name="Salt Transport from mesoscale eddy advection: Pacific+Indian"     unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt"          long_name="Heat Transport"                     unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_atl"      long_name="Heat Transport: Atlantic"           unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_ind"      long_name="Heat Transport: Indian"             unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_pac"      long_name="Heat Transport: Pacific"            unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopht_vt_ipc"      long_name="Heat Transport: Indo-Pacific"       unit="PW"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs"          long_name="Salt Transport"                     unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_atl"      long_name="Salt Transport: Atlantic"           unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_ind"      long_name="Salt Transport: Indian"             unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_pac"      long_name="Salt Transport: Pacific"            unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="sopst_vs_ipc"      long_name="Salt Transport: Indo-Pacific"       unit="Giga g/s"       grid_ref="gznl_T_2D" />
+        <field id="vsum" grid_ref="gznl_T_2D" unit="none" standard_name="none" />
+        <field id="tmean" grid_ref="gznl_T_2D" unit="none" standard_name="none" />
+        <field id="section_area" grid_ref="gznl_T_2D" unit="none" standard_name="none" />
+      </field_group>
+
+    <!-- 
+         ============================================================================================================
+                  Physical ocean model trend diagnostics : temperature, KE, PE, momentum
+============================================================================================================
+    -->
+
+    <field_group id="trendT" grid_ref="grid_T_3D">
+      <!-- variables available with ln_tra_trd -->
+      <field id="ttrd_xad"      long_name="temperature-trend: i-advection"                                                                                          unit="degC/s"                        />
+      <field id="strd_xad"      long_name="salinity   -trend: i-advection"                                                                                          unit="1e-3/s"                        />
+      <field id="ttrd_yad"      long_name="temperature-trend: j-advection"                                                                                          unit="degC/s"                        />
+      <field id="strd_yad"      long_name="salinity   -trend: j-advection"                                                                                          unit="1e-3/s"                        />
+      <field id="ttrd_zad"      long_name="temperature-trend: k-advection"                                                                                          unit="degC/s"                        />
+      <field id="strd_zad"      long_name="salinity   -trend: k-advection"                                                                                          unit="1e-3/s"                        />
+      <field id="ttrd_ad"       long_name="temperature-trend: advection"               standard_name="tendency_of_sea_water_temperature_due_to_advection"           unit="degC/s"                         > sqrt( ttrd_xad^2 + ttrd_yad^2 + ttrd_zad^2 ) </field>
+      <field id="strd_ad"       long_name="salinity   -trend: advection"               standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="1e-3/s"                         > sqrt( strd_xad^2 + strd_yad^2 + strd_zad^2 ) </field>
+      <field id="ttrd_totad"    long_name="temperature-trend: total advection"         standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="degC/s"                        />
+      <field id="strd_totad"    long_name="salinity   -trend: total advection"         standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="1e-3/s"                        />
+      <field id="ttrd_sad"      long_name="temperature-trend: surface adv. (no-vvl)"                                                                                unit="degC/s"   grid_ref="grid_T_2D" />
+      <field id="strd_sad"      long_name="salinity   -trend: surface adv. (no-vvl)"                                                                                unit="1e-3/s"   grid_ref="grid_T_2D" />
+      <field id="ttrd_ldf"      long_name="temperature-trend: lateral  diffusion"      standard_name="tendency_of_sea_water_temperature_due_to_horizontal_mixing"   unit="degC/s"                        />
+      <field id="strd_ldf"      long_name="salinity   -trend: lateral  diffusion"      standard_name="tendency_of_sea_water_salinity_due_to_horizontal_mixing"      unit="1e-3/s"                        />
+      <field id="ttrd_zdf"      long_name="temperature-trend: vertical diffusion"      standard_name="tendency_of_sea_water_temperature_due_to_vertical_mixing"     unit="degC/s"                        />
+      <field id="strd_zdf"      long_name="salinity   -trend: vertical diffusion"      standard_name="tendency_of_sea_water_salinity_due_to_vertical_mixing"        unit="1e-3/s"                        />
+      <field id="ttrd_evd"      long_name="temperature-trend: EVD convection"                                                                                       unit="degC/s"                        />
+      <field id="strd_evd"      long_name="salinity   -trend: EVD convection"                                                                                       unit="1e-3/s"                        />
+
+      <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+      <field id="ttrd_iso_x"    long_name="temperature-trend: isopycnal diffusion x-component"                                                                      unit="degC/s"                        />
+      <field id="strd_iso_x"    long_name="salinity   -trend: isopycnal diffusion x-component"                                                                      unit="1e-3/s"                        />
+      <field id="ttrd_iso_y"    long_name="temperature-trend: isopycnal diffusion y-component"                                                                      unit="degC/s"                        />
+      <field id="strd_iso_y"    long_name="salinity   -trend: isopycnal diffusion y-component"                                                                      unit="1e-3/s"                        />
+      <field id="ttrd_iso_z1"   long_name="temperature-trend: isopycnal diffusion z-component part 1"                                                               unit="degC/s"                        />
+      <field id="strd_iso_z1"   long_name="salinity   -trend: isopycnal diffusion z-component part 1"                                                               unit="1e-3/s"                        />
+      <field id="ttrd_iso_z"    long_name="temperature-trend: isopycnal diffusion z-component"                 unit="degC/s" > ttrd_iso_z1 + ttrd_zdf - ttrd_zdfp </field>
+      <field id="strd_iso_z"    long_name="salinity   -trend: isopycnal diffusion z-component"                 unit="1e-3/s" > strd_iso_z1 + strd_zdf - strd_zdfp </field>
+      <field id="ttrd_iso"      long_name="temperature-trend: isopycnal diffusion"                             unit="degC/s" > ttrd_ldf + ttrd_zdf - ttrd_zdfp </field>
+      <field id="strd_iso"      long_name="salinity   -trend: isopycnal diffusion"                             unit="1e-3/s" > strd_ldf + strd_zdf - strd_zdfp </field>
+      <field id="ttrd_zdfp"     long_name="temperature-trend: pure vert. diffusion"   unit="degC/s" />
+      <field id="strd_zdfp"     long_name="salinity   -trend: pure vert. diffusion"   unit="1e-3/s" />
+
+      <!-- -->
+      <field id="ttrd_dmp"      long_name="temperature-trend: interior restoring"        unit="degree_C/s" />
+      <field id="strd_dmp"      long_name="salinity   -trend: interior restoring"        unit="0.001/s" />
+      <field id="ttrd_bbl"      long_name="temperature-trend: bottom boundary layer"     unit="degree_C/s" />
+      <field id="strd_bbl"      long_name="salinity   -trend: bottom boundary layer"     unit="0.001/s" />
+      <field id="ttrd_npc"      long_name="temperature-trend: non-penetrative conv."     unit="degree_C/s" />
+      <field id="strd_npc"      long_name="salinity   -trend: non-penetrative conv."     unit="0.001/s" />
+      <field id="ttrd_qns"      long_name="temperature-trend: non-solar flux + runoff"   unit="degC/s" grid_ref="grid_T_2D"/>
+      <field id="strd_cdt"      long_name="salinity   -trend: C/D term       + runoff"   unit="degC/s" grid_ref="grid_T_2D"/>
+      <field id="ttrd_qsr"      long_name="temperature-trend: solar penetr. heating"     unit="degree_C/s" />
+      <field id="ttrd_bbc"      long_name="temperature-trend: geothermal heating"        unit="degree_C/s" />
+      <field id="ttrd_atf"      long_name="temperature-trend: asselin time filter"       unit="degree_C/s" />
+      <field id="strd_atf"      long_name="salinity   -trend: asselin time filter"       unit="0.001/s" />
+      <field id="ttrd_tot"      long_name="temperature-trend: total model trend"         unit="degC/s" />
+      <field id="strd_tot"      long_name="salinity   -trend: total model trend"         unit="1e-3/s" />
+
+      <!-- Thickness weighted versions: -->
+      <field id="ttrd_xad_e3t"      unit="degC/s * m" >  ttrd_xad * e3t </field>
+      <field id="strd_xad_e3t"      unit="1e-3/s * m" >  strd_xad * e3t </field>
+      <field id="ttrd_yad_e3t"      unit="degC/s * m" >  ttrd_yad * e3t </field>
+      <field id="strd_yad_e3t"      unit="1e-3/s * m" >  strd_yad * e3t </field>
+      <field id="ttrd_zad_e3t"      unit="degC/s * m" >  ttrd_zad * e3t </field>
+      <field id="strd_zad_e3t"      unit="1e-3/s * m" >  strd_zad * e3t </field>
+      <field id="ttrd_ad_e3t"       unit="degC/s * m" >  ttrd_ad  * e3t </field>
+      <field id="strd_ad_e3t"       unit="1e-3/s * m" >  strd_ad  * e3t </field>
+      <field id="ttrd_totad_e3t"    unit="degC/s * m" >  ttrd_totad  * e3t </field>
+      <field id="strd_totad_e3t"    unit="1e-3/s * m" >  strd_totad  * e3t </field>
+      <field id="ttrd_ldf_e3t"      unit="degC/s * m" >  ttrd_ldf * e3t </field>
+      <field id="strd_ldf_e3t"      unit="1e-3/s * m" >  strd_ldf * e3t </field>
+      <field id="ttrd_zdf_e3t"      unit="degC/s * m" >  ttrd_zdf * e3t </field>
+      <field id="strd_zdf_e3t"      unit="1e-3/s * m" >  strd_zdf * e3t </field>
+      <field id="ttrd_evd_e3t"      unit="degC/s * m" >  ttrd_evd * e3t </field>
+      <field id="strd_evd_e3t"      unit="1e-3/s * m" >  strd_evd * e3t </field>
+
+      <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+      <field id="ttrd_iso_x_e3t"    unit="degC/s * m"  >  ttrd_iso_x * e3t </field>
+      <field id="strd_iso_x_e3t"    unit="1e-3/s * m"  >  strd_iso_x * e3t </field>
+      <field id="ttrd_iso_y_e3t"    unit="degC/s * m"  >  ttrd_iso_y * e3t </field>
+      <field id="strd_iso_y_e3t"    unit="1e-3/s * m"  >  strd_iso_y * e3t </field>
+      <field id="ttrd_iso_z_e3t"    unit="degC/s * m"  >  ttrd_iso_z * e3t </field>
+      <field id="strd_iso_z_e3t"    unit="1e-3/s * m"  >  strd_iso_z * e3t </field>
+      <field id="ttrd_iso_e3t"      unit="degC/s * m"  >  ttrd_iso * e3t </field>
+      <field id="strd_iso_e3t"      unit="1e-3/s * m"  >  strd_iso * e3t </field>
+      <field id="ttrd_zdfp_e3t"     unit="degC/s * m"  >  ttrd_zdfp * e3t </field>
+      <field id="strd_zdfp_e3t"     unit="1e-3/s * m"  >  strd_zdfp * e3t </field>
+
+      <!-- -->
+      <field id="ttrd_dmp_e3t"      unit="degC/s * m"  >  ttrd_dmp * e3t </field>
+      <field id="strd_dmp_e3t"      unit="1e-3/s * m"  >  strd_dmp * e3t </field>
+      <field id="ttrd_bbl_e3t"      unit="degC/s * m"  >  ttrd_bbl * e3t </field>
+      <field id="strd_bbl_e3t"      unit="1e-3/s * m"  >  strd_bbl * e3t </field>
+      <field id="ttrd_npc_e3t"      unit="degC/s * m"  >  ttrd_npc * e3t </field>
+      <field id="strd_npc_e3t"      unit="1e-3/s * m"  >  strd_npc * e3t </field>
+      <field id="ttrd_qns_e3t"      unit="degC/s * m"  >  ttrd_qns * e3t_surf </field>
+      <field id="strd_cdt_e3t"      unit="degC/s * m"  >  strd_cdt * e3t_surf </field>
+      <field id="ttrd_qsr_e3t"      unit="degC/s * m"  >  ttrd_qsr * e3t </field>
+      <field id="ttrd_bbc_e3t"      unit="degC/s * m"  >  ttrd_bbc * e3t </field>
+      <field id="ttrd_atf_e3t"      unit="degC/s * m"  >  ttrd_atf * e3t </field>
+      <field id="strd_atf_e3t"      unit="1e-3/s * m"  >  strd_atf * e3t </field>
+      <field id="ttrd_tot_e3t"      unit="degC/s * m"  >  ttrd_tot * e3t </field>
+      <field id="strd_tot_e3t"      unit="1e-3/s * m"  >  strd_tot * e3t </field>
+
+      <!-- variables available with ln_KE_trd -->
+      <field id="ketrd_hpg"     long_name="ke-trend: hydrostatic pressure gradient"          unit="W/s^3"                        />
+      <field id="ketrd_spg"     long_name="ke-trend: surface     pressure gradient"          unit="W/s^3"                        />
+      <field id="ketrd_spgexp"  long_name="ke-trend: surface pressure gradient (explicit)"   unit="W/s^3"                        />
+      <field id="ketrd_spgflt"  long_name="ke-trend: surface pressure gradient (filter)"     unit="W/s^3"                        />
+      <field id="ssh_flt"       long_name="filtered contribution to ssh (dynspg_flt)"        unit="m"       grid_ref="grid_T_2D" />
+      <field id="w0"            long_name="surface vertical velocity"                        unit="m/s"     grid_ref="grid_T_2D" />
+      <field id="pw0_exp"       long_name="surface pressure flux due to ssh"                 unit="W/s^2"   grid_ref="grid_T_2D" />
+      <field id="pw0_flt"       long_name="surface pressure flux due to filtered ssh"        unit="W/s^2"   grid_ref="grid_T_2D" />
+      <field id="ketrd_keg"     long_name="ke-trend: KE gradient         or hor. adv."       unit="W/s^3"                        />
+      <field id="ketrd_rvo"     long_name="ke-trend: relative  vorticity or metric term"     unit="W/s^3"                        />
+      <field id="ketrd_pvo"     long_name="ke-trend: planetary vorticity"                    unit="W/s^3"                        />
+      <field id="ketrd_zad"     long_name="ke-trend: vertical  advection"                    unit="W/s^3"                        />
+      <field id="ketrd_udx"     long_name="ke-trend: U.dx[U]"                                unit="W/s^3"                        />
+      <field id="ketrd_ldf"     long_name="ke-trend: lateral   diffusion"                    unit="W/m^3"                        />
+      <field id="ketrd_ldf_e3t" field_ref="ketrd_ldf" long_name="ke-trend: lateral   diffusion * e3t" unit="W/m^2" >ketrd_ldf*e3t</field>
+      <field id="ketrd_ldf_vsum" field_ref="ketrd_ldf_e3t" long_name="ke-trend: lateral diffusion vertical integral" unit="W/m^2" grid_ref="vert_sum" />
+      <field id="ketrd_zdf"     long_name="ke-trend: vertical  diffusion"                    unit="W/s^3"                        />
+      <field id="ketrd_tau"     long_name="ke-trend: wind stress "                           unit="W/s^3"   grid_ref="grid_T_2D" />
+      <field id="ketrd_bfr"     long_name="ke-trend: bottom friction (explicit)"             unit="W/s^3"                        />
+      <field id="ketrd_bfri"    long_name="ke-trend: bottom friction (implicit)"             unit="W/s^3"                        />
+      <field id="ketrd_atf"     long_name="ke-trend: asselin time filter trend"              unit="W/s^3"                        />
+      <field id="ketrd_convP2K" long_name="ke-trend: conversion (potential to kinetic)"      unit="W/s^3"                        />
+      <field id="KE"            long_name="kinetic energy: u(n)*u(n+1)/2"                    unit="W/s^2"                        />
+      <field id="ketrd_eiv"     long_name="Kinetic energy trend from mesoscale eddy advection"   unit="W/s^2" grid_ref="grid_T_2D" />
+
+      <!-- variables available with ln_PE_trd -->
+      <field id="petrd_xad"     long_name="pe-trend: i-advection"                unit="W/m^3"                        />
+      <field id="petrd_yad"     long_name="pe-trend: j-advection"                unit="W/m^3"                        />
+      <field id="petrd_zad"     long_name="pe-trend: k-advection"                unit="W/m^3"                        />
+      <field id="petrd_sad"     long_name="pe-trend: surface adv. (no-vvl)"      unit="W/m^3"   grid_ref="grid_T_2D" />
+      <field id="petrd_ldf"     long_name="pe-trend: lateral  diffusion"         unit="W/m^3"                        />
+      <field id="petrd_zdf"     long_name="pe-trend: vertical diffusion"         unit="W/m^3"                        />
+      <field id="petrd_zdfp"    long_name="pe-trend: pure vert. diffusion"       unit="W/m^3"                        />
+      <field id="petrd_dmp"     long_name="pe-trend: interior restoring"         unit="W/m^3"                        />
+      <field id="petrd_bbl"     long_name="pe-trend: bottom boundary layer"      unit="W/m^3"                        />
+      <field id="petrd_npc"     long_name="pe-trend: non-penetrative conv."      unit="W/m^3"                        />
+      <field id="petrd_nsr"     long_name="pe-trend: surface forcing + runoff"   unit="W/m^3"                        />
+      <field id="petrd_qsr"     long_name="pe-trend: solar penetr. heating"      unit="W/m^3"                        />
+      <field id="petrd_bbc"     long_name="pe-trend: geothermal heating"         unit="W/m^3"                        />
+      <field id="petrd_atf"     long_name="pe-trend: asselin time filter"        unit="W/m^3"                        />
+      <field id="PEanom"        long_name="potential energy anomaly"             unit="1"                            />
+      <field id="alphaPE"       long_name="partial deriv. of PEanom wrt T"       unit="degree_C-1"                       />
+      <field id="betaPE"        long_name="partial deriv. of PEanom wrt S"       unit="1e3"                          />
+      <field id="petrd_zdfp_e3t"    unit="W/m^2" grid_ref="grid_T_3D"  > petrd_zdfp * e3t </field>
+      <field id="petrd_2d" field_ref="petrd_zdfp_e3t" grid_ref="vert_sum" />
+    </field_group>
+
+    <field_group id="trendU" grid_ref="grid_U_3D">
+     <!-- variables available with ln_dyn_trd -->
+     <field id="utrd_hpg"       long_name="i-trend: hydrostatic pressure gradient"          unit="m/s^2"                        />
+     <field id="utrd_spg"       long_name="i-trend: surface     pressure gradient"          unit="m/s^2"                        />
+     <field id="utrd_spgexp"    long_name="i-trend: surface pressure gradient (explicit)"   unit="m/s^2"                        />
+     <field id="utrd_spgflt"    long_name="i-trend: surface pressure gradient (filtered)"   unit="m/s^2"                        />
+     <field id="utrd_keg"       long_name="i-trend: KE gradient         or hor. adv."       unit="m/s^2"                        />
+     <field id="utrd_rvo"       long_name="i-trend: relative  vorticity or metric term"     unit="m/s^2"                        />
+     <field id="utrd_pvo"       long_name="i-trend: planetary vorticity"                    unit="m/s^2"                        />
+     <field id="utrd_zad"       long_name="i-trend: vertical  advection"                    unit="m/s^2"                        />
+     <field id="utrd_udx"       long_name="i-trend: U.dx[U]"                                unit="m/s^2"                        />
+     <field id="utrd_ldf"       long_name="i-trend: lateral   diffusion"                    unit="m/s^2"                        />
+     <field id="utrd_zdf"       long_name="i-trend: vertical  diffusion"                    unit="m/s^2"                        />
+     <field id="utrd_tau"       long_name="i-trend: wind stress "                           unit="m/s^2"   grid_ref="grid_U_2D" />
+     <field id="utrd_bfr"       long_name="i-trend: bottom friction (explicit)"             unit="m/s^2"                        />
+     <field id="utrd_bfri"      long_name="i-trend: bottom friction (implicit)"             unit="m/s^2"                        />
+     <field id="utrd_tot"       long_name="i-trend: total momentum trend before atf"        unit="m/s^2"                        />
+     <field id="utrd_atf"       long_name="i-trend: asselin time filter trend"              unit="m/s^2"                        />
+    </field_group>
+
+    <field_group id="trendV" grid_ref="grid_V_3D">
+     <!-- variables available with ln_dyn_trd -->
+     <field id="vtrd_hpg"       long_name="j-trend: hydrostatic pressure gradient"          unit="m/s^2"                        />
+     <field id="vtrd_spg"       long_name="j-trend: surface     pressure gradient"          unit="m/s^2"                        />
+     <field id="vtrd_spgexp"    long_name="j-trend: surface pressure gradient (explicit)"   unit="m/s^2"                        />
+     <field id="vtrd_spgflt"    long_name="j-trend: surface pressure gradient (filtered)"   unit="m/s^2"                        />
+     <field id="vtrd_keg"       long_name="j-trend: KE gradient         or hor. adv."       unit="m/s^2"                        />
+     <field id="vtrd_rvo"       long_name="j-trend: relative  vorticity or metric term"     unit="m/s^2"                        />
+     <field id="vtrd_pvo"       long_name="j-trend: planetary vorticity"                    unit="m/s^2"                        />
+     <field id="vtrd_zad"       long_name="j-trend: vertical  advection"                    unit="m/s^2"                        />
+     <field id="vtrd_vdy"       long_name="i-trend: V.dx[V]"                                unit="m/s^2"                        />
+     <field id="vtrd_ldf"       long_name="j-trend: lateral   diffusion"                    unit="m/s^2"                        />
+     <field id="vtrd_zdf"       long_name="j-trend: vertical  diffusion"                    unit="m/s^2"                        />
+     <field id="vtrd_tau"       long_name="j-trend: wind stress "                           unit="m/s^2"   grid_ref="grid_V_2D" />
+     <field id="vtrd_bfr"       long_name="j-trend: bottom friction (explicit)"             unit="m/s^2"                        />
+     <field id="vtrd_bfri"      long_name="j-trend: bottom friction (implicit)"             unit="m/s^2"                        />
+     <field id="vtrd_tot"       long_name="j-trend: total momentum trend before atf"        unit="m/s^2"                        />
+     <field id="vtrd_atf"       long_name="j-trend: asselin time filter trend"              unit="m/s^2"                        />
+    </field_group>
+
+
+    <!-- 
+============================================================================================================
+                                        Definitions for iodef_demo.xml
+============================================================================================================
+    -->
+
+    <field_group id="mooring" >
+      <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"      />
+      <field field_ref="soce"         name="so"       long_name="sea_water_salinity"                   />
+      <field field_ref="uoce"         name="uo"       long_name="sea_water_x_velocity"                 />
+      <field field_ref="voce"         name="vo"       long_name="sea_water_y_velocity"                 />
+      <field field_ref="woce"         name="wo"       long_name="sea_water_z_velocity"                 />
+      <field field_ref="avt"          name="difvho"   long_name="ocean_vertical_heat_diffusivity"      />
+      <field field_ref="avm"          name="difvmo"   long_name="ocean_vertical_momentum_diffusivity"  />
+   
+      <field field_ref="sst"          name="tos"      long_name="sea_surface_temperature"                       />
+      <field field_ref="sst2"         name="tossq"    long_name="square_of_sea_surface_temperature"             />
+      <field field_ref="sstgrad"      name="tosgrad"  long_name="module_of_sea_surface_temperature_gradient"    />
+      <field field_ref="sss"          name="sos"      long_name="sea_surface_salinity"                          />
+      <field field_ref="ssh"          name="zos"      long_name="sea_surface_height_above_geoid"                />
+      <field field_ref="empmr"        name="wfo"      long_name="water_flux_into_sea_water"                     />
+      <field field_ref="qsr"          name="rsntds"   long_name="surface_net_downward_shortwave_flux"           />
+      <field field_ref="qt"           name="tohfls"   long_name="surface_net_downward_total_heat_flux"          />
+      <field field_ref="taum"                                                                                   />
+      <field field_ref="20d"                                                                                    />
+      <field field_ref="mldkz5"                                                                                 />
+      <field field_ref="mldr10_1"                                                                               />
+      <field field_ref="mldr10_3"                                                                               />
+      <field field_ref="mldr0_1"                                                                                />
+      <field field_ref="mldr0_3"                                                                                />
+      <field field_ref="mld_dt02"                                                                               />
+      <field field_ref="topthdep"                                                                               />
+      <field field_ref="pycndep"                                                                                />
+      <field field_ref="tinv"                                                                                   />
+      <field field_ref="depti"                                                                                  />
+      <field field_ref="BLT"          name="blt"      long_name="barrier_layer_thickness"                       />
+      <field field_ref="utau"         name="tauuo"    long_name="surface_downward_x_stress"                     />
+      <field field_ref="vtau"         name="tauvo"    long_name="surface_downward_y_stress"                     />
+    </field_group>
+
+    <field_group id="groupT" >
+      <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"               />
+      <field field_ref="soce"         name="so"       long_name="sea_water_salinity"                            />
+      <field field_ref="sst"          name="tos"      long_name="sea_surface_temperature"                       />
+      <field field_ref="sst2"         name="tossq"    long_name="square_of_sea_surface_temperature"             />
+      <field field_ref="sss"          name="sos"      long_name="sea_surface_salinity"                          />
+      <field field_ref="ssh"          name="zos"      long_name="sea_surface_height_above_geoid"                />
+      <field field_ref="empmr"        name="wfo"      long_name="water_flux_into_sea_water"                     />
+      <field field_ref="qsr"          name="rsntds"   long_name="surface_net_downward_shortwave_flux"           />
+      <field field_ref="qt"           name="tohfls"   long_name="surface_net_downward_total_heat_flux"          />
+      <field field_ref="taum"                                                                                   />
+      <field field_ref="20d"                                                                                    />
+      <field field_ref="mldkz5"                                                                                 />
+      <field field_ref="mldr10_1"                                                                               />
+      <field field_ref="mldr10_3"                                                                               />
+      <field field_ref="mld_dt02"                                                                               />
+      <field field_ref="topthdep"                                                                               />
+      <field field_ref="pycndep"                                                                                />
+      <field field_ref="tinv"                                                                                   />
+      <field field_ref="depti"                                                                                  />
+      <field field_ref="BLT"          name="blt"      long_name="Barrier Layer Thickness"                       />
+    </field_group>
+    
+    <field_group id="groupU" >
+      <field field_ref="uoce"         name="uo"      long_name="sea_water_x_velocity"      />
+      <field field_ref="ssu"          name="uos"     long_name="sea_surface_x_velocity"    />
+      <field field_ref="utau"         name="tauuo"   long_name="surface_downward_x_stress" />
+    </field_group>
+    
+    <field_group id="groupV" >
+      <field field_ref="voce"         name="vo"      long_name="sea_water_y_velocity"      />
+      <field field_ref="ssv"          name="vos"     long_name="sea_surface_y_velocity"    />
+      <field field_ref="vtau"         name="tauvo"   long_name="surface_downward_y_stress" />
+    </field_group>
+    
+    <field_group id="groupW" >
+      <field field_ref="woce"         name="wo"       long_name="ocean vertical velocity"  />
+    </field_group>
+    
+    <field_group id="groupT1" > 
+     <field field_ref="sst"          name="sosstsst"   standard_name="sea_surface_temperature"                                 />
+     <field field_ref="sss"          name="sossssss"   standard_name="sea_surface_salinity"                                    />
+     <field field_ref="ssh"          name="sossheig"   standard_name="sea_surface_height_above_geoid"                          />
+     <field field_ref="empmr"        name="sowaflup"   standard_name="water_flux_out_of_sea_ice_and_sea_water"                 />
+     <field field_ref="qt"           name="sohefldo"   standard_name="surface_downward_heat_flux_in_sea_water"                 />
+   </field_group>
+
+   <field_group id="groupT2" >
+     <field field_ref="toce"         name="votemper"     operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+     <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+     <field field_ref="ssh"          name="sossheig"   standard_name="sea_surface_height_above_geoid"                          />
+     <field field_ref="empmr"        name="sowaflup"   standard_name="water_flux_out_of_sea_ice_and_sea_water"                 />
+     <field field_ref="runoffs"      name="sorunoff"   standard_name=""                                                        />
+     <field field_ref="saltflx"      name="sosafldo"   standard_name="salt_flux_into_sea_water"                                />
+     <field field_ref="qt"           name="sohefldo"   standard_name="surface_downward_heat_flux_in_sea_water"                 />
+     <field field_ref="qsr"          name="soshfldo"   standard_name="downwelling_photosynthetic_radiative_flux_in_sea_water"  />
+     <field field_ref="mldkz5" name="somixhgt" standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity" />
+     <field field_ref="mldr10_1"     name="somxl010"   standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"      />
+     <field field_ref="ice_cover"    name="soicecov"   standard_name="sea_ice_area_fraction"                                   />
+     <field field_ref="wspd"         name="sowindsp"   standard_name="wind_speed"                                              />
+     <field field_ref="qrp"          name="sohefldp"   standard_name="heat_flux_into_sea_water_due_to_newtonian_relaxation"    />
+     <field field_ref="erp"          name="sowafldp"   standard_name="water_flux_out_of_sea_water_due_to_newtonian_relaxation" />
+     <field field_ref="qisf"         name="sohflisf"   standard_name=""                                                        />
+     <field field_ref="fwfisf"       name="sowflisf"   standard_name=""                                                        />
+   </field_group>
+
+   <field_group id="SPIN-UP_T" >
+          <field field_ref="e3t"          name="e3t"        standard_name="cell_thickness" />
+          <field field_ref="toce"         name="votemper"        operation="average" freq_op="10d" > @toce_e3t / @e3t </field>
+          <field field_ref="toce"         name="votemper2"       operation="average" freq_op="10d" > @toce2_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"        operation="average" freq_op="10d" > @soce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline2"       operation="average" freq_op="10d" > @soce2_e3t / @e3t </field>
+          <field field_ref="ttrd_totad"   name="opottempadvect"  operation="average" freq_op="10d" > @ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_iso"     name="opottemppmdiff"  operation="average" freq_op="10d" > @ttrd_iso_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_zdfp"    name="opottempdiff"    operation="average" freq_op="10d" > @ttrd_zdfp_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_evd"     name="ttrd_evd"        operation="average" freq_op="10d" > @ttrd_evd_e3t / @e3t </field>
+          <field field_ref="ttrd_qns"     name="ttrd_qns"        operation="average" freq_op="10d" > @ttrd_qns_e3t / @e3t_surf </field>
+          <field field_ref="ttrd_qsr"     name="rsdoabsorb"      operation="average" freq_op="10d" > @ttrd_qsr_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_bbl"     name="ttrd_bbl"        operation="average" freq_op="10d" > @ttrd_bbl_e3t / @e3t </field>
+          <field field_ref="ttrd_tot"     name="opottemptend"    operation="average" freq_op="10d" > @ttrd_tot_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="strd_totad"   name="osaltadvect"     operation="average" freq_op="10d" > @strd_totad_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_iso"     name="osaltpmdiff"     operation="average" freq_op="10d" > @strd_iso_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_zdfp"    name="osaltdiff"       operation="average" freq_op="10d" > @strd_zdfp_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_evd"     name="strd_evd"        operation="average" freq_op="10d" > @strd_evd_e3t / @e3t </field>
+          <field field_ref="strd_tot"     name="osalttend"       operation="average" freq_op="10d" > @strd_tot_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_bbl"     name="strd_bbl"        operation="average" freq_op="10d" > @strd_bbl_e3t / @e3t </field>
+          <field field_ref="ssh"          name="sossheig"   standard_name="sea_surface_height_above_geoid"                          />
+          <field field_ref="ssh2"         name="zossq"      standard_name="square_of_sea_surface_height_above_geoid"                />
+          <field field_ref="empmr"        name="sowaflup"   standard_name="water_flux_out_of_sea_ice_and_sea_water"                 />
+          <field field_ref="saltflx"      name="sosafldo"   standard_name="salt_flux_into_sea_water"                                />
+          <field field_ref="qt"           name="sohefldo"   standard_name="surface_downward_heat_flux_in_sea_water"                 />
+          <field field_ref="qsr"          name="soshfldo"   standard_name="downwelling_photosynthetic_radiative_flux_in_sea_water"               />
+          <field field_ref="mldkz5"       name="somixhgt"   standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity"   />
+          <field field_ref="mldr10_1"     name="somxl010"   standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"      />
+          <field field_ref="mldzint_1"    name="sokaraml"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="mldzint_2"    name="somlddbm"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="ice_cover"    name="soicecov"   standard_name="sea_ice_area_fraction"                                   />
+          <field field_ref="wspd"         name="sowindsp"   standard_name="wind_speed"                                              />
+          <field field_ref="qhcisf"       name="sohflisf"   standard_name="ice_shelf_heat_flux"                                                        />
+          <field field_ref="qlatisf"      name="soqlatisf"  standard_name="ice_shelf_latent_heat_flux"                                                        />
+          <field field_ref="fwfisf"       name="sowflisf"   standard_name="ice_shelf_melting"                                                        />
+          <field field_ref="berg_total_melt"       name="berg_total_melt"          standard_name=""                                 />
+          <field field_ref="berg_total_heat_flux"  name="berg_total_heat_flux"     standard_name=""                                 />
+          <field field_ref="runoffs"       name="sorunoff"    standard_name="water_flux_into_sea_water_from_rivers"                 />
+          <field field_ref="hflx_rain_cea" name="hfrainds"    standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"/>
+          <field field_ref="hflx_evap_cea" name="hfevapds"    standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"/>
+          <field field_ref="evap_ao_cea"   name="evap_ao_cea" standard_name="water_evaporation_flux"                                />
+          <field field_ref="rain"          name="pr"          standard_name="rainfall_flux"                                         />
+          <field field_ref="snowpre"       name="snowpre"     standard_name="snowfall_flux"                                         />
+          <field field_ref="snow_ao_cea"   name="snow_ao_cea" standard_name="snowfall_flux_over_ocean"                              />
+          <field field_ref="snow_ai_cea"   name="snow_ai_cea" standard_name="snowfall_flux_over_sea_ice"                            />
+
+   </field_group>
+
+   <field_group id="groupU1" >
+     <field field_ref="ssu"          name="sozocrtx"   standard_name="sea_surface_eastward_sea_water_velocity"                 />
+     <field field_ref="utau"         name="sozotaux"   standard_name="surface_downward_x_stress" />
+   </field_group>
+
+   <field_group id="groupU2" >
+     <field field_ref="uoce"         name="vozocrtx"     operation="instant" freq_op="1d" > @uoce_e3u / @e3u </field>
+     <field field_ref="utau"         name="sozotaux"   standard_name="surface_downward_x_stress" />
+   </field_group>
+
+   <field_group id="SPIN-UP_U" >
+          <field field_ref="e3u"          name="e3u"        standard_name="cell_thickness" />
+          <field field_ref="uoce"         name="vozocrtx"     operation="average" freq_op="10d" > @uoce_e3u / @e3u </field>
+          <field field_ref="uoce"         name="vozocrtx2"    operation="average" freq_op="10d" > @uoce2_e3u / @e3u </field>
+          <field field_ref="ut"           name="ut"           operation="average" freq_op="10d" > @ut_e3u / @e3u </field>
+          <field field_ref="us"           name="us"           operation="average" freq_op="10d" > @us_e3u / @e3u </field>
+   </field_group>
+
+   <field_group id="groupV1" >
+     <field field_ref="ssv"          name="somecrty"   standard_name="sea_surface_northward_sea_water_velocity"                 />
+     <field field_ref="vtau"         name="sometauy"   standard_name="surface_downward_y_stress" />
+   </field_group>
+
+   <field_group id="groupV2" >
+     <field field_ref="voce"         name="vomecrty"     operation="instant" freq_op="1d" > @voce_e3v / @e3v </field>
+     <field field_ref="vtau"         name="sometauy"   standard_name="surface_downward_y_stress" />   
+   </field_group>
+
+   <field_group id="SPIN-UP_V" >
+          <field field_ref="e3v"          name="e3v"        standard_name="cell_thickness" />
+          <field field_ref="voce"         name="vomecrty"     operation="average" freq_op="10d" > @voce_e3v / @e3v </field>
+          <field field_ref="voce"         name="vomecrty2"    operation="average" freq_op="10d" > @voce2_e3v / @e3v </field>
+          <field field_ref="vt"           name="vt"           operation="average" freq_op="10d" > @vt_e3v / @e3v </field>
+          <field field_ref="vs"           name="vs"           operation="average" freq_op="10d" > @vs_e3v / @e3v </field>
+          <field field_ref="vtau"         name="sometauy"   standard_name="surface_downward_y_stress" />
+   </field_group>
+
+   <field_group id="groupW2" >
+     <field field_ref="woce"         name="vovecrtz"   standard_name="upward_sea_water_velocity"                         />
+     <field field_ref="avt"          name="votkeavt"   standard_name="ocean_vertical_heat_diffusivity"                   />
+     <field field_ref="avm"          name="votkeavm"   standard_name="ocean_vertical_momentum_diffusivity"               />
+     <field field_ref="aht2d"        name="soleahtw"   standard_name="vertical_component_of_ocean_xy_tracer_diffusivity" />
+   </field_group>
+
+   <field_group id="SPIN-UP_W" >
+          <field field_ref="woce"         name="vovecrtz"   standard_name="upward_sea_water_velocity"                         />
+          <field field_ref="wt"           name="wt"         standard_name=""                                                  />
+          <field field_ref="ws"           name="ws"         standard_name=""                                                  />
+          <field field_ref="avt"          name="votkeavt"   standard_name="ocean_vertical_heat_diffusivity"                   />
+          <field field_ref="avm"          name="votkeavm"   standard_name="ocean_vertical_momentum_diffusivity"               />
+          <field field_ref="aht2d"        name="soleahtw"   standard_name="vertical_component_of_ocean_xy_tracer_diffusivity" />
+   </field_group>
+
+   <field_group id="SPIN-UP_diaptr" >
+          <field field_ref="zomsfglo"     name="zomsfglo"   standard_name="meridional_streamfunction_global"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemglo"     name="zotemglo"   standard_name="zonal_mean_temperature_global"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfglo"     name="zosrfglo"   standard_name="zonal_mean_surface_global"                  grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalglo"     name="zosalglo"   standard_name="zonal_mean_salinity_global"                 grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfatl"     name="zomsfatl"   standard_name="meridional_streamfunction_atlantic"         grid_ref="gznl_W_3D"       />
+          <field field_ref="zotematl"     name="zotematl"   standard_name="zonal_mean_temperature_atlantic"            grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfatl"     name="zosrfatl"   standard_name="zonal_mean_surface_atlantic"                grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalatl"     name="zosalatl"   standard_name="zonal_mean_salinity_atlantic"               grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfpac"     name="zomsfpac"   standard_name="meridional_streamfunction_pacific"          grid_ref="gznl_W_3D"       />
+          <field field_ref="zotempac"     name="zotempac"   standard_name="zonal_mean_temperature_pacific"             grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfpac"     name="zosrfpac"   standard_name="zonal_mean_surface_pacific"                 grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalpac"     name="zosalpac"   standard_name="zonal_mean_salinity_pacific"                grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfind"     name="zomsfind"   standard_name="meridional_streamfunction_indian"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemind"     name="zotemind"   standard_name="zonal_mean_temperature_indian"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfind"     name="zosrfind"   standard_name="zonal_mean_surface_indian"                  grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalind"     name="zosalind"   standard_name="zonal_mean_salinity_indian"                 grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfipc"     name="zomsfipc"   standard_name="meridional_streamfunction_indian_pacific"   grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemipc"     name="zotemipc"   standard_name="zonal_mean_temperature_indian_pacific"      grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfipc"     name="zosrfipc"   standard_name="zonal_mean_surface_indian_pacific"          grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalipc"     name="zosalipc"   standard_name="zonal_mean_salinity_indian_pacific"         grid_ref="gznl_T_3D"       />
+          <field field_ref="sophtadv"     name="sophtadv"   standard_name="advective_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv"     name="sopstadv"   standard_name="advective_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf"     name="sophtldf"   standard_name="diffusive_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf"     name="sopstldf"   standard_name="diffusive_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_atl" name="sophtadv_atl"   standard_name="advective_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_atl" name="sopstadv_atl"   standard_name="advective_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_atl" name="sophtldf_atl"   standard_name="diffusive_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_atl" name="sopstldf_atl"   standard_name="diffusive_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_pac" name="sophtadv_pac"   standard_name="advective_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_pac" name="sopstadv_pac"   standard_name="advective_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_pac" name="sophtldf_pac"   standard_name="diffusive_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_pac" name="sopstldf_pac"   standard_name="diffusive_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ind" name="sophtadv_ind"   standard_name="advective_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ind" name="sopstadv_ind"   standard_name="advective_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ind" name="sophtldf_ind"   standard_name="diffusive_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ind" name="sopstldf_ind"   standard_name="diffusive_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ipc" name="sophtadv_ipc"   standard_name="advective_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ipc" name="sopstadv_ipc"   standard_name="advective_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ipc" name="sophtldf_ipc"   standard_name="diffusive_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ipc" name="sopstldf_ipc"   standard_name="diffusive_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+   </field_group>
+
+  </field_definition>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/iodef_medusa_et_al.xml
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/iodef_medusa_et_al.xml	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/iodef_medusa_et_al.xml	(revision 9987)
@@ -0,0 +1,452 @@
+<!-- GO6.0 version of the XIOS namelist -->
+<!-- XIOS version 2 -->
+<?xml version="1.0"?>
+
+<simulation> 
+
+ <context id="nemo">
+    
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+    <field_definition src="./field_def_bgc.xml"/>
+    <field_definition src="./field_def.xml"/>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->
+     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+
+      <file_group id="10d" output_freq="10d" output_level="10" enabled=".TRUE."> <!-- 10d files -->
+
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"          name="e3t"        standard_name="cell_thickness" />
+          <field field_ref="toce"         name="votemper"        operation="average" freq_op="1mo" > @toce_e3t / @e3t </field>
+          <field field_ref="toce"         name="votemper2"       operation="average" freq_op="1mo" > @toce2_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"        operation="average" freq_op="1mo" > @soce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline2"       operation="average" freq_op="1mo" > @soce2_e3t / @e3t </field>
+          <field field_ref="ttrd_totad"   name="opottempadvect"  operation="average" freq_op="1mo" > @ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_iso"     name="opottemppmdiff"  operation="average" freq_op="1mo" > @ttrd_iso_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_zdfp"    name="opottempdiff"    operation="average" freq_op="1mo" > @ttrd_zdfp_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_evd"     name="ttrd_evd"        operation="average" freq_op="1mo" > @ttrd_evd_e3t / @e3t </field>
+          <field field_ref="ttrd_qns"     name="ttrd_qns"        operation="average" freq_op="1mo" > @ttrd_qns_e3t / @e3t_surf </field>
+          <field field_ref="ttrd_qsr"     name="rsdoabsorb"      operation="average" freq_op="1mo" > @ttrd_qsr_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_bbl"     name="ttrd_bbl"        operation="average" freq_op="1mo" > @ttrd_bbl_e3t / @e3t </field>
+          <field field_ref="ttrd_tot"     name="opottemptend"    operation="average" freq_op="1mo" > @ttrd_tot_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="strd_totad"   name="osaltadvect"     operation="average" freq_op="1mo" > @strd_totad_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_iso"     name="osaltpmdiff"     operation="average" freq_op="1mo" > @strd_iso_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_zdfp"    name="osaltdiff"       operation="average" freq_op="1mo" > @strd_zdfp_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_evd"     name="strd_evd"        operation="average" freq_op="1mo" > @strd_evd_e3t / @e3t </field>
+          <field field_ref="strd_tot"     name="osalttend"       operation="average" freq_op="1mo" > @strd_tot_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_bbl"     name="strd_bbl"        operation="average" freq_op="1mo" > @strd_bbl_e3t / @e3t </field>
+	  <field field_ref="ssh"          name="sossheig"   standard_name="sea_surface_height_above_geoid"                          />
+          <field field_ref="ssh2"         name="zossq"      standard_name="square_of_sea_surface_height_above_geoid"                />
+	  <field field_ref="empmr"        name="sowaflup"   standard_name="water_flux_out_of_sea_ice_and_sea_water"                 />
+	  <field field_ref="saltflx"      name="sosafldo"   standard_name="salt_flux_into_sea_water"                                />
+	  <field field_ref="qt"           name="sohefldo"   standard_name="surface_downward_heat_flux_in_sea_water"                 />
+	  <field field_ref="qsr"          name="soshfldo"   standard_name="downwelling_photosynthetic_radiative_flux_in_sea_water"               />
+          <field field_ref="mldkz5"       name="somixhgt"   standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity"   />
+          <field field_ref="mldr10_1"     name="somxl010"   standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"      />
+          <field field_ref="mldzint_1"    name="sokaraml"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="mldzint_2"    name="somlddbm"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="ice_cover"    name="soicecov"   standard_name="sea_ice_area_fraction"                                   />
+          <field field_ref="wspd"         name="sowindsp"   standard_name="wind_speed"                                              />          
+          <field field_ref="qhcisf"       name="sohflisf"   standard_name="ice_shelf_heat_flux"                                                        />
+          <field field_ref="qlatisf"      name="soqlatisf"  standard_name="ice_shelf_latent_heat_flux"                                                        />
+          <field field_ref="fwfisf"       name="sowflisf"   standard_name="ice_shelf_melting"                                                        />
+          <field field_ref="berg_total_melt"       name="berg_total_melt"          standard_name=""                                 />
+          <field field_ref="berg_total_heat_flux"  name="berg_total_heat_flux"     standard_name=""                                 />
+          <field field_ref="runoffs"       name="sorunoff"    standard_name="water_flux_into_sea_water_from_rivers"                 />
+          <field field_ref="hflx_rain_cea" name="hfrainds"    standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"/>
+          <field field_ref="hflx_evap_cea" name="hfevapds"    standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"/>
+          <field field_ref="evap_ao_cea"   name="evap_ao_cea" standard_name="water_evaporation_flux"                                />
+          <field field_ref="rain"          name="pr"          standard_name="rainfall_flux"                                         />
+          <field field_ref="snowpre"       name="snowpre"     standard_name="snowfall_flux"                                         />
+          <field field_ref="snow_ao_cea"   name="snow_ao_cea" standard_name="snowfall_flux_over_ocean"                              />
+          <field field_ref="snow_ai_cea"   name="snow_ai_cea" standard_name="snowfall_flux_over_sea_ice"                            />
+	</file>
+	
+	<file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="e3u"          name="e3u"        standard_name="cell_thickness" />
+          <field field_ref="uoce"         name="vozocrtx"     operation="average" freq_op="1mo" > @uoce_e3u / @e3u </field>
+          <field field_ref="uoce"         name="vozocrtx2"    operation="average" freq_op="1mo" > @uoce2_e3u / @e3u </field>
+          <field field_ref="ut"           name="ut"           operation="average" freq_op="1mo" > @ut_e3u / @e3u </field>
+          <field field_ref="us"           name="us"           operation="average" freq_op="1mo" > @us_e3u / @e3u </field>
+	  <field field_ref="utau"         name="sozotaux"   standard_name="surface_downward_x_stress" />
+	</file>
+	
+	<file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="e3v"          name="e3v"        standard_name="cell_thickness" />
+          <field field_ref="voce"         name="vomecrty"     operation="average" freq_op="1mo" > @voce_e3v / @e3v </field>
+          <field field_ref="voce"         name="vomecrty2"    operation="average" freq_op="1mo" > @voce2_e3v / @e3v </field>
+          <field field_ref="vt"           name="vt"           operation="average" freq_op="1mo" > @vt_e3v / @e3v </field>
+          <field field_ref="vs"           name="vs"           operation="average" freq_op="1mo" > @vs_e3v / @e3v </field>
+	  <field field_ref="vtau"         name="sometauy"   standard_name="surface_downward_y_stress" />
+	</file>
+	
+	<file id="file4" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="woce"         name="vovecrtz"   standard_name="upward_sea_water_velocity"                         />
+          <field field_ref="wt"           name="wt"         standard_name=""                                                  />
+          <field field_ref="ws"           name="ws"         standard_name=""                                                  />
+	  <field field_ref="avt"          name="votkeavt"   standard_name="ocean_vertical_heat_diffusivity"                   />
+          <field field_ref="avm"          name="votkeavm"   standard_name="ocean_vertical_momentum_diffusivity"               />
+          <field field_ref="aht2d"        name="soleahtw"   standard_name="vertical_component_of_ocean_xy_tracer_diffusivity" />
+	</file>
+        
+        <file id="file5" name_suffix="_diaptr" description="processed diagnostics" >
+	  <field field_ref="zomsfglo"     name="zomsfglo"   standard_name="meridional_streamfunction_global"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemglo"     name="zotemglo"   standard_name="zonal_mean_temperature_global"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfglo"     name="zosrfglo"   standard_name="zonal_mean_surface_global"                  grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalglo"     name="zosalglo"   standard_name="zonal_mean_salinity_global"                 grid_ref="gznl_T_3D"       />          
+          <field field_ref="zomsfatl"     name="zomsfatl"   standard_name="meridional_streamfunction_atlantic"         grid_ref="gznl_W_3D"       />
+          <field field_ref="zotematl"     name="zotematl"   standard_name="zonal_mean_temperature_atlantic"            grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfatl"     name="zosrfatl"   standard_name="zonal_mean_surface_atlantic"                grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalatl"     name="zosalatl"   standard_name="zonal_mean_salinity_atlantic"               grid_ref="gznl_T_3D"       />          
+          <field field_ref="zomsfpac"     name="zomsfpac"   standard_name="meridional_streamfunction_pacific"          grid_ref="gznl_W_3D"       />
+          <field field_ref="zotempac"     name="zotempac"   standard_name="zonal_mean_temperature_pacific"             grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfpac"     name="zosrfpac"   standard_name="zonal_mean_surface_pacific"                 grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalpac"     name="zosalpac"   standard_name="zonal_mean_salinity_pacific"                grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfind"     name="zomsfind"   standard_name="meridional_streamfunction_indian"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemind"     name="zotemind"   standard_name="zonal_mean_temperature_indian"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfind"     name="zosrfind"   standard_name="zonal_mean_surface_indian"                  grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalind"     name="zosalind"   standard_name="zonal_mean_salinity_indian"                 grid_ref="gznl_T_3D"       />          
+          <field field_ref="zomsfipc"     name="zomsfipc"   standard_name="meridional_streamfunction_indian_pacific"   grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemipc"     name="zotemipc"   standard_name="zonal_mean_temperature_indian_pacific"      grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfipc"     name="zosrfipc"   standard_name="zonal_mean_surface_indian_pacific"          grid_ref="gznl_T_3D"       />
+	  <field field_ref="zosalipc"     name="zosalipc"   standard_name="zonal_mean_salinity_indian_pacific"         grid_ref="gznl_T_3D"       />          
+          <field field_ref="sophtadv"     name="sophtadv"   standard_name="advective_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv"     name="sopstadv"   standard_name="advective_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf"     name="sophtldf"   standard_name="diffusive_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf"     name="sopstldf"   standard_name="diffusive_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_atl" name="sophtadv_atl"   standard_name="advective_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_atl" name="sopstadv_atl"   standard_name="advective_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_atl" name="sophtldf_atl"   standard_name="diffusive_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_atl" name="sopstldf_atl"   standard_name="diffusive_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_pac" name="sophtadv_pac"   standard_name="advective_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_pac" name="sopstadv_pac"   standard_name="advective_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_pac" name="sophtldf_pac"   standard_name="diffusive_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_pac" name="sopstldf_pac"   standard_name="diffusive_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ind" name="sophtadv_ind"   standard_name="advective_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ind" name="sopstadv_ind"   standard_name="advective_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ind" name="sophtldf_ind"   standard_name="diffusive_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ind" name="sopstldf_ind"   standard_name="diffusive_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ipc" name="sophtadv_ipc"   standard_name="advective_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ipc" name="sopstadv_ipc"   standard_name="advective_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ipc" name="sophtldf_ipc"   standard_name="diffusive_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ipc" name="sopstldf_ipc"   standard_name="diffusive_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+	</file>
+
+        <file id="file6" name_suffix="_ptrc_T" description="Medusa sms variables" >
+          <field_group group_ref="groupMEDUSA" />
+          <field_group group_ref="groupIDTRA" />
+          <field_group group_ref="groupCFC" />
+          <field_group group_ref="groupAGE" />
+        </file>
+
+        <file id="file7" name_suffix="_diad_T" description="Medusa diagnostic variables" >
+          <field_group group_ref="groupMEDUSA_dia" /> 
+          <field_group group_ref="groupMEDUSA_3dd" /> 
+          <field_group group_ref="groupMEDUSA_dms" />
+          <field_group group_ref="groupIDTRA_dia" />
+          <field_group group_ref="groupCFC_dia" />
+          <field_group group_ref="groupMEDUSA_cmip6" />
+        </file>
+       
+      </file_group>
+      
+  
+      <file_group id="1m" output_freq="1mo" split_freq="1mo" output_level="10" enabled=".FALSE."> <!-- 1mo files -->   
+      <!-- <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE.">  - 1mo files -->   
+
+        <file id="file9" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"          name="e3t"        standard_name="cell_thickness" />
+          <field field_ref="toce"         name="votemper"        operation="average" freq_op="1mo" > @toce_e3t / @e3t </field>
+          <field field_ref="toce"         name="votemper2"       operation="average" freq_op="1mo" > @toce2_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"        operation="average" freq_op="1mo" > @soce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline2"       operation="average" freq_op="1mo" > @soce2_e3t / @e3t </field>
+          <field field_ref="ttrd_totad"   name="opottempadvect"  operation="average" freq_op="1mo" > @ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_iso"     name="opottemppmdiff"  operation="average" freq_op="1mo" > @ttrd_iso_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_zdfp"    name="opottempdiff"    operation="average" freq_op="1mo" > @ttrd_zdfp_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_evd"     name="ttrd_evd"        operation="average" freq_op="1mo" > @ttrd_evd_e3t / @e3t </field>
+          <field field_ref="ttrd_qns"     name="ttrd_qns"        operation="average" freq_op="1mo" > @ttrd_qns_e3t / @e3t_surf </field>
+          <field field_ref="ttrd_qsr"     name="rsdoabsorb"      operation="average" freq_op="1mo" > @ttrd_qsr_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="ttrd_bbl"     name="ttrd_bbl"        operation="average" freq_op="1mo" > @ttrd_bbl_e3t / @e3t </field>
+          <field field_ref="ttrd_tot"     name="opottemptend"    operation="average" freq_op="1mo" > @ttrd_tot_e3t * 1026.0 * 3991.86795711963 </field>
+          <field field_ref="strd_totad"   name="osaltadvect"     operation="average" freq_op="1mo" > @strd_totad_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_iso"     name="osaltpmdiff"     operation="average" freq_op="1mo" > @strd_iso_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_zdfp"    name="osaltdiff"       operation="average" freq_op="1mo" > @strd_zdfp_e3t * 1026.0 * 0.001  </field>
+          <field field_ref="strd_evd"     name="strd_evd"        operation="average" freq_op="1mo" > @strd_evd_e3t / @e3t </field>
+          <field field_ref="strd_tot"     name="osalttend"       operation="average" freq_op="1mo" > @strd_tot_e3t * 1026.0 * 0.001 </field>
+          <field field_ref="strd_bbl"     name="strd_bbl"        operation="average" freq_op="1mo" > @strd_bbl_e3t / @e3t </field>
+          <field field_ref="ssh"          name="sossheig"   standard_name="sea_surface_height_above_geoid"                          />
+          <field field_ref="ssh2"         name="zossq"      standard_name="square_of_sea_surface_height_above_geoid"                />
+          <field field_ref="empmr"        name="sowaflup"   standard_name="water_flux_out_of_sea_ice_and_sea_water"                 />
+          <field field_ref="saltflx"      name="sosafldo"   standard_name="salt_flux_into_sea_water"                                />
+          <field field_ref="qt"           name="sohefldo"   standard_name="surface_downward_heat_flux_in_sea_water"                 />
+          <field field_ref="qsr"          name="soshfldo"   standard_name="downwelling_photosynthetic_radiative_flux_in_sea_water"               />
+          <field field_ref="mldkz5"       name="somixhgt"   standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity"   />
+          <field field_ref="mldr10_1"     name="somxl010"   standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"      />
+          <field field_ref="mldzint_1"    name="sokaraml"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="mldzint_2"    name="somlddbm"   standard_name="ocean_mixed_layer_thickness"                             />
+          <field field_ref="ice_cover"    name="soicecov"   standard_name="sea_ice_area_fraction"                                   />
+          <field field_ref="wspd"         name="sowindsp"   standard_name="wind_speed"                                              />
+          <field field_ref="qhcisf"       name="sohflisf"   standard_name="ice_shelf_heat_flux"                                                        />
+          <field field_ref="qlatisf"      name="soqlatisf"  standard_name="ice_shelf_latent_heat_flux"                                                        />
+          <field field_ref="fwfisf"       name="sowflisf"   standard_name="ice_shelf_melting"                                                        />
+          <field field_ref="berg_total_melt"       name="berg_total_melt"          standard_name=""                                 />
+          <field field_ref="berg_total_heat_flux"  name="berg_total_heat_flux"     standard_name=""                                 />
+          <field field_ref="runoffs"       name="sorunoff"    standard_name="water_flux_into_sea_water_from_rivers"                 />
+          <field field_ref="hflx_rain_cea" name="hfrainds"    standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"/>
+          <field field_ref="hflx_evap_cea" name="hfevapds"    standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"/>
+          <field field_ref="evap_ao_cea"   name="evap_ao_cea" standard_name="water_evaporation_flux"                                />
+          <field field_ref="rain"          name="pr"          standard_name="rainfall_flux"                                         />
+          <field field_ref="snowpre"       name="snowpre"     standard_name="snowfall_flux"                                         />
+          <field field_ref="snow_ao_cea"   name="snow_ao_cea" standard_name="snowfall_flux_over_ocean"                              />
+          <field field_ref="snow_ai_cea"   name="snow_ai_cea" standard_name="snowfall_flux_over_sea_ice"                            />
+        </file>
+
+	<file id="file10" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="e3u"          name="e3u"        standard_name="cell_thickness" />
+          <field field_ref="uoce"         name="vozocrtx"     operation="average" freq_op="1mo" > @uoce_e3u / @e3u </field>
+          <field field_ref="uoce"         name="vozocrtx2"    operation="average" freq_op="1mo" > @uoce2_e3u / @e3u </field>
+          <field field_ref="ut"           name="ut"           operation="average" freq_op="1mo" > @ut_e3u / @e3u </field>
+          <field field_ref="us"           name="us"           operation="average" freq_op="1mo" > @us_e3u / @e3u </field>
+          <field field_ref="utau"         name="sozotaux"   standard_name="surface_downward_x_stress" />
+        </file>
+
+	<file id="file11" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="e3v"          name="e3v"        standard_name="cell_thickness" />
+          <field field_ref="voce"         name="vomecrty"     operation="average" freq_op="1mo" > @voce_e3v / @e3v </field>
+          <field field_ref="voce"         name="vomecrty2"    operation="average" freq_op="1mo" > @voce2_e3v / @e3v </field>
+          <field field_ref="vt"           name="vt"           operation="average" freq_op="1mo" > @vt_e3v / @e3v </field>
+          <field field_ref="vs"           name="vs"           operation="average" freq_op="1mo" > @vs_e3v / @e3v </field>
+          <field field_ref="vtau"         name="sometauy"   standard_name="surface_downward_y_stress" />
+        </file>
+
+	<file id="file12" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="woce"         name="vovecrtz"   standard_name="upward_sea_water_velocity"                         />
+          <field field_ref="wt"           name="wt"         standard_name=""                                                  />
+          <field field_ref="ws"           name="ws"         standard_name=""                                                  />
+          <field field_ref="avt"          name="votkeavt"   standard_name="ocean_vertical_heat_diffusivity"                   />
+          <field field_ref="avm"          name="votkeavm"   standard_name="ocean_vertical_momentum_diffusivity"               />
+          <field field_ref="aht2d"        name="soleahtw"   standard_name="vertical_component_of_ocean_xy_tracer_diffusivity" />
+        </file>
+
+	<file id="file13" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="zomsfglo"     name="zomsfglo"   standard_name="meridional_streamfunction_global"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemglo"     name="zotemglo"   standard_name="zonal_mean_temperature_global"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfglo"     name="zosrfglo"   standard_name="zonal_mean_surface_global"                  grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalglo"     name="zosalglo"   standard_name="zonal_mean_salinity_global"                 grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfatl"     name="zomsfatl"   standard_name="meridional_streamfunction_atlantic"         grid_ref="gznl_W_3D"       />
+          <field field_ref="zotematl"     name="zotematl"   standard_name="zonal_mean_temperature_atlantic"            grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfatl"     name="zosrfatl"   standard_name="zonal_mean_surface_atlantic"                grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalatl"     name="zosalatl"   standard_name="zonal_mean_salinity_atlantic"               grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfpac"     name="zomsfpac"   standard_name="meridional_streamfunction_pacific"          grid_ref="gznl_W_3D"       />
+          <field field_ref="zotempac"     name="zotempac"   standard_name="zonal_mean_temperature_pacific"             grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfpac"     name="zosrfpac"   standard_name="zonal_mean_surface_pacific"                 grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalpac"     name="zosalpac"   standard_name="zonal_mean_salinity_pacific"                grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfind"     name="zomsfind"   standard_name="meridional_streamfunction_indian"           grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemind"     name="zotemind"   standard_name="zonal_mean_temperature_indian"              grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfind"     name="zosrfind"   standard_name="zonal_mean_surface_indian"                  grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalind"     name="zosalind"   standard_name="zonal_mean_salinity_indian"                 grid_ref="gznl_T_3D"       />
+          <field field_ref="zomsfipc"     name="zomsfipc"   standard_name="meridional_streamfunction_indian_pacific"   grid_ref="gznl_W_3D"       />
+          <field field_ref="zotemipc"     name="zotemipc"   standard_name="zonal_mean_temperature_indian_pacific"      grid_ref="gznl_T_3D"       />
+          <field field_ref="zosrfipc"     name="zosrfipc"   standard_name="zonal_mean_surface_indian_pacific"          grid_ref="gznl_T_3D"       />
+          <field field_ref="zosalipc"     name="zosalipc"   standard_name="zonal_mean_salinity_indian_pacific"         grid_ref="gznl_T_3D"       />
+          <field field_ref="sophtadv"     name="sophtadv"   standard_name="advective_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv"     name="sopstadv"   standard_name="advective_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf"     name="sophtldf"   standard_name="diffusive_heat_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf"     name="sopstldf"   standard_name="diffusive_salt_transport"                   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_atl" name="sophtadv_atl"   standard_name="advective_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_atl" name="sopstadv_atl"   standard_name="advective_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_atl" name="sophtldf_atl"   standard_name="diffusive_heat_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_atl" name="sopstldf_atl"   standard_name="diffusive_salt_transport_atlantic"      grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_pac" name="sophtadv_pac"   standard_name="advective_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_pac" name="sopstadv_pac"   standard_name="advective_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_pac" name="sophtldf_pac"   standard_name="diffusive_heat_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_pac" name="sopstldf_pac"   standard_name="diffusive_salt_transport_pacific"       grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ind" name="sophtadv_ind"   standard_name="advective_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ind" name="sopstadv_ind"   standard_name="advective_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ind" name="sophtldf_ind"   standard_name="diffusive_heat_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ind" name="sopstldf_ind"   standard_name="diffusive_salt_transport_indian"        grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtadv_ipc" name="sophtadv_ipc"   standard_name="advective_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstadv_ipc" name="sopstadv_ipc"   standard_name="advective_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sophtldf_ipc" name="sophtldf_ipc"   standard_name="diffusive_heat_transport_indopacific"   grid_ref="gznl_T_2D"       />
+          <field field_ref="sopstldf_ipc" name="sopstldf_ipc"   standard_name="diffusive_salt_transport_indopacific"   grid_ref="gznl_T_2D"       />
+        </file>
+
+        <file id="file14" name_suffix="_ptrc_T" description="Medusa sms variables" >
+          <field_group group_ref="groupMEDUSA" />
+          <field_group group_ref="groupIDTRA" />
+          <field_group group_ref="groupCFC" />
+          <field_group group_ref="groupAGE" />
+        </file>
+
+        <file id="file15" name_suffix="_diad_T" description="Medusa diagnostic variables" >
+          <field_group group_ref="groupMEDUSA_dia" /> 
+          <field_group group_ref="groupMEDUSA_3dd" /> 
+          <field_group group_ref="groupMEDUSA_dms" />
+          <field_group group_ref="groupIDTRA_dia" />
+          <field_group group_ref="groupCFC_dia" />
+          <field_group group_ref="groupMEDUSA_cmip6" />
+        </file>
+
+      </file_group>
+
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
+    <!-- 
+============================================================================================================
+= grid definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+    
+   <axis_definition>
+      <axis id="deptht" standard_name="depth" long_name="Vertical T levels" unit="m" positive="down" />
+      <axis id="depthu" standard_name="depth" long_name="Vertical U levels" unit="m" positive="down" />
+      <axis id="depthv" standard_name="depth" long_name="Vertical V levels" unit="m" positive="down" />
+      <axis id="depthw" standard_name="depth" long_name="Vertical W levels" unit="m" positive="down" />
+      <axis id="nfloat" long_name="Float number"      unit="-"  />
+      <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
+      <axis id="ncatice" long_name="Ice category"       unit="1"               />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"            />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"            />
+      <axis id="deptht_surface" axis_ref="deptht" >
+         <zoom_axis begin=" 1 " n=" 1 " />
+      </axis>
+
+   </axis_definition>
+    
+   <domain_definition src="./domain_def.xml"/>
+   
+    <grid_definition>
+        <!--  -->
+       <grid id="grid_T_2D" >
+         <domain id="grid_T" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_3D_ncatice" >
+         <domain id="grid_T" />
+         <axis id="ncatice" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_3D" >
+         <domain id="grid_T" />
+         <axis id="deptht" />
+       </grid>
+        <!--  -->
+       <grid id="grid_U_2D" >
+         <domain id="grid_U" />
+       </grid>
+        <!--  -->
+       <grid id="grid_U_3D" >
+         <domain id="grid_U" />
+         <axis id="depthu" />
+       </grid>
+        <!--  -->
+       <grid id="grid_V_2D" >
+         <domain id="grid_V" />
+       </grid>
+        <!--  -->
+       <grid id="grid_V_3D" >
+         <domain id="grid_V" />
+         <axis id="depthv" />
+       </grid>
+        <!--  -->
+       <grid id="grid_W_2D" >
+         <domain id="grid_W" />
+       </grid>
+        <!--  -->
+       <grid id="grid_W_3D" >
+         <domain id="grid_W" />
+         <axis id="depthw" />
+       </grid>
+        <!--  -->
+       <grid id="grid_1point" >
+         <domain id="1point"/>
+       </grid>
+        <!--  -->
+       <grid id="scalar" >
+       <!--A blank grid to represent a 0D scalar variable -->
+       </grid>
+        <!--  -->
+       <grid id="grid_T_nfloat" >
+         <domain id="grid_T" />
+         <axis id="nfloat" />
+       </grid>
+        <!--  -->
+       <grid id="grid_EqT" >
+         <domain id="EqT" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_T_2D">
+         <domain id="ptr" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_T_3D">
+         <domain id="ptr" />
+         <axis id="deptht" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_W_2D">
+         <domain id="ptr" />
+       </grid>
+        <!--  -->
+       <grid id="gznl_W_3D">
+         <domain id="ptr" />
+         <axis id="depthw" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_surface_extract">
+         <domain domain_ref="grid_T" />
+         <axis   axis_ref="deptht_surface" />
+       </grid>
+
+    </grid_definition>
+  </context>
+  
+
+  <context id="xios">
+
+      <variable_definition>
+	
+	  <variable id="info_level"            type="int">0</variable>
+	  <variable id="using_server"          type="bool">false</variable>
+	  <variable id="using_oasis"           type="bool">true</variable>
+	  <variable id="oasis_codes_id"        type="string" >toyoce</variable>
+	
+      </variable_definition>
+               
+  </context>
+  
+</simulation>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_age_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_age_ref	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_age_ref	(revision 9987)
@@ -0,0 +1,9 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! AGE  :       1  - dates                                 (namage)
+!! namelists
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+&namage     !   dates
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+   rn_age_depth       = 10            ! depth over which age tracer reset to zero
+   rn_age_kill_rate   = -0.000138888  !  = -1/7200 recip of relaxation timescale (s) for  age tracer shallower than age_depth
+/
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_cfc_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_cfc_ref	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_cfc_ref	(revision 9987)
@@ -7,5 +7,7 @@
 !,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
    ndate_beg  = 300101    !  datedeb1
-   nyear_res  = 1932      !  iannee1
+   nyear_res  = 1600      !  iannee1
+   simu_type  = 1         ! kind of Simulation: 1 = SPIN-UP (90y-cycle)
+!!                                           !! 2 = Hindcast/proj (100y cycle)
 /
 !'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_cfc_v1_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_cfc_v1_ref	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_cfc_v1_ref	(revision 9987)
@@ -0,0 +1,20 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! CFC  :       1  - dates                                 (namcfcdate)
+!! namelists    
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+&namcfcdate     !   dates
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+   ndate_beg  = 300101    !  datedeb1
+   nyear_res  = 1600      !  iannee1
+   simu_type  = 1         ! kind of Simulation: 1 = SPIN-UP (90y-cycle)
+!!                                           !! 2 = Hindcast/proj (100y cycle)
+/
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+&namcfcdia     !   additional 2D/3D tracers diagnostics 
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!              !    name   !           title of the field          !     units      !
+!              !           !                                       !                !
+   cfcdia2d(1)  = 'qtr_c11 ' , 'Air-sea flux of CFC-11           ',  'mol/m2/s    '
+   cfcdia2d(2)  = 'qint_c11' , 'Cumulative air-sea flux of CFC-11 ', 'mol/m2      '
+/
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_ice_lim3_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_ice_lim3_ref	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_ice_lim3_ref	(revision 9987)
@@ -21,5 +21,6 @@
    cn_icerst_outdir = "."          !  directory in which to write output ice restarts
    ln_limdyn     = .true.          !  ice dynamics (T) or thermodynamics only (F)
-   rn_amax       = 0.999           !  maximum tolerated ice concentration 
+   rn_amax_n     = 0.999           !  maximum tolerated ice concentration NH
+   rn_amax_s     = 0.999           !  maximum tolerated ice concentration SH
    ln_limdiahsb  = .false.         !  check the heat and salt budgets (T) or not (F)
    ln_limdiaout  = .true.          !  output the heat and salt budgets (T) or not (F)
@@ -85,5 +86,5 @@
    rn_hnewice  = 0.1               !  thickness for new ice formation in open water (m)
    ln_frazil   = .false.           !  use frazil ice collection thickness as a function of wind (T) or not (F)
-   rn_maxfrazb = 0.0               !  maximum fraction of frazil ice collecting at the ice base
+   rn_maxfrazb = 1.0               !  maximum fraction of frazil ice collecting at the ice base
    rn_vfrazb   = 0.417             !  thresold drift speed for frazil ice collecting at the ice bottom (m/s)
    rn_Cfrazb   = 5.0               !  squeezing coefficient for frazil ice collecting at the ice bottom
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_idtra_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_idtra_ref	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_idtra_ref	(revision 9987)
@@ -0,0 +1,43 @@
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+! idealize Tracer namelist :  NEMO idealize traceur model option and parameter input
+! -------------
+! 
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+!       namidtra   parameter for 1/2 decay time
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!
+!! idealize tracer 1/2 decay time
+!!       tmp_decay   :  1/2 decay time
+!!
+!! idealize tracer names (to be added if needed)
+!!
+&namidtra
+!
+!! idealize tracer 1/2 decay time
+      tmp_decay = 10        !! years
+!! idealize tracer names
+!!###############################################
+!!   names are defined in the top namelist (namtrc) 
+!!   
+!!###############################################
+/
+!=================================================
+! nammeddia    Passive tracers additional diagnostics
+!=================================================
+!
+!      ctrc2d  : 2d output field name
+!      ctrc2u  : 2d output field unit
+!      ctrc2l  : 2d output field long name
+!
+!      nwriteadd: frequency of additional arrays outputs(namelist)
+!&nammeddia
+!!##########################################################
+!! No aditional diagnostics associated to idealize tracers.
+!! If one want to add additional diag, 
+!! can be done here, following the example just below 
+!!##########################################################
+!            meddia2d(1)  = 'INVTN'             ,              'Column N inventory'                            ,              'mmolN/m2'
+!            meddia2d(2)  = 'INVTSI'            ,              'Column Si inventory'                           ,              'mmolSi/m2'
+!/
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_medusa_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_medusa_ref	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_medusa_ref	(revision 9987)
@@ -0,0 +1,372 @@
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+! BIO namelist :  MEDUSA biological model option and parameter input
+! -------------
+!
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+!       natbio   Shared parameters for dynamics/advection/thermo
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!
+!! Primary production and chl related quantities
+!!       xxi         :  conversion factor from gC to mmolN 
+!!       xaln        :  Chl-a specific initial slope of P-I curve for non-diatoms 
+!!       xald        :  Chl-a specific initial slope of P-I curve for diatoms
+!!       jphy        :  phytoplankton T-dependent growth switch
+!!       xvpn        :  maximum growth rate for non-diatoms
+!!       xvpd        :  maximum growth rate for diatoms
+!!       xthetam     :  maximum Chl to C ratio for non-diatoms      
+!!       xthetamd    :  maximum Chl to C ratio for diatoms
+!!
+!! Diatom silicon parameters
+!!       xsin0       :  minimum diatom Si:N ratio
+!!       xnsi0       :  minimum diatom N:Si ratio
+!!       xuif        :  hypothetical growth ratio at infinite Si:N ratio
+!!
+!! Nutrient limitation
+!!       jliebig     :  Liebig nutrient uptake switch
+!!       xnln        :  half-sat constant for DIN uptake by non-diatoms 
+!!       xnld        :  half-sat constant for DIN uptake by diatoms 
+!!       xsl         :  half-sat constant for Si uptake by diatoms 
+!!       xfld        :  half-sat constant for Fe uptake by diatoms  
+!!       xfln        :  half-sat constant for Fe uptake by non-datoms 
+!!
+!! Grazing
+!!       xgmi        :  microzoo maximum growth rate 
+!!       xgme        :  mesozoo maximum growth rate 
+!!       xkmi        :  microzoo grazing half-sat parameter
+!!       xkme        :  mesozoo grazing half-sat parameter
+!!       xphi        :  micro/mesozoo grazing inefficiency
+!!       xbetan      :  micro/mesozoo N assimilation efficiency
+!!       xbetac      :  micro/mesozoo C assimilation efficiency
+!!       xkc         :  micro/mesozoo net C growth efficiency
+!!       xpmipn      :  grazing preference of microzoo for non-diatoms
+!!       xpmid       :  grazing preference of microzoo for diatoms
+!!       xpmepn      :  grazing preference of mesozoo for non-diatoms 
+!!       xpmepd      :  grazing preference of mesozoo for diatoms
+!!       xpmezmi     :  grazing preference of mesozoo for microzoo
+!!       xpmed       :  grazing preference of mesozoo for detritus
+!!
+!! Metabolic losses
+!!       xmetapn     :  non-diatom metabolic loss rate
+!!       xmetapd     :  diatom     metabolic loss rate
+!!       xmetazmi    :  microzoo   metabolic loss rate
+!!       xmetazme    :  mesozoo    metabolic loss rate
+!!
+!! Mortality losses
+!!       jmpn        :  non-diatom mortality functional form
+!!       xmpn        :  non-diatom mortality rate
+!!       xkphn       :  non-diatom mortality half-sat constant
+!!       jmpd        :  diatom     mortality functional form
+!!       xmpd        :  diatom     mortality rate
+!!       xkphd       :  diatom     mortality half-sat constant
+!!       jmzmi       :  microzoo   mortality functional form
+!!       xmzmi       :  microzoo   mortality rate
+!!       xkzmi       :  microzoo   mortality half-sat constant
+!!       jmzme       :  mesozoo    mortality functional form
+!!       xmzme       :  mesozoo    mortality rate
+!!       xkzme       :  mesozoo    mortality half-sat constant
+!!
+!! Remineralisation
+!!       jmd         :  detritus T-dependent remineralisation switch
+!!       jsfd        :  accelerate seafloor detritus remin. switch
+!!       xmd         :  detrital nitrogen remineralisation rate 
+!!       xmdc        :  detrital carbon   remineralisation rate 
+!!
+!! Stochiometric ratios
+!!       xthetapn    :  non-diatom C:N ratio
+!!       xthetapd    :  diatom C:N ratio
+!!       xthetazmi   :  microzoo C:N ratio
+!!       xthetazme   :  mesozoo C:N ratio
+!!       xthetad     :  detritus C:N ratio (FOR IMPLICIT DTC ONLY)
+!!       xrfn        :  phytoplankton Fe:N ratio
+!!	 xrsn        :  phytoplankton Si:N ratio (LEGACY; NOT USED)
+!!
+!! Iron parameters
+!!       jiron       :  iron scavenging submodel switch
+!!       xfe_mass    :  iron atomic mass
+!!	 xfe_sol     :  aeolian iron solubility
+!!	 xfe_sed     :  sediment iron input
+!!	 xLgT	     :  total ligand concentration (umol/m3)
+!!	 xk_FeL	     :  dissociation constant for (Fe + L)
+!!	 xk_sc_Fe    :  scavenging rate of "free" iron
+!!	 
+!! Fast-sinking detritus parameters
+!!       jmartin     :  fast detritus remineralisation switch
+!!       jfdfate     :  fate of fast detritus at seafloor switch
+!!       jrratio     :  rain ratio switch
+!!	 jocalccd    :  CCD switch
+!!	 xridg_r0    :  Ridgwell rain ratio coefficient
+!!       xfdfrac1    :  fast-sinking fraction of diatom nat. mort. losses
+!!       xfdfrac2    :  fast-sinking fraction of mesozooplankton mort. losses
+!!       xfdfrac3    :  fast-sinking fraction of diatom silicon grazing losses
+!!       xcaco3a     :  polar (high latitude) CaCO3 fraction
+!!       xcaco3b     :  equatorial (low latitude) CaCO3 fraction
+!!       xmassc      :  organic C mass:mole ratio, C106 H175 O40 N16 P1
+!!       xmassca     :  calcium carbonate mass:mole ratio, CaCO3
+!!       xmasssi     :  biogenic silicon mass:mole ratio, (H2SiO3)n
+!!       xprotca     :  calcium carbonate protection ratio
+!!       xprotsi     :  biogenic silicon protection ratio
+!!       xfastc      :  organic C remineralisation length scale
+!!       xfastca     :  calcium carbonate dissolution length scale
+!!       xfastsi     :  biogenic silicon dissolution length scale
+!!
+!! Benthos parameters
+!!       jorgben     :  does   organic detritus go to the benthos?
+!!       jinorgben   :  does inorganic detritus go to the benthos?
+!!       xsedn       :  organic   nitrogen sediment remineralisation rate 
+!!       xsedfe      :  organic   iron     sediment remineralisation rate 
+!!       xsedsi      :  inorganic silicon  sediment dissolution      rate 
+!!       xsedc       :  organic   carbon   sediment remineralisation rate 
+!!       xsedca      :  inorganic carbon   sediment dissolution      rate 
+!!       xburial     :  burial fraction of sediment material
+!!
+!! River parameters
+!!       jriver_n    :  riverine N          input?
+!!       jriver_si   :  riverine Si         input?
+!!       jriver_c    :  riverine C          input?
+!!       jriver_alk  :  riverine alkalinity input?
+!!       jriver_dep  :  depth of riverine   input?
+!!
+!! Miscellaneous
+!!       xsdiss      :  diatom frustule dissolution rate
+!!
+!! Gravitational sinking      
+!!       vsed        :  detritus gravitational sinking rate 
+!!       xhr         :  coeff for Martin's remineralisation profile
+!!
+!! Additional parameters
+!!       jpkb        :  vertical layer for diagnostic of the vertical flux 
+!!
+!! UKESM1 - new diagnostics  !! Jpalm
+!!       jdms        :  include dms diagnostics
+!!       jdms_input  :  use instant (0) or diel-avg (1) inputs
+!!       jdms_model  :  which DMS model is passed to atmosphere
+!!
+!!       
+&natbio
+!
+!! Primary production and chl related quantities
+      xxi       = 0.01257   !!
+      xaln      = 15.0      !! EKP (05/03/09)
+      xald      = 11.25     !! EKP (05/03/09)
+      jphy      = 1         !! 0 = T-independent; 1 = T-dependent; 2 = T-dependent-Q10
+      xvpn      = 0.640     !! EKP (05/03/09) -- daily avg = 0.530; daily cycle = 1.060; Q10 = 0.64
+      xvpd      = 0.600     !! EKP (05/03/09) -- daily avg = 0.500; daily cycle = 1.000; Q10 = 0.6
+      xthetam   = 0.05      !! EKP (05/03/09)
+      xthetamd  = 0.05      !! EKP (05/03/09)
+      jq10      = 1.50      !! Jpalm (17-06-2016)
+!!
+!! Diatom silicon parameters
+      xsin0     = 0.2       !! Mongin et al. (2003)
+      xnsi0     = 0.2       !! Mongin et al. (2003)
+      xuif      = 1.5       !! Mongin et al. (2003)
+!!
+!! Nutrient limitation
+      jliebig   = 0         !! 0 = multiplicative, 1 = Liebig
+      xnln      = 0.5       !! Fasham (1993)
+      xnld      = 0.75      !! EKP (05/03/09)
+      xsld      = 3.00      !! Fasham et al. (2006)-ish
+      xfln      = 0.00033   !! EKP (29/10/09); Parekh et al. (2005)
+      xfld      = 0.00067   !! EKP (29/10/09); Parekh et al. (2005); filtered through Moore et al. (2004)
+!!
+!! Grazing
+      xgmi      = 2.0       !! EKP (05/03/09)
+      xgme      = 0.5       !! AXY (21/12/09)
+      xkmi      = 0.8       !! EKP (26/02/09)
+      xkme      = 0.3       !! EKP (26/02/09)
+      xphi      = 0.20      !! Anderson & Pondaven (2003; 0.23); EKP (05/03/09; 0.20)
+      xbetan    = 0.77      !! Anderson & Pondaven (2003)
+      xbetac    = 0.64      !! Anderson & Pondaven (2003)
+!!    xbetan    = 0.69      !! compromise values inbetween those from ...
+!!    xbetac    = 0.69      !! Anderson & Pondaven (2003)for detrital carbon model
+      xkc       = 0.80      !! Anderson & Pondaven (2003)
+      xpmipn    = 0.75      !! 
+      xpmid     = 0.25      !!
+      xpmepn    = 0.15      !! EKP (26/02/09)
+      xpmepd    = 0.35      !! EKP (26/02/09)
+      xpmezmi   = 0.35      !! EKP (26/02/09)
+      xpmed     = 0.15      !! EKP (26/02/09)
+!!
+!! Metabolic losses
+      xmetapn   = 0.02      !! 
+      xmetapd   = 0.02      !! 
+      xmetazmi  = 0.02      !! 
+      xmetazme  = 0.02      !! 
+!!
+!! Mortality losses
+      jmpn      = 3         !! 1=linear; 2=quadratic; 3=hyperbolic; 4=sigmoid
+      xmpn      = 0.1       !!
+      xkphn     = 0.5       !! EKP (26/02/09): new parameter
+      jmpd      = 3         !! 1=linear; 2=quadratic; 3=hyperbolic; 4=sigmoid
+      xmpd      = 0.1       !!
+      xkphd     = 0.5       !! EKP (26/02/09): new parameter
+      jmzmi     = 3         !! 1=linear; 2=quadratic; 3=hyperbolic; 4=sigmoid
+      xmzmi     = 0.1       !!
+      xkzmi     = 0.5       !!
+      jmzme     = 3         !! 1=linear; 2=quadratic; 3=hyperbolic; 4=sigmoid
+      xmzme     = 0.2       !! EKP (26/02/09)
+      xkzme     = 0.75      !! EKP (26/02/09)
+!!
+!! Remineralisation
+      jmd       = 2         !! 0 = T-independent; 1 = T-dependent; 2 = T-dependent-Q10
+      jsfd      = 0         !! 0 = unchanged seafloor remin.; 1 = accelerated seafloor remin.
+      xmd       = 0.0190    !! T-dependent; 0.05 at 18C (Yool et al., 2010) - Q10 = 0.0190
+      xmdc      = 0.0152    !! T-dependent; 0.04 at 18C (Yool et al., 2010) - Q10 = 0.0152
+!! 
+!! Stochiometric ratios
+      xthetapn  = 6.625     !! Redfield
+      xthetapd  = 6.625     !! Redfield
+      xthetazmi = 5.625     !! Redfield
+      xthetazme = 5.625     !! Redfield
+!! AXY (26/11/08): implicit detrital carbon change
+      xthetad   = 6.625     !! Redfield
+      xrfn      = 30.0e-6   !! Parekh et al. (2005)
+      xrsn      = 1.0       !! not used here; retained for Lobster
+!!
+!! Iron parameters
+      jiron     = 1         !! iron scavenging submodel switch
+      xfe_mass  = 55.485    !! Fe atomic mass
+      xfe_sol   = 0.00532   !! scaled to get same input as Parekh et al. (2005)
+      xfe_sed   = 0.000228  !! AXY (10/07/12): Moore-ish
+      xLgT      = 1.0       !! from Diat-HadOCC; from Parekh et al. (2005)
+      xk_FeL	= 100.0     !! from Diat-HadOCC
+      xk_sc_Fe  = 1.e-3     !! from Dutkiewicz et al. (2005)
+!!
+!! Fast-sinking detritus parameters
+      jexport   = 1         !! 1 = ballast; 2 = Martin (1987); 3 = Henson (2011)
+      jfdfate   = 0         !! 0 = instant remin.; 1 = transmogrify into slow detritus
+      jrratio   = 2         !! 0 = Dunne (2005); 1 = Ridgwell (2007) surface; 2 = Ridgwell (2007) 3D
+      jocalccd  = 1         !! 0 = default, fixed; 1 = calculated, dynamic
+      xridg_r0  = 0.026     !! = 0.044, Ridgwell et al. (2007); scaled to 60% from preliminary sims
+      xfdfrac1  = 0.333     !! control parameter; no "real" value (AXY; 12/03/09)
+      xfdfrac2  = 1.00      !! control parameter; no "real" value (AXY; 12/03/09)
+      xfdfrac3  = 0.80      !! control parameter; no "real" value (AXY; 12/03/09)
+      xcaco3a   = 0.02      !! Dunne et al. (2005); not an exact value
+      xcaco3b   = 0.10      !! Dunne et al. (2005); not an exact value
+!! AXY (06/01/09): after contacting Dunne, new values are used for masses ...
+!!    xmassc    = 22.1188   !!
+!!    xmassca   = 100.086   !! original values; replaced by Dunne suggestion
+!!    xmasssi   = 78.0988   !!
+      xmassc    = 12.011    !! C atomic mass
+      xmassca   = 100.086   !! CaCO3; based on atomic masses
+      xmasssi   = 60.084    !! SiO2; based on atomic masses
+      xprotca   = 0.070     !! Dunne et al. (2005)
+      xprotsi   = 0.026     !! Dunne et al. (2005)
+      xfastc    = 188.0     !! Dunne et al. (2005)
+      xfastca   = 3500.0    !! Dunne et al. (2005)
+      xfastsi   = 2000.0    !! Dunne et al. (2005)
+!!
+!! Benthos parameters
+      jorgben   = 1         !! 0 = no; 1 = yes
+      jinorgben = 1         !! 0 = no; 1 = yes
+      xsedn     = 0.05      !! default ERSEM-ish value
+      xsedfe    = 0.05      !! default ERSEM-ish value
+      xsedsi    = 0.01      !! default ERSEM-ish value
+      xsedc     = 0.05      !! default ERSEM-ish value
+      xsedca    = 0.01      !! default ERSEM-ish value
+      xburial   = 0.0       !! set to zero
+!! 
+!! River parameters
+      jriver_n  = 0         !! 0 = no; 1 = runoff-dependent fluxes; 2= fixed fluxes
+      jriver_si = 0         !! 0 = no; 1 = runoff-dependent fluxes; 2= fixed fluxes
+      jriver_c  = 0         !! 0 = no; 1 = runoff-dependent fluxes; 2= fixed fluxes
+      jriver_alk= 0         !! 0 = no; 1 = runoff-dependent fluxes; 2= fixed fluxes
+      jriver_dep= 5         !! depth to which river nutrients are added
+!!
+!! Miscellaneous
+      xsdiss    = 0.006     !! Mongin et al. (2003); 0.006 is an alternative
+!!
+!! Gravitational sinking
+      vsed      = 3.472e-5  !! EKP (05/03/09)
+!!
+!! Additional parameters
+      jpkb      = 16        !! 
+!!
+!! UKESM1 - new diagnostics !! Jpalm
+      jdms       = 1        !! include dms diagnostics
+      jdms_input = 1        !! use instant (0) or diel-avg (1) inputs
+      jdms_model = 3        !! choice of DMS model passed to atmosphere
+!!                             1 = ANDR, 2 = SIMO, 3 = ARAN, 4 = HALL
+!!
+/
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+!       natroam
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!
+!!       xthetaphy :  oxygen evolution/consumption by phytoplankton
+!!                    = (32 / 16) + (6.625 * (119 / 106)) = (2 + 7.4375) mol O2 / mol N
+!!       xthetazoo :  oxygen consumption by zooplankton
+!!                    = (32 / 16) + (5.625 * (119 / 106)) = (2 + 6.3149) mol O2 / mol N
+!!       xthetanit :  oxygen consumption by nitrogen remineralisation
+!!                    = (32 / 16) = 2 mol O2 / mol N
+!!       xthetarem :  oxygen consumption by carbon remineralisation
+!!                    = (119 / 106) = 1.1226 mol O2 / mol C
+!!       xo2min    :  oxygen minimum concentration
+!
+&natroam
+   xthetaphy = 9.4375
+   xthetazoo = 8.3149
+   xthetanit = 2.0
+   xthetarem = 1.1226
+   xo2min    = 4.0
+/
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+!       natopt
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!
+!   xkg0 : green water absorption coefficient   [m-1]
+!   xkr0 : red water absorption coefficient     [m-1]
+!  xkgp  : pigment green absorption coefficient [m-1]
+!  xkrp  : pigment red absorption coefficient   [m-1]
+!  xlg   : green chl exposant
+!  xlr   : red chl exposant
+!  rpig  : chla / (chla+phea) ratio
+!
+&natopt
+   xkg0 = 0.0232
+   xkr0 = 0.225
+   xkgp = 0.074
+   xkrp = 0.037
+   xlg  = 0.629
+   xlr  = 0.674
+   rpig = 0.7
+/
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+!       natdbi used if key_trc_diabio is set
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!
+!  ctrbio    : array of biological trend numbers
+!  ctrbil    : character string describing each biological trend
+!  ctrbiu    : array of unit numbers used for trend output
+!  nwritebio : frequency of biological model output [timesteps]
+!
+&natdbi
+   ctrbio    = "BIO_01", "BIO_02", "BIO_03", "BIO_04", "BIO_05", "BIO_06", "BIO_07", "BIO_08", "BIO_09", "BIO_10", "BIO_11", "BIO_12", "BIO_13", "BIO_14", "BIO_15", "BIO_16", "BIO_17", "BIO_18", "BIO_19", "BIO_20", "BIO_21", "BIO_22", "BIO_23", "BIO_24", "BIO_25", "BIO_26", "BIO_27", "BIO_28", "BIO_29", "BIO_30", "BIO_31", "BIO_32", "BIO_33", "BIO_34"
+   ctrbil    = "BIO_01", "BIO_02", "BIO_03", "BIO_04", "BIO_05", "BIO_06", "BIO_07", "BIO_08", "BIO_09", "BIO_10", "BIO_11", "BIO_12", "BIO_13", "BIO_14", "BIO_15", "BIO_16", "BIO_17", "BIO_18", "BIO_19", "BIO_20", "BIO_21", "BIO_22", "BIO_23", "BIO_24", "BIO_25", "BIO_26", "BIO_27", "BIO_28", "BIO_29", "BIO_30", "BIO_31", "BIO_32", "BIO_33", "BIO_34"
+   ctrbiu    = "m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m"
+   nwritebio = 10
+!/
+!&natopt
+/
+!=================================================
+! nammeddia    Passive tracers additional diagnostics
+!=================================================
+!
+!      ctrc2d  : 2d output field name
+!      ctrc2u  : 2d output field unit
+!      ctrc2l  : 2d output field long name
+!
+!      nwriteadd: frequency of additional arrays outputs(namelist)
+&nammeddia
+/
+!'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
+&nammedsbc     !   parameters for inputs deposition
+!,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
+!              !  file name        ! frequency (hours) ! variable      ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
+!              !                   !  (if <0  months)  !   name        !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
+   sn_dust     = 'dust.orca'       ,     -1            , 'dust'        ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+!
+   cn_dir      = './'      !  root directory for the location of the dynamical files
+   bdustfer    =  .true.   ! boolean for dust input from the atmosphere
+/
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_pisces_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_pisces_ref	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_pisces_ref	(revision 9987)
@@ -66,4 +66,5 @@
    qdfelim    =  7.E-6    ! Optimal quota of diatoms
    caco3r     =  0.3      ! mean rain ratio
+   oxymin    =  1.E-6     ! Half-saturation constant for anoxia
 /
 !'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
@@ -162,5 +163,4 @@
    xsiremlab =  0.03      ! fast remineralization rate of Si
    xsilab    =  0.5       ! Fraction of labile biogenic silica
-   oxymin    =  1.E-6     ! Half-saturation constant for anoxia
 /
 !'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_ref	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_ref	(revision 9987)
@@ -5,9 +5,9 @@
 !!                                    namsbc_cpl, namtra_qsr, namsbc_rnf,
 !!                                    namsbc_apr, namsbc_ssr, namsbc_alb)
-!!              4 - lateral boundary (namlbc, namcla, namobc, namagrif, nambdy, nambdy_tide)
+!!              4 - lateral boundary (namlbc, namcla, namagrif, nambdy, nambdy_tide)
 !!              5 - bottom  boundary (nambfr, nambbc, nambbl)
 !!              6 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_dmp)
 !!              7 - dynamics         (namdyn_adv, namdyn_vor, namdyn_hpg, namdyn_spg, namdyn_ldf)
-!!              8 - Verical physics  (namzdf, namzdf_ric, namzdf_tke, namzdf_kpp, namzdf_ddm, namzdf_tmx)
+!!              8 - Verical physics  (namzdf, namzdf_ric, namzdf_tke, namzdf_kpp, namzdf_ddm, namzdf_tmx, namzdf_tmx_new)
 !!              9 - diagnostics      (namnc4, namtrd, namspr, namflo, namhsb, namsto)
 !!             10 - miscellaneous    (namsol, nammpp, namctl)
@@ -363,4 +363,11 @@
    sn_snd_crt    =       'none'                 ,    'no'    , 'spherical' , 'eastward-northward' ,  'T'
    sn_snd_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_bio_co2 =      'medusa'               ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_bio_dms =      'medusa'               ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_bio_chloro =   'medusa'               ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_cond   =       'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_mpnd   =       'ice only'             ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_sstfrz =       'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_thick1 =       'ice and snow'         ,    'no'    ,     ''      ,         ''           ,   ''
 ! receive
    sn_rcv_w10m   =       'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
@@ -374,8 +381,28 @@
    sn_rcv_cal    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
    sn_rcv_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_antm   =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_grnm   =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_iceflx =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_ts_ice =       'ice'                  ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_atm_dust =     'medusa'               ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_atm_pco2 =     'medusa'               ,    'no'    ,     ''      ,         ''          ,   ''
+
 !
    nn_cplmodel   =     1     !  Maximum number of models to/from which NEMO is potentialy sending/receiving data
    ln_usecplmask = .false.   !  use a coupling mask file to merge data received from several models
                              !   -> file cplmask.nc with the float variable called cplmask (jpi,jpj,nn_cplmodel)
+   nn_coupled_iceshelf_fluxes = 0 ! =0 : total freshwater input from iceberg calving and ice shelf basal melting 
+                                  ! taken from climatologies used (no action in coupling routines).
+                                  ! =1 :  use rate of change of mass of Greenland and Antarctic icesheets to set the 
+                                  ! combined magnitude of the iceberg calving and iceshelf melting freshwater fluxes.
+                                  ! =2 :  specify constant freshwater inputs in this namelist to set the combined
+                                  ! magnitude of iceberg calving and iceshelf melting freshwater fluxes.
+   ln_iceshelf_init_atmos     = .true.  ! If true force ocean to initialise icesheet masses from atmospheric values rather than
+                                        ! from values in ocean restart file. 
+   rn_greenland_total_fw_flux   = 0.0  ! Constant total rate of freshwater input (kg/s) for Greenland (if nn_coupled_iceshelf_fluxes=2) 
+   rn_greenland_calving_fraction = 0.5  ! Set fraction of total freshwater flux for iceberg calving - remainder goes to iceshelf melting.
+   rn_antarctica_total_fw_flux  = 0.0  ! Constant total rate of freshwater input (kg/s) for Antarctica (if nn_coupled_iceshelf_fluxes=2)
+   rn_antarctica_calving_fraction = 0.5 ! Set fraction of total freshwater flux for iceberg calving - remainder goes to iceshelf melting.
+   rn_iceshelf_fluxes_tolerance = 1e-6  ! Fractional threshold for detecting differences in icesheet masses (must be positive definite).
 /
 !-----------------------------------------------------------------------
@@ -408,5 +435,5 @@
    ln_qsr_2bd  = .false.   !  2 bands              light penetration
    ln_qsr_bio  = .false.   !  bio-model light penetration
-   nn_chldta   =      1    !  RGB : Chl data (=1) or cst value (=0)
+   nn_chldta   =      1    !  RGB : 2D Chl data (=1), 3D Chl data (=2) or cst value (=0)
    rn_abs      =   0.58    !  RGB & 2 bands: fraction of light (rn_si1)
    rn_si0      =   0.35    !  RGB & 2 bands: shortess depth of extinction
@@ -500,9 +527,11 @@
 &namsbc_alb    !   albedo parameters
 !-----------------------------------------------------------------------
-   rn_cloud    =    0.06   !  cloud correction to snow and ice albedo
-   rn_albice   =    0.53   !  albedo of melting ice in the arctic and antarctic
-   rn_alphd    =    0.80   !  coefficients for linear interpolation used to
-   rn_alphc    =    0.65   !  compute albedo between two extremes values
-   rn_alphdi   =    0.72   !  (Pyane, 1972)
+   nn_ice_alb  =    0   !  parameterization of ice/snow albedo
+                        !     0: Shine & Henderson-Sellers (JGR 1985)
+                        !     1: "home made" based on Brandt et al. (J. Climate 2005)
+                        !                         and Grenfell & Perovich (JGR 2004)
+   rn_albice   =  0.53  !  albedo of bare puddled ice (values from 0.49 to 0.58)
+                        !     0.53 (default) => if nn_ice_alb=0
+                        !     0.50 (default) => if nn_ice_alb=1
 /
 !-----------------------------------------------------------------------
@@ -546,5 +575,4 @@
 !!   namlbc        lateral momentum boundary condition
 !!   namcla        cross land advection
-!!   namobc        open boundaries parameters                           ("key_obc")
 !!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
 !!   nambdy        Unstructured open boundaries                         ("key_bdy")
@@ -563,25 +591,4 @@
 !-----------------------------------------------------------------------
    nn_cla      =    0      !  advection between 2 ocean pts separates by land
-/
-!-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-   ln_obc_clim = .false.   !  climatological obc data files (T) or not (F)
-   ln_vol_cst  = .true.    !  impose the total volume conservation (T) or not (F)
-   ln_obc_fla  = .false.   !  Flather open boundary condition
-   nn_obcdta   =    1      !  = 0 the obc data are equal to the initial state
-                           !  = 1 the obc data are read in 'obc.dta' files
-   cn_obcdta   = 'annual'  !  set to annual if obc datafile hold 1 year of data
-                           !  set to monthly if obc datafile hold 1 month of data
-   rn_dpein    =    1.     !  damping time scale for inflow at east  open boundary
-   rn_dpwin    =    1.     !     -           -         -       west    -      -
-   rn_dpnin    =    1.     !     -           -         -       north   -      -
-   rn_dpsin    =    1.     !     -           -         -       south   -      -
-   rn_dpeob    = 3000.     !  time relaxation (days) for the east  open boundary
-   rn_dpwob    =   15.     !     -           -         -     west    -      -
-   rn_dpnob    = 3000.     !     -           -         -     north   -      -
-   rn_dpsob    =   15.     !     -           -         -     south   -      -
-   rn_volemp   =    1.     !  = 0 the total volume change with the surface flux (E-P-R)
-                           !  = 1 the total volume remains constant
 /
 !-----------------------------------------------------------------------
@@ -904,4 +911,6 @@
 !!    namzdf_ddm    double diffusive mixing parameterization            ("key_zdfddm")
 !!    namzdf_tmx    tidal mixing parameterization                       ("key_zdftmx")
+!!    namzdf_tmx_new    new tidal mixing parameterization               ("key_zdftmx_new")
+!!    namzdf_mldzint vertically-interpolated mixed-layer depth parameters
 !!======================================================================
 !
@@ -962,4 +971,5 @@
                            !        = 0  constant 10 m length scale
                            !        = 1  0.5m at the equator to 30m poleward of 40 degrees
+   rn_c        =   0.8     !  Default value only used when nn_htau = 2 (typically never!)
 /
 !------------------------------------------------------------------------
@@ -1009,4 +1019,24 @@
    ln_tmx_itf  = .true.    !  ITF specific parameterisation
    rn_tfe_itf  = 1.        !  ITF tidal dissipation efficiency
+/
+!-----------------------------------------------------------------------
+&namzdf_tmx_new    !   new tidal mixing parameterization                ("key_zdftmx_new")
+!-----------------------------------------------------------------------
+   nn_zpyc     = 1         !  pycnocline-intensified dissipation scales as N (=1) or N^2 (=2)
+   ln_mevar    = .true.    !  variable (T) or constant (F) mixing efficiency
+   ln_tsdiff   = .true.    !  account for differential T/S mixing (T) or not (F)
+/
+!------------------------------------------------------------------------------------------
+&namzdf_mldzint    !   Parameters for vertically-interpolated mixed-layer depth diagnostic
+!------------------------------------------------------------------------------------------
+   nn_mld_diag = 0         !  Number of MLD diagnostics to use from below
+
+!              ! MLD criterion ! Reference ! Finite difference ! Gradient layer !
+!              ! type          ! depth     ! criterion         ! criterion      !
+   sn_mld1     =       1       ,    10.0   ,        0.2        ,       0.1
+   sn_mld2     =       0      ,      0.0   ,        0.0        ,       0.0 
+   sn_mld3     =       0      ,      0.0   ,        0.0        ,       0.0 
+   sn_mld4     =       0      ,      0.0   ,        0.0        ,       0.0 
+   sn_mld5     =       0      ,      0.0   ,        0.0        ,       0.0 
 /
 
@@ -1302,4 +1332,6 @@
     ln_asmdin = .false.    !  Logical switch for Direct Initialization (DI)
     ln_asmiau = .false.    !  Logical switch for Incremental Analysis Updating (IAU)
+    ln_seaiceinc = .false. !  Logical switch for applying sea ice increments
+    ln_temnofreeze = .false. !  Logical to not add increments if temperature would fall below freezing
     nitbkg    = 0          !  Timestep of background in [0,nitend-nit000-1]
     nitdin    = 0          !  Timestep of background for DI in [0,nitend-nit000-1]
@@ -1338,2 +1370,36 @@
    rn_htrmax         =  200.0   ! max. depth of transition range
 /
+!-----------------------------------------------------------------------
+&nambias   ! Bias pressure correctiom
+!-----------------------------------------------------------------------
+   ln_bias        = .false.
+   ln_bias_asm    = .false.
+   ln_bias_rlx    = .false.
+   ln_bias_ofl    = .false.
+   ln_bias_ts_app = .false.
+   ln_bias_pc_app = .false.        
+   fb_t_asm       = 0.0
+   fb_t_rlx       = 0.0
+   fb_t_ofl       = 1.0
+   fb_p_asm       = 1.0
+   fb_p_rlx       = 1.0
+   fb_p_ofl       = 0.0
+   eft_rlx        = 365.0
+   eft_asm        = 365.0
+   t_rlx_upd      = 0.1
+   t_asm_upd      = 0.1
+   nn_lat_ramp    = 0          
+   bias_time_unit_asm = 86400.0
+   bias_time_unit_rlx = 1.0
+   bias_time_unit_ofl = 1.0 
+   cn_bias_tot    = "bias_tot.nc" 
+   cn_bias_asm    = "bias_asm.nc"
+   cn_dir         = './'  
+   ln_bsyncro     = .FALSE. 
+   fctamp         = 1.
+   rn_maxlat_bias = 23.0      
+   rn_minlat_bias = 10.0
+   nn_bias_itwrt  = 15
+   ln_itdecay     = .FALSE.
+   ln_incpc       = .FALSE.
+/
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_top_MEDUSA_et_al_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_top_MEDUSA_et_al_ref	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_top_MEDUSA_et_al_ref	(revision 9987)
@@ -0,0 +1,120 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/TOP1 :   - tracer run information                (namtrc_run)
+!!               - tracer definition                     (namtrc    )
+!!               - tracer data initialisation            (namtrc_dta)
+!!               - tracer advection                      (namtrc_adv)
+!!               - tracer lateral diffusion              (namtrc_ldf)
+!!               - tracer vertical physics               (namtrc_zdf)
+!!               - tracer newtonian damping              (namtrc_dmp)
+!!               - dynamical tracer trends               (namtrc_trd)
+!!               - tracer output diagonstics             (namtrc_dia)
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namtrc_run     !   run information
+!-----------------------------------------------------------------------
+   nn_dttrc      =  1        !  time step frequency for passive sn_tracers
+   nn_writetrc   =  640     !  time step frequency for sn_tracer outputs
+   ln_top_euler  = .false.    !  use Euler time-stepping for TOP
+   ln_rsttr      = .false.   !  start from a restart file (T) or not (F)
+   nn_rsttr      =   0       !  restart control = 0 initial time step is not compared to the restart file value
+                           !                  = 1 do not use the value in the restart file
+                           !                  = 2 calendar parameters read in the restart file
+   cn_trcrst_in  = "restart_trc"   !  suffix of pass. sn_tracer restart name (input)
+   cn_trcrst_indir = "."           !  directory from which to read input passive tracer restarts
+   cn_trcrst_out = "restart_trc"   !  suffix of pass. sn_tracer restart name (output)
+   cn_trcrst_outdir = "."          !  directory to which to write output passive tracer restarts
+/
+!-----------------------------------------------------------------------
+&namtrc     !   tracers definition
+!-----------------------------------------------------------------------
+   ln_trcdta     =  .false.  !  Initialisation from data input file (T) or not (F)
+   ln_trcdmp     =  .false.  !  add a damping termn (T) or not (F)
+   ln_trcdmp_clo =  .false.  !  damping term (T) or not (F) on closed seas
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+!
+   cn_dir        =  './'      !  root directory for the location of the data files
+/
+!-----------------------------------------------------------------------
+&namtrc_adv    !   advection scheme for passive tracer 
+!-----------------------------------------------------------------------
+   ln_trcadv_cen2    =  .false.  !  2nd order centered scheme   
+   ln_trcadv_tvd     =  .true.  !  TVD scheme
+   ln_trcadv_muscl   =  .false.   !  MUSCL scheme
+   ln_trcadv_muscl2  =  .false.  !  MUSCL2 scheme + cen2 at boundaries
+   ln_trcadv_ubs     =  .false.  !  UBS scheme
+   ln_trcadv_qck     =  .false.  !  QUICKEST scheme
+   ln_trcadv_msc_ups =  .false.  !  use upstream scheme within muscl
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf    !   lateral diffusion scheme for passive tracer 
+!-----------------------------------------------------------------------
+!                               !  Type of the operator : 
+   ln_trcldf_lap    =  .true.   !     laplacian operator       
+   ln_trcldf_bilap  =  .false.  !     bilaplacian operator     
+                                !  Direction of action  :
+   ln_trcldf_level  =  .false.  !     iso-level                
+   ln_trcldf_hor    =  .false.  !     horizontal (geopotential)         (require "key_ldfslp" when ln_sco=T)
+   ln_trcldf_iso    =  .true.   !     iso-neutral                       (require "key_ldfslp")
+!                               !  Coefficient
+   rn_ahtrc_0       =  2000.    !  horizontal eddy diffusivity for tracers [m2/s]
+   rn_ahtrb_0       =     0.    !     background eddy diffusivity for ldf_iso [m2/s]
+   rn_fact_lap      =     1.    !     enhanced zonal eddy diffusivity
+/
+!-----------------------------------------------------------------------
+&namtrc_zdf        !   vertical physics
+!-----------------------------------------------------------------------
+   ln_trczdf_exp   =  .false.  !  split explicit (T) or implicit (F) time stepping
+   nn_trczdf_exp   =   3       !  number of sub-timestep for ln_trczdfexp=T
+/
+!-----------------------------------------------------------------------
+&namtrc_rad        !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+   ln_trcrad   =  .true.  !  artificially correct negative concentrations (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp    !   passive tracer newtonian damping   
+!-----------------------------------------------------------------------
+   nn_zdmp_tr  =    1      !  vertical   shape =0    damping throughout the water column
+                           !                   =1 no damping in the mixing layer (kz  criteria)
+                           !                   =2 no damping in the mixed  layer (rho crieria)
+   cn_resto_tr  = 'resto_tr.nc'    !  create a damping.coeff NetCDF file (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namtrc_ice       !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+   nn_ice_tr   =  -1        !  tracer concentration in sea ice 
+                           !    =-1 (no vvl: identical cc in ice and ocean / vvl: cc_ice = 0)
+                           !    = 0 (no vvl: cc_ice = zero / vvl: cc_ice = )
+                           !    = 1 prescribed to a namelist value (implemented in pisces only)
+/
+!-----------------------------------------------------------------------
+&namtrc_trd       !   diagnostics on tracer trends        ('key_trdtrc')
+!                          or mixed-layer trends          ('key_trdmld_trc')
+!----------------------------------------------------------------------
+   nn_trd_trc  =  640       !  time step frequency and tracers trends
+   nn_ctls_trc =   0        !  control surface type in mixed-layer trends (0,1 or n<jpk)
+   rn_ucf_trc  =   1        !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
+   ln_trdmld_trc_restart = .false.  !  restart for ML diagnostics
+   ln_trdmld_trc_instant = .true.  !  flag to diagnose trends of instantantaneous or mean ML T/S
+   ln_trdtrc(1)  =   .true.
+   ln_trdtrc(2)  =   .true.
+   ln_trdtrc(23) =   .true.
+/
+!-----------------------------------------------------------------------
+&namtrc_dia       !   parameters for passive tracer additional diagnostics
+!----------------------------------------------------------------------
+   ln_diatrc     =  .false.  !  save additional diag. (T) or not (F)
+   ln_diabio     =  .true.   !  output biological trends
+   nn_writedia   =  640      !  time step frequency for diagnostics
+   nn_writebio   =  640      !: frequency of biological outputs
+/
+!----------------------------------------------------------------------
+! namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+&namtrc_bc
+!
+   cn_dir        =  './'      !  root directory for the location of the data files
+/
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_top_ref
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_top_ref	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/SHARED/namelist_top_ref	(revision 9987)
@@ -62,4 +62,5 @@
    rn_ahtrc_0       =  2000.    !  horizontal eddy diffusivity for tracers [m2/s]
    rn_ahtrb_0       =     0.    !     background eddy diffusivity for ldf_iso [m2/s]
+   rn_fact_lap      =     1.    !     enhanced zonal eddy diffusivity
 /
 !-----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/cfg.txt
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/cfg.txt	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/CONFIG/cfg.txt	(revision 9987)
@@ -6,7 +6,8 @@
 GYRE_BFM OPA_SRC TOP_SRC
 AMM12 OPA_SRC
+ORCA2_OFF_PISCES OPA_SRC OFF_SRC TOP_SRC
 ORCA2_LIM_PISCES OPA_SRC LIM_SRC_2 NST_SRC TOP_SRC
+ORCA2_LIM3 OPA_SRC LIM_SRC_3 NST_SRC
 GYRE OPA_SRC
-ORCA2_LIM3 OPA_SRC LIM_SRC_3 NST_SRC
 ORCA2_LIM OPA_SRC LIM_SRC_2 NST_SRC
-ORCA2_OFF_PISCES OPA_SRC OFF_SRC TOP_SRC
+ORCA2_OFF_MEDUSA OPA_SRC OFF_SRC TOP_SRC
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modarrays.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modarrays.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modarrays.F90	(revision 9987)
@@ -0,0 +1,826 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Arrays
+!
+module Agrif_Arrays
+!
+    use Agrif_Types
+    use Agrif_Grids
+!
+    implicit none
+!
+#if defined AGRIF_MPI
+    interface
+        subroutine Agrif_InvLoc ( indloc, proc_id, dir, indglob )
+            integer, intent(in)     :: indloc   !< local index
+            integer, intent(in)     :: proc_id  !< rank of the proc calling this function
+            integer, intent(in)     :: dir      !< direction of the index
+            integer, intent(out)    :: indglob  !< global index
+        end subroutine Agrif_InvLoc
+    end interface
+    private :: Agrif_InvLoc
+#endif
+!
+contains
+!
+!===================================================================================================
+! subroutine Agrif_Childbounds
+!
+!> Computes the global indices of the child grid
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Childbounds ( nbdim,           &
+                               lb_var, ub_var,  &
+                               lb_tab, ub_tab,  &
+                               proc_id,         &
+                               coords,          &
+                               lb_tab_true, ub_tab_true, memberin )
+!---------------------------------------------------------------------------------------------------
+    integer,                   intent(in)  :: nbdim         !< Number of dimensions
+    integer, dimension(nbdim), intent(in)  :: lb_var        !< Local lower boundary on the current processor
+    integer, dimension(nbdim), intent(in)  :: ub_var        !< Local upper boundary on the current processor
+    integer, dimension(nbdim), intent(in)  :: lb_tab        !< Global lower boundary of the variable
+    integer, dimension(nbdim), intent(in)  :: ub_tab        !< Global upper boundary of the variable
+    integer,                   intent(in)  :: proc_id       !< Current processor
+    integer, dimension(nbdim), intent(in)  :: coords
+    integer, dimension(nbdim), intent(out) :: lb_tab_true   !< Global value of lb_var on the current processor
+    integer, dimension(nbdim), intent(out) :: ub_tab_true   !< Global value of ub_var on the current processor
+    logical,                   intent(out) :: memberin
+!
+    integer :: i, coord_i
+    integer :: lb_glob_index, ub_glob_index ! Lower and upper global indices
+!
+    do i = 1, nbdim
+!
+        coord_i = coords(i)
+!
+#if defined AGRIF_MPI
+        call Agrif_InvLoc( lb_var(i), proc_id, coord_i, lb_glob_index )
+        call Agrif_InvLoc( ub_var(i), proc_id, coord_i, ub_glob_index )
+#else
+        lb_glob_index = lb_var(i)
+        ub_glob_index = ub_var(i)
+#endif
+        lb_tab_true(i) = max(lb_tab(i), lb_glob_index)
+        ub_tab_true(i) = min(ub_tab(i), ub_glob_index)
+    enddo
+!
+    memberin = .true.
+    do i = 1,nbdim
+        if (ub_tab_true(i) < lb_tab_true(i)) then
+            memberin = .false.
+            exit
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Childbounds
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_get_var_global_bounds( var, lubglob, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),        intent(in)  :: var
+    integer, dimension(nbdim,2), intent(out) :: lubglob
+    integer,                     intent(in)  :: nbdim
+!
+#if defined AGRIF_MPI
+    include 'mpif.h'
+    integer, dimension(nbdim)   :: lb, ub
+    integer, dimension(nbdim,2) :: iminmaxg
+    integer :: i, code, coord_i
+#endif
+!
+#if !defined AGRIF_MPI
+    call Agrif_get_var_bounds_array(var, lubglob(:,1), lubglob(:,2), nbdim)
+#else
+    call Agrif_get_var_bounds_array(var, lb, ub, nbdim)
+
+    do i = 1,nbdim
+        coord_i = var % root_var % coords(i)
+        call Agrif_InvLoc( lb(i), Agrif_Procrank, coord_i, iminmaxg(i,1) )
+        call Agrif_InvLoc( ub(i), Agrif_Procrank, coord_i, iminmaxg(i,2) )
+    enddo
+!
+    iminmaxg(1:nbdim,2) = - iminmaxg(1:nbdim,2)
+    call MPI_ALLREDUCE(iminmaxg, lubglob, 2*nbdim, MPI_INTEGER, MPI_MIN, Agrif_mpi_comm, code)
+    lubglob(1:nbdim,2)  = - lubglob(1:nbdim,2)
+#endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_get_var_global_bounds
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_get_var_bounds
+!
+!> Gets the lower and the upper boundaries of a variable, for one particular direction.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_get_var_bounds ( variable, lower, upper, index )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), intent(in)    :: variable   !< Variable for which we want to extract boundaries
+    integer,              intent(out)   :: lower      !< Lower bound
+    integer,              intent(out)   :: upper      !< Upper bound
+    integer,              intent(in)    :: index      !< Direction for wich we want to know the boundaries
+!
+    lower = variable % lb(index)
+    upper = variable % ub(index)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_get_var_bounds
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_get_var_bounds_array
+!
+!> Gets the lower and the upper boundaries of a table.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_get_var_bounds_array ( variable, lower, upper, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),      intent(in)   :: variable   !< Variable for which we want to extract boundaries
+    integer, dimension(nbdim), intent(out)  :: lower      !< Lower bounds array
+    integer, dimension(nbdim), intent(out)  :: upper      !< Upper bounds array
+    integer, intent(in)                     :: nbdim      !< Numer of dimensions of the variable
+!
+    lower = variable % lb(1:nbdim)
+    upper = variable % ub(1:nbdim)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_get_var_bounds_array
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_array_allocate
+!
+!> Allocates data array in \b variable, according to the required dimension.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_array_allocate ( variable, lb, ub, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),      intent(inout) :: variable    !< Variable struct for allocation
+    integer, dimension(nbdim), intent(in)    :: lb          !< Lower bound
+    integer, dimension(nbdim), intent(in)    :: ub          !< Upper bound
+    integer,                   intent(in)    :: nbdim       !< Dimension of the array
+!
+    select case (nbdim)
+    case (1) ; allocate(variable%array1(lb(1):ub(1)))
+    case (2) ; allocate(variable%array2(lb(1):ub(1),lb(2):ub(2)))
+    case (3) ; allocate(variable%array3(lb(1):ub(1),lb(2):ub(2),lb(3):ub(3)))
+    case (4) ; allocate(variable%array4(lb(1):ub(1),lb(2):ub(2),lb(3):ub(3),lb(4):ub(4)))
+    case (5) ; allocate(variable%array5(lb(1):ub(1),lb(2):ub(2),lb(3):ub(3),lb(4):ub(4),lb(5):ub(5)))
+    case (6) ; allocate(variable%array6(lb(1):ub(1),lb(2):ub(2),lb(3):ub(3),lb(4):ub(4),lb(5):ub(5),lb(6):ub(6)))
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_array_allocate
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_array_deallocate
+!
+!> Dellocates data array in \b variable, according to the required dimension.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_array_deallocate ( variable, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), intent(inout) :: variable     !< Variable struct for deallocation
+    integer,              intent(in)    :: nbdim        !< Dimension of the array
+!
+    select case (nbdim)
+    case (1) ; deallocate(variable%array1)
+    case (2) ; deallocate(variable%array2)
+    case (3) ; deallocate(variable%array3)
+    case (4) ; deallocate(variable%array4)
+    case (5) ; deallocate(variable%array5)
+    case (6) ; deallocate(variable%array6)
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_array_deallocate
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_var_set_array_tozero
+!
+!> Reset the value of the data array in \b variable, according to the required dimension.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_var_set_array_tozero ( variable, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), intent(inout) :: variable     !< Variable
+    integer, intent(in)                 :: nbdim        !< Dimension of the array you want to reset
+!
+    select case (nbdim)
+    case (1) ; call Agrif_set_array_tozero_1D(variable%array1)
+    case (2) ; call Agrif_set_array_tozero_2D(variable%array2)
+    case (3) ; call Agrif_set_array_tozero_3D(variable%array3)
+    case (4) ; call Agrif_set_array_tozero_4D(variable%array4)
+    case (5) ; call Agrif_set_array_tozero_5D(variable%array5)
+    case (6) ; call Agrif_set_array_tozero_6D(variable%array6)
+    end select
+!---------------------------------------------------------------------------------------------------
+contains
+!---------------------------------------------------------------------------------------------------
+    subroutine Agrif_set_array_tozero_1D ( array )
+        real, dimension(:),           intent(out) :: array
+        array = 0.
+    end subroutine Agrif_set_array_tozero_1D
+!
+    subroutine Agrif_set_array_tozero_2D ( array )
+        real, dimension(:,:),         intent(out) :: array
+        array = 0.
+    end subroutine Agrif_set_array_tozero_2D
+!
+    subroutine Agrif_set_array_tozero_3D ( array )
+        real, dimension(:,:,:),       intent(out) :: array
+        array = 0.
+    end subroutine Agrif_set_array_tozero_3D
+!
+    subroutine Agrif_set_array_tozero_4D ( array )
+        real, dimension(:,:,:,:),     intent(out) :: array
+        array = 0.
+    end subroutine Agrif_set_array_tozero_4D
+!
+    subroutine Agrif_set_array_tozero_5D ( array )
+        real, dimension(:,:,:,:,:),   intent(out) :: array
+        array = 0.
+    end subroutine Agrif_set_array_tozero_5D
+!
+    subroutine Agrif_set_array_tozero_6D ( array )
+        real, dimension(:,:,:,:,:,:), intent(out) :: array
+        array = 0.
+    end subroutine Agrif_set_array_tozero_6D
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_var_set_array_tozero
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_var_copy_array
+!
+!> Copy a part of data array from var2 to var1
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_var_copy_array ( var1, inf1, sup1, var2, inf2, sup2, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),      intent(inout) :: var1    !< Modified variable
+    integer, dimension(nbdim), intent(in)    :: inf1    !< Lower boundary for var1
+    integer, dimension(nbdim), intent(in)    :: sup1    !< Upper boundary for var1
+    type(Agrif_Variable),      intent(in)    :: var2    !< Input variable
+    integer, dimension(nbdim), intent(in)    :: inf2    !< Lower boundary for var2
+    integer, dimension(nbdim), intent(in)    :: sup2    !< Upper boundary for var2
+    integer,                   intent(in)    :: nbdim   !< Dimension of the array
+!
+    select case (nbdim)
+    case (1) ; var1%array1(inf1(1):sup1(1)) = var2%array1(inf2(1):sup2(1))
+    case (2) ; call Agrif_copy_array_2d( var1%array2, var2%array2, &
+                                         lbound(var1%array2), lbound(var2%array2), inf1, sup1, inf2, sup2 )
+    case (3) ; call Agrif_copy_array_3d( var1%array3, var2%array3, &
+                                         lbound(var1%array3), lbound(var2%array3), inf1, sup1, inf2, sup2 )
+    case (4) ; call Agrif_copy_array_4d( var1%array4, var2%array4, &
+                                         lbound(var1%array4), lbound(var2%array4), inf1, sup1, inf2, sup2 )
+    case (5) ; var1%array5(inf1(1):sup1(1),   &
+                           inf1(2):sup1(2),   &
+                           inf1(3):sup1(3),   &
+                           inf1(4):sup1(4),   &
+                           inf1(5):sup1(5)) = var2%array5(inf2(1):sup2(1), &
+                                                          inf2(2):sup2(2), &
+                                                          inf2(3):sup2(3), &
+                                                          inf2(4):sup2(4), &
+                                                          inf2(5):sup2(5))
+    case (6) ; var1%array6(inf1(1):sup1(1),   &
+                           inf1(2):sup1(2),   &
+                           inf1(3):sup1(3),   &
+                           inf1(4):sup1(4),   &
+                           inf1(5):sup1(5),   &
+                           inf1(6):sup1(6)) = var2%array6(inf2(1):sup2(1), &
+                                                          inf2(2):sup2(2), &
+                                                          inf2(3):sup2(3), &
+                                                          inf2(4):sup2(4), &
+                                                          inf2(5):sup2(5), &
+                                                          inf2(6):sup2(6))
+    end select
+!---------------------------------------------------------------------------------------------------
+contains
+!---------------------------------------------------------------------------------------------------
+    subroutine Agrif_copy_array_2d ( tabout, tabin, l, m, inf1, sup1, inf2, sup2 )
+        integer, dimension(2), intent(in)   :: l, m
+        integer, dimension(2), intent(in)   :: inf1, sup1
+        integer, dimension(2), intent(in)   :: inf2, sup2
+        real, dimension(l(1):,l(2):), intent(out) :: tabout
+        real, dimension(m(1):,m(2):), intent(in)  :: tabin
+        tabout(inf1(1):sup1(1), &
+               inf1(2):sup1(2)) = tabin(inf2(1):sup2(1), &
+                                        inf2(2):sup2(2))
+    end subroutine Agrif_copy_array_2d
+!
+    subroutine Agrif_copy_array_3d ( tabout, tabin, l, m, inf1, sup1, inf2, sup2 )
+        integer, dimension(3), intent(in)   :: l, m
+        integer, dimension(3), intent(in)   :: inf1, sup1
+        integer, dimension(3), intent(in)   :: inf2,sup2
+        real, dimension(l(1):,l(2):,l(3):), intent(out) :: tabout
+        real, dimension(m(1):,m(2):,m(3):), intent(in)  :: tabin
+        tabout(inf1(1):sup1(1), &
+               inf1(2):sup1(2), &
+               inf1(3):sup1(3)) = tabin(inf2(1):sup2(1), &
+                                        inf2(2):sup2(2), &
+                                        inf2(3):sup2(3))
+    end subroutine Agrif_copy_array_3d
+!
+    subroutine Agrif_copy_array_4d ( tabout, tabin, l, m, inf1, sup1, inf2, sup2 )
+        integer, dimension(4), intent(in)   :: l, m
+        integer, dimension(4), intent(in)   :: inf1, sup1
+        integer, dimension(4), intent(in)   :: inf2, sup2
+        real, dimension(l(1):,l(2):,l(3):,l(4):), intent(out) :: tabout
+        real, dimension(m(1):,m(2):,m(3):,m(4):), intent(in)  :: tabin
+        tabout(inf1(1):sup1(1), &
+               inf1(2):sup1(2), &
+               inf1(3):sup1(3), &
+               inf1(4):sup1(4)) = tabin(inf2(1):sup2(1), &
+                                        inf2(2):sup2(2), &
+                                        inf2(3):sup2(3), &
+                                        inf2(4):sup2(4))
+    end subroutine Agrif_copy_array_4d
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_var_copy_array
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_var_full_copy_array
+!
+!> Copy the full data array from var2 to var1
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_var_full_copy_array ( var1, var2, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), intent(inout) :: var1    !< Modified variable
+    type(Agrif_Variable), intent(in)    :: var2    !< Input variable
+    integer,              intent(in)    :: nbdim   !< Dimension of the array
+!
+    select case (nbdim)
+    case (1) ; var1 % array1 = var2 % array1
+    case (2) ; var1 % array2 = var2 % array2
+    case (3) ; var1 % array3 = var2 % array3
+    case (4) ; var1 % array4 = var2 % array4
+    case (5) ; var1 % array5 = var2 % array5
+    case (6) ; var1 % array6 = var2 % array6
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_var_full_copy_array
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine GiveAgrif_SpecialValueToTab_mpi
+!
+!> Copy \b value in data array \b var2 where it is present in \b var1.
+!---------------------------------------------------------------------------------------------------
+subroutine GiveAgrif_SpecialValueToTab_mpi ( var1, var2, bounds, value, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),      intent(in)    :: var1    !< Modified variable
+    type(Agrif_Variable),      intent(inout) :: var2    !< Input variable
+    integer, dimension(:,:,:), intent(in)    :: bounds  !< Bound for both arrays
+    real,                      intent(in)    :: value   !< Special value
+    integer,                   intent(in)    :: nbdim   !< Dimension of the array
+!
+    select case (nbdim)
+    case (1)
+        where (var1 % array1(bounds(1,1,2):bounds(1,2,2)) == value )
+            var2 % array1(bounds(1,1,1):bounds(1,2,1)) = value
+        end where
+    case (2)
+        where (var1 % array2(bounds(1,1,2):bounds(1,2,2), &
+                             bounds(2,1,2):bounds(2,2,2)) == value)
+            var2 % array2(bounds(1,1,1):bounds(1,2,1), &
+                          bounds(2,1,1):bounds(2,2,1)) = value
+        end where
+    case (3)
+        where (var1 % array3(bounds(1,1,2):bounds(1,2,2), &
+                             bounds(2,1,2):bounds(2,2,2), &
+                             bounds(3,1,2):bounds(3,2,2)) == value)
+            var2 % array3(bounds(1,1,1):bounds(1,2,1), &
+                          bounds(2,1,1):bounds(2,2,1), &
+                          bounds(3,1,1):bounds(3,2,1)) = value
+        end where
+    case (4)
+        where (var1 % array4(bounds(1,1,2):bounds(1,2,2), &
+                             bounds(2,1,2):bounds(2,2,2), &
+                             bounds(3,1,2):bounds(3,2,2), &
+                             bounds(4,1,2):bounds(4,2,2)) == value)
+            var2 % array4(bounds(1,1,1):bounds(1,2,1), &
+                          bounds(2,1,1):bounds(2,2,1), &
+                          bounds(3,1,1):bounds(3,2,1), &
+                          bounds(4,1,1):bounds(4,2,1)) = value
+        end where
+    case (5)
+        where (var1 % array5(bounds(1,1,2):bounds(1,2,2), &
+                             bounds(2,1,2):bounds(2,2,2), &
+                             bounds(3,1,2):bounds(3,2,2), &
+                             bounds(4,1,2):bounds(4,2,2), &
+                             bounds(5,1,2):bounds(5,2,2)) == value)
+            var2 % array5(bounds(1,1,1):bounds(1,2,1), &
+                          bounds(2,1,1):bounds(2,2,1), &
+                          bounds(3,1,1):bounds(3,2,1), &
+                          bounds(4,1,1):bounds(4,2,1), &
+                          bounds(5,1,1):bounds(5,2,1)) = value
+        end where
+    case (6)
+        where (var1 % array6(bounds(1,1,2):bounds(1,2,2), &
+                             bounds(2,1,2):bounds(2,2,2), &
+                             bounds(3,1,2):bounds(3,2,2), &
+                             bounds(4,1,2):bounds(4,2,2), &
+                             bounds(5,1,2):bounds(5,2,2), &
+                             bounds(6,1,2):bounds(6,2,2)) == value)
+            var2 % array6(bounds(1,1,1):bounds(1,2,1), &
+                          bounds(2,1,1):bounds(2,2,1), &
+                          bounds(3,1,1):bounds(3,2,1), &
+                          bounds(4,1,1):bounds(4,2,1), &
+                          bounds(5,1,1):bounds(5,2,1), &
+                          bounds(6,1,1):bounds(6,2,1)) = value
+        end where
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine GiveAgrif_SpecialValueToTab_mpi
+!===================================================================================================
+!
+! no more used ???
+#if 0
+!===================================================================================================
+!  subroutine GiveAgrif_SpecialValueToTab
+!---------------------------------------------------------------------------------------------------
+subroutine GiveAgrif_SpecialValueToTab ( var1, var2, &
+                                         lower, upper, Value, nbdim )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Variable),      pointer      :: var1
+    TYPE(Agrif_Variable),      pointer      :: var2
+    INTEGER,                   intent(in)   :: nbdim
+    INTEGER, DIMENSION(nbdim), intent(in)   :: lower, upper
+    REAL,                      intent(in)   :: Value
+!
+    select case (nbdim)
+    case (1)
+        where (var1 % array1( lower(1):upper(1)) == Value)
+            var2 % array1(lower(1):upper(1)) = Value
+        end where
+    case (2)
+        where (var1 % array2( lower(1):upper(1), &
+                                   lower(2):upper(2)) == Value)
+            var2 % array2(lower(1):upper(1), &
+                               lower(2):upper(2)) = Value
+        end where
+    case (3)
+        where (var1 % array3( lower(1):upper(1), &
+                                   lower(2):upper(2), &
+                                   lower(3):upper(3)) == Value)
+            var2 % array3(lower(1):upper(1), &
+                               lower(2):upper(2), &
+                               lower(3):upper(3)) = Value
+        end where
+    case (4)
+        where (var1 % array4( lower(1):upper(1), &
+                                   lower(2):upper(2), &
+                                   lower(3):upper(3), &
+                                   lower(4):upper(4)) == Value)
+            var2 % array4(lower(1):upper(1), &
+                               lower(2):upper(2), &
+                               lower(3):upper(3), &
+                               lower(4):upper(4)) = Value
+        end where
+    case (5)
+        where (var1 % array5( lower(1):upper(1), &
+                                   lower(2):upper(2), &
+                                   lower(3):upper(3), &
+                                   lower(4):upper(4), &
+                                   lower(5):upper(5)) == Value)
+            var2 % array5(lower(1):upper(1), &
+                               lower(2):upper(2), &
+                               lower(3):upper(3), &
+                               lower(4):upper(4), &
+                               lower(5):upper(5)) = Value
+        end where
+    case (6)
+        where (var1 % array6( lower(1):upper(1), &
+                                   lower(2):upper(2), &
+                                   lower(3):upper(3), &
+                                   lower(4):upper(4), &
+                                   lower(5):upper(5), &
+                                   lower(6):upper(6)) == Value)
+            var2 % array6(lower(1):upper(1), &
+                               lower(2):upper(2), &
+                               lower(3):upper(3), &
+                               lower(4):upper(4), &
+                               lower(5):upper(5), &
+                               lower(6):upper(6)) = Value
+        end where
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine GiveAgrif_SpecialValueToTab
+!===================================================================================================
+#endif
+!
+#if defined AGRIF_MPI
+!===================================================================================================
+!  subroutine Agrif_var_replace_value
+!
+!> Replace \b value by \var2 content in \var1 data array.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_var_replace_value ( var1, var2, lower, upper, value, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),      intent(inout) :: var1    !< Modified variable
+    type(Agrif_Variable),      intent(in)    :: var2    !< Input variable
+    integer, dimension(nbdim), intent(in)    :: lower   !< Lower bound
+    integer, dimension(nbdim), intent(in)    :: upper   !< Upper bound
+    real,                      intent(in)    :: value   !< Special value
+    integer,                   intent(in)    :: nbdim   !< Dimension of the array
+!
+    integer :: i,j,k,l,m,n
+!
+    select case (nbdim)
+    case (1)
+        do i = lower(1),upper(1)
+            if (var1%array1(i) == value) then
+                var1%array1(i) = var2%array1(i)
+            endif
+        enddo
+    case (2)
+        do j = lower(2),upper(2)
+        do i = lower(1),upper(1)
+            if (var1%array2(i,j) == value) then
+                var1%array2(i,j) = var2%array2(i,j)
+            endif
+        enddo
+        enddo
+    case (3)
+        do k = lower(3),upper(3)
+        do j = lower(2),upper(2)
+        do i = lower(1),upper(1)
+            if (var1%array3(i,j,k) == value) then
+                var1%array3(i,j,k) = var2%array3(i,j,k)
+            endif
+        enddo
+        enddo
+        enddo
+    case (4)
+        do l = lower(4),upper(4)
+        do k = lower(3),upper(3)
+        do j = lower(2),upper(2)
+        do i = lower(1),upper(1)
+            if (var1%array4(i,j,k,l) == value) then
+                var1%array4(i,j,k,l) = var2%array4(i,j,k,l)
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+    case (5)
+        do m = lower(5),upper(5)
+        do l = lower(4),upper(4)
+        do k = lower(3),upper(3)
+        do j = lower(2),upper(2)
+        do i = lower(1),upper(1)
+            if (var1%array5(i,j,k,l,m) == value) then
+                var1%array5(i,j,k,l,m) = var2%array5(i,j,k,l,m)
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+    case (6)
+        do n = lower(6),upper(6)
+        do m = lower(5),upper(5)
+        do l = lower(4),upper(4)
+        do k = lower(3),upper(3)
+        do j = lower(2),upper(2)
+        do i = lower(1),upper(1)
+            if (var1%array6(i,j,k,l,m,n) == value) then
+                var1%array6(i,j,k,l,m,n) = var2%array6(i,j,k,l,m,n)
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_var_replace_value
+!===================================================================================================
+#endif
+!
+!===================================================================================================
+!  subroutine PreProcessToInterpOrUpdate
+!---------------------------------------------------------------------------------------------------
+subroutine PreProcessToInterpOrUpdate ( parent, child,              &
+                                        nb_child, ub_child,         &
+                                        lb_child, lb_parent,        &
+                                        s_child,  s_parent,         &
+                                        ds_child, ds_parent, nbdim, interp )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), pointer, intent(in)   :: parent       !< Variable on the parent grid
+    type(Agrif_Variable), pointer, intent(in)   :: child        !< Variable on the child grid
+    integer, dimension(6), intent(out)          :: nb_child     !< Number of cells on the child grid
+    integer, dimension(6), intent(out)          :: ub_child     !< Upper bound on the child grid
+    integer, dimension(6), intent(out)          :: lb_child     !< Lower bound on the child grid
+    integer, dimension(6), intent(out)          :: lb_parent    !< Lower bound on the parent grid
+    real, dimension(6),    intent(out)          :: s_child      !< Child  grid position (s_root = 0)
+    real, dimension(6),    intent(out)          :: s_parent     !< Parent grid position (s_root = 0)
+    real, dimension(6),    intent(out)          :: ds_child     !< Child  grid dx (ds_root = 1)
+    real, dimension(6),    intent(out)          :: ds_parent    !< Parent grid dx (ds_root = 1)
+    integer,               intent(out)          :: nbdim        !< Number of dimensions
+    logical,               intent(in)           :: interp       !< .true. if preprocess for interpolation, \n
+                                                                !! .false. if preprocess for update
+!
+    type(Agrif_Variable), pointer :: root_var
+    type(Agrif_Grid),     pointer :: Agrif_Child_Gr
+    type(Agrif_Grid),     pointer :: Agrif_Parent_Gr
+    integer :: n
+!
+    Agrif_Child_Gr  => Agrif_Curgrid
+    Agrif_Parent_Gr => Agrif_Curgrid % parent
+!
+    root_var => child % root_var
+!
+!   Number of dimensions of the current grid
+    nbdim = root_var % nbdim
+!
+    do n = 1,nbdim
+!
+!       Value of interptab(n) can be either x,y,z or N for a no space dimension
+        select case(root_var % interptab(n))
+!
+        case('x')
+!
+            lb_child(n)  = root_var % point(n)
+            lb_parent(n) = root_var % point(n)
+            nb_child(n)  = Agrif_Child_Gr % nb(1)
+            s_child(n)   = Agrif_Child_Gr  % Agrif_x(1)
+            s_parent(n)  = Agrif_Parent_Gr % Agrif_x(1)
+            ds_child(n)  = Agrif_Child_Gr  % Agrif_dx(1)
+            ds_parent(n) = Agrif_Parent_Gr % Agrif_dx(1)
+!
+            if ( root_var % posvar(n) == 1 ) then
+                ub_child(n) = lb_child(n) + Agrif_Child_Gr % nb(1)
+            else
+                ub_child(n) = lb_child(n) + Agrif_Child_Gr % nb(1) - 1
+                s_child(n)  = s_child(n)  + 0.5*ds_child(n)
+                s_parent(n) = s_parent(n) + 0.5*ds_parent(n)
+            endif
+!
+        case('y')
+!
+            lb_child(n)  = root_var % point(n)
+            lb_parent(n) = root_var % point(n)
+            nb_child(n)  = Agrif_Child_Gr % nb(2)
+            s_child(n)   = Agrif_Child_Gr  % Agrif_x(2)
+            s_parent(n)  = Agrif_Parent_Gr % Agrif_x(2)
+            ds_child(n)  = Agrif_Child_Gr  % Agrif_dx(2)
+            ds_parent(n) = Agrif_Parent_Gr % Agrif_dx(2)
+!
+            if (root_var % posvar(n)==1) then
+                ub_child(n) = lb_child(n) + Agrif_Child_Gr % nb(2)
+            else
+                ub_child(n) = lb_child(n) + Agrif_Child_Gr % nb(2) - 1
+                s_child(n)  = s_child(n)  + 0.5*ds_child(n)
+                s_parent(n) = s_parent(n) + 0.5*ds_parent(n)
+            endif
+!
+        case('z')
+!
+            lb_child(n)  = root_var % point(n)
+            lb_parent(n) = root_var % point(n)
+            nb_child(n)  = Agrif_Child_Gr % nb(3)
+            s_child(n)   = Agrif_Child_Gr  % Agrif_x(3)
+            s_parent(n)  = Agrif_Parent_Gr % Agrif_x(3)
+            ds_child(n)  = Agrif_Child_Gr  % Agrif_dx(3)
+            ds_parent(n) = Agrif_Parent_Gr % Agrif_dx(3)
+!
+            if (root_var % posvar(n)==1) then
+                ub_child(n) = lb_child(n) + Agrif_Child_Gr % nb(3)
+            else
+                ub_child(n) = lb_child(n) + Agrif_Child_Gr % nb(3) - 1
+                s_child(n)  = s_child(n)  + 0.5*ds_child(n)
+                s_parent(n) = s_parent(n) + 0.5*ds_parent(n)
+            endif
+!
+        case('N') ! No space dimension
+!
+!       The next coefficients are calculated in order to do a simple copy of
+!       values of the grid variable when the interpolation routine is
+!       called for this dimension.
+!
+            if (interp) then
+                call Agrif_get_var_bounds(parent, lb_child(n), ub_child(n), n)
+                nb_child(n) = parent % ub(n) - parent % lb(n)
+            else
+                call Agrif_get_var_bounds(child,  lb_child(n), ub_child(n), n)
+                nb_child(n) = child % ub(n) - child % lb(n)
+            endif
+!
+!           No interpolation but only a copy of the values of the grid variable
+            lb_parent(n) = lb_child(n)
+            s_child(n)   = 0.
+            s_parent(n)  = 0.
+            ds_child(n)  = 1.
+            ds_parent(n) = 1.
+!
+        end select
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine PreProcessToInterpOrUpdate
+!===================================================================================================
+!
+#if defined AGRIF_MPI
+!===================================================================================================
+!   subroutine Agrif_GetLocalBoundaries
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_GetLocalBoundaries ( tab1, tab2, coord, lb, ub, deb, fin )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in)     ::  tab1
+    integer, intent(in)     ::  tab2
+    integer, intent(in)     ::  coord
+    integer, intent(in)     ::  lb, ub
+    integer, intent(out)    ::  deb, fin
+!
+    integer :: imin, imax
+    integer :: i1, i2
+!
+    call Agrif_InvLoc(lb, AGRIF_ProcRank, coord, imin)
+    call Agrif_InvLoc(ub, AGRIF_ProcRank, coord, imax)
+!
+    if ( imin > tab2 ) then
+        i1 = imax - imin
+    else
+        i1 = max(tab1 - imin,0)
+    endif
+!
+    if (imax < tab1) then
+        i2 = -(imax - imin)
+    else
+        i2 = min(tab2 - imax,0)
+    endif
+!
+    deb = lb + i1
+    fin = ub + i2
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_GetLocalBoundaries
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_GlobalToLocalBounds
+!
+!> For a global index located on the current processor, tabarray gives the corresponding local index
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_GlobalToLocalBounds ( locbounds, lb_var, ub_var, lb_glob, ub_glob,    &
+                                       coords, nbdim, rank, member )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(nbdim,2,2), intent(out)   :: locbounds   !< Local values of \b lb_glob and \b ub_glob
+    integer, dimension(nbdim),     intent(in)    :: lb_var      !< Local lower boundary on the current processor
+    integer, dimension(nbdim),     intent(in)    :: ub_var      !< Local upper boundary on the current processor
+    integer, dimension(nbdim),     intent(in)    :: lb_glob     !< Global lower boundary
+    integer, dimension(nbdim),     intent(in)    :: ub_glob     !< Global upper boundary
+    integer, dimension(nbdim),     intent(in)    :: coords
+    integer,                       intent(in)    :: nbdim       !< Dimension of the array
+    integer,                       intent(in)    :: rank        !< Rank of the processor
+    logical,                       intent(out)   :: member
+!
+    integer     :: i, i1, k
+    integer     :: nbloc(nbdim)
+!
+    locbounds(:,1,:) =  HUGE(1)
+    locbounds(:,2,:) = -HUGE(1)
+!
+    nbloc = 0
+!
+    do i = 1,nbdim
+!
+        call Agrif_InvLoc(lb_var(i), rank, coords(i), i1)
+!
+        do k = lb_glob(i)+lb_var(i)-i1,ub_glob(i)+lb_var(i)-i1
+!
+            if ( (k >= lb_var(i)) .AND. (k <= ub_var(i)) ) then
+                nbloc(i) = 1
+                locbounds(i,1,1) = min(locbounds(i,1,1),k-lb_var(i)+i1)
+                locbounds(i,2,1) = max(locbounds(i,2,1),k-lb_var(i)+i1)
+
+                locbounds(i,1,2) = min(locbounds(i,1,2),k)
+                locbounds(i,2,2) = max(locbounds(i,2,2),k)
+            endif
+        enddo
+    enddo
+
+    member = ( sum(nbloc) == nbdim )
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_GlobalToLocalBounds
+!===================================================================================================
+#endif
+!
+end module Agrif_Arrays
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modbc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modbc.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modbc.F90	(revision 9987)
@@ -0,0 +1,649 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Boundary.
+!>
+!> Contains subroutines to calculate the boundary conditions on the child grids from their
+!> parent grids.
+!
+module Agrif_Boundary
+!
+    use Agrif_Interpolation
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_CorrectVariable
+!
+!> subroutine to calculate the boundary conditions on a fine grid
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_CorrectVariable ( parent, child, pweight, weight, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), pointer       :: parent       !< Variable on the parent grid
+    type(Agrif_Variable), pointer       :: child        !< Variable on the child grid
+    logical                             :: pweight      !< Indicates if weight is used for the time interpolation
+    real                                :: weight       !< Coefficient for the time interpolation
+    procedure()                         :: procname     !< Data recovery procedure
+!
+    type(Agrif_Grid)    , pointer :: Agrif_Child_Gr, Agrif_Parent_Gr
+    type(Agrif_Variable), pointer :: root_var   ! Variable on the root grid
+    integer                :: nbdim  ! Number of dimensions of the grid variable
+    integer                :: n
+    integer, dimension(6)  :: lb_child       ! Index of the first point inside the domain for
+                                                !    the child grid variable
+    integer, dimension(6)  :: lb_parent      ! Index of the first point inside the domain for
+                                                !    the parent grid variable
+    integer, dimension(6)  :: ub_child     !  Upper bound on the child grid
+    integer, dimension(6)  :: nb_child       ! Number of cells for child
+    integer, dimension(6)  :: posvartab_child   ! Position of the variable on the cell
+    integer, dimension(6)  :: loctab_child      ! Indicates if the child grid has a common border
+                                                !    with the root grid
+    real, dimension(6)     :: s_child, s_parent   ! Positions of the parent and child grids
+    real, dimension(6)     :: ds_child, ds_parent ! Space steps of the parent and child grids
+!
+    call PreProcessToInterpOrUpdate( parent,   child,       &
+                                     nb_child, ub_child,    &
+                                     lb_child, lb_parent,   &
+                                      s_child,  s_parent,   &
+                                     ds_child, ds_parent, nbdim, interp=.true.)
+    root_var => child % root_var
+    Agrif_Child_Gr => Agrif_Curgrid
+    Agrif_Parent_Gr => Agrif_Curgrid % parent
+!
+    loctab_child(:) = 0
+    posvartab_child(1:nbdim) = root_var % posvar(1:nbdim)
+!
+    do n = 1,nbdim
+!
+        select case(root_var % interptab(n))
+!
+        case('x') ! x DIMENSION
+!
+            if (Agrif_Curgrid % NearRootBorder(1))      loctab_child(n) = -1
+            if (Agrif_Curgrid % DistantRootBorder(1))   loctab_child(n) = -2
+            if ((Agrif_Curgrid % NearRootBorder(1)) .AND. &
+                (Agrif_Curgrid % DistantRootBorder(1))) loctab_child(n) = -3
+!
+        case('y') ! y DIMENSION
+!
+            if (Agrif_Curgrid % NearRootBorder(2))      loctab_child(n) = -1
+            if (Agrif_Curgrid % DistantRootBorder(2))   loctab_child(n) = -2
+            if ((Agrif_Curgrid % NearRootBorder(2)) .AND. &
+                (Agrif_Curgrid % DistantRootBorder(2))) loctab_child(n) = -3
+!
+        case('z') ! z DIMENSION
+!
+            if (Agrif_Curgrid % NearRootBorder(3))      loctab_child(n) = -1
+            if (Agrif_Curgrid % DistantRootBorder(3))   loctab_child(n) = -2
+            if ((Agrif_Curgrid % NearRootBorder(3)) .AND. &
+                (Agrif_Curgrid % DistantRootBorder(3))) loctab_child(n) = -3
+!
+        case('N') ! No space DIMENSION
+!
+            posvartab_child(n) = 1
+            loctab_child(n) = -3
+!
+        end select
+!
+    enddo
+!
+    call Agrif_Correctnd(parent, child, pweight, weight,                    &
+                         lb_child(1:nbdim), lb_parent(1:nbdim),             &
+                         nb_child(1:nbdim), posvartab_child(1:nbdim),       &
+                         loctab_child(1:nbdim),                             &
+                         s_child(1:nbdim), s_parent(1:nbdim),               &
+                         ds_child(1:nbdim),ds_parent(1:nbdim), nbdim, procname )
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CorrectVariable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Correctnd
+!
+!> calculates the boundary conditions for a nD grid variable on a fine grid by using
+!> a space and time interpolations; it is called by the #Agrif_CorrectVariable procedure
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Correctnd ( parent, child, pweight, weight,                        &
+                             pttab_child, pttab_Parent,                             &
+                             nbtab_Child, posvartab_Child, loctab_Child,            &
+                             s_Child, s_Parent, ds_Child, ds_Parent,                &
+                             nbdim, procname )
+!---------------------------------------------------------------------------------------------------
+#if defined AGRIF_MPI
+    include 'mpif.h'
+#endif
+!
+    TYPE(Agrif_Variable), pointer       :: parent       !< Variable on the parent grid
+    TYPE(Agrif_Variable), pointer       :: child        !< Variable on the child grid
+    LOGICAL                             :: pweight      !< Indicates if weight is used for the temporal interpolation
+    REAL                                :: weight       !< Coefficient for the temporal interpolation
+    INTEGER, DIMENSION(nbdim)   :: pttab_child          !< Index of the first point inside the domain for the parent grid variable
+    INTEGER, DIMENSION(nbdim)   :: pttab_Parent         !< Index of the first point inside the domain for the child  grid variable
+    INTEGER, DIMENSION(nbdim)   :: nbtab_Child          !< Number of cells of the child grid
+    INTEGER, DIMENSION(nbdim)   :: posvartab_Child      !< Position of the grid variable (1 or 2)
+    INTEGER, DIMENSION(nbdim)   :: loctab_Child         !< Indicates if the child grid has a common border with the root grid
+    REAL   , DIMENSION(nbdim)   :: s_Child,  s_Parent   !< Positions of the parent and child grids
+    REAL   , DIMENSION(nbdim)   :: ds_Child, ds_Parent  !< Space steps of the parent and child grids
+    INTEGER                             :: nbdim        !< Number of dimensions of the grid variable
+    procedure()                         :: procname     !< Data recovery procedure
+!
+    INTEGER,DIMENSION(6)                :: type_interp     ! Type of interpolation (linear, spline,...)
+    INTEGER,DIMENSION(6,6)              :: type_interp_bc  ! Type of interpolation (linear, spline,...)
+    INTEGER,DIMENSION(nbdim,2,2)        :: childarray
+    INTEGER,DIMENSION(nbdim,2)          :: lubglob
+    INTEGER                             :: kindex       ! Index used for safeguard and time interpolation
+    INTEGER,DIMENSION(nbdim,2,2)        :: indtab       ! Arrays indicating the limits of the child
+    INTEGER,DIMENSION(nbdim,2,2)        :: indtruetab   ! grid variable where boundary conditions are
+    INTEGER,DIMENSION(nbdim,2,2,nbdim)  :: ptres,ptres2 ! calculated
+    INTEGER,DIMENSION(nbdim)            :: coords
+    INTEGER                             :: i, nb, ndir
+    INTEGER                             :: n, sizetab
+    INTEGER                             :: ibeg, iend
+    INTEGER                             :: i1,i2,j1,j2,k1,k2,l1,l2,m1,m2,n1,n2
+    REAL                                :: c1t,c2t      ! Coefficients for the time interpolation (c2t=1-c1t)
+#if defined AGRIF_MPI
+!
+    INTEGER, DIMENSION(nbdim)   :: lower, upper
+    INTEGER, DIMENSION(nbdim)   :: ltab, utab
+!
+#endif
+!
+    type_interp_bc = child % root_var % type_interp_bc
+    coords         = child % root_var % coords
+!
+    ibeg = child % bcinf
+    iend = child % bcsup
+!
+    indtab(1:nbdim,2,1) = pttab_child(1:nbdim) + nbtab_child(1:nbdim) + ibeg
+    indtab(1:nbdim,2,2) = indtab(1:nbdim,2,1) + ( iend - ibeg )
+
+    indtab(1:nbdim,1,1) = pttab_child(1:nbdim) - iend
+    indtab(1:nbdim,1,2) = pttab_child(1:nbdim) - ibeg
+
+    WHERE (posvartab_child(1:nbdim) == 2)
+        indtab(1:nbdim,1,1) = indtab(1:nbdim,1,1) - 1
+        indtab(1:nbdim,1,2) = indtab(1:nbdim,1,2) - 1
+    END WHERE
+!
+    call Agrif_get_var_global_bounds(child,lubglob,nbdim)
+!
+    indtruetab(1:nbdim,1,1) = max(indtab(1:nbdim,1,1), lubglob(1:nbdim,1))
+    indtruetab(1:nbdim,1,2) = max(indtab(1:nbdim,1,2), lubglob(1:nbdim,1))
+    indtruetab(1:nbdim,2,1) = min(indtab(1:nbdim,2,1), lubglob(1:nbdim,2))
+    indtruetab(1:nbdim,2,2) = min(indtab(1:nbdim,2,2), lubglob(1:nbdim,2))
+!
+    do nb = 1,nbdim
+        do ndir = 1,2
+!
+            if (loctab_child(nb) /= (-ndir) .AND. loctab_child(nb) /= -3) then
+!
+                do n = 1,2
+                    ptres(nb,n,ndir,nb) = indtruetab(nb,ndir,n)
+                enddo
+!
+                do i = 1,nbdim
+!
+                    if (i /= nb) then
+!
+                        if (loctab_child(i) == -1 .OR. loctab_child(i) == -3) then
+                            ptres(i,1,ndir,nb) = pttab_child(i)
+                        else
+                            ptres(i,1,ndir,nb) = indtruetab(i,1,1)
+                        endif
+                        if (loctab_child(i) == -2 .OR. loctab_child(i) == -3) then
+                            if (posvartab_child(i) == 1) then
+                                ptres(i,2,ndir,nb) = pttab_child(i) + nbtab_child(i)
+                            else
+                                ptres(i,2,ndir,nb) = pttab_child(i) + nbtab_child(i) - 1
+                            endif
+                        else
+                            ptres(i,2,ndir,nb) = indtruetab(i,2,2)
+                        endif
+!
+                    endif
+!
+                enddo
+
+!
+#if defined AGRIF_MPI
+                call Agrif_get_var_bounds_array(child,lower,upper,nbdim)
+
+                do i = 1,nbdim
+!
+                    Call Agrif_GetLocalBoundaries(ptres(i,1,ndir,nb), ptres(i,2,ndir,nb),  &
+                                                  coords(i), lower(i), upper(i), ltab(i), utab(i) )
+                    ptres2(i,1,ndir,nb) = max(ltab(i),lower(i))
+                    ptres2(i,2,ndir,nb) = min(utab(i),upper(i))
+                    if ((i == nb) .AND. (ndir == 1)) then
+                        ptres2(i,2,ndir,nb) = max(utab(i),lower(i))
+                    elseif ((i == nb) .AND. (ndir == 2)) then
+                        ptres2(i,1,ndir,nb) = min(ltab(i),upper(i))
+                    endif
+!
+                enddo
+#else
+                ptres2(:,:,ndir,nb) = ptres(:,:,ndir,nb)
+#endif
+            endif
+!
+        enddo   ! ndir = 1,2
+    enddo       ! nb = 1,nbdim
+!
+    if ( child % interpIndex /= Agrif_Curgrid % parent % ngridstep .OR. &
+         child % Interpolationshouldbemade ) then
+!
+!     Space interpolation
+!
+        kindex = 1
+!
+        do nb = 1,nbdim
+
+            type_interp = type_interp_bc(nb,:)
+
+            do ndir = 1,2
+!
+                if (loctab_child(nb) /= (-ndir) .AND. loctab_child(nb) /= -3) then
+!
+                    call Agrif_InterpnD(type_interp, parent, child,             &
+                                        ptres(1:nbdim,1,ndir,nb),               &
+                                        ptres(1:nbdim,2,ndir,nb),               &
+                                        pttab_child(1:nbdim),                   &
+                                        pttab_Parent(1:nbdim),                  &
+                                        s_Child(1:nbdim), s_Parent(1:nbdim),    &
+                                        ds_Child(1:nbdim),ds_Parent(1:nbdim),   &
+                                        NULL(), .FALSE., nbdim,                 &
+                                        childarray,                             &
+                                        child%memberin(nb,ndir), .TRUE., procname, coords(nb), ndir)
+
+                    child % childarray(1:nbdim,:,:,nb,ndir) = childarray
+
+                    if (.not. child%interpolationshouldbemade) then
+!
+!                       Safeguard of the values of the grid variable (at times n and n+1 on the parent grid)
+!
+                        sizetab = 1
+                        do i = 1,nbdim
+                            sizetab = sizetab * (ptres2(i,2,ndir,nb)-ptres2(i,1,ndir,nb)+1)
+                        enddo
+
+                        call saveAfterInterp(child,ptres2(:,:,ndir,nb),kindex,sizetab,nbdim)
+!
+                    endif
+!
+                endif
+!
+            enddo   ! ndir = 1,2
+        enddo       ! nb = 1,nbdim
+!
+        child % interpIndex = Agrif_Curgrid % parent % ngridstep
+!
+    endif
+!
+    if (.not. child%interpolationshouldbemade) then
+!
+!       Calculation of the coefficients c1t and c2t for the temporary interpolation
+!
+        if (pweight) then
+            c1t = weight
+        else
+            c1t = (REAL(Agrif_Nbstepint()) + 1.) / Agrif_Rhot()
+        endif
+        c2t = 1. - c1t
+!
+!       Time interpolation
+!
+        kindex = 1
+!
+        do nb = 1,nbdim
+            do ndir = 1,2
+                if (loctab_child(nb) /= (-ndir) .AND. loctab_child(nb) /= -3) then
+                    Call timeInterpolation(child,ptres2(:,:,ndir,nb),kindex,c1t,c2t,nbdim)
+                endif
+            enddo
+        enddo
+!
+    endif
+!
+    do nb = 1,nbdim
+    do ndir = 1,2
+        if ( (loctab_child(nb) /= (-ndir)) .AND. (loctab_child(nb) /= -3) .AND. child%memberin(nb,ndir) ) then
+            select case(nbdim)
+            case(1)
+                i1 = child % childarray(1,1,2,nb,ndir)
+                i2 = child % childarray(1,2,2,nb,ndir)
+
+                call procname(parray1(i1:i2),                               &
+                              i1,i2, .FALSE.,coords(nb),ndir)
+            case(2)
+                i1 = child % childarray(1,1,2,nb,ndir)
+                i2 = child % childarray(1,2,2,nb,ndir)
+                j1 = child % childarray(2,1,2,nb,ndir)
+                j2 = child % childarray(2,2,2,nb,ndir)
+
+                call procname(parray2(i1:i2,j1:j2),                         &
+                              i1,i2,j1,j2, .FALSE.,coords(nb),ndir)
+            case(3)
+                i1 = child % childarray(1,1,2,nb,ndir)
+                i2 = child % childarray(1,2,2,nb,ndir)
+                j1 = child % childarray(2,1,2,nb,ndir)
+                j2 = child % childarray(2,2,2,nb,ndir)
+                k1 = child % childarray(3,1,2,nb,ndir)
+                k2 = child % childarray(3,2,2,nb,ndir)
+
+                call procname(parray3(i1:i2,j1:j2,k1:k2),                   &
+                              i1,i2,j1,j2,k1,k2, .FALSE.,coords(nb),ndir)
+            case(4)
+                i1 = child % childarray(1,1,2,nb,ndir)
+                i2 = child % childarray(1,2,2,nb,ndir)
+                j1 = child % childarray(2,1,2,nb,ndir)
+                j2 = child % childarray(2,2,2,nb,ndir)
+                k1 = child % childarray(3,1,2,nb,ndir)
+                k2 = child % childarray(3,2,2,nb,ndir)
+                l1 = child % childarray(4,1,2,nb,ndir)
+                l2 = child % childarray(4,2,2,nb,ndir)
+
+                call procname(parray4(i1:i2,j1:j2,k1:k2,l1:l2),             &
+                              i1,i2,j1,j2,k1,k2,l1,l2, .FALSE.,coords(nb),ndir)
+            case(5)
+                i1 = child % childarray(1,1,2,nb,ndir)
+                i2 = child % childarray(1,2,2,nb,ndir)
+                j1 = child % childarray(2,1,2,nb,ndir)
+                j2 = child % childarray(2,2,2,nb,ndir)
+                k1 = child % childarray(3,1,2,nb,ndir)
+                k2 = child % childarray(3,2,2,nb,ndir)
+                l1 = child % childarray(4,1,2,nb,ndir)
+                l2 = child % childarray(4,2,2,nb,ndir)
+                m1 = child % childarray(5,1,2,nb,ndir)
+                m2 = child % childarray(5,2,2,nb,ndir)
+
+                call procname(parray5(i1:i2,j1:j2,k1:k2,l1:l2,m1:m2),       &
+                              i1,i2,j1,j2,k1,k2,l1,l2,m1,m2, .FALSE.,coords(nb),ndir)
+            case(6)
+                i1 = child % childarray(1,1,2,nb,ndir)
+                i2 = child % childarray(1,2,2,nb,ndir)
+                j1 = child % childarray(2,1,2,nb,ndir)
+                j2 = child % childarray(2,2,2,nb,ndir)
+                k1 = child % childarray(3,1,2,nb,ndir)
+                k2 = child % childarray(3,2,2,nb,ndir)
+                l1 = child % childarray(4,1,2,nb,ndir)
+                l2 = child % childarray(4,2,2,nb,ndir)
+                m1 = child % childarray(5,1,2,nb,ndir)
+                m2 = child % childarray(5,2,2,nb,ndir)
+                n1 = child % childarray(6,1,2,nb,ndir)
+                n2 = child % childarray(6,2,2,nb,ndir)
+
+                call procname(parray6(i1:i2,j1:j2,k1:k2,l1:l2,m1:m2,n1:n2), &
+                              i1,i2,j1,j2,k1,k2,l1,l2,m1,m2,n1,n2, .FALSE.,coords(nb),ndir)
+            end select
+        endif
+    enddo
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Correctnd
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine saveAfterInterp
+!
+!> saves the values of the grid variable on the fine grid after the space interpolation
+!---------------------------------------------------------------------------------------------------
+subroutine saveAfterInterp ( child_var, bounds, kindex, newsize, nbdim )
+!---------------------------------------------------------------------------------------------------
+    TYPE (Agrif_Variable),       INTENT(inout)  :: child_var !< The fine grid variable
+    INTEGER, DIMENSION(nbdim,2), INTENT(in)     :: bounds
+    INTEGER,                     INTENT(inout)  :: kindex    !< Index indicating where this safeguard
+                                                             !<     is done on the fine grid
+    INTEGER,                     INTENT(in)     :: newsize
+    INTEGER,                     INTENT(in)     :: nbdim
+!
+    INTEGER     :: ir,jr,kr,lr,mr,nr
+!
+!    Allocation of the array oldvalues2d
+!
+    if (newsize .LE. 0) return
+!
+    Call Agrif_Checksize(child_var,kindex+newsize)
+
+    if (child_var % interpIndex /= Agrif_Curgrid % parent % ngridstep ) then
+        child_var % oldvalues2d(1,kindex:kindex+newsize-1) = &
+        child_var % oldvalues2d(2,kindex:kindex+newsize-1)
+    endif
+
+    SELECT CASE (nbdim)
+    CASE (1)
+!CDIR ALTCODE
+        do ir = bounds(1,1), bounds(1,2)
+            child_var % oldvalues2d(2,kindex) = parray1(ir)
+            kindex = kindex + 1
+        enddo
+!
+    CASE (2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            child_var % oldvalues2d(2,kindex) = parray2(ir,jr)
+            kindex = kindex + 1
+        enddo
+        enddo
+!
+    CASE (3)
+        do kr = bounds(3,1),bounds(3,2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            child_var % oldvalues2d(2,kindex) = parray3(ir,jr,kr)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+!
+      CASE (4)
+        do lr = bounds(4,1),bounds(4,2)
+        do kr = bounds(3,1),bounds(3,2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            child_var % oldvalues2d(2,kindex) = parray4(ir,jr,kr,lr)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+        enddo
+!
+    CASE (5)
+        do mr = bounds(5,1),bounds(5,2)
+        do lr = bounds(4,1),bounds(4,2)
+        do kr = bounds(3,1),bounds(3,2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            child_var % oldvalues2d(2,kindex) = parray5(ir,jr,kr,lr,mr)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+!
+    CASE (6)
+        do nr = bounds(6,1),bounds(6,2)
+        do mr = bounds(5,1),bounds(5,2)
+        do lr = bounds(4,1),bounds(4,2)
+        do kr = bounds(3,1),bounds(3,2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            child_var % oldvalues2d(2,kindex) = parray6(ir,jr,kr,lr,mr,nr)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+    END SELECT
+!---------------------------------------------------------------------------------------------------
+end subroutine saveAfterInterp
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine timeInterpolation
+!
+!> subroutine for a linear time interpolation on the child grid
+!---------------------------------------------------------------------------------------------------
+subroutine timeInterpolation ( child_var, bounds, kindex, c1t, c2t, nbdim )
+!---------------------------------------------------------------------------------------------------
+    TYPE (Agrif_Variable)       :: child_var !< The fine grid variable
+    INTEGER, DIMENSION(nbdim,2) :: bounds
+    INTEGER                     :: kindex    !< Index indicating the values of the fine grid got
+                                             !<    before and after the space interpolation and
+                                             !<    used for the time interpolation
+    REAL                        :: c1t, c2t  !< Coefficients for the time interpolation (c2t=1-c1t)
+    INTEGER                     :: nbdim
+!
+    INTEGER :: ir,jr,kr,lr,mr,nr
+!
+    SELECT CASE (nbdim)
+    CASE (1)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            parray1(ir) = c2t*child_var % oldvalues2d(1,kindex) + &
+                                      c1t*child_var % oldvalues2d(2,kindex)
+            kindex = kindex + 1
+        enddo
+!
+    CASE (2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            parray2(ir,jr) = c2t*child_var % oldvalues2d(1,kindex) + &
+                                         c1t*child_var % oldvalues2d(2,kindex)
+            kindex = kindex + 1
+        enddo
+        enddo
+!
+    CASE (3)
+        do kr = bounds(3,1),bounds(3,2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            parray3(ir,jr,kr) = c2t*child_var % oldvalues2d(1,kindex) + &
+                                            c1t*child_var % oldvalues2d(2,kindex)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+!
+    CASE (4)
+        do lr = bounds(4,1),bounds(4,2)
+        do kr = bounds(3,1),bounds(3,2)
+        do jr = bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir = bounds(1,1),bounds(1,2)
+            parray4(ir,jr,kr,lr) = c2t*child_var % oldvalues2d(1,kindex) + &
+                                               c1t*child_var % oldvalues2d(2,kindex)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+        enddo
+!
+    CASE (5)
+        do mr=bounds(5,1),bounds(5,2)
+        do lr=bounds(4,1),bounds(4,2)
+        do kr=bounds(3,1),bounds(3,2)
+        do jr=bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir=bounds(1,1),bounds(1,2)
+            parray5(ir,jr,kr,lr,mr) = c2t*child_var % oldvalues2d(1,kindex) + &
+                                                  c1t*child_var % oldvalues2d(2,kindex)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+!
+    CASE (6)
+        do nr=bounds(6,1),bounds(6,2)
+        do mr=bounds(5,1),bounds(5,2)
+        do lr=bounds(4,1),bounds(4,2)
+        do kr=bounds(3,1),bounds(3,2)
+        do jr=bounds(2,1),bounds(2,2)
+!CDIR ALTCODE
+        do ir=bounds(1,1),bounds(1,2)
+            parray6(ir,jr,kr,lr,mr,nr) = c2t*child_var % oldvalues2d(1,kindex) + &
+                                                     c1t*child_var % oldvalues2d(2,kindex)
+            kindex = kindex + 1
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+    END SELECT
+!---------------------------------------------------------------------------------------------------
+end subroutine timeInterpolation
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Checksize
+!
+!> subroutine used in the saveAfterInterp procedure to allocate the oldvalues2d array
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Checksize ( child_var, newsize )
+!---------------------------------------------------------------------------------------------------
+    TYPE (Agrif_Variable), INTENT(inout)  :: child_var !< The fine grid variable
+    INTEGER              , INTENT(in)     :: newsize   !< Size of the domains where the boundary
+                                                       !<    conditions are calculated
+!
+    REAL, DIMENSION(:,:), Allocatable :: tempoldvalues ! Temporary array
+!
+    if (.NOT. associated(child_var % oldvalues2d)) then
+!
+        allocate(child_var % oldvalues2d(2,newsize))
+        child_var % oldvalues2d = 0.
+!
+    else
+!
+        if (SIZE(child_var % oldvalues2d,2) < newsize) then
+!
+            allocate(tempoldvalues(2,SIZE(child_var % oldvalues2d,2)))
+            tempoldvalues = child_var % oldvalues2d
+            deallocate(child_var % oldvalues2d)
+            allocate(  child_var % oldvalues2d(2,newsize))
+            child_var % oldvalues2d = 0.
+            child_var % oldvalues2d(:,1:SIZE(tempoldvalues,2)) = tempoldvalues(:,:)
+            deallocate(tempoldvalues)
+!
+        endif
+!
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Checksize
+!===================================================================================================
+!
+end module Agrif_Boundary
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modbcfunction.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modbcfunction.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modbcfunction.F90	(revision 9987)
@@ -0,0 +1,680 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+!
+!> Module Agrif_BcFunction.
+!
+module Agrif_BcFunction
+!
+!     Modules used:
+!
+    use Agrif_Boundary
+    use Agrif_Update
+    use Agrif_Save
+!
+    implicit none
+!
+    interface Agrif_Set_Parent
+        module procedure Agrif_Set_Parent_int,      &
+                         Agrif_Set_Parent_real4,    &
+                         Agrif_Set_Parent_real8
+    end interface
+!
+    interface Agrif_Save_Forrestore
+        module procedure Agrif_Save_Forrestore0d,   &
+                         Agrif_Save_Forrestore2d,   &
+                         Agrif_Save_Forrestore3d,   &
+                         Agrif_Save_Forrestore4d
+    end interface
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_Set_parent_int
+!
+!> To set the TYPE of the variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_parent_int(tabvarsindic,value)
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in)     :: tabvarsindic !< indice of the variable in tabvars
+    integer, intent(in)     :: value        !< input value
+!
+    Agrif_Curgrid % parent % tabvars_i(tabvarsindic) % iarray0 = value
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_parent_int
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_parent_real4
+!---------------------------------------------------------------------------------------------------
+!> To set the TYPE of the variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_parent_real4 ( tabvarsindic, value )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in)     :: tabvarsindic !< indice of the variable in tabvars
+    real(kind=4),intent(in) :: value        !< input value
+!
+    Agrif_Curgrid % parent % tabvars_r(tabvarsindic) % array0 = value
+    Agrif_Curgrid % parent % tabvars_r(tabvarsindic) % sarray0 = value
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_parent_real4
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_parent_real8
+!---------------------------------------------------------------------------------------------------
+!> To set the TYPE of the variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_parent_real8 ( tabvarsindic, value )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in)     :: tabvarsindic !< indice of the variable in tabvars
+    real(kind=8),intent(in) :: value        !< input value
+!
+    Agrif_Curgrid % parent % tabvars_r(tabvarsindic) % darray0 = value
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_parent_real8
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_bc
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_bc ( tabvarsindic, bcinfsup, Interpolationshouldbemade )
+!---------------------------------------------------------------------------------------------------
+    integer,               intent(in)   :: tabvarsindic !< indice of the variable in tabvars
+    integer, dimension(2), intent(in)   :: bcinfsup     !< bcinfsup
+    logical, optional,     intent(in)   :: Interpolationshouldbemade !< interpolation should be made
+!
+    integer                         :: indic ! indice of the variable in tabvars
+    type(Agrif_Variable),  pointer  :: var
+!
+    indic = Agrif_Curgrid % tabvars_i(tabvarsindic) % iarray0
+!
+    if (indic <= 0) then
+        var => Agrif_Search_Variable(Agrif_Curgrid,-indic)
+    else
+        print*,"Agrif_Set_bc : warning indic >= 0 !!!"
+        var => Agrif_Curgrid % tabvars(indic)
+    endif
+
+    if (.not.associated(var)) return ! Grand mother grid case
+!
+    if ( Agrif_Curgrid % fixedrank /= 0 ) then
+        if ( .not.associated(var % oldvalues2D) ) then
+            allocate(var % oldvalues2D(2,1))
+            var % interpIndex = -1
+            var % oldvalues2D = 0.
+        endif
+        if ( present(Interpolationshouldbemade) ) then
+            var % Interpolationshouldbemade = Interpolationshouldbemade
+        endif
+    endif
+!
+    var % bcinf = bcinfsup(1)
+    var % bcsup = bcinfsup(2)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_bc
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_interp
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_interp ( tabvarsindic, interp, interp1, interp2, interp3 , interp4)
+!---------------------------------------------------------------------------------------------------
+    integer,           intent(in)   :: tabvarsindic !< indice of the variable in tabvars
+    integer, optional, intent(in)   :: interp, interp1, interp2, interp3, interp4
+!
+    integer                         :: indic ! indice of the variable in tabvars
+    type(Agrif_Variable), pointer   :: var
+!
+    indic = Agrif_Curgrid % tabvars_i(tabvarsindic) % iarray0
+!
+    if (indic <= 0) then
+        var => Agrif_Search_Variable(Agrif_Mygrid,-indic)
+    else
+        print*,"Agrif_Set_interp : warning indic >= 0 !!!"
+        var => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    var % type_interp = Agrif_Constant
+!
+    if (present(interp))    var % type_interp    = interp
+    if (present(interp1))   var % type_interp(1) = interp1
+    if (present(interp2))   var % type_interp(2) = interp2
+    if (present(interp3))   var % type_interp(3) = interp3
+    if (present(interp4))   var % type_interp(4) = interp4
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_interp
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_bcinterp
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_bcinterp ( tabvarsindic, interp,   interp1,  interp2,  interp3, interp4, &
+                                              interp11, interp12, interp21, interp22 )
+!---------------------------------------------------------------------------------------------------
+    INTEGER,           intent(in)   :: tabvarsindic !< indice of the variable in tabvars
+    INTEGER, OPTIONAL, intent(in)   :: interp,   interp1,  interp2,  interp3, interp4
+    INTEGER, OPTIONAL, intent(in)   :: interp11, interp12, interp21, interp22
+!
+    INTEGER                         :: indic ! indice of the variable in tabvars
+    TYPE(Agrif_Variable), pointer   :: var
+!
+    indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+!
+    if (indic <= 0) then
+        var => Agrif_Search_Variable(Agrif_Mygrid,-indic)
+    else
+        print*,"Agrif_Set_bcinterp : warning indic >= 0 !!!"
+        var => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    var % type_interp_bc = Agrif_Constant
+!
+    if (present(interp))    var % type_interp_bc      = interp
+    if (present(interp1))   var % type_interp_bc(:,1) = interp1
+    if (present(interp11))  var % type_interp_bc(1,1) = interp11
+    if (present(interp12))  var % type_interp_bc(1,2) = interp12
+    if (present(interp2))   var % type_interp_bc(:,2) = interp2
+    if (present(interp21))  var % type_interp_bc(2,1) = interp21
+    if (present(interp22))  var % type_interp_bc(2,2) = interp22
+    if (present(interp3))   var % type_interp_bc(:,3) = interp3
+    if (present(interp4))   var % type_interp_bc(:,4) = interp4
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_bcinterp
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_UpdateType
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_UpdateType ( tabvarsindic, update,  update1, update2, &
+                                                update3, update4, update5 )
+!---------------------------------------------------------------------------------------------------
+    INTEGER,           intent(in) :: tabvarsindic     !< indice of the variable in tabvars
+    INTEGER, OPTIONAL, intent(in) :: update, update1, update2, update3, update4, update5
+!
+    INTEGER                         :: indic ! indice of the variable in tabvars
+    type(Agrif_Variable),  pointer  :: root_var
+!
+    indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+!
+    if (indic <= 0) then
+        root_var => Agrif_Search_Variable(Agrif_Mygrid,-indic)
+    else
+        print*,"Agrif_Set_UpdateType : warning indic >= 0 !!!"
+        root_var => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    root_var % type_update = Agrif_Update_Copy
+    if (present(update))    root_var % type_update    = update
+    if (present(update1))   root_var % type_update(1) = update1
+    if (present(update2))   root_var % type_update(2) = update2
+    if (present(update3))   root_var % type_update(3) = update3
+    if (present(update4))   root_var % type_update(4) = update4
+    if (present(update5))   root_var % type_update(5) = update5
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_UpdateType
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_restore
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_restore ( tabvarsindic )
+!---------------------------------------------------------------------------------------------------
+    INTEGER, intent(in) :: tabvarsindic     !< indice of the variable in tabvars
+!
+    INTEGER :: indic  !  indice of the variable in tabvars
+!
+    indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+!
+    Agrif_Mygrid%tabvars(indic) % restore = .TRUE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_restore
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Init_variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Init_variable ( tabvarsindic, procname )
+!---------------------------------------------------------------------------------------------------
+    INTEGER, intent(in)  :: tabvarsindic     !< indice of the variable in tabvars
+    procedure()          :: procname         !< Data recovery procedure
+!
+    if ( Agrif_Curgrid%level <= 0 ) return
+!
+    call Agrif_Interp_variable(tabvarsindic, procname)
+    call Agrif_Bc_variable(tabvarsindic, procname, 1.)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Init_variable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Bc_variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Bc_variable ( tabvarsindic, procname, calledweight )
+!---------------------------------------------------------------------------------------------------
+    integer,        intent(in) :: tabvarsindic     !< indice of the variable in tabvars
+    procedure()                :: procname
+    real, optional, intent(in) :: calledweight
+!
+    real    :: weight
+    logical :: pweight
+    integer :: indic
+    integer :: nbdim
+    type(Agrif_Variable), pointer :: root_var
+    type(Agrif_Variable), pointer :: parent_var
+    type(Agrif_Variable), pointer :: child_var
+    type(Agrif_Variable), pointer :: child_tmp      ! Temporary variable on the child grid
+!
+    if ( Agrif_Curgrid%level <= 0 ) return
+!
+    indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+!
+    if ( present(calledweight) ) then
+        weight  = calledweight
+        pweight = .true.
+    else
+        weight  = 0.
+        pweight = .false.
+    endif
+!
+    if (indic <= 0) then
+        child_var  => Agrif_Search_Variable(Agrif_Curgrid,-indic)
+        parent_var => child_var % parent_var
+        root_var   => child_var % root_var
+    else
+        print*,"Agrif_Bc_variable : warning indic >= 0 !!!"
+        child_var  => Agrif_Curgrid % tabvars(indic)
+        parent_var => Agrif_Curgrid % parent % tabvars(indic)
+        root_var   => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    nbdim = root_var % nbdim
+!
+    select case( nbdim )
+    case(1)
+        allocate(parray1(child_var%lb(1):child_var%ub(1)))
+    case(2)
+        allocate(parray2(child_var%lb(1):child_var%ub(1), &
+                         child_var%lb(2):child_var%ub(2) ))
+    case(3)
+        allocate(parray3(child_var%lb(1):child_var%ub(1), &
+                         child_var%lb(2):child_var%ub(2), &
+                         child_var%lb(3):child_var%ub(3) ))
+    case(4)
+        allocate(parray4(child_var%lb(1):child_var%ub(1), &
+                         child_var%lb(2):child_var%ub(2), &
+                         child_var%lb(3):child_var%ub(3), &
+                         child_var%lb(4):child_var%ub(4) ))
+    case(5)
+        allocate(parray5(child_var%lb(1):child_var%ub(1), &
+                         child_var%lb(2):child_var%ub(2), &
+                         child_var%lb(3):child_var%ub(3), &
+                         child_var%lb(4):child_var%ub(4), &
+                         child_var%lb(5):child_var%ub(5) ))
+    case(6)
+        allocate(parray6(child_var%lb(1):child_var%ub(1), &
+                         child_var%lb(2):child_var%ub(2), &
+                         child_var%lb(3):child_var%ub(3), &
+                         child_var%lb(4):child_var%ub(4), &
+                         child_var%lb(5):child_var%ub(5), &
+                         child_var%lb(6):child_var%ub(6) ))
+    end select
+!
+!   Create temporary child variable
+    allocate(child_tmp)
+!
+    child_tmp % root_var => root_var
+    child_tmp % oldvalues2D => child_var % oldvalues2D
+!
+!   Index indicating if a space interpolation is necessary
+    child_tmp % interpIndex =  child_var % interpIndex
+    child_tmp % list_interp => child_var % list_interp
+    child_tmp % Interpolationshouldbemade = child_var % Interpolationshouldbemade
+!
+    child_tmp % point = child_var % point
+    child_tmp % lb = child_var % lb
+    child_tmp % ub = child_var % ub
+!
+    child_tmp % bcinf = child_var % bcinf
+    child_tmp % bcsup = child_var % bcsup
+!
+    child_tmp % childarray = child_var % childarray
+    child_tmp % memberin   = child_var % memberin
+!
+    call Agrif_CorrectVariable(parent_var, child_tmp, pweight, weight, procname)
+!
+    child_var % childarray = child_tmp % childarray
+    child_var % memberin   = child_tmp % memberin
+!
+    child_var % oldvalues2D => child_tmp % oldvalues2D
+    child_var % list_interp => child_tmp % list_interp
+!
+    child_var % interpIndex = child_tmp % interpIndex
+!
+    deallocate(child_tmp)
+!
+    select case( nbdim )
+        case(1); deallocate(parray1)
+        case(2); deallocate(parray2)
+        case(3); deallocate(parray3)
+        case(4); deallocate(parray4)
+        case(5); deallocate(parray5)
+        case(6); deallocate(parray6)
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Bc_variable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_variable ( tabvarsindic, procname )
+!---------------------------------------------------------------------------------------------------
+    integer,     intent(in)     :: tabvarsindic     !< indice of the variable in tabvars
+    procedure()                 :: procname         !< Data recovery procedure
+!
+    integer :: nbdim
+    integer :: indic  ! indice of the variable in tabvars
+    logical :: torestore
+    type(Agrif_Variable), pointer   :: root_var
+    type(Agrif_Variable), pointer   :: parent_var       ! Variable on the parent grid
+    type(Agrif_Variable), pointer   :: child_var        ! Variable on the parent grid
+    type(Agrif_Variable), pointer   :: child_tmp        ! Temporary variable on the child grid
+!
+    if ( Agrif_Curgrid%level <= 0 ) return
+!
+    indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+!
+    if (indic <= 0) then
+        child_var  => Agrif_Search_Variable(Agrif_Curgrid,-indic)
+        parent_var => child_var % parent_var
+        root_var   => child_var % root_var
+    else
+        print*,"Agrif_Interp_variable : warning indic >= 0 !!!"
+        child_var  => Agrif_Curgrid % tabvars(indic)
+        parent_var => Agrif_Curgrid % parent % tabvars(indic)
+        root_var   => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    nbdim     = root_var % nbdim
+    torestore = root_var % restore
+!
+    allocate(child_tmp)
+!
+    child_tmp % root_var => root_var
+    child_tmp % nbdim = root_var % nbdim
+    child_tmp % point = child_var % point
+    child_tmp % lb = child_var % lb
+    child_tmp % ub = child_var % ub
+    child_tmp % interpIndex =  child_var % interpIndex
+    child_tmp % list_interp => child_var % list_interp
+    child_tmp % Interpolationshouldbemade = child_var % Interpolationshouldbemade
+!
+    if ( torestore ) then
+        select case( nbdim )
+        case(1)
+            parray1 = child_var % array1
+            child_tmp % restore1D => child_var % restore1D
+        case(2)
+            parray2 = child_var % array2
+            child_tmp % restore2D => child_var % restore2D
+        case(3)
+            parray3 = child_var % array3
+            child_tmp % restore3D => child_var % restore3D
+        case(4)
+            parray4 = child_var % array4
+            child_tmp % restore4D => child_var % restore4D
+        case(5)
+            parray5 = child_var % array5
+            child_tmp % restore5D => child_var % restore5D
+        case(6)
+            parray6 = child_var % array6
+            child_tmp % restore6D => child_var % restore6D
+        end select
+    endif
+!
+    call Agrif_InterpVariable(parent_var, child_tmp, torestore, procname)
+!
+    child_var % list_interp => child_tmp % list_interp
+!
+    deallocate(child_tmp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_variable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Update_Variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_Variable ( tabvarsindic, procname, &
+                                   locupdate, locupdate1, locupdate2, locupdate3, locupdate4 )
+!---------------------------------------------------------------------------------------------------
+    integer,               intent(in)           :: tabvarsindic     !< Indice of the variable in tabvars
+    procedure()                                 :: procname         !< Data recovery procedure
+    integer, dimension(2), intent(in), optional :: locupdate
+    integer, dimension(2), intent(in), optional :: locupdate1
+    integer, dimension(2), intent(in), optional :: locupdate2
+    integer, dimension(2), intent(in), optional :: locupdate3
+    integer, dimension(2), intent(in), optional :: locupdate4
+!---------------------------------------------------------------------------------------------------
+    integer :: indic
+    integer :: nbdim
+    integer, dimension(6)           :: updateinf    ! First positions where interpolations are calculated
+    integer, dimension(6)           :: updatesup    ! Last  positions where interpolations are calculated
+    type(Agrif_Variable), pointer   :: root_var
+    type(Agrif_Variable), pointer   :: parent_var
+    type(Agrif_Variable), pointer   :: child_var
+!
+    if ( Agrif_Root() .AND. (.not.agrif_coarse) ) return
+    if (agrif_curgrid%grand_mother_grid) return
+!
+    indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+!
+    if (indic <= 0) then
+        child_var  => Agrif_Search_Variable(Agrif_Curgrid, -indic)
+        parent_var => child_var % parent_var
+
+        if (.not.associated(parent_var)) then
+          ! can occur during the first update of Agrif_Coarsegrid (if any)
+          parent_var => Agrif_Search_Variable(Agrif_Curgrid % parent, -indic)
+          child_var % parent_var => parent_var
+        endif
+
+        root_var   => child_var % root_var
+    else
+        print*,"Agrif_Update_Variable : warning indic >= 0 !!!"
+        root_var   => Agrif_Mygrid  % tabvars(indic)
+        child_var  => Agrif_Curgrid % tabvars(indic)
+        parent_var => Agrif_Curgrid % parent % tabvars(indic)
+    endif
+!
+    nbdim = root_var % nbdim
+!
+    updateinf = -99
+    updatesup = -99
+!
+    if ( present(locupdate) ) then
+        updateinf(1:nbdim) = locupdate(1)
+        updatesup(1:nbdim) = locupdate(2)
+    endif
+!
+    if ( present(locupdate1) ) then
+        updateinf(1) = locupdate1(1)
+        updatesup(1) = locupdate1(2)
+    endif
+!
+    if ( present(locupdate2) ) then
+        updateinf(2) = locupdate2(1)
+        updatesup(2) = locupdate2(2)
+    endif
+
+    if ( present(locupdate3) ) then
+        updateinf(3) = locupdate3(1)
+        updatesup(3) = locupdate3(2)
+    endif
+
+    if ( present(locupdate4) ) then
+        updateinf(4) = locupdate4(1)
+        updatesup(4) = locupdate4(2)
+    endif
+!
+    call Agrif_UpdateVariable( parent_var, child_var, updateinf, updatesup, procname )
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_Variable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Save_ForRestore0D
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Save_ForRestore0D ( tabvarsindic0, tabvarsindic )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: tabvarsindic0, tabvarsindic
+!
+    type(Agrif_Variable), pointer   :: root_var, save_var
+    integer :: nbdim
+!
+    root_var => Agrif_Mygrid % tabvars(tabvarsindic0)
+    save_var => Agrif_Curgrid % tabvars(tabvarsindic0)
+    nbdim =  root_var % nbdim
+!
+    select case(nbdim)
+        case(2); call Agrif_Save_ForRestore2D(save_var % array2, tabvarsindic)
+        case(3); call Agrif_Save_ForRestore3D(save_var % array3, tabvarsindic)
+        case(4); call Agrif_Save_ForRestore4D(save_var % array4, tabvarsindic)
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Save_ForRestore0D
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Save_ForRestore2D
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Save_ForRestore2D ( q, tabvarsindic )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(:,:), intent(in)        :: q
+    integer,              intent(in)        :: tabvarsindic
+!
+    type(Agrif_Variable),  pointer  :: root_var, save_var
+    integer                         :: indic
+!
+    indic = tabvarsindic
+    if (tabvarsindic >= 0) then
+        if (Agrif_Curgrid%tabvars_i(tabvarsindic)%nbdim == 0) then
+            indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+        endif
+    endif
+!
+    if (indic <= 0) then
+        save_var => Agrif_Search_Variable(Agrif_Curgrid,-indic)
+        root_var => Agrif_Search_Variable(Agrif_Mygrid,-indic)
+    else
+        save_var => Agrif_Curgrid % tabvars(indic)
+        root_var => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    if ( .not.allocated(save_var%array2) ) then
+        allocate(save_var%array2(save_var%lb(1):save_var%ub(1),  &
+                                 save_var%lb(2):save_var%ub(2)))
+    endif
+!
+    save_var % array2  = q
+    root_var % restore = .true.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Save_ForRestore2D
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Save_ForRestore3D
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Save_ForRestore3D ( q, tabvarsindic )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(:,:,:), intent(in)      :: q
+    integer,                intent(in)      :: tabvarsindic
+!
+    type(Agrif_Variable),  pointer  :: root_var, save_var
+    integer                         :: indic
+!
+    indic = tabvarsindic
+    if (tabvarsindic >= 0) then
+        if (Agrif_Curgrid%tabvars_i(tabvarsindic)%nbdim == 0) then
+            indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+        endif
+    endif
+!
+    if (indic <= 0) then
+        save_var => Agrif_Search_Variable(Agrif_Curgrid,-indic)
+        root_var => Agrif_Search_Variable(Agrif_Mygrid,-indic)
+    else
+        save_var => Agrif_Curgrid % tabvars(indic)
+        root_var => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    if ( .not.allocated(save_var%array3) ) then
+        allocate(save_var%array3(save_var%lb(1):save_var%ub(1), &
+                                 save_var%lb(2):save_var%ub(2), &
+                                 save_var%lb(3):save_var%ub(3)))
+    endif
+!
+    save_var % array3  = q
+    root_var % restore = .true.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Save_ForRestore3D
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Save_ForRestore4D
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Save_ForRestore4D ( q, tabvarsindic )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(:,:,:,:), intent(in)    :: q
+    integer,                  intent(in)    :: tabvarsindic
+!
+    type(Agrif_Variable),  pointer  :: root_var, save_var
+    integer                         :: indic
+!
+    indic = tabvarsindic
+    if (tabvarsindic >= 0) then
+        if (Agrif_Curgrid%tabvars_i(tabvarsindic)%nbdim == 0) then
+            indic = Agrif_Curgrid%tabvars_i(tabvarsindic)%iarray0
+        endif
+    endif
+!
+    if (indic <= 0) then
+        save_var => Agrif_Search_Variable(Agrif_Curgrid,-indic)
+        root_var => Agrif_Search_Variable(Agrif_Mygrid,-indic)
+    else
+        save_var => Agrif_Curgrid % tabvars(indic)
+        root_var => Agrif_Mygrid % tabvars(indic)
+    endif
+!
+    if (.not.allocated(save_var%array4)) then
+        allocate(save_var%array4(save_var%lb(1):save_var%ub(1),&
+                                 save_var%lb(2):save_var%ub(2),&
+                                 save_var%lb(3):save_var%ub(3),&
+                                 save_var%lb(4):save_var%ub(4)))
+    endif
+!
+    save_var % array4  = q
+    root_var % restore = .true.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Save_ForRestore4D
+!===================================================================================================
+!
+end module Agrif_BcFunction
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modcluster.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modcluster.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modcluster.F90	(revision 9987)
@@ -0,0 +1,1277 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Clustering
+!>
+!> Contains subroutines to create and initialize the grid hierarchy from the
+!> AGRIF_FixedGrids.in file.
+!
+module Agrif_Clustering
+!
+    use Agrif_CurgridFunctions
+    use Agrif_Init_Vars
+    use Agrif_Save
+!
+    implicit none
+!
+    abstract interface
+        subroutine init_proc()
+        end subroutine init_proc
+    end interface
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_Cluster_All
+!
+!> Subroutine for the clustering. A temporary grid hierarchy, pointed by parent_rect, is created.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Cluster_All ( g, parent_rect )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid)     , pointer   :: g        !< Pointer on the current grid
+    TYPE(Agrif_Rectangle), pointer   :: parent_rect
+!
+    TYPE(Agrif_LRectangle), pointer  :: parcours
+    TYPE(Agrif_Grid)      , pointer  :: newgrid
+    REAL                             :: g_eps
+    INTEGER                          :: i
+!
+    g_eps = huge(1.)
+    do i = 1,Agrif_Probdim
+        g_eps = min(g_eps, g % Agrif_dx(i))
+    enddo
+!
+    g_eps = g_eps / 100.
+!
+!   Necessary condition for clustering
+    do i = 1,Agrif_Probdim
+        if ( g%Agrif_dx(i)/Agrif_coeffref(i) < (Agrif_mind(i)-g_eps)) return
+    enddo
+!
+    nullify(parent_rect%childgrids)
+!
+    call Agrif_ClusterGridnD(g,parent_rect)
+!
+    parcours => parent_rect % childgrids
+!
+    do while ( associated(parcours) )
+!
+!       Newgrid is created. It is a copy of a fine grid created previously by clustering.
+        allocate(newgrid)
+!
+        do i = 1,Agrif_Probdim
+            newgrid % nb(i) = (parcours % r % imax(i) - parcours % r % imin(i)) * Agrif_Coeffref(i)
+            newgrid % Agrif_x(i)  = g % Agrif_x(i)  + (parcours % r % imin(i) -1) * g%Agrif_dx(i)
+            newgrid % Agrif_dx(i) = g % Agrif_dx(i) / Agrif_Coeffref(i)
+        enddo
+!
+        if ( Agrif_Probdim == 1 ) then
+            allocate(newgrid%tabpoint1D(newgrid%nb(1)+1))
+            newgrid%tabpoint1D = 0
+        endif
+!
+        if ( Agrif_Probdim == 2 ) then
+            allocate(newgrid%tabpoint2D(newgrid%nb(1)+1, newgrid%nb(2)+1))
+            newgrid%tabpoint2D = 0
+        endif
+!
+        if ( Agrif_Probdim == 3 ) then
+            allocate(newgrid%tabpoint3D(newgrid%nb(1)+1, newgrid%nb(2)+1, newgrid%nb(3)+1))
+            newgrid%tabpoint3D = 0
+        endif
+!
+!       Points detection on newgrid
+        call Agrif_TabpointsnD(Agrif_mygrid,newgrid)
+!
+!       recursive call to Agrif_Cluster_All
+        call Agrif_Cluster_All(newgrid, parcours % r)
+!
+        parcours => parcours % next
+!
+        if ( Agrif_Probdim == 1 ) deallocate(newgrid%tabpoint1D)
+        if ( Agrif_Probdim == 2 ) deallocate(newgrid%tabpoint2D)
+        if ( Agrif_Probdim == 3 ) deallocate(newgrid%tabpoint3D)
+!
+        deallocate(newgrid)
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Cluster_All
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_TabpointsnD
+!
+!> Copy on newgrid of points detected on the grid hierarchy pointed by g.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_TabpointsnD ( g, newgrid )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid), pointer   :: g, newgrid
+!
+    TYPE(Agrif_PGrid), pointer  :: parcours
+!
+    REAL                  :: g_eps, newgrid_eps, eps
+    REAL   , DIMENSION(3) :: newmin, newmax
+    REAL   , DIMENSION(3) :: gmin, gmax
+    REAL   , DIMENSION(3) :: xmin
+    INTEGER, DIMENSION(3) :: igmin, inewmin
+    INTEGER, DIMENSION(3) :: inewmax
+    INTEGER               :: i,  j,  k
+    INTEGER               :: i0, j0, k0
+!
+    parcours => g % child_list % first
+!
+    do while( associated(parcours) )
+        call Agrif_TabpointsnD(parcours%gr,newgrid)
+        parcours => parcours % next
+    enddo
+!
+    g_eps = 10.
+    newgrid_eps = 10.
+!
+    do i = 1,Agrif_probdim
+        g_eps = min( g_eps , g % Agrif_dx(i) )
+        newgrid_eps = min(newgrid_eps,newgrid%Agrif_dx(i))
+    enddo
+!
+    eps = min(g_eps,newgrid_eps)/100.
+!
+    do i = 1,Agrif_probdim
+!
+         if ( newgrid%Agrif_dx(i) < (g%Agrif_dx(i)-eps) ) return
+!
+         gmin(i) = g%Agrif_x(i)
+         gmax(i) = g%Agrif_x(i) + g%nb(i) * g%Agrif_dx(i)
+!
+         newmin(i) = newgrid%Agrif_x(i)
+         newmax(i) = newgrid%Agrif_x(i) + newgrid%nb(i) * newgrid%Agrif_dx(i)
+!
+         if (gmax(i) < newmin(i)) return
+         if (gmin(i) > newmax(i)) return
+!
+         inewmin(i) = 1 - floor(-(max(gmin(i),newmin(i))-newmin(i)) / newgrid%Agrif_dx(i))
+!
+         xmin(i) = newgrid%Agrif_x(i) + (inewmin(i)-1)*newgrid%Agrif_dx(i)
+!
+         igmin(i) = 1 + nint((xmin(i)-gmin(i))/g%Agrif_dx(i))
+!
+         inewmax(i) = 1 + int(   (min(gmax(i),newmax(i))-newmin(i)) / newgrid%Agrif_dx(i))
+!
+    enddo
+!
+    if ( Agrif_probdim == 1 ) then
+        i0 = igmin(1)
+        do i = inewmin(1),inewmax(1)
+            newgrid%tabpoint1D(i) = max( newgrid%tabpoint1D(i), g%tabpoint1D(i0) )
+        enddo
+        i0 = i0 + int(newgrid%Agrif_dx(1)/g%Agrif_dx(1))
+    endif
+!
+    if ( Agrif_probdim == 2 ) then
+        i0 = igmin(1)
+        do i = inewmin(1),inewmax(1)
+            j0 = igmin(2)
+            do j = inewmin(2),inewmax(2)
+                newgrid%tabpoint2D(i,j) = max( newgrid%tabpoint2D(i,j), g%tabpoint2D(i0,j0) )
+                j0 = j0 + int(newgrid%Agrif_dx(2)/g%Agrif_dx(2))
+            enddo
+            i0 = i0 + int(newgrid%Agrif_dx(1)/g%Agrif_dx(1))
+        enddo
+    endif
+!
+    if ( Agrif_probdim == 3 ) then
+        i0 = igmin(1)
+        do i = inewmin(1),inewmax(1)
+            j0 = igmin(2)
+            do j = inewmin(2),inewmax(2)
+                k0 = igmin(3)
+                do k = inewmin(3),inewmax(3)
+                    newgrid%tabpoint3D(i,j,k) = max( newgrid%tabpoint3D(i,j,k), g%tabpoint3D(i0,j0,k0))
+                    k0 = k0 + int(newgrid%Agrif_dx(3)/g%Agrif_dx(3))
+                enddo
+                j0 = j0 + int(newgrid%Agrif_dx(2)/g%Agrif_dx(2))
+            enddo
+            i0 = i0 + int(newgrid%Agrif_dx(1)/g%Agrif_dx(1))
+        enddo
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_TabpointsnD
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_ClusterGridnD
+!
+!> Clustering on the grid pointed by g.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_ClusterGridnD ( g, parent_rect )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid)     , pointer  :: g          !< Pointer on the current grid
+    TYPE(Agrif_Rectangle), pointer  :: parent_rect
+!
+    TYPE(Agrif_Rectangle) :: newrect
+    TYPE(Agrif_Variable_i)  :: newflag
+!
+    INTEGER               :: i,j,k
+    INTEGER, DIMENSION(3) :: sx
+    INTEGER               :: bufferwidth,flagpoints
+    INTEGER               :: n1,n2,m1,m2,o1,o2
+!
+    bufferwidth = int(Agrif_Minwidth/5.)
+!
+    do i = 1,Agrif_probdim
+        sx(i) = g % nb(i) + 1
+    enddo
+!
+    if ( Agrif_probdim == 1 ) then
+        allocate(newflag%iarray1(sx(1)))
+        newflag%iarray1 = 0
+    endif
+    if ( Agrif_probdim == 2 ) then
+        allocate(newflag%iarray2(sx(1),sx(2)))
+        newflag%iarray2 = 0
+    endif
+    if ( Agrif_probdim == 3 ) then
+        allocate(newflag%iarray3(sx(1),sx(2),sx(3)))
+        newflag%iarray3 = 0
+    endif
+!
+    flagpoints = 0
+!
+    if ( bufferwidth>0 ) then
+!
+        if ( Agrif_probdim == 1 ) then
+            do i = bufferwidth,sx(1)-bufferwidth+1
+                if (g % tabpoint1D(i) == 1) then
+                    m1 = i - bufferwidth + 1
+                    m2 = i + bufferwidth - 1
+                    flagpoints = flagpoints + 1
+                    newflag%iarray1(m1:m2) = 1
+                endif
+            enddo
+        endif
+!
+        if ( Agrif_probdim == 2 ) then
+            do i = bufferwidth,sx(1)-bufferwidth+1
+            do j = bufferwidth,sx(2)-bufferwidth+1
+                if (g % tabpoint2D(i,j) == 1) then
+                    n1 = j - bufferwidth + 1
+                    n2 = j + bufferwidth - 1
+                    m1 = i - bufferwidth + 1
+                    m2 = i + bufferwidth - 1
+                    flagpoints = flagpoints + 1
+                    newflag%iarray2(m1:m2,n1:n2) = 1
+                endif
+            enddo
+            enddo
+        endif
+!
+        if ( Agrif_probdim == 3 ) then
+            do i = bufferwidth,sx(1)-bufferwidth+1
+            do j = bufferwidth,sx(2)-bufferwidth+1
+            do k = bufferwidth,sx(3)-bufferwidth+1
+                if (g % tabpoint3D(i,j,k) == 1) then
+                    o1 = k - bufferwidth + 1
+                    o2 = k + bufferwidth - 1
+                    n1 = j - bufferwidth + 1
+                    n2 = j + bufferwidth - 1
+                    m1 = i - bufferwidth + 1
+                    m2 = i + bufferwidth - 1
+                    flagpoints = flagpoints + 1
+                    newflag%iarray3(m1:m2,n1:n2,o1:o2) = 1
+                endif
+            enddo
+            enddo
+            enddo
+        endif
+!
+    else
+!
+        flagpoints = 1
+        if ( Agrif_probdim == 1 ) newflag%iarray1 = g % tabpoint1D
+        if ( Agrif_probdim == 2 ) newflag%iarray2 = g % tabpoint2D
+        if ( Agrif_probdim == 3 ) newflag%iarray3 = g % tabpoint3D
+!
+    endif
+!
+    if (flagpoints == 0) then
+        if ( Agrif_probdim == 1 ) deallocate(newflag%iarray1)
+        if ( Agrif_probdim == 2 ) deallocate(newflag%iarray2)
+        if ( Agrif_probdim == 3 ) deallocate(newflag%iarray3)
+        return
+    endif
+!
+    do i = 1 , Agrif_probdim
+        newrect % imin(i) = 1
+        newrect % imax(i) = sx(i)
+    enddo
+!
+    call Agrif_Clusternd(newflag,parent_rect%childgrids,newrect)
+!
+    if ( Agrif_probdim == 1 ) deallocate(newflag%iarray1)
+    if ( Agrif_probdim == 2 ) deallocate(newflag%iarray2)
+    if ( Agrif_probdim == 3 ) deallocate(newflag%iarray3)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_ClusterGridnD
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_ClusternD
+!
+!> Clustering on the grid pointed by oldB.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Clusternd ( flag, boxlib, oldB )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Variable_i)            :: flag
+    TYPE(Agrif_LRectangle), pointer :: boxlib
+    TYPE(Agrif_Rectangle)           :: oldB
+!
+    TYPE(Agrif_LRectangle),pointer :: tempbox,parcbox,parcbox2
+    TYPE(Agrif_Rectangle) :: newB,newB2
+    INTEGER :: i,j,k
+    INTEGER, DIMENSION(:), allocatable :: i_sig, j_sig, k_sig
+    INTEGER, DIMENSION(3) :: ipu,ipl
+    INTEGER, DIMENSION(3) :: istr,islice
+    REAL :: cureff, neweff
+    INTEGER :: ValMax,ValSum,TailleTab
+    INTEGER :: nbpoints,nbpointsflag
+    LOGICAL :: test
+!
+                              allocate( i_sig(oldB%imin(1):oldB%imax(1)) )
+    if ( Agrif_probdim >= 2 ) allocate( j_sig(oldB%imin(2):oldB%imax(2)) )
+    if ( Agrif_probdim == 3 ) allocate( k_sig(oldB%imin(3):oldB%imax(3)) )
+!
+    test = .FALSE.
+    do i = 1,Agrif_probdim
+        test = test .OR. ( (oldB%imax(i)-oldB%imin(i)+1) <  Agrif_Minwidth)
+    enddo
+    if ( test ) return
+!
+    if ( Agrif_probdim == 1 ) i_sig = flag%iarray1
+    if ( Agrif_probdim == 2 ) then
+        do i = oldB%imin(1),oldB%imax(1)
+            i_sig(i) = SUM(flag%iarray2(i, oldB%imin(2):oldB%imax(2)))
+        enddo
+        do j = oldB%imin(2),oldB%imax(2)
+            j_sig(j) = SUM(flag%iarray2(oldB%imin(1):oldB%imax(1),j))
+        enddo
+    endif
+    if ( Agrif_probdim == 3 ) then
+        do i = oldB%imin(1),oldB%imax(1)
+            i_sig(i) = SUM(flag%iarray3(i,oldB%imin(2):oldB%imax(2),    &
+                                          oldB%imin(3):oldB%imax(3)))
+        enddo
+        do j = oldB%imin(2),oldB%imax(2)
+            j_sig(j) = SUM(flag%iarray3(  oldB%imin(1):oldB%imax(1), j, &
+                                          oldB%imin(3):oldB%imax(3)))
+        enddo
+        do k = oldB%imin(3),oldB%imax(3)
+            k_sig(k) = SUM(flag%iarray3(  oldB%imin(1):oldB%imax(1),    &
+                                          oldB%imin(2):oldB%imax(2), k) )
+        enddo
+    endif
+!
+    do i = 1,Agrif_probdim
+        ipl(i) = oldB%imin(i)
+        ipu(i) = oldB%imax(i)
+    enddo
+!
+                              call Agrif_Clusterprune(i_sig,ipl(1),ipu(1))
+    if ( Agrif_probdim >= 2 ) call Agrif_Clusterprune(j_sig,ipl(2),ipu(2))
+    if ( Agrif_probdim == 3 ) call Agrif_Clusterprune(k_sig,ipl(3),ipu(3))
+!
+    test = .TRUE.
+    do i = 1,Agrif_probdim
+        test = test .AND. (ipl(i) == oldB%imin(i))
+        test = test .AND. (ipu(i) == oldB%imax(i))
+    enddo
+
+    if (.NOT. test) then
+        do i = 1 , Agrif_probdim
+            newB%imin(i) = ipl(i)
+            newB%imax(i) = ipu(i)
+        enddo
+!
+        if ( Agrif_probdim == 1 ) nbpoints = SUM(flag%iarray1(newB%imin(1):newB%imax(1)))
+        if ( Agrif_probdim == 2 ) nbpoints = SUM(flag%iarray2(newB%imin(1):newB%imax(1),    &
+                                                              newB%imin(2):newB%imax(2)))
+        if ( Agrif_probdim == 3 ) nbpoints = SUM(flag%iarray3(newB%imin(1):newB%imax(1),    &
+                                                              newB%imin(2):newB%imax(2),    &
+                                                              newB%imin(3):newB%imax(3)))
+!
+        if ( Agrif_probdim == 1 ) TailleTab = (newB%imax(1)-newB%imin(1)+1)
+        if ( Agrif_probdim == 2 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                              (newB%imax(2)-newB%imin(2)+1)
+        if ( Agrif_probdim == 3 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                              (newB%imax(2)-newB%imin(2)+1) * &
+                                              (newB%imax(3)-newB%imin(3)+1)
+        neweff = REAL(nbpoints) / TailleTab
+!
+        if (nbpoints > 0) then
+!
+            if ((neweff > Agrif_efficiency)) then
+                call Agrif_Add_Rectangle(newB,boxlib)
+                return
+            else
+!
+                tempbox => boxlib
+                newB2 = newB
+                call Agrif_Clusternd(flag,boxlib,newB)
+!
+!               Compute new efficiency
+                cureff = neweff
+                parcbox2 => boxlib
+                nbpoints = 0
+                nbpointsflag = 0
+!
+                do while (associated(parcbox2))
+                    if (associated(parcbox2,tempbox)) exit
+                    newB = parcbox2%r
+!
+                    if ( Agrif_probdim == 1 ) Valsum = SUM(flag%iarray1(newB%imin(1):newB%imax(1)))
+                    if ( Agrif_probdim == 2 ) Valsum = SUM(flag%iarray2(newB%imin(1):newB%imax(1), &
+                                                                        newB%imin(2):newB%imax(2)))
+                    if ( Agrif_probdim == 3 ) Valsum = SUM(flag%iarray3(newB%imin(1):newB%imax(1), &
+                                                                        newB%imin(2):newB%imax(2), &
+                                                                        newB%imin(3):newB%imax(3)))
+                    nbpointsflag = nbpointsflag + ValSum
+!
+                    if ( Agrif_probdim == 1 ) TailleTab = (newB%imax(1)-newB%imin(1)+1)
+                    if ( Agrif_probdim == 2 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                                          (newB%imax(2)-newB%imin(2)+1)
+                    if ( Agrif_probdim == 3 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                                          (newB%imax(2)-newB%imin(2)+1) * &
+                                                          (newB%imax(3)-newB%imin(3)+1)
+                    nbpoints = nbpoints + TailleTab
+                    parcbox2 => parcbox2%next
+                enddo
+!
+! coefficient 1.05 avant 1.15 possibilite de laisser choix a l utilisateur
+                if ( REAL(nbpointsflag)/REAL(nbpoints) < (1.0001*cureff)) then
+                    parcbox2 => boxlib
+                    do while (associated(parcbox2))
+                        if (associated(parcbox2,tempbox)) exit
+                        deallocate(parcbox2%r)
+                        parcbox2 => parcbox2%next
+                    enddo
+                    boxlib => tempbox
+                    call Agrif_Add_Rectangle(newB2,boxlib)
+                    return
+                endif
+            endif
+        endif
+        return
+    endif
+!
+    do i = 1,Agrif_Probdim
+        istr(i) = oldB%imax(i)
+        islice(i) = oldB%imin(i)
+    enddo
+!
+                              call Agrif_Clusterslice(i_sig,islice(1),istr(1))
+    if ( Agrif_probdim >= 2 ) call Agrif_Clusterslice(j_sig,islice(2),istr(2))
+    if ( Agrif_probdim == 3 ) call Agrif_Clusterslice(k_sig,islice(3),istr(3))
+!
+    ValSum = 0
+    do i = 1,Agrif_Probdim
+        Valsum = valSum + islice(i)
+    enddo
+!
+    if ( Valsum == -Agrif_Probdim ) then
+        call Agrif_Add_Rectangle(oldB,boxlib)
+        return
+    endif
+!
+    nullify(tempbox)
+    tempbox => boxlib
+    if ( Agrif_probdim == 1 ) cureff = (oldB%imax(1)-oldB%imin(1)+1)
+    if ( Agrif_probdim == 2 ) cureff = (oldB%imax(1)-oldB%imin(1)+1) * &
+                                       (oldB%imax(2)-oldB%imin(2)+1)
+    if ( Agrif_probdim == 3 ) cureff = (oldB%imax(1)-oldB%imin(1)+1) * &
+                                       (oldB%imax(2)-oldB%imin(2)+1) * &
+                                       (oldB%imax(3)-oldB%imin(3)+1)
+    nullify(parcbox)
+!
+    do i = 1,Agrif_Probdim
+        newB%imax(i) = oldB%imax(i)
+        newB%imin(i) = oldB%imin(i)
+    enddo
+!
+    ValMax = 0
+    do i = 1 , Agrif_Probdim
+        ValMax = Max(ValMax,istr(i))
+    enddo
+!
+    if (istr(1) == ValMax ) then
+        newB%imax(1) = islice(1)
+        call Agrif_Add_Rectangle(newB,parcbox)
+        newB%imin(1) = islice(1)+1
+        newB%imax(1) = oldB%imax(1)
+        call Agrif_Add_Rectangle(newB,parcbox)
+    else if ( Agrif_probdim >= 2 ) then
+        if (istr(2) == ValMax ) then
+            newB%imax(2) = islice(2)
+            call Agrif_Add_Rectangle(newB,parcbox)
+            newB%imin(2) = islice(2)+1
+            newB%imax(2) = oldB%imax(2)
+            call Agrif_Add_Rectangle(newB,parcbox)
+        else if ( Agrif_probdim == 3 ) then
+            newB%imax(3) = islice(3)
+            call Agrif_Add_Rectangle(newB,parcbox)
+            newB%imin(3) = islice(3)+1
+            newB%imax(3) = oldB%imax(3)
+            call Agrif_Add_Rectangle(newB,parcbox)
+        endif
+    endif
+!
+    do while ( associated(parcbox) )
+        newB = parcbox%r
+!
+        if ( Agrif_probdim == 1 ) nbpoints = SUM(flag%iarray1(newB%imin(1):newB%imax(1)))
+        if ( Agrif_probdim == 2 ) nbpoints = SUM(flag%iarray2(newB%imin(1):newB%imax(1),    &
+                                                              newB%imin(2):newB%imax(2)))
+        if ( Agrif_probdim == 3 ) nbpoints = SUM(flag%iarray3(newB%imin(1):newB%imax(1),    &
+                                                              newB%imin(2):newB%imax(2),    &
+                                                              newB%imin(3):newB%imax(3)))
+!
+        if ( Agrif_probdim == 1 ) TailleTab = (newB%imax(1)-newB%imin(1)+1)
+        if ( Agrif_probdim == 2 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                              (newB%imax(2)-newB%imin(2)+1)
+        if ( Agrif_probdim == 3 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                              (newB%imax(2)-newB%imin(2)+1) * &
+                                              (newB%imax(3)-newB%imin(3)+1)
+        neweff = REAL(nbpoints) / TailleTab
+!
+        if ( nbpoints > 0 ) then
+!
+            if ( (neweff > Agrif_efficiency)) then
+                call Agrif_Add_Rectangle(newB,boxlib)
+            else
+                tempbox => boxlib
+                newB2 = newB
+                call Agrif_Clusternd(flag,boxlib,newB)
+!
+!               Compute new efficiency
+                cureff = neweff
+                parcbox2 => boxlib
+                nbpoints = 0
+                nbpointsflag = 0
+!
+                do while (associated(parcbox2))
+                    if (associated(parcbox2,tempbox)) exit
+                    newB = parcbox2%r
+!
+                    if ( Agrif_probdim == 1 ) ValSum = SUM(flag%iarray1(newB%imin(1):newB%imax(1)))
+                    if ( Agrif_probdim == 2 ) ValSum = SUM(flag%iarray2(newB%imin(1):newB%imax(1),  &
+                                                                        newB%imin(2):newB%imax(2)))
+                    if ( Agrif_probdim == 3 ) ValSum = SUM(flag%iarray3(newB%imin(1):newB%imax(1),  &
+                                                                        newB%imin(2):newB%imax(2),  &
+                                                                        newB%imin(3):newB%imax(3)))
+                    nbpointsflag = nbpointsflag + ValSum
+!
+                    if ( Agrif_probdim == 1 ) TailleTab = (newB%imax(1)-newB%imin(1)+1)
+                    if ( Agrif_probdim == 2 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                                          (newB%imax(2)-newB%imin(2)+1)
+                    if ( Agrif_probdim == 3 ) TailleTab = (newB%imax(1)-newB%imin(1)+1) * &
+                                                          (newB%imax(2)-newB%imin(2)+1) * &
+                                                          (newB%imax(3)-newB%imin(3)+1)
+                    nbpoints = nbpoints + TailleTab
+                    parcbox2 => parcbox2%next
+                enddo
+!
+                if  ( REAL(nbpointsflag)/REAL(nbpoints) < (1.15*cureff)) then
+                    parcbox2 => boxlib
+                    do while (associated(parcbox2))
+                        if (associated(parcbox2,tempbox)) exit
+                        deallocate(parcbox2%r)
+                        parcbox2 => parcbox2%next
+                    enddo
+                    boxlib => tempbox
+                    call Agrif_Add_Rectangle(newB2,boxlib)
+                endif
+            endif
+        endif
+        parcbox => parcbox%next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Clusternd
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Clusterslice
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Clusterslice ( sig, slice, str )
+!---------------------------------------------------------------------------------------------------
+    INTEGER,                       intent(inout) :: slice
+    INTEGER,                       intent(inout) :: str
+    INTEGER, DIMENSION(slice:str), intent(in)    :: sig
+!
+    INTEGER                         :: ideb, ifin
+    INTEGER                         :: i, t, a, di, ts
+    INTEGER, DIMENSION(slice:str)   :: lap
+!
+    ideb = slice
+    ifin = str
+!
+    if (SIZE(sig) <= 2*Agrif_Minwidth) then
+        str = -1
+        slice = -1
+        return
+    endif
+!
+    t = -1
+    a = -1
+!
+    do i = ideb+Agrif_Minwidth-1,ifin-Agrif_Minwidth
+        if (sig(i) == 0) then
+            if ((i-ideb) < (ifin-i)) then
+                di = i - ideb
+            else
+                di = ifin - i
+            endif
+!
+            if (di > t) then
+                a = i
+                t = di
+            endif
+        endif
+    enddo
+!
+    if (a /= -1) then
+        slice = a
+        str = t
+        return
+    endif
+!
+    t = -1
+    a = -1
+!
+    do i = ideb+1,ifin-1
+        lap(i) = sig(i+1) + sig(i-1) - 2*sig(i)
+    enddo
+!
+    do i = ideb + Agrif_Minwidth-1,ifin-Agrif_Minwidth
+        if ((lap(i+1)*lap(i)) <= 0) then
+            ts = ABS(lap(i+1) - lap(i))
+            if (ts > t) then
+                t = ts
+                a = i
+            endif
+       endif
+    enddo
+!
+    if (a == (ideb + Agrif_Minwidth - 1)) then
+        a = -1
+        t = -1
+    endif
+!
+    slice = a
+    str = t
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Clusterslice
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Clusterprune
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Clusterprune ( sig, pl, pu )
+!---------------------------------------------------------------------------------------------------
+    INTEGER,                   intent(inout)    :: pl, pu
+    INTEGER, DIMENSION(pl:pu), intent(in)       :: sig
+!
+    INTEGER :: ideb, ifin
+    INTEGER :: diff, addl, addu, udist, ldist
+!
+    ideb = pl
+    ifin = pu
+!
+    if (SIZE(sig) <= Agrif_Minwidth) return
+!
+    do while ((sig(pl) == 0) .AND. (pl < ifin))
+        pl = pl + 1
+    enddo
+!
+    do while ((sig(pu) == 0) .AND. (pu > ideb))
+        pu = pu - 1
+    enddo
+!
+    if ( (pu-pl) < Agrif_Minwidth ) then
+        diff = Agrif_Minwidth - (pu - pl + 1)
+        udist = ifin - pu
+        ldist = pl - ideb
+        addl = diff / 2
+        addu = diff - addl
+        if (addu > udist) then
+            addu = udist
+            addl = diff - addu
+        endif
+!
+        if (addl > ldist) then
+            addl = ldist
+            addu = diff - addl
+        endif
+!
+        pu = pu + addu
+        pl = pl - addl
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Clusterprune
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Add_Rectangle
+!
+!> Adds the Agrif_Rectangle R in a list managed by LR.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Add_Rectangle ( R, LR )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Rectangle)           :: R
+    TYPE(Agrif_LRectangle), pointer :: LR
+!
+    TYPE(Agrif_LRectangle), pointer :: newrect
+!
+    integer                         :: i
+!
+    allocate(newrect)
+    allocate(newrect % r)
+!
+    newrect % r = R
+!
+    do i = 1,Agrif_Probdim
+        newrect % r % spaceref(i) = Agrif_Coeffref(i)
+        newrect % r % timeref(i)  = Agrif_Coeffreft(i)
+    enddo
+!
+    newrect % r % number = -1
+    newrect % next => LR
+    LR => newrect
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Add_Rectangle
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Copy_Rectangle
+!
+!> Creates and returns a copy of Agrif_Rectangle R.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Copy_Rectangle ( R, expand ) result( copy )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Rectangle), pointer, intent(in) :: R
+    integer, optional,              intent(in) :: expand
+!
+    TYPE(Agrif_Rectangle), pointer :: copy
+!
+    allocate(copy)
+!
+    copy = R
+    if ( present(expand) ) then
+        copy % imin = copy % imin - expand
+        copy % imax = copy % imax + expand
+    endif
+    copy % childgrids => R % childgrids
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Copy_Rectangle
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Read_Fix_Grd
+!
+!> Creates the grid hierarchy from the reading of the AGRIF_FixedGrids.in file.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Read_Fix_Grd ( parent_rect, j, nunit )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Rectangle), pointer   :: parent_rect !< Pointer on the first grid of the grid hierarchy
+    INTEGER                          :: j          !< Number of the new grid
+    INTEGER                          :: nunit      !< unit associated with file
+!
+    TYPE(Agrif_Rectangle)            :: newrect    ! Pointer on a new grid
+    TYPE(Agrif_LRectangle), pointer  :: parcours   ! Pointer for the recursive procedure
+    TYPE(Agrif_LRectangle), pointer  :: newlrect
+    TYPE(Agrif_LRectangle), pointer  :: end_list
+    INTEGER                          :: i,n        ! for each child grid
+    INTEGER                          :: nb_grids   ! Number of child grids
+!
+!   Reading of the number of child grids
+    read(nunit,*,end=99) nb_grids
+!
+    allocate(end_list)
+!
+    parent_rect % childgrids => end_list
+!
+!   Reading of imin(1),imax(1),imin(2),imax(2),imin(3),imax(3), and space and
+!        time refinement factors for each child grid.
+!   Creation and addition of the new grid to the grid hierarchy.
+!
+    do n = 1,nb_grids
+!
+        allocate(newlrect)
+        newrect % number = j   ! Number of the grid
+!
+        if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) then
+            if (Agrif_Probdim == 3) then
+                read(nunit,*) newrect % imin(1), newrect % imax(1), &
+                              newrect % imin(2), newrect % imax(2), &
+                              newrect % imin(3), newrect % imax(3), &
+                              newrect % spaceref(1), newrect % spaceref(2), newrect % spaceref(3), &
+                              newrect % timeref(1), newrect % timeref(2), newrect % timeref(3)
+            elseif (Agrif_Probdim == 2) then
+                read(nunit,*) newrect % imin(1), newrect % imax(1), &
+                              newrect % imin(2), newrect % imax(2), &
+                              newrect % spaceref(1), newrect % spaceref(2), &
+                              newrect % timeref(1),  newrect % timeref(2)
+            elseif (Agrif_Probdim == 1) then
+                read(nunit,*) newrect % imin(1), newrect % imax(1), &
+                              newrect % spaceref(1), &
+                              newrect % timeref(1)
+            endif
+        else
+            if (Agrif_Probdim == 3) then
+                read(nunit,*) newrect % imin(1), newrect % imax(1), &
+                              newrect % imin(2), newrect % imax(2), &
+                              newrect % imin(3), newrect % imax(3), &
+                              newrect % spaceref(1), newrect % spaceref(2), newrect % spaceref(3), &
+                              newrect % timeref(1)
+            elseif (Agrif_Probdim == 2) then
+                read(nunit,*) newrect % imin(1), newrect % imax(1), &
+                              newrect % imin(2), newrect % imax(2), &
+                              newrect % spaceref(1), newrect % spaceref(2), &
+                              newrect % timeref(1)
+            elseif (Agrif_Probdim == 1) then
+                read(nunit,*) newrect % imin(1), newrect % imax(1), &
+                              newrect % spaceref(1), &
+                              newrect % timeref(1)
+            endif
+!
+            if ( Agrif_probdim >= 2 ) then
+                do i = 2,Agrif_probdim
+                    newrect % timeref(i) = newrect % timeref(1)
+                enddo
+            endif
+!
+        endif
+!
+!       Addition to the grid hierarchy
+!
+        j = j + 1
+        allocate(newlrect%r)
+        newlrect % r = newrect
+        end_list % next => newlrect
+        end_list => end_list % next
+!
+    enddo
+!
+    parent_rect % childgrids => parent_rect % childgrids % next
+    parcours => parent_rect % childgrids
+!
+!   recursive operation to create the grid hierarchy branch by branch
+!
+    do while ( associated(parcours) )
+        call Agrif_Read_Fix_Grd(parcours % r, j, nunit)
+        parcours => parcours % next
+    enddo
+99  continue
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Read_Fix_Grd
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Create_Grids
+!
+!> Creates the grid hierarchy (g) from the one created with the #Agrif_Read_Fix_Grd or
+!! #Agrif_Cluster_All procedures (parent_rect).
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Create_Grids ( parent_grid, parent_rect )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid)     , pointer  :: parent_grid  !< Pointer on the root coarse grid
+    TYPE(Agrif_Rectangle), pointer  :: parent_rect  !< Pointer on the root coarse grid of the grid hierarchy
+                                                    !!   created with the #Agrif_Read_Fix_Grd subroutine
+!
+    TYPE(Agrif_Grid)      , pointer :: child_grid   ! Newly created child grid
+    TYPE(Agrif_PGrid)     , pointer :: child_grid_p
+    TYPE(Agrif_LRectangle), pointer :: child_rect_p
+    type(Agrif_Rectangle),  pointer :: child_rect
+!
+    INTEGER                         :: i
+    INTEGER, save                   :: moving_grid_id = 0
+!
+    child_rect_p => parent_rect % childgrids
+!
+!   Creation of the grid hierarchy from the one created by using the Agrif_Read_Fix_Grd subroutine
+!
+    do while ( associated(child_rect_p) )
+!
+        child_rect => child_rect_p % r
+!
+        allocate(child_grid)
+!
+!       Pointer on the parent grid
+        child_grid % parent => parent_grid
+        child_grid % rect_in_parent => Agrif_Copy_Rectangle(child_rect_p % r, expand=Agrif_Extra_Boundary_Cells)
+!
+        moving_grid_id = moving_grid_id+1
+        child_grid % grid_id = moving_grid_id
+!
+        do i = 1,Agrif_Probdim
+            child_grid % spaceref(i) = child_rect % spaceref(i)
+            child_grid % timeref(i)  = child_rect % timeref(i)
+            child_grid % nb(i) = (child_rect % imax(i) - child_rect % imin(i)) * child_rect % spaceref(i)
+            child_grid % ix(i) =  child_rect % imin(i)
+            child_grid % Agrif_dt(i) = parent_grid % Agrif_dt(i) / REAL(child_grid % timeref(i))
+            child_grid % Agrif_dx(i) = parent_grid % Agrif_dx(i) / REAL(child_grid % spaceref(i))
+            child_grid % Agrif_x(i)  = parent_grid % Agrif_x(i) + &
+                                            (child_rect % imin(i) - 1) * parent_grid % Agrif_dx(i)
+        enddo
+!
+!       Size of the grid in terms of cpu cost (nx*ny*timeref)
+        child_grid % size = product( child_grid % nb(1:Agrif_Probdim) ) * child_grid % timeref(1)
+!
+!       Level of the current grid
+        child_grid % level = child_grid % parent % level + 1
+        if (child_grid % level > Agrif_MaxLevelLoc) then
+          Agrif_MaxLevelLoc = child_grid%level
+        endif
+!
+!       Number of the grid pointed by child_grid
+        child_grid % fixedrank = child_rect % number
+!
+!       Grid pointed by child_grid is a fixed grid
+        child_grid % fixed = ( child_grid % fixedrank > 0 )
+!
+!       Update the total number of fixed grids
+        if (child_grid % fixed) then
+            Agrif_nbfixedgrids = Agrif_nbfixedgrids + 1
+        endif
+!
+!       Initialize integration counter
+        child_grid % ngridstep = 0
+!
+!       Test indicating if the current grid has a common border with the root
+!       coarse grid in the x direction
+        do i = 1 , Agrif_Probdim
+!
+            child_grid % NearRootBorder(i) = (                  &
+                (child_grid % parent % NearRootBorder(i)) .AND. &
+                (child_grid % ix(i) == 1) )
+!
+            child_grid % DistantRootBorder(i) = (                  &
+                (child_grid % parent % DistantRootBorder(i)) .AND. &
+                (child_grid % ix(i) + (child_grid%nb(i)/child_grid%spaceref(i))-1  == child_grid % parent % nb(i)) )
+        enddo
+!
+!       Writing in output files
+        child_grid % oldgrid = .FALSE.
+!
+#if defined AGRIF_MPI
+        child_grid % communicator = parent_grid % communicator
+#endif
+!
+!       Definition of the characteristics of the variable of the grid pointed by child_grid
+        call Agrif_Create_Var(child_grid)
+!
+!       Addition of this grid to the grid hierarchy
+        call Agrif_gl_append( parent_grid % child_list, child_grid )
+!
+        child_rect_p => child_rect_p % next
+!
+    enddo
+!
+!   Recursive call to the subroutine Agrif_Create_Fixed_Grids to create the grid hierarchy
+!
+    child_grid_p => parent_grid % child_list % first
+    child_rect_p => parent_rect % childgrids
+!
+    do while ( associated(child_rect_p) )
+        call Agrif_Create_Grids( child_grid_p % gr, child_rect_p % r )
+        child_grid_p => child_grid_p % next
+        child_rect_p => child_rect_p % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Create_Grids
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Init_Hierarchy
+!
+!> Initializes all the grids except the root coarse grid (this one, pointed by Agrif_Types::Agrif_Mygrid, is
+!! initialized by the subroutine Agrif_Util#Agrif_Init_Grids defined in the module Agrif_Util and
+!! called in the main program).
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Init_Hierarchy ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    use Agrif_seq
+!
+    type(Agrif_Grid), pointer       :: g            !< Pointer on the current grid
+    procedure(init_proc), optional  :: procname     !< Initialisation subroutine (Default: Agrif_InitValues)
+!
+    TYPE(Agrif_PGrid), pointer :: parcours  ! Pointer for the recursive call
+    LOGICAL                    :: Init_Hierarchy
+!
+! Initialise the grand mother grid (if any)
+!
+    if ( associated(g, Agrif_Mygrid) .and. agrif_coarse ) then
+        call Agrif_Instance(Agrif_Coarsegrid)
+        call Agrif_Allocation(Agrif_Coarsegrid)
+        call Agrif_initialisations(Agrif_Coarsegrid)
+        call Agrif_InitWorkspace()
+!
+!       Initialization by interpolation (this routine is written by the user)
+        if (present(procname)) Then
+            call procname()
+        else
+            call Agrif_InitValues()
+        endif
+        call Agrif_Instance(Agrif_Mygrid)
+    endif
+
+    parcours => g % child_list % first
+!
+    do while ( associated(parcours) )
+!
+        Init_Hierarchy = .false.
+        if ( Agrif_USE_FIXED_GRIDS == 1 .OR. Agrif_USE_ONLY_FIXED_GRIDS == 1 ) then
+            if ( (parcours%gr%fixed) .AND. (Agrif_Mygrid%ngridstep == 0) ) then
+                Init_Hierarchy = .true.
+            endif
+        endif
+!
+        if (.NOT. parcours % gr % fixed) Init_Hierarchy = .true.
+        if (parcours % gr % oldgrid)     Init_Hierarchy = .false.
+!
+        if (Init_Hierarchy) then
+!
+!           Instanciation of the grid pointed by parcours%gr and its variables
+            call Agrif_Instance(parcours % gr)
+!
+!           Allocation of the arrays containing values of the variables of the
+!           grid pointed by parcours%gr
+!
+            call Agrif_Allocation(parcours % gr)
+            call Agrif_initialisations(parcours % gr)
+!
+            if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) then
+!               Initialization by copy of the grids created by clustering
+                call Agrif_Allocate_Restore(parcours % gr)
+                call Agrif_CopyFromOld_All(parcours % gr, Agrif_oldmygrid)
+            endif
+!
+!           Initialization by interpolation (this routine is written by the user)
+            call Agrif_InitWorkSpace()
+            if (present(procname)) Then
+                call procname()
+            else
+                call Agrif_InitValues()
+            endif
+!
+            if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) then
+                call Agrif_Free_Restore(parcours % gr)
+            endif
+!
+        endif
+!
+        parcours => parcours % next
+!
+    enddo
+!
+    parcours => g % child_list % first
+!
+!   recursive operation to initialize all the grids
+    do while ( associated(parcours) )
+        call Agrif_Init_Hierarchy(parcours%gr,procname)
+        parcours => parcours%next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Init_Hierarchy
+!===================================================================================================
+!
+#if defined AGRIF_MPI
+!===================================================================================================
+!  subroutine Agrif_Init_Hierarchy_Parallel_1
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Init_Hierarchy_Parallel_1 ( g )
+!---------------------------------------------------------------------------------------------------
+    use Agrif_seq
+!
+    type(Agrif_Grid), pointer       :: g            !< Pointer on the current grid
+!
+    TYPE(Agrif_PGrid), pointer :: parcours  ! Pointer for the recursive call
+    LOGICAL                    :: Init_Hierarchy
+!
+    parcours => g % child_list % first
+!
+    do while ( associated(parcours) )
+!
+        Init_Hierarchy = .false.
+        if ( Agrif_USE_FIXED_GRIDS == 1 .OR. Agrif_USE_ONLY_FIXED_GRIDS == 1 ) then
+            if ( (parcours%gr%fixed) .AND. (Agrif_Mygrid%ngridstep == 0) ) then
+                Init_Hierarchy = .true.
+            endif
+        endif
+!
+        if (.NOT. parcours % gr % fixed) Init_Hierarchy = .true.
+        if (parcours % gr % oldgrid)     Init_Hierarchy = .false.
+!
+        if (Init_Hierarchy) then
+!
+!           Instanciation of the grid pointed by parcours%gr and its variables
+            call Agrif_Instance(parcours % gr)
+!
+!           Allocation of the arrays containing values of the variables of the
+!           grid pointed by parcours%gr
+!
+            call Agrif_Allocation(parcours % gr)
+            call Agrif_initialisations(parcours % gr)
+!
+        endif
+!
+        parcours => parcours % next
+!
+    enddo
+!
+    parcours => g % child_list % first
+!
+!   recursive operation to initialize all the grids
+    do while ( associated(parcours) )
+        call Agrif_Init_Hierarchy_Parallel_1(parcours%gr)
+        parcours => parcours%next
+    enddo
+!
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Init_Hierarchy_Parallel_1
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Init_Hierarchy_Parallel_2
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Init_Hierarchy_Parallel_2 ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    use Agrif_seq
+!
+    type(Agrif_Grid),     pointer   :: g            !< Pointer on the current grid
+    procedure(init_proc), optional  :: procname     !< Initialisation subroutine (Default: Agrif_InitValues)
+!
+    type(Agrif_PGrid), pointer :: parcours  ! Pointer for the recursive call
+    integer :: is
+!
+    call Agrif_Instance(g)
+    call Agrif_seq_init_sequences( g )
+!
+    if ( .not. associated(g % child_seq) ) return
+!
+    do is = 1, g % child_seq % nb_seqs
+!
+        parcours => Agrif_seq_select_child(g,is)
+!
+!     Instanciation of the variables of the current grid
+        call Agrif_Instance(parcours % gr)
+!
+!     Initialization by interpolation (this routine is written by the user)
+        if (present(procname)) Then
+            call procname()
+        else
+            call Agrif_InitValues()
+        endif
+!
+        call Agrif_Init_ProcList(parcours % gr % proc_def_list, &
+                                 parcours % gr % proc_def_in_parent_list % nitems)
+!
+        call Agrif_Init_Hierarchy_Parallel_2(parcours%gr,procname)
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Init_Hierarchy_Parallel_2
+!===================================================================================================
+#endif
+!
+!===================================================================================================
+!  subroutine Agrif_Allocate_Restore
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Allocate_Restore ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid), pointer  :: Agrif_Gr   !< Pointer on the root coarse grid
+!
+    integer :: i
+!
+    do i = 1,Agrif_NbVariables(0)
+!
+        if ( Agrif_Mygrid%tabvars(i) % restore ) then
+            if ( Agrif_Gr%tabvars(i) % nbdim == 1 ) then
+                allocate( Agrif_Gr%tabvars(i)%Restore1D( &
+                    lbound(Agrif_Gr%tabvars(i)%array1,1):&
+                    ubound(Agrif_Gr%tabvars(i)%array1,1)))
+                Agrif_Gr%tabvars(i)%Restore1D = 0
+            endif
+            if ( Agrif_Gr%tabvars(i) % nbdim == 2 ) then
+                allocate( Agrif_Gr%tabvars(i)%Restore2D( &
+                    lbound(Agrif_Gr%tabvars(i)%array2,1):&
+                    ubound(Agrif_Gr%tabvars(i)%array2,1),&
+                    lbound(Agrif_Gr%tabvars(i)%array2,2):&
+                    ubound(Agrif_Gr%tabvars(i)%array2,2)))
+                Agrif_Gr%tabvars(i)%Restore2D = 0
+            endif
+            if ( Agrif_Mygrid%tabvars(i) % nbdim == 3 ) then
+                allocate( Agrif_Gr%tabvars(i)%Restore3D( &
+                    lbound(Agrif_Gr%tabvars(i)%array3,1):&
+                    ubound(Agrif_Gr%tabvars(i)%array3,1),&
+                    lbound(Agrif_Gr%tabvars(i)%array3,2):&
+                    ubound(Agrif_Gr%tabvars(i)%array3,2),&
+                    lbound(Agrif_Gr%tabvars(i)%array3,3):&
+                    ubound(Agrif_Gr%tabvars(i)%array3,3)))
+                Agrif_Gr%tabvars(i)%Restore3D = 0
+            endif
+        endif
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Allocate_Restore
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Free_Restore
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Free_Restore ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid), pointer  :: Agrif_Gr   !< Pointer on the root coarse grid
+!
+    TYPE(Agrif_Variable), pointer :: var
+    integer                       :: i
+!
+    do i = 1,Agrif_NbVariables(0)
+!
+        if ( Agrif_Mygrid % tabvars(i) % restore ) then
+!
+            var = Agrif_Gr % tabvars(i)
+!
+            if (associated(var%Restore1D)) deallocate(var%Restore1D)
+            if (associated(var%Restore2D)) deallocate(var%Restore2D)
+            if (associated(var%Restore3D)) deallocate(var%Restore3D)
+            if (associated(var%Restore4D)) deallocate(var%Restore4D)
+            if (associated(var%Restore5D)) deallocate(var%Restore5D)
+            if (associated(var%Restore6D)) deallocate(var%Restore6D)
+!
+        endif
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Free_Restore
+!===================================================================================================
+!
+end module Agrif_Clustering
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modcurgridfunctions.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modcurgridfunctions.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modcurgridfunctions.F90	(revision 9987)
@@ -0,0 +1,765 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place-  Suite 330, Boston, MA 02111-1307, USA.
+!
+!> Module to define some procedures concerning the current grid
+!
+module Agrif_CurgridFunctions
+!
+    use Agrif_Init
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+!  function Agrif_rel_dt
+!
+!> Returns the time step of the current grid, relatively to the root grid (for which dt=1.).
+!---------------------------------------------------------------------------------------------------
+function Agrif_rel_dt ( ) result( rel_dt )
+!---------------------------------------------------------------------------------------------------
+    integer :: i
+    real    :: rel_dt
+!
+    rel_dt = 1.
+!
+    do i = 1,Agrif_Probdim
+        rel_dt = min(rel_dt, Agrif_Curgrid % Agrif_dt(i))
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_rel_dt
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_rel_idt
+!
+!> Returns the time refinement factor of the current grid, relatively to the root grid (for which idt=1).
+!---------------------------------------------------------------------------------------------------
+function Agrif_rel_idt ( ) result( rel_idt )
+!---------------------------------------------------------------------------------------------------
+    integer :: rel_idt
+!
+    rel_idt = nint(1./Agrif_rel_dt())
+!---------------------------------------------------------------------------------------------------
+end function Agrif_rel_idt
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_IRhot
+!
+!> Returns the time refinement factor of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_IRhot ( ) result( irhot )
+!---------------------------------------------------------------------------------------------------
+    integer :: i, irhot
+!
+    irhot = 1
+!
+    do i = 1,Agrif_Probdim
+        irhot = max(irhot, Agrif_Curgrid % timeref(i))
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_IRhot
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Rhot
+!
+!> Returns the time refinement factor of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Rhot ( ) result( rhot )
+!---------------------------------------------------------------------------------------------------
+    real    :: rhot
+!
+    rhot = float(Agrif_IRhot())
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Rhot
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_IRhot
+!
+!> Returns the time refinement factor of the parent of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_IRhot ( ) result( irhot )
+!---------------------------------------------------------------------------------------------------
+    integer :: i, irhot
+!
+    irhot = 1
+!
+    do i = 1,Agrif_Probdim
+        irhot = max(irhot, Agrif_Curgrid % parent % timeref(i))
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_IRhot
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_Rhot
+!
+!> Returns the time refinement factor of the parent of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_Rhot ( ) result( rhot )
+!---------------------------------------------------------------------------------------------------
+    real :: rhot
+!
+    rhot = float(Agrif_Parent_IRhot())
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_Rhot
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Nbstepint
+!
+!> function for the calculation of the coefficients used for the time interpolation
+!! (module #Agrif_Boundary).
+!---------------------------------------------------------------------------------------------------
+function Agrif_Nbstepint ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_nbstepint ! result
+!
+    Agrif_nbstepint = mod(Agrif_Curgrid % ngridstep, Agrif_iRhot())
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Nbstepint
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_Nbstepint
+!
+!> function for the calculation of the coefficients used for the time interpolation
+!! (module #Agrif_Boundary).
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_Nbstepint ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_Parent_Nbstepint ! result
+!
+    Agrif_Parent_Nbstepint = mod(Agrif_Curgrid % parent % ngridstep, int(Agrif_Parent_Rhot()))
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_Nbstepint
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpNearBorderX
+!
+!> Allows to interpolate (in the x direction) on a near border of the current grid if this one
+!! has a common border with the root coarse grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpNearBorderX ( )
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % NearRootBorder(1) = .FALSE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpNearBorderX
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpDistantBorderX
+!
+!> Allows to interpolate (in the x direction) on a distant border of the current grid if this one
+!! has a common border with the root coarse grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpDistantBorderX ( )
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % DistantRootBorder(1) = .FALSE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpDistantBorderX
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpNearBorderY
+!
+!> Allows to interpolate (in the y direction) on a near border of the current grid if this one
+!! has a common border with the root coarse grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpNearBorderY ( )
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % NearRootBorder(2) = .FALSE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpNearBorderY
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpDistantBorderY
+!
+!> Allows to interpolate (in the y direction) on a distant border of the current grid if this one
+!! has a common border with the root coarse grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpDistantBorderY ( )
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % DistantRootBorder(2) = .FALSE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpDistantBorderY
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpNearBorderZ
+!
+!> Allows to interpolate (in the z direction) on a near border of the current grid if this one
+!! has a common border with the root coarse grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpNearBorderZ ( )
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % NearRootBorder(3) = .FALSE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpNearBorderZ
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpDistantBorderZ
+!
+!> Allows to interpolate (in the z direction) on a distant border of the current grid if this one
+!! has a common border with the root coarse grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpDistantBorderZ()
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % DistantRootBorder(3) = .FALSE.
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpDistantBorderZ
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_Nb_Step
+!
+!> Returns the number of time steps of the parent of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_Nb_Step ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_Parent_Nb_Step ! Result
+!
+    if (Agrif_Root()) then
+        Agrif_Parent_Nb_Step = -1
+    else
+        Agrif_Parent_Nb_Step = Agrif_Curgrid % parent % ngridstep
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_Nb_Step
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Root
+!
+!> Indicates if the current grid is or not the root grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Root ( )
+!---------------------------------------------------------------------------------------------------
+    logical :: Agrif_Root ! Result
+!
+    Agrif_Root = (Agrif_Curgrid % fixedrank == 0)
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Root
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_GrandMother
+!
+!> Indicates if the current grid is or not the root grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_GrandMother ( )
+!---------------------------------------------------------------------------------------------------
+    logical :: Agrif_GrandMother ! Result
+!
+    Agrif_GrandMother = Agrif_Curgrid % grand_mother_grid
+!---------------------------------------------------------------------------------------------------
+end function Agrif_GrandMother
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_Root
+!
+!> Indicates if the parent of the current grid is or not the root grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_Root ( )
+!---------------------------------------------------------------------------------------------------
+    logical :: Agrif_Parent_Root ! Result
+!
+    Agrif_Parent_Root = (Agrif_Curgrid % parent % fixedrank == 0)
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_Root
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Fixed
+!
+!> Returns the number of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Fixed ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_Fixed   ! Result
+!
+    if (Agrif_Curgrid % fixed) then
+        Agrif_Fixed = Agrif_Curgrid % fixedrank
+    else
+        Agrif_Fixed = -1
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Fixed
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_Fixed
+!
+!> Returns the number of the parent of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_Fixed ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_Parent_Fixed   ! Result
+!
+    if (Agrif_Curgrid % parent % fixed) then
+        Agrif_Parent_Fixed = Agrif_Curgrid % parent % fixedrank
+    else
+        Agrif_Parent_Fixed = 0
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_Fixed
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Is_Fixed
+!
+!> Returns .TRUE. if the current grid is fixed.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Is_Fixed ( )
+!---------------------------------------------------------------------------------------------------
+    logical :: Agrif_Is_Fixed   ! Result
+!
+    Agrif_Is_Fixed = Agrif_Curgrid % fixed
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Is_Fixed
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Parent_Is_Fixed
+!
+!> Returns .TRUE. if the parent of the current grid is fixed.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Parent_Is_Fixed ( )
+!---------------------------------------------------------------------------------------------------
+    logical :: Agrif_Parent_Is_Fixed   ! Result
+!
+    Agrif_Parent_Is_Fixed = Agrif_Curgrid % parent % fixed
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Parent_Is_Fixed
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_CFixed
+!
+!> Returns the number of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_CFixed ( )
+!---------------------------------------------------------------------------------------------------
+    character(3) :: Agrif_CFixed   ! Result
+!
+    character(3) :: cfixed
+    integer      :: fixed
+!
+    fixed = Agrif_Fixed()
+!
+    if (fixed /= -1) then
+!
+        if (fixed <= 9) then
+            write(cfixed,'(i1)') fixed
+        else
+            write(cfixed,'(i2)') fixed
+        endif
+!
+        Agrif_CFixed = cfixed
+        
+        if (associated(agrif_curgrid,agrif_coarsegrid)) then
+          Agrif_CFixed = 'gm'
+        endif
+!
+    else
+        print*,'Call to Agrif_CFixed() on a moving grid'
+        stop
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_CFixed
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrid_Parent_CFixed
+!
+!> Returns the number of the parent of the current grid.
+!---------------------------------------------------------------------------------------------------
+function Agrid_Parent_CFixed ( )
+!---------------------------------------------------------------------------------------------------
+    character(3) :: Agrid_Parent_CFixed   ! Result
+!
+    character(3) :: cfixed
+    integer      :: fixed
+!
+    fixed = Agrif_Parent_Fixed()
+!
+    if(fixed /= -1) then
+!
+        if (fixed <= 9) then
+            write(cfixed,'(i1)')fixed
+        else
+            write(cfixed,'(i2)')fixed
+        endif
+!
+        Agrid_Parent_CFixed=cfixed
+!
+    else
+        print*,'Illegal call to Agrid_Parent_CFixed()'
+        stop
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrid_Parent_CFixed
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_ChildGrid_to_ParentGrid
+!
+!> Make the pointer #Agrif_Curgrid point on the parent grid of the current grid.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_ChildGrid_to_ParentGrid ( )
+!---------------------------------------------------------------------------------------------------
+    Agrif_Curgrid % parent % save_grid => Agrif_Curgrid
+    call Agrif_Instance(Agrif_Curgrid%parent)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_ChildGrid_to_ParentGrid
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_ParentGrid_to_ChildGrid
+!
+!> Make the pointer #Agrif_Curgrid point on the child grid after having called the
+!! #Agrif_ChildGrid_to_ParentGrid subroutine.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_ParentGrid_to_ChildGrid ( )
+!---------------------------------------------------------------------------------------------------
+    call Agrif_Instance(Agrif_Curgrid%save_grid)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_ParentGrid_to_ChildGrid
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Get_Unit
+!
+!> Returns a unit not connected to any file.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Get_Unit ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_Get_Unit  ! Result
+!
+    integer :: n
+    logical :: op
+!
+    integer :: nunit
+    integer :: iii, out, iiimax
+    logical :: bexist
+    integer,dimension(1:1000) :: forbiddenunit
+!
+!   Load forbidden Unit if the file Agrif_forbidenUnit exist
+!
+    INQUIRE(file='Agrif_forbiddenUnit.txt', exist=bexist)
+!
+    if (.not. bexist) then
+!       File Agrif_forbiddenUnit.txt not found
+    else
+        nunit = 777
+        OPEN(nunit,file='Agrif_forbiddenUnit.txt', form='formatted', status="old")
+        iii = 1
+        do while ( .TRUE. )
+            READ(nunit,*, end=99) forbiddenunit(iii)
+            iii = iii + 1
+        enddo
+   99   continue
+        iiimax = iii
+        close(nunit)
+    endif
+!
+    do n = 7,1000
+!
+        INQUIRE(Unit=n,Opened=op)
+!
+        out = 0
+        if ( bexist .AND. (.NOT.op) ) then
+            do iii = 1,iiimax
+                if ( n == forbiddenunit(iii) ) out = 1
+            enddo
+        endif
+!
+        if ( (.NOT.op) .AND. (out == 0) ) exit
+!
+    enddo
+!
+    Agrif_Get_Unit = n
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Get_Unit
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_Extra_Boundary_Cells
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_Extra_Boundary_Cells ( nb_extra_cells )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: nb_extra_cells
+!
+    Agrif_Extra_Boundary_Cells = nb_extra_cells
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_Extra_Boundary_Cells
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_Efficiency
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_Efficiency ( eff )
+!---------------------------------------------------------------------------------------------------
+    real, intent(in) :: eff
+!
+    if ( (eff < 0.) .OR. (eff > 1) ) then
+        write(*,*) 'Error Efficiency should be between 0 and 1'
+        stop
+    else
+        Agrif_Efficiency = eff
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_Efficiency
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_Regridding
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_Regridding ( regfreq )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: regfreq
+!
+    if (regfreq < 0) then
+        write(*,*) 'Regridding frequency should be positive'
+        stop
+    else
+        Agrif_Regridding = regfreq
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_Regridding
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_coeffref_x
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_coeffref_x ( coeffref )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coeffref
+
+      if (coeffref < 0) then
+         write(*,*) 'Coefficient of raffinement should be positive'
+         stop
+      else
+         Agrif_coeffref(1) = coeffref
+      endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_coeffref_x
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_coeffref_y
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_coeffref_y ( coeffref )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coeffref
+
+    if (coeffref < 0) then
+        write(*,*) 'Coefficient of raffinement should be positive'
+        stop
+    else
+        Agrif_coeffref(2) = coeffref
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_coeffref_y
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_coeffref_z
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_coeffref_z ( coeffref )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coeffref
+!
+    if (coeffref < 0) then
+        write(*,*) 'Coefficient of raffinement should be positive'
+        stop
+    else
+        Agrif_coeffref(3) = coeffref
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_coeffref_z
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_coeffreft_x
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_coeffreft_x ( coeffref )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coeffref
+
+    if (coeffref < 0) then
+        write(*,*) 'Coefficient of time raffinement should be positive'
+        stop
+    else
+        Agrif_coeffreft(1) = coeffref
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_coeffreft_x
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_coeffreft_y
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_coeffreft_y ( coeffref )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coeffref
+!
+    if (coeffref < 0) then
+        write(*,*) 'Coefficient of time raffinement should be positive'
+        stop
+    else
+        Agrif_coeffreft(2) = coeffref
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_coeffreft_y
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_coeffreft_z
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_coeffreft_z ( coeffref )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coeffref
+
+    if (coeffref < 0) then
+        write(*,*)'Coefficient of time raffinement should be positive'
+        stop
+    else
+        Agrif_coeffreft(3) = coeffref
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_coeffreft_z
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_Minwidth
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_Minwidth ( coefminwidth )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coefminwidth
+!
+    if (coefminwidth < 0) then
+        write(*,*)'Coefficient of Minwidth should be positive'
+        stop
+    else
+        Agrif_Minwidth = coefminwidth
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_Minwidth
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_Rafmax
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_Rafmax ( coefrafmax )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: coefrafmax
+!
+    integer :: i
+    real    :: res
+!
+    if (coefrafmax < 0) then
+        write(*,*)'Coefficient of  should be positive'
+        stop
+    else
+        res = 1.
+        do i = 1,coefrafmax-1
+            res = res * FLOAT(Agrif_coeffref(1))
+        enddo
+        if ( res == 0 ) res = 1
+        Agrif_Mind(1) = 1. / res
+!
+        res = 1.
+        do i = 1,coefrafmax-1
+            res = res * FLOAT(Agrif_coeffref(2))
+        enddo
+        if ( res == 0 ) res = 1
+        Agrif_Mind(2) = 1. / res
+!
+        res = 1.
+        do i = 1,coefrafmax-1
+            res = res * FLOAT(Agrif_coeffref(3))
+        enddo
+        if ( res == 0 ) res = 1
+        Agrif_Mind(3) = 1. / res
+!
+      endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_Rafmax
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Set_MaskMaxSearch
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Set_MaskMaxSearch ( mymaxsearch )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: mymaxsearch
+!
+    MaxSearch = mymaxsearch
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Set_MaskMaxSearch
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Level
+!---------------------------------------------------------------------------------------------------
+function Agrif_Level ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_Level  ! Result
+!
+    Agrif_Level = Agrif_Curgrid % level
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Level
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_MaxLevel
+!---------------------------------------------------------------------------------------------------
+function Agrif_MaxLevel ( )
+!---------------------------------------------------------------------------------------------------
+    integer :: Agrif_MaxLevel  ! Result
+!
+    Agrif_MaxLevel = Agrif_MaxLevelLoc
+!---------------------------------------------------------------------------------------------------
+end function Agrif_MaxLevel
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_GridAllocation_is_done
+!---------------------------------------------------------------------------------------------------
+function Agrif_GridAllocation_is_done ( ) result(isdone)
+!---------------------------------------------------------------------------------------------------
+    logical :: isdone
+!
+    isdone = Agrif_Curgrid % allocation_is_done
+!---------------------------------------------------------------------------------------------------
+end function Agrif_GridAllocation_is_done
+!===================================================================================================
+!
+end module Agrif_CurgridFunctions
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modgrids.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modgrids.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modgrids.F90	(revision 9987)
@@ -0,0 +1,478 @@
+module Agrif_Grids
+
+    use Agrif_Types
+!
+    implicit none
+!
+!===================================================================================================
+type Agrif_Grid_List
+!---------------------------------------------------------------------------------------------------
+!<  List of grids.
+!
+    integer                     :: nitems = 0      !< Number of elements in the list
+    type(Agrif_PGrid), pointer  :: first => NULL() !< Pointer to the first grid in the list
+    type(Agrif_PGrid), pointer  :: last  => NULL() !< Pointer to the last  grid inserted in the list
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Grid_List
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_PGrid
+!---------------------------------------------------------------------------------------------------
+!<  Data type to go over the grid hierarchy (used for the creation of this grid hierarchy
+!<  and during the time integration).
+!
+    type(Agrif_Grid) , pointer :: gr   => NULL()  !< Pointer to the actual grid data structure
+    type(Agrif_PGrid), pointer :: next => NULL()  !< Next grid in the list
+!
+!---------------------------------------------------------------------------------------------------
+end type Agrif_PGrid
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Grid
+!---------------------------------------------------------------------------------------------------
+!<  Data type to define a grid (position, space and time refinement factors).
+!
+    type(Agrif_Grid)                    , pointer :: parent      => NULL() !< pointer on the parent grid
+    type(Agrif_Grid)                    , pointer :: save_grid   => NULL() !< pointer on the save grid
+    type(Agrif_Grid_List)                         :: child_list            !< List of child grids
+    type(Agrif_Variable),   dimension(:), allocatable :: tabvars    !< List of grid variables
+    type(Agrif_Variable_c), dimension(:), allocatable :: tabvars_c  !< List of character grid variables
+    type(Agrif_Variable_r), dimension(:), allocatable :: tabvars_r  !< List of real      grid variables
+    type(Agrif_Variable_l), dimension(:), allocatable :: tabvars_l  !< List of logical   grid variables
+    type(Agrif_Variable_i), dimension(:), allocatable :: tabvars_i  !< List of integer   grid variables
+!
+    real   , dimension(3)              :: Agrif_x   !< global x, y and z position
+    real   , dimension(3)              :: Agrif_dx  !< global space step in the x, y and z direction
+    real   , dimension(3)              :: Agrif_dt  !< global time  step in the x, y and z direction
+    integer, dimension(3)              :: nb        !< number of cells in the x, y and z direction
+    integer, dimension(3)              :: ix        !< minimal position in the x, y and z direction
+    integer, dimension(3)              :: spaceref  !< space refinement factor in the x, y and z direction
+    integer, dimension(3)              :: timeref   !< Time refinement factor in the x, y and z direction
+    integer                            :: ngridstep !< number of time steps
+    integer                            :: rank
+    integer                            :: grid_id   !< moving grid id
+    integer                            :: fixedrank !< number of the grid
+    logical                            :: fixed     !< fixed or moving grid ?
+    logical                            :: oldgrid
+!> \name Logicals indicating if the current grid has a common border with the root coarse grid
+!> @{
+    logical, dimension(3)              :: NearRootBorder
+    logical, dimension(3)              :: DistantRootBorder
+!> @}
+!> \name Arrays for adaptive grid refinement
+!> @{
+    integer, dimension(:)    ,   allocatable :: tabpoint1D
+    integer, dimension(:,:)  ,   allocatable :: tabpoint2D
+    integer, dimension(:,:,:),   allocatable :: tabpoint3D
+!> @}
+!> \name Members for parallel integration
+!> @{
+    type(Agrif_Rectangle),  pointer    :: rect_in_parent => NULL()
+    type(Agrif_Grid_List)              :: neigh_list                !< List of neighboring grids (ie. connected through a common proc)
+    type(Agrif_Proc_List)              :: proc_def_list             !< List of procs that will integrate this grid
+    type(Agrif_Proc_List)              :: proc_def_in_parent_list   !< List of procs that will integrate this grid (defined as in the parent grid)
+    type(Agrif_Proc_List)              :: required_proc_list        !< List of procs that are required for this grid
+    type(Agrif_Sequence_List), pointer :: child_seq => NULL()       !< Sequence for childs
+    integer                            :: seq_num = 0
+    integer                            :: size = 0
+    integer                            :: dsat = 0
+#if defined AGRIF_MPI
+    integer                            :: communicator = -1
+#endif
+!> @}
+    type(Agrif_Variables_List), pointer :: variables => NULL()
+    integer                             :: NbVariables = 0
+    integer                             :: level    !< level of the grid in the hierarchy
+    logical                             :: allocation_is_done = .false.
+    logical                             :: grand_mother_grid = .false.
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Grid
+!===================================================================================================
+!
+!> this pointer always points on the root grid of the grid hierarchy
+type(Agrif_Grid) , pointer :: Agrif_Mygrid => NULL()
+
+!> this pointer always points on the grand mother grid of the grid hierarchy (if any)
+type(Agrif_Grid) , pointer :: Agrif_Coarsegrid => NULL()
+
+!> Grid list used in the \link Agrif_Util::Agrif_Regrid() Agrif_regrid \endlink subroutine.
+!> It contains  the safeguard of the grid hierarchy.
+type(Agrif_Grid_List), pointer :: Agrif_oldmygrid => NULL()
+
+!> Pointer to the current grid (the link is done by using the Agrif_Instance procedure (\see module Agrif_Init))
+type(Agrif_Grid) , pointer :: Agrif_Curgrid => NULL()
+!
+!===================================================================================================
+type Agrif_Sequence
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List) :: gridlist
+    type(Agrif_Proc_List) :: proclist
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Sequence
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Sequence_List
+!---------------------------------------------------------------------------------------------------
+    integer :: nb_seqs
+    type(Agrif_Sequence), dimension(:), allocatable :: sequences
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Sequence_List
+!===================================================================================================
+!
+interface
+    function compare_grids ( grid1, grid2 ) result( res )
+        import Agrif_Grid
+        type(Agrif_Grid), intent(in)    :: grid1
+        type(Agrif_Grid), intent(in)    :: grid2
+        integer                         :: res  !< Result of the comparison :
+                                                !!  - res  < 0   if grid1 <  grid2
+                                                !!  - res == 0   if grid1 == grid2
+                                                !!  - res  > 0   if grid1 >  grid2
+    end function compare_grids
+end interface
+!
+contains
+!
+!===================================================================================================
+subroutine Agrif_gl_print ( gridlist )
+!
+!< DEBUG : a virer à terme.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)   :: gridlist
+!
+    type(Agrif_PGrid), pointer  :: gridp
+    type(Agrif_Grid),  pointer  :: grid
+!
+    gridp => gridlist % first
+    do while ( associated(gridp) )
+        grid => gridp % gr
+        write(*,'("G",i0,", ")', advance='no') grid % fixedrank
+        gridp => gridp % next
+    enddo
+    write(*,*)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gl_print
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_gl_print_debug ( gridlist )
+!
+!< DEBUG : a virer à terme.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)   :: gridlist
+!
+    type(Agrif_PGrid), pointer  :: gridp
+    type(Agrif_Grid),  pointer  :: grid
+!
+    write(*,'(" (nitems=",i2,"), (id,neighs,color,dsat,size) = ")', advance='no') gridlist % nitems
+    gridp => gridlist % first
+    do while ( associated(gridp) )
+        grid => gridp % gr
+        write(*,'("(G",i0,4(",",i0),"), ")', advance='no') grid % fixedrank, &
+            grid % neigh_list % nitems, grid % seq_num, grid % dsat, grid % size
+        gridp => gridp % next
+    enddo
+    write(*,*)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gl_print_debug
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_gl_append ( gridlist, grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List),     intent(inout)  :: gridlist
+    type(Agrif_Grid), pointer, intent(in)     :: grid
+!
+    type(Agrif_PGrid), pointer   :: new_gp
+!
+    allocate( new_gp )
+!
+    new_gp % gr   => grid
+    new_gp % next => NULL()
+!
+    if ( associated(gridlist % last) ) then
+    ! the list is not empty, append the new pointer at the end
+        gridlist % last % next => new_gp
+    else
+    ! the list is empty, the new pointer is the first one
+        gridlist % first => new_gp
+    endif
+    ! anyway, for next time 'grid' will be the last one.
+    gridlist % last => new_gp
+    gridlist % nitems = gridlist % nitems + 1
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gl_append
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_gl_popfirst ( gridlist ) result ( grid )
+!
+!<  Removes the first item of the list and returns it.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(inout)    :: gridlist
+!
+    type(Agrif_PGrid), pointer :: grid_p
+    type(Agrif_Grid),  pointer :: grid
+!
+    grid_p => gridlist % first
+!
+    if ( .not. associated( grid_p ) ) then
+        grid => NULL()
+        return
+    endif
+!
+    grid              => grid_p % gr
+    gridlist % first  => grid_p % next
+    gridlist % nitems =  gridlist % nitems - 1
+    if ( .not. associated(gridlist % first) ) then
+       nullify(gridlist % last)
+    endif
+    deallocate(grid_p)
+!---------------------------------------------------------------------------------------------------
+end function Agrif_gl_popfirst
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_gl_copy ( new_gl, model )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(out)  :: new_gl
+    type(Agrif_Grid_List), intent(in)   :: model
+!
+    type(Agrif_PGrid), pointer :: gp
+!
+    call Agrif_gl_clear(new_gl)
+    gp => model % first
+!
+    do while( associated(gp) )
+        call Agrif_gl_append( new_gl, gp % gr )
+        gp => gp % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gl_copy
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_gl_build_from_gp ( gridp ) result ( gridlist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_PGrid), pointer, intent(in)   :: gridp
+!
+    type(Agrif_Grid_List), pointer  :: gridlist
+    type(Agrif_PGrid),     pointer  :: gp
+!
+    allocate(gridlist)
+!
+    gp => gridp
+!
+    do while ( associated( gp ) )
+        call Agrif_gl_append( gridlist, gp % gr )
+        gp => gp % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_gl_build_from_gp
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_gp_delete ( gridp )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_PGrid), pointer, intent(inout)  :: gridp
+!
+    type(Agrif_PGrid), pointer   :: gp, gpd
+!
+    if ( .not. associated( gridp ) ) return
+!
+    gp => gridp
+!
+    do while( associated(gp) )
+        gpd => gp
+        gp  => gp % next
+        deallocate(gpd)
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gp_delete
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_gl_clear ( gridlist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(inout)  :: gridlist
+!
+    call Agrif_gp_delete(gridlist % first)
+    gridlist % first => NULL()
+    gridlist % last  => NULL()
+    gridlist % nitems = 0
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gl_clear
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_gl_delete ( gridlist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), pointer, intent(inout)  :: gridlist
+!
+    if ( .not. associated( gridlist ) ) return
+!
+    call Agrif_gp_delete(gridlist % first)
+    deallocate( gridlist )
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_gl_delete
+!===================================================================================================
+!
+!===================================================================================================
+recursive function Agrif_gl_merge_sort ( gridlist, compare_func, compare_func_opt ) result( gl_sorted )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)    :: gridlist
+    procedure(compare_grids)             :: compare_func
+    procedure(compare_grids), optional   :: compare_func_opt
+!
+    type(Agrif_Grid_List), pointer  :: gl_sorted
+    type(Agrif_Grid_List), pointer  :: gl_left,  gl_sorted_left
+    type(Agrif_Grid_List), pointer  :: gl_right, gl_sorted_right
+    type(Agrif_PGrid),     pointer  :: grid_p
+    integer                         :: n, middle
+!
+! if list size is 1, consider it sorted and return it
+    if  ( (gridlist % nitems <= 1) ) then
+        gl_sorted => Agrif_gl_build_from_gp(gridlist % first)
+        return
+    endif
+!
+! else split the list into two sublists
+    n = 1
+    middle    =  gridlist % nitems / 2
+    grid_p    => gridlist % first
+!
+    allocate( gl_left, gl_right )
+!
+    do while ( associated(grid_p) )
+        if ( n <= middle ) then
+            call Agrif_gl_append(gl_left,  grid_p % gr)
+        else
+            call Agrif_gl_append(gl_right, grid_p % gr)
+        endif
+        grid_p => grid_p % next
+        n = n+1
+    enddo
+!
+! recursively call Agrif_gl_merge_sort() to further split each sublist until sublist size is 1
+    gl_sorted_left  => Agrif_gl_merge_sort(gl_left,  compare_func, compare_func_opt)
+    gl_sorted_right => Agrif_gl_merge_sort(gl_right, compare_func, compare_func_opt)
+!
+! merge the sublists returned from prior calls to gl_merge_sort() and return the resulting merged sublist
+    gl_sorted => Agrif_gl_merge(gl_sorted_left, gl_sorted_right, compare_func, compare_func_opt)
+!
+    call Agrif_gl_delete( gl_left )
+    call Agrif_gl_delete( gl_right )
+    call Agrif_gl_delete( gl_sorted_left )
+    call Agrif_gl_delete( gl_sorted_right )
+!---------------------------------------------------------------------------------------------------
+end function Agrif_gl_merge_sort
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_gl_merge ( gl_left, gl_right, compare_func, compare_func_opt ) result( gl_merged )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(inout)    :: gl_left
+    type(Agrif_Grid_List), intent(inout)    :: gl_right
+    procedure(compare_grids)                :: compare_func
+    procedure(compare_grids), optional      :: compare_func_opt
+!
+    type(Agrif_Grid_List), pointer  :: gl_merged
+    type(Agrif_Grid),      pointer  :: poped_grid
+    integer                         :: comp_value
+!
+    allocate( gl_merged )
+!
+    do while ( gl_left % nitems > 0 .or. gl_right % nitems > 0 )
+!
+        if ( gl_left % nitems > 0 .and. gl_right % nitems > 0 ) then
+!
+!         Let.s compare both items with the first compare function
+            comp_value = compare_func( gl_left % first % gr, gl_right % first % gr )
+!
+            if     ( comp_value < 0 ) then ; poped_grid => Agrif_gl_popfirst(gl_left)
+            elseif ( comp_value > 0 ) then ; poped_grid => Agrif_gl_popfirst(gl_right)
+            else ! ( comp_value == 0 )
+!
+!             Both items are equal, let.s use the second criterion if the optional
+!             compare function is present.
+                if ( present(compare_func_opt) ) then
+!
+                    comp_value = compare_func_opt( gl_left % first % gr, gl_right % first % gr )
+!
+                    if ( comp_value <= 0 ) then ; poped_grid => Agrif_gl_popfirst(gl_left)
+                    else                        ; poped_grid => Agrif_gl_popfirst(gl_right)
+                    endif
+                else
+!                 If the second criterion is not present, let.s just pick the left item
+                    poped_grid => Agrif_gl_popfirst(gl_left)
+                endif
+            endif
+!
+!     If one of the lists is empty, we just have to pick in the other one.
+        elseif ( gl_left  % nitems > 0 ) then ; poped_grid => Agrif_gl_popfirst(gl_left)
+        elseif ( gl_right % nitems > 0 ) then ; poped_grid => Agrif_gl_popfirst(gl_right)
+        endif
+!
+        call Agrif_gl_append( gl_merged, poped_grid )
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_gl_merge
+!===================================================================================================
+!
+!===================================================================================================
+function compare_grid_degrees ( grid1, grid2 ) result( res )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(in)    :: grid1
+    type(Agrif_Grid), intent(in)    :: grid2
+!
+    integer     :: res
+!
+    res = grid2 % neigh_list % nitems - grid1 % neigh_list % nitems
+!---------------------------------------------------------------------------------------------------
+end function compare_grid_degrees
+!===================================================================================================
+!
+!===================================================================================================
+function compare_colors ( grid1, grid2 ) result( res )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(in)    :: grid1
+    type(Agrif_Grid), intent(in)    :: grid2
+!
+    integer     :: res
+!
+    res = grid1 % seq_num - grid2 % seq_num
+!---------------------------------------------------------------------------------------------------
+end function compare_colors
+!===================================================================================================
+!
+!===================================================================================================
+function compare_dsat_values ( grid1, grid2 ) result( res )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(in)    :: grid1
+    type(Agrif_Grid), intent(in)    :: grid2
+!
+    integer     :: res
+!
+    res = grid2 % dsat - grid1 % dsat
+!---------------------------------------------------------------------------------------------------
+end function compare_dsat_values
+!===================================================================================================
+!
+!===================================================================================================
+function compare_size_values ( grid1, grid2 ) result( res )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(in)    :: grid1
+    type(Agrif_Grid), intent(in)    :: grid2
+!
+    integer     :: res
+!
+    res = grid2 % size - grid1 % size
+!---------------------------------------------------------------------------------------------------
+end function compare_size_values
+!===================================================================================================
+!
+end module Agrif_Grids
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinit.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinit.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinit.F90	(revision 9987)
@@ -0,0 +1,209 @@
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place-  Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Init.
+!>
+!> Several operations on the variables of the current grid (creation, instanciation, ...)
+!! used during the creation of the grid hierarchy and during the time integration.
+!
+module Agrif_Init
+!
+    use Agrif_Grids
+    use Agrif_Link
+    use Agrif_Mpp
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_Allocation
+!
+!> Allocates the arrays containing the values of the variables of the current grd.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Allocation ( Agrif_Gr, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid),       pointer   :: Agrif_Gr   !< Pointer on the current grid
+    procedure(alloc_proc),  optional  :: procname   !< Allocation procedure (Default: Agrif_Allocationcalls)
+!
+    if ( present(procname) ) then
+        call procname(Agrif_Gr)
+    else
+        call Agrif_Allocationcalls(Agrif_Gr)
+    endif
+    Agrif_Gr % allocation_is_done = .true.
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) then
+!
+        if ( Agrif_Probdim == 1 ) allocate( Agrif_Gr%tabpoint1D(Agrif_Gr%nb(1)+1) )
+        if ( Agrif_Probdim == 2 ) allocate( Agrif_Gr%tabpoint2D(Agrif_Gr%nb(1)+1, &
+                                                                Agrif_Gr%nb(2)+1) )
+        if ( Agrif_Probdim == 3 ) allocate( Agrif_Gr%tabpoint3D(Agrif_Gr%nb(1)+1, &
+                                                                Agrif_Gr%nb(2)+1, &
+                                                                Agrif_Gr%nb(3)+1) )
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Allocation
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Instance
+!
+!> Make the pointer Agrif_Types::Agrif_Curgrid point to Agrif_Gr
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Instance ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer :: Agrif_Gr   !< Pointer on the current grid
+!
+    Agrif_Curgrid => Agrif_Gr
+    Agrif_tabvars => Agrif_Curgrid % tabvars
+    Agrif_tabvars_c => Agrif_Curgrid % tabvars_c
+    Agrif_tabvars_r => Agrif_Curgrid % tabvars_r
+    Agrif_tabvars_l => Agrif_Curgrid % tabvars_l
+    Agrif_tabvars_i => Agrif_Curgrid % tabvars_i
+!
+#if defined AGRIF_MPI
+    if ( Agrif_Gr % communicator /= -1 ) then
+        call Agrif_MPI_switch_comm( Agrif_Gr % communicator )
+    endif
+#endif
+!
+    call Agrif_Get_numberofcells(Agrif_Gr)
+    call Agrif_InitWorkSpace()
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Instance
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_initialisations
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_initialisations ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer :: Agrif_Gr   !< Pointer on the current grid
+!
+    integer                         :: i
+    type(Agrif_Variable),   pointer :: var => NULL()
+    type(Agrif_Variable_c), pointer :: var_c => NULL()
+    type(Agrif_Variable_r), pointer :: var_r => NULL()
+    type(Agrif_Variable_l), pointer :: var_l => NULL()
+    type(Agrif_Variable_i), pointer :: var_i => NULL()
+!
+    do i = 1,Agrif_NbVariables(0)
+!
+        var => Agrif_Gr % tabvars(i)
+        var % nbdim = 0
+!
+        if (allocated(var%array1)) then
+            var % nbdim = 1
+            var % lb(1:1) = lbound(var%array1)
+            var % ub(1:1) = ubound(var%array1)
+        endif
+        if (allocated(var%array2)) then
+            var % nbdim = 2
+            var % lb(1:2) = lbound(var%array2)
+            var % ub(1:2) = ubound(var%array2)
+        endif
+        if (allocated(var%array3)) then
+            var % nbdim = 3
+            var % lb(1:3) = lbound(var%array3)
+            var % ub(1:3) = ubound(var%array3)
+        endif
+        if (allocated(var%array4)) then
+            var % nbdim = 4
+            var % lb(1:4) = lbound(var%array4)
+            var % ub(1:4) = ubound(var%array4)
+        endif
+        if (allocated(var%array5)) then
+            var % nbdim = 5
+            var % lb(1:5) = lbound(var%array5)
+            var % ub(1:5) = ubound(var%array5)
+        endif
+        if (allocated(var%array6)) then
+            var % nbdim = 6
+            var % lb(1:6) = lbound(var%array6)
+            var % ub(1:6) = ubound(var%array6)
+        endif
+!
+        if (allocated(var%darray1)) var % nbdim = 1
+        if (allocated(var%darray2)) var % nbdim = 2
+        if (allocated(var%darray3)) var % nbdim = 3
+        if (allocated(var%darray4)) var % nbdim = 4
+        if (allocated(var%darray5)) var % nbdim = 5
+        if (allocated(var%darray6)) var % nbdim = 6
+!
+        if (allocated(var%sarray1)) var % nbdim = 1
+        if (allocated(var%sarray2)) var % nbdim = 2
+        if (allocated(var%sarray3)) var % nbdim = 3
+        if (allocated(var%sarray4)) var % nbdim = 4
+        if (allocated(var%sarray5)) var % nbdim = 5
+        if (allocated(var%sarray6)) var % nbdim = 6
+!
+    enddo
+
+    do i = 1,Agrif_NbVariables(1)
+!
+        var_c => Agrif_Gr % tabvars_c(i)
+        var_c % nbdim = 0
+!
+        if (allocated(var_c%carray1)) var_c % nbdim = 1
+        if (allocated(var_c%carray2)) var_c % nbdim = 2
+!
+    enddo
+
+    do i = 1,Agrif_NbVariables(2)
+!
+        var_r => Agrif_Gr % tabvars_r(i)
+        var_r % nbdim = 0
+!
+    enddo
+
+    do i = 1,Agrif_NbVariables(3)
+!
+        var_l => Agrif_Gr % tabvars_l(i)
+        var_l % nbdim = 0
+!
+        if (allocated(var_l%larray1)) var_l % nbdim = 1
+        if (allocated(var_l%larray2)) var_l % nbdim = 2
+        if (allocated(var_l%larray3)) var_l % nbdim = 3
+        if (allocated(var_l%larray4)) var_l % nbdim = 4
+        if (allocated(var_l%larray5)) var_l % nbdim = 5
+        if (allocated(var_l%larray6)) var_l % nbdim = 6
+!
+    enddo
+
+    do i = 1,Agrif_NbVariables(4)
+!
+        var_i => Agrif_Gr % tabvars_i(i)
+        var_i % nbdim = 0
+!
+        if (allocated(var_i%iarray1)) var_i % nbdim = 1
+        if (allocated(var_i%iarray2)) var_i % nbdim = 2
+        if (allocated(var_i%iarray3)) var_i % nbdim = 3
+        if (allocated(var_i%iarray4)) var_i % nbdim = 4
+        if (allocated(var_i%iarray5)) var_i % nbdim = 5
+        if (allocated(var_i%iarray6)) var_i % nbdim = 6
+!
+    enddo
+
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_initialisations
+!===================================================================================================
+!
+end module Agrif_Init
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinitvars.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinitvars.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinitvars.F90	(revision 9987)
@@ -0,0 +1,86 @@
+!
+! $Id$
+!
+!     Agrif (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Init_Vars
+!>
+!> Initialization of the variables of the current grid.
+!
+module Agrif_Init_Vars
+!
+    use Agrif_Types
+    use Agrif_Grids
+    use Agrif_Link
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_Create_Var
+!
+!> Allocation of the list of grid variables for grid Agrif_Gr.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Create_Var ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: Agrif_Gr  !< Pointer on the current grid
+!
+    integer :: nb
+!
+    if (Agrif_NbVariables(0) > 0) allocate(Agrif_Gr % tabvars  (Agrif_NbVariables(0)))
+    if (Agrif_NbVariables(1) > 0) allocate(Agrif_Gr % tabvars_c(Agrif_NbVariables(1)))
+    if (Agrif_NbVariables(2) > 0) allocate(Agrif_Gr % tabvars_r(Agrif_NbVariables(2)))
+    if (Agrif_NbVariables(3) > 0) allocate(Agrif_Gr % tabvars_l(Agrif_NbVariables(3)))
+    if (Agrif_NbVariables(4) > 0) allocate(Agrif_Gr % tabvars_i(Agrif_NbVariables(4)))
+!
+    if ( Agrif_Gr % fixedrank /= 0 ) then
+        do nb = 1, Agrif_NbVariables(0)
+            Agrif_Gr % tabvars(nb) % parent_var => Agrif_Gr % parent % tabvars(nb)
+            Agrif_Gr % tabvars(nb) % nbdim      =  Agrif_Mygrid % tabvars(nb) % nbdim
+            Agrif_Gr % tabvars(nb) % root_var   => Agrif_Mygrid % tabvars(nb)
+        enddo
+        do nb = 1, Agrif_NbVariables(1)
+            Agrif_Gr % tabvars_c(nb) % parent_var => Agrif_Gr % parent % tabvars_c(nb)
+            Agrif_Gr % tabvars_c(nb) % nbdim      =  Agrif_Mygrid % tabvars_c(nb) % nbdim
+            Agrif_Gr % tabvars_c(nb) % root_var   => Agrif_Mygrid % tabvars_c(nb)
+        enddo
+        do nb = 1, Agrif_NbVariables(2)
+            Agrif_Gr % tabvars_r(nb) % parent_var => Agrif_Gr % parent % tabvars_r(nb)
+            Agrif_Gr % tabvars_r(nb) % nbdim      =  Agrif_Mygrid % tabvars_r(nb) % nbdim
+            Agrif_Gr % tabvars_r(nb) % root_var   => Agrif_Mygrid % tabvars_r(nb)
+        enddo
+        do nb = 1, Agrif_NbVariables(3)
+            Agrif_Gr % tabvars_l(nb) % parent_var => Agrif_Gr % parent % tabvars_l(nb)
+            Agrif_Gr % tabvars_l(nb) % nbdim      =  Agrif_Mygrid % tabvars_l(nb) % nbdim
+            Agrif_Gr % tabvars_l(nb) % root_var   => Agrif_Mygrid % tabvars_l(nb)
+        enddo
+        do nb = 1, Agrif_NbVariables(4)
+            Agrif_Gr % tabvars_i(nb) % parent_var => Agrif_Gr % parent % tabvars_i(nb)
+            Agrif_Gr % tabvars_i(nb) % nbdim      =  Agrif_Mygrid % tabvars_i(nb) % nbdim
+            Agrif_Gr % tabvars_i(nb) % root_var   => Agrif_Mygrid % tabvars_i(nb)
+        enddo
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Create_Var
+!===================================================================================================
+!
+end module Agrif_Init_Vars
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinterp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinterp.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinterp.F90	(revision 9987)
@@ -0,0 +1,1507 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module to initialize a fine grid from its parent grid, by using a space interpolation
+!
+module Agrif_Interpolation
+!
+    use Agrif_InterpBasic
+    use Agrif_Arrays
+    use Agrif_Mask
+    use Agrif_CurgridFunctions
+#if defined AGRIF_MPI
+    use Agrif_Mpp
+#endif
+!
+    implicit none
+!
+    logical, private:: precomputedone(7) = .FALSE.
+!
+    private :: Agrif_Parentbounds
+    private :: Agrif_Interp_1D_recursive, Agrif_Interp_2D_recursive, Agrif_Interp_3D_recursive
+    private :: Agrif_Interp_4D_recursive, Agrif_Interp_5D_recursive, Agrif_Interp_6D_recursive
+    private :: Agrif_InterpBase
+    private :: Agrif_Find_list_interp, Agrif_AddTo_list_interp
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_InterpVariable
+!
+!> Sets some arguments of subroutine Agrif_InterpnD, n being the dimension of the grid variable
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpVariable ( parent, child, torestore, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), pointer       :: parent       !< Variable on the parent grid
+    type(Agrif_Variable), pointer       :: child        !< Variable on the child grid
+    logical,              intent(in)    :: torestore    !< .false. indicates that the results of the
+                                                        !! interpolation are applied on the whole current grid
+    procedure()                         :: procname     !< Data recovery procedure
+!---------------------------------------------------------------------------------------------------
+    logical               :: memberin
+    integer               :: nbdim        ! Number of dimensions of the current grid
+    integer, dimension(6) :: type_interp  ! Type of interpolation (linear,spline,...)
+    integer, dimension(6) :: nb_child
+    integer, dimension(6) :: lb_child
+    integer, dimension(6) :: ub_child
+    integer, dimension(6) :: lb_parent
+    real   , dimension(6) :: s_child,   s_parent
+    real   , dimension(6) :: ds_child, ds_parent
+    integer, dimension(child % root_var % nbdim,2,2) :: childarray
+!
+    nbdim       = child % root_var % nbdim
+    type_interp = child % root_var % type_interp
+!
+    call PreProcessToInterpOrUpdate( parent,   child,       &
+                                     nb_child, ub_child,    &
+                                     lb_child, lb_parent,   &
+                                      s_child,  s_parent,   &
+                                     ds_child, ds_parent, nbdim, interp=.true.)
+!
+!   Call to a procedure of interpolation against the number of dimensions of the grid variable
+!
+    call Agrif_InterpnD(type_interp, parent, child, &
+                        lb_child, ub_child,         &
+                        lb_child, lb_parent,        &
+                        s_child,   s_parent,        &
+                        ds_child, ds_parent,        &
+                        child, torestore, nbdim,    &
+                        childarray, memberin,       &
+                        .false., procname, 0, 0)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpVariable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpnD
+!
+!> Interpolates a nD grid variable from its parent grid, by using a space interpolation
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpnD ( type_interp, parent, child, pttab, petab, pttab_Child, pttab_Parent, &
+                            s_Child, s_Parent, ds_Child, ds_Parent, restore, torestore,          &
+                            nbdim, childarray, memberin, in_bc, procname, nb, ndir )
+!---------------------------------------------------------------------------------------------------
+#if defined AGRIF_MPI
+    include 'mpif.h'
+#endif
+!
+    INTEGER, DIMENSION(6),     INTENT(in)   :: type_interp  !< Type of interpolation !    (linear,...)
+    TYPE(Agrif_Variable),      pointer      :: parent       !< Variable of the parent grid
+    TYPE(Agrif_Variable),      pointer      :: child        !< Variable of the child grid
+    INTEGER, DIMENSION(nbdim), INTENT(in)   :: pttab        !< Index of the first point inside the domain
+    INTEGER, DIMENSION(nbdim), INTENT(in)   :: petab        !< Index of the first point inside the domain
+    INTEGER, DIMENSION(nbdim), INTENT(in)   :: pttab_Child  !< Index of the first point inside the domain
+                                                            !<    for the child grid variable
+    INTEGER, DIMENSION(nbdim), INTENT(in)   :: pttab_Parent !< Index of the first point inside the domain
+                                                            !<    for the parent grid variable
+    REAL,    DIMENSION(nbdim), INTENT(in)   :: s_Child,s_Parent   !< Positions of the parent and child grids
+    REAL,    DIMENSION(nbdim), INTENT(in)   :: ds_Child,ds_Parent !< Space steps of the parent and child grids
+    TYPE(Agrif_Variable),      pointer      :: restore            !< Indicates points where interpolation
+    LOGICAL,                   INTENT(in)   :: torestore          !< Indicates if the array restore is used
+    INTEGER,                   INTENT(in)   :: nbdim
+    LOGICAL,                   INTENT(out)  :: memberin
+    LOGICAL,                   INTENT(in)   :: in_bc              !< .true. if called from Agrif_CorrectVariable \n
+                                                                  !! .false. if called from Agrif_InterpVariable
+    procedure()                             :: procname           !< Data recovery procedure
+    INTEGER,                   INTENT(in)   :: nb, ndir
+!
+    INTEGER                       :: i,j,k,l,m,n
+    INTEGER, DIMENSION(nbdim)     :: pttruetab,cetruetab
+    INTEGER, DIMENSION(nbdim)     :: indmin,     indmax
+    INTEGER, DIMENSION(nbdim)     :: indminglob, indmaxglob
+#if defined AGRIF_MPI
+    INTEGER, DIMENSION(nbdim)     :: indminglob2,indmaxglob2
+#endif
+    LOGICAL, DIMENSION(nbdim)     :: noraftab
+    REAL   , DIMENSION(nbdim)     :: s_Child_temp,s_Parent_temp
+    INTEGER, DIMENSION(nbdim)     :: lowerbound, upperbound, coords
+    INTEGER, DIMENSION(nbdim,2,2), INTENT(OUT) :: childarray
+    INTEGER, DIMENSION(nbdim,2,2)              :: parentarray
+    LOGICAL :: member
+    LOGICAL :: find_list_interp
+!
+#if defined AGRIF_MPI
+!
+    INTEGER, PARAMETER          :: etiquette = 100
+    INTEGER                     :: code, local_proc
+    INTEGER, DIMENSION(nbdim,4)                     :: tab3
+    INTEGER, DIMENSION(nbdim,4,0:Agrif_Nbprocs-1)   :: tab4
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1,8)   :: tab4t
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1)           :: memberinall
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1)           :: sendtoproc1, recvfromproc1
+    LOGICAL, DIMENSION(1)                           :: memberin1
+    LOGICAL                                         :: memberout
+!
+#endif
+!
+    type(Agrif_Variable), pointer, save :: tempC => NULL()        ! Temporary child grid variable
+    type(Agrif_Variable), pointer, save :: tempP => NULL()        ! Temporary parent grid variable
+    type(Agrif_Variable), pointer, save :: tempPextend => NULL()  ! Temporary parent grid variable
+    type(Agrif_Variable), pointer, save :: parentvalues => NULL()
+!
+    coords = child % root_var % coords
+!
+!   Boundaries of the current grid where interpolation is done
+    find_list_interp =                                              &
+        Agrif_Find_list_interp(                                     &
+            child % list_interp,                                    &
+            pttab, petab, pttab_Child, pttab_Parent, nbdim,         &
+            indmin, indmax, indminglob, indmaxglob,                 &
+            pttruetab, cetruetab, memberin                          &
+#if defined AGRIF_MPI
+           ,indminglob2, indmaxglob2, parentarray,                  &
+            member, tab4t,memberinall,  sendtoproc1, recvfromproc1  &
+#endif
+        )
+!
+    if (.not.find_list_interp) then
+!
+        call Agrif_get_var_bounds_array(child, lowerbound, upperbound, nbdim)
+        call Agrif_Childbounds(nbdim, lowerbound, upperbound,               &
+                               pttab, petab, Agrif_Procrank, coords,        &
+                               pttruetab, cetruetab, memberin)
+        call Agrif_Parentbounds(type_interp,nbdim,indminglob,indmaxglob,    &
+                                s_Parent_temp,s_Child_temp,                 &
+                                s_Child,ds_Child,                           &
+                                s_Parent,ds_Parent,                         &
+                                pttab,petab,                                &
+                                pttab_Child,pttab_Parent,                   &
+                                child%root_var % posvar, coords)
+#if defined AGRIF_MPI
+        if (memberin) then
+            call Agrif_Parentbounds(type_interp,nbdim,indmin,indmax,        &
+                                    s_Parent_temp,s_Child_temp,             &
+                                    s_Child,ds_Child,                       &
+                                    s_Parent,ds_Parent,                     &
+                                    pttruetab,cetruetab,                    &
+                                    pttab_Child,pttab_Parent,               &
+                                    child%root_var % posvar, coords)
+        endif
+
+        local_proc = Agrif_Procrank
+        call Agrif_get_var_bounds_array(parent,lowerbound,upperbound,nbdim)
+        call Agrif_ChildGrid_to_ParentGrid()
+!
+        call Agrif_Childbounds(nbdim,lowerbound,upperbound,                 &
+                               indminglob,indmaxglob, local_proc, coords,   &
+                               indminglob2,indmaxglob2,member)
+!
+        if (member) then
+            call Agrif_GlobalToLocalBounds(parentarray,                     &
+                                           lowerbound,  upperbound,         &
+                                           indminglob2, indmaxglob2, coords,&
+                                           nbdim, local_proc, member)
+        endif
+
+        call Agrif_ParentGrid_to_ChildGrid()
+#else
+        parentarray(:,1,1) = indminglob
+        parentarray(:,2,1) = indmaxglob
+        parentarray(:,1,2) = indminglob
+        parentarray(:,2,2) = indmaxglob
+        indmin = indminglob
+        indmax = indmaxglob
+        member = .TRUE.
+#endif
+
+    else
+
+#if defined AGRIF_MPI
+        s_Parent_temp = s_Parent + (indmin - pttab_Parent) * ds_Parent
+        s_Child_temp  = s_Child + (pttruetab - pttab_Child) * ds_Child
+#else
+        parentarray(:,1,1) = indminglob
+        parentarray(:,2,1) = indmaxglob
+        parentarray(:,1,2) = indminglob
+        parentarray(:,2,2) = indmaxglob
+        indmin = indminglob
+        indmax = indmaxglob
+        member = .TRUE.
+        s_Parent_temp = s_Parent + (indminglob - pttab_Parent) * ds_Parent
+        s_Child_temp  = s_Child + (pttab - pttab_Child) * ds_Child
+#endif
+    endif
+!
+    if (member) then
+        if (.not.associated(tempP)) allocate(tempP)
+!
+        call Agrif_array_allocate(tempP,parentarray(:,1,1),parentarray(:,2,1),nbdim)
+        call Agrif_var_set_array_tozero(tempP,nbdim)
+
+        call Agrif_ChildGrid_to_ParentGrid()
+!
+        select case (nbdim)
+        case(1)
+            call procname(tempP%array1,                         &
+                      parentarray(1,1,2),parentarray(1,2,2),.TRUE.,nb,ndir)
+        case(2)
+            call procname(tempP%array2,                         &
+                      parentarray(1,1,2),parentarray(1,2,2),    &
+                      parentarray(2,1,2),parentarray(2,2,2),.TRUE.,nb,ndir)
+        case(3)
+            call procname(tempP%array3,                         &
+                      parentarray(1,1,2),parentarray(1,2,2),    &
+                      parentarray(2,1,2),parentarray(2,2,2),    &
+                      parentarray(3,1,2),parentarray(3,2,2),.TRUE.,nb,ndir)
+        case(4)
+            call procname(tempP%array4,                         &
+                      parentarray(1,1,2),parentarray(1,2,2),    &
+                      parentarray(2,1,2),parentarray(2,2,2),    &
+                      parentarray(3,1,2),parentarray(3,2,2),    &
+                      parentarray(4,1,2),parentarray(4,2,2),.TRUE.,nb,ndir)
+        case(5)
+            call procname(tempP%array5,                         &
+                      parentarray(1,1,2),parentarray(1,2,2),    &
+                      parentarray(2,1,2),parentarray(2,2,2),    &
+                      parentarray(3,1,2),parentarray(3,2,2),    &
+                      parentarray(4,1,2),parentarray(4,2,2),    &
+                      parentarray(5,1,2),parentarray(5,2,2),.TRUE.,nb,ndir)
+        case(6)
+            call procname(tempP%array6,                         &
+                      parentarray(1,1,2),parentarray(1,2,2),    &
+                      parentarray(2,1,2),parentarray(2,2,2),    &
+                      parentarray(3,1,2),parentarray(3,2,2),    &
+                      parentarray(4,1,2),parentarray(4,2,2),    &
+                      parentarray(5,1,2),parentarray(5,2,2),    &
+                      parentarray(6,1,2),parentarray(6,2,2),.TRUE.,nb,ndir)
+        end select
+!
+        call Agrif_ParentGrid_to_ChildGrid()
+!
+    endif
+
+#if defined AGRIF_MPI
+    if (.not.find_list_interp) then
+!
+        tab3(:,1) = indminglob2(:)
+        tab3(:,2) = indmaxglob2(:)
+        tab3(:,3) = indmin(:)
+        tab3(:,4) = indmax(:)
+!
+        call MPI_ALLGATHER(tab3,4*nbdim,MPI_INTEGER,tab4,4*nbdim,MPI_INTEGER,Agrif_mpi_comm,code)
+
+        if (.not.associated(tempPextend))   allocate(tempPextend)
+
+        do k=0,Agrif_Nbprocs-1
+            do j=1,4
+                do i=1,nbdim
+                    tab4t(i,k,j) = tab4(i,j,k)
+                enddo
+            enddo
+        enddo
+
+        memberin1(1) = memberin
+        call MPI_ALLGATHER(memberin1,1,MPI_LOGICAL,memberinall,1,MPI_LOGICAL,Agrif_mpi_comm,code)
+
+        call Get_External_Data_first(tab4t(:,:,1),tab4t(:,:,2),         &
+                                     tab4t(:,:,3),tab4t(:,:,4),         &
+                                     nbdim,memberinall, coords,         &
+                                     sendtoproc1,recvfromproc1,         &
+                                     tab4t(:,:,5),tab4t(:,:,6),         &
+                                     tab4t(:,:,7),tab4t(:,:,8) )
+    endif
+
+    call ExchangeSameLevel(sendtoproc1,recvfromproc1,nbdim,         &
+            tab4t(:,:,3),tab4t(:,:,4),tab4t(:,:,5),tab4t(:,:,6),    &
+            tab4t(:,:,7),tab4t(:,:,8),memberin,tempP,tempPextend)
+#else
+    tempPextend => tempP
+#endif
+
+    if (.not.find_list_interp) then
+        call Agrif_Addto_list_interp(                           &
+                child%list_interp,pttab,petab,                  &
+                pttab_Child,pttab_Parent,indmin,indmax,         &
+                indminglob,indmaxglob,                          &
+                pttruetab,cetruetab,                            &
+                memberin,nbdim                                  &
+#if defined AGRIF_MPI
+               ,indminglob2,indmaxglob2,                        &
+                parentarray,                                    &
+                member,                                         &
+                tab4t,memberinall,sendtoproc1,recvfromproc1     &
+#endif
+        )
+    endif
+!
+    if (memberin) then
+!
+        if (.not.associated(tempC)) allocate(tempC)
+!
+        call Agrif_array_allocate(tempC,pttruetab,cetruetab,nbdim)
+!
+!       Special values on the parent grid
+        if (Agrif_UseSpecialValue) then
+!
+            noraftab(1:nbdim) = child % root_var % interptab(1:nbdim) == 'N'
+!
+            if (.not.associated(parentvalues))  allocate(parentvalues)
+!
+            call Agrif_array_allocate(parentvalues,indmin,indmax,nbdim)
+            call Agrif_var_full_copy_array(parentvalues,tempPextend,nbdim)
+!
+            call Agrif_CheckMasknD(tempPextend,parentvalues,    &
+                    indmin(1:nbdim),indmax(1:nbdim),            &
+                    indmin(1:nbdim),indmax(1:nbdim),            &
+                    noraftab(1:nbdim),nbdim)
+!
+            call Agrif_array_deallocate(parentvalues,nbdim)
+!
+        endif
+!
+!       Interpolation of the current grid
+!
+        if ( memberin ) then
+            select case(nbdim)
+            case(1)
+                call Agrif_Interp_1D_recursive( type_interp(1),                         &
+                                                tempPextend%array1,                     &
+                                                tempC%array1,                           &
+                                                indmin(1), indmax(1),                   &
+                                                pttruetab(1),    cetruetab(1),          &
+                                                s_Child_temp(1), s_Parent_temp(1),      &
+                                                ds_Child(1),     ds_Parent(1) )
+            case(2)
+                call Agrif_Interp_2D_recursive( type_interp(1:2),                       &
+                                                tempPextend % array2,                   &
+                                                tempC       % array2,                   &
+                                                indmin(1:2), indmax(1:2),               &
+                                                pttruetab(1:2),    cetruetab(1:2),      &
+                                                s_Child_temp(1:2), s_Parent_temp(1:2),  &
+                                                ds_Child(1:2),    ds_Parent(1:2) )
+            case(3)
+                call Agrif_Interp_3D_recursive( type_interp(1:3),                       &
+                                                tempPextend % array3,                   &
+                                                tempC       % array3,                   &
+                                                indmin(1:3), indmax(1:3),               &
+                                                pttruetab(1:3),    cetruetab(1:3),      &
+                                                s_Child_temp(1:3), s_Parent_temp(1:3),  &
+                                                ds_Child(1:3),    ds_Parent(1:3) )
+            case(4)
+                call Agrif_Interp_4D_recursive( type_interp(1:4),                       &
+                                                tempPextend % array4,                   &
+                                                tempC       % array4,                   &
+                                                indmin(1:4), indmax(1:4),               &
+                                                pttruetab(1:4),    cetruetab(1:4),      &
+                                                s_Child_temp(1:4), s_Parent_temp(1:4),  &
+                                                ds_Child(1:4),    ds_Parent(1:4) )
+            case(5)
+                call Agrif_Interp_5D_recursive( type_interp(1:5),                       &
+                                                tempPextend % array5,                   &
+                                                tempC       % array5,                   &
+                                                indmin(1:5), indmax(1:5),               &
+                                                pttruetab(1:5),    cetruetab(1:5),      &
+                                                s_Child_temp(1:5), s_Parent_temp(1:5),  &
+                                                ds_Child(1:5),    ds_Parent(1:5) )
+            case(6)
+                call Agrif_Interp_6D_recursive( type_interp(1:6),                       &
+                                                tempPextend % array6,                   &
+                                                tempC       % array6,                   &
+                                                indmin(1:6), indmax(1:6),               &
+                                                pttruetab(1:6),    cetruetab(1:6),      &
+                                                s_Child_temp(1:6), s_Parent_temp(1:6),  &
+                                                ds_Child(1:6),    ds_Parent(1:6) )
+            end select
+!
+            call Agrif_get_var_bounds_array(child,lowerbound,upperbound,nbdim)
+
+#if defined AGRIF_MPI
+            call Agrif_GlobalToLocalBounds(childarray, lowerbound, upperbound,  &
+                                            pttruetab, cetruetab, coords,       &
+                                            nbdim, Agrif_Procrank, memberout)
+#else
+            childarray(:,1,1) = pttruetab
+            childarray(:,2,1) = cetruetab
+            childarray(:,1,2) = pttruetab
+            childarray(:,2,2) = cetruetab
+!cccccccccccccc       memberout = .TRUE.
+#endif
+!
+!           Special values on the child grid
+            if (Agrif_UseSpecialValueFineGrid) then
+                call GiveAgrif_SpecialValueToTab_mpi( child, tempC, childarray, Agrif_SpecialValueFineGrid,nbdim )
+            endif
+!
+        endif   ! ( memberin )
+!
+        if (torestore) then
+!
+#if defined AGRIF_MPI
+!
+            SELECT CASE (nbdim)
+            CASE (1)
+                do i = pttruetab(1),cetruetab(1)
+!hildarrayAModifier     if (restore%restore1D(i) == 0)      &
+!hildarrayAModifier         child%array1(childarray(i,1,2)) = tempC%array1(i)
+                enddo
+            CASE (2)
+                do i = pttruetab(1),cetruetab(1)
+                do j = pttruetab(2),cetruetab(2)
+!hildarrayAModifier     if (restore%restore2D(i,j) == 0)    &
+!hildarrayAModifier         child%array2(childarray(i,1,2), &
+!hildarrayAModifier                          childarray(j,2,2)) = tempC%array2(i,j)
+                enddo
+                enddo
+            CASE (3)
+                do i = pttruetab(1),cetruetab(1)
+                do j = pttruetab(2),cetruetab(2)
+                do k = pttruetab(3),cetruetab(3)
+!hildarrayAModifier     if (restore%restore3D(i,j,k) == 0)  &
+!hildarrayAModifier         child%array3(childarray(i,1,2), &
+!hildarrayAModifier                          childarray(j,2,2), &
+!hildarrayAModifier                          childarray(k,3,2)) = tempC%array3(i,j,k)
+                enddo
+                enddo
+                enddo
+            CASE (4)
+                do i = pttruetab(1),cetruetab(1)
+                do j = pttruetab(2),cetruetab(2)
+                do k = pttruetab(3),cetruetab(3)
+                do l = pttruetab(4),cetruetab(4)
+!hildarrayAModifier     if (restore%restore4D(i,j,k,l) == 0)    &
+!hildarrayAModifier         child%array4(childarray(i,1,2),     &
+!hildarrayAModifier                          childarray(j,2,2),     &
+!hildarrayAModifier                          childarray(k,3,2),     &
+!hildarrayAModifier                          childarray(l,4,2)) = tempC%array4(i,j,k,l)
+                enddo
+                enddo
+                enddo
+                enddo
+            CASE (5)
+                do i = pttruetab(1),cetruetab(1)
+                do j = pttruetab(2),cetruetab(2)
+                do k = pttruetab(3),cetruetab(3)
+                do l = pttruetab(4),cetruetab(4)
+                do m = pttruetab(5),cetruetab(5)
+!hildarrayAModifier     if (restore%restore5D(i,j,k,l,m) == 0)  &
+!hildarrayAModifier         child%array5(childarray(i,1,2),     &
+!hildarrayAModifier                          childarray(j,2,2),     &
+!hildarrayAModifier                          childarray(k,3,2),     &
+!hildarrayAModifier                          childarray(l,4,2),     &
+!hildarrayAModifier                          childarray(m,5,2)) = tempC%array5(i,j,k,l,m)
+                enddo
+                enddo
+                enddo
+                enddo
+                enddo
+            CASE (6)
+                do i = pttruetab(1),cetruetab(1)
+                do j = pttruetab(2),cetruetab(2)
+                do k = pttruetab(3),cetruetab(3)
+                do l = pttruetab(4),cetruetab(4)
+                do m = pttruetab(5),cetruetab(5)
+                do n = pttruetab(6),cetruetab(6)
+!hildarrayAModifier     if (restore%restore6D(i,j,k,l,m,n) == 0)    &
+!hildarrayAModifier         child%array6(childarray(i,1,2),         &
+!hildarrayAModifier                          childarray(j,2,2),         &
+!hildarrayAModifier                          childarray(k,3,2),         &
+!hildarrayAModifier                          childarray(l,4,2),         &
+!hildarrayAModifier                          childarray(m,5,2),         &
+!hildarrayAModifier                          childarray(n,6,2)) = tempC%array6(i,j,k,l,m,n)
+                enddo
+                enddo
+                enddo
+                enddo
+                enddo
+                enddo
+            END SELECT
+!
+#else
+            select case (nbdim)
+            case (1)
+                do i = pttruetab(1),cetruetab(1)
+                    if (restore%restore1D(i) == 0)          &
+                        parray1(i) = tempC % array1(i)
+                enddo
+            case (2)
+                do j = pttruetab(2),cetruetab(2)
+                do i = pttruetab(1),cetruetab(1)
+                    if (restore%restore2D(i,j) == 0)        &
+                        parray2(i,j) = tempC % array2(i,j)
+                enddo
+                enddo
+            case (3)
+                do k = pttruetab(3),cetruetab(3)
+                do j = pttruetab(2),cetruetab(2)
+                do i = pttruetab(1),cetruetab(1)
+                    if (restore%restore3D(i,j,k) == 0)      &
+                        parray3(i,j,k) = tempC % array3(i,j,k)
+                enddo
+                enddo
+                enddo
+            case (4)
+                do l = pttruetab(4),cetruetab(4)
+                do k = pttruetab(3),cetruetab(3)
+                do j = pttruetab(2),cetruetab(2)
+                do i = pttruetab(1),cetruetab(1)
+                    if (restore%restore4D(i,j,k,l) == 0)    &
+                        parray4(i,j,k,l) = tempC % array4(i,j,k,l)
+                enddo
+                enddo
+                enddo
+                enddo
+            case (5)
+                do m = pttruetab(5),cetruetab(5)
+                do l = pttruetab(4),cetruetab(4)
+                do k = pttruetab(3),cetruetab(3)
+                do j = pttruetab(2),cetruetab(2)
+                do i = pttruetab(1),cetruetab(1)
+                    if (restore%restore5D(i,j,k,l,m) == 0)  &
+                        parray5(i,j,k,l,m) = tempC % array5(i,j,k,l,m)
+                enddo
+                enddo
+                enddo
+                enddo
+                enddo
+            case (6)
+                do n = pttruetab(6),cetruetab(6)
+                do m = pttruetab(5),cetruetab(5)
+                do l = pttruetab(4),cetruetab(4)
+                do k = pttruetab(3),cetruetab(3)
+                do j = pttruetab(2),cetruetab(2)
+                do i = pttruetab(1),cetruetab(1)
+                    if (restore%restore6D(i,j,k,l,m,n) == 0)    &
+                        parray6(i,j,k,l,m,n) = tempC % array6(i,j,k,l,m,n)
+                enddo
+                enddo
+                enddo
+                enddo
+                enddo
+                enddo
+            end select
+!
+#endif
+!
+        else    ! .not.to_restore
+!
+            if (memberin) then
+    !
+                if ( .not.in_bc ) then
+                    select case(nbdim)
+                    case(1)
+                        call procname(tempC % array1(            &
+                                childarray(1,1,1):childarray(1,2,1)), &
+                                childarray(1,1,2),childarray(1,2,2),.FALSE.,nb,ndir)
+                    case(2)
+                        call procname(                                &
+                                tempC % array2(            &
+                                childarray(1,1,1):childarray(1,2,1),  &
+                                childarray(2,1,1):childarray(2,2,1)), &
+                                childarray(1,1,2),childarray(1,2,2),  &
+                                childarray(2,1,2),childarray(2,2,2),.FALSE.,nb,ndir)
+                    case(3)
+                        call procname(                                &
+                                tempC % array3(            &
+                                childarray(1,1,1):childarray(1,2,1),  &
+                                childarray(2,1,1):childarray(2,2,1),  &
+                                childarray(3,1,1):childarray(3,2,1)), &
+                                childarray(1,1,2),childarray(1,2,2),  &
+                                childarray(2,1,2),childarray(2,2,2),  &
+                                childarray(3,1,2),childarray(3,2,2),.FALSE.,nb,ndir)
+                    case(4)
+                        call procname(                                &
+                                tempC % array4(            &
+                                childarray(1,1,1):childarray(1,2,1),  &
+                                childarray(2,1,1):childarray(2,2,1),  &
+                                childarray(3,1,1):childarray(3,2,1),  &
+                                childarray(4,1,1):childarray(4,2,1)), &
+                                childarray(1,1,2),childarray(1,2,2),  &
+                                childarray(2,1,2),childarray(2,2,2),  &
+                                childarray(3,1,2),childarray(3,2,2),  &
+                                childarray(4,1,2),childarray(4,2,2),.FALSE.,nb,ndir)
+                    case(5)
+                        call procname(                                &
+                                tempC % array5(            &
+                                childarray(1,1,1):childarray(1,2,1),  &
+                                childarray(2,1,1):childarray(2,2,1),  &
+                                childarray(3,1,1):childarray(3,2,1),  &
+                                childarray(4,1,1):childarray(4,2,1),  &
+                                childarray(5,1,1):childarray(5,2,1)), &
+                                childarray(1,1,2),childarray(1,2,2),  &
+                                childarray(2,1,2),childarray(2,2,2),  &
+                                childarray(3,1,2),childarray(3,2,2),  &
+                                childarray(4,1,2),childarray(4,2,2),  &
+                                childarray(5,1,2),childarray(5,2,2),.FALSE.,nb,ndir)
+                    case(6)
+                        call procname(                                &
+                                tempC % array6(            &
+                                childarray(1,1,1):childarray(1,2,1),  &
+                                childarray(2,1,1):childarray(2,2,1),  &
+                                childarray(3,1,1):childarray(3,2,1),  &
+                                childarray(4,1,1):childarray(4,2,1),  &
+                                childarray(5,1,1):childarray(5,2,1),  &
+                                childarray(6,1,1):childarray(6,2,1)), &
+                                childarray(1,1,2),childarray(1,2,2),  &
+                                childarray(2,1,2),childarray(2,2,2),  &
+                                childarray(3,1,2),childarray(3,2,2),  &
+                                childarray(4,1,2),childarray(4,2,2),  &
+                                childarray(5,1,2),childarray(5,2,2),  &
+                                childarray(6,1,2),childarray(6,2,2),.FALSE.,nb,ndir)
+                    end select
+                else    ! we are in_bc
+                    select case (nbdim)
+                    case (1)
+                        parray1(childarray(1,1,2):childarray(1,2,2)) =    &
+                         tempC%array1(childarray(1,1,1):childarray(1,2,1))
+                    case (2)
+                        parray2(childarray(1,1,2):childarray(1,2,2),      &
+                                      childarray(2,1,2):childarray(2,2,2)) =    &
+                         tempC%array2(childarray(1,1,1):childarray(1,2,1),      &
+                                      childarray(2,1,1):childarray(2,2,1))
+                    case (3)
+                        parray3(childarray(1,1,2):childarray(1,2,2),      &
+                                      childarray(2,1,2):childarray(2,2,2),      &
+                                      childarray(3,1,2):childarray(3,2,2)) =    &
+                         tempC%array3(childarray(1,1,1):childarray(1,2,1),      &
+                                      childarray(2,1,1):childarray(2,2,1),      &
+                                      childarray(3,1,1):childarray(3,2,1))
+                    case (4)
+                        parray4(childarray(1,1,2):childarray(1,2,2),      &
+                                      childarray(2,1,2):childarray(2,2,2),      &
+                                      childarray(3,1,2):childarray(3,2,2),      &
+                                      childarray(4,1,2):childarray(4,2,2)) =    &
+                         tempC%array4(childarray(1,1,1):childarray(1,2,1),      &
+                                      childarray(2,1,1):childarray(2,2,1),      &
+                                      childarray(3,1,1):childarray(3,2,1),      &
+                                      childarray(4,1,1):childarray(4,2,1))
+                    case (5)
+                        parray5(childarray(1,1,2):childarray(1,2,2),      &
+                                      childarray(2,1,2):childarray(2,2,2),      &
+                                      childarray(3,1,2):childarray(3,2,2),      &
+                                      childarray(4,1,2):childarray(4,2,2),      &
+                                      childarray(5,1,2):childarray(5,2,2)) =    &
+                         tempC%array5(childarray(1,1,1):childarray(1,2,1),      &
+                                      childarray(2,1,1):childarray(2,2,1),      &
+                                      childarray(3,1,1):childarray(3,2,1),      &
+                                      childarray(4,1,1):childarray(4,2,1),      &
+                                      childarray(5,1,1):childarray(5,2,1))
+                    case (6)
+                        parray6(childarray(1,1,2):childarray(1,2,2),      &
+                                      childarray(2,1,2):childarray(2,2,2),      &
+                                      childarray(3,1,2):childarray(3,2,2),      &
+                                      childarray(4,1,2):childarray(4,2,2),      &
+                                      childarray(5,1,2):childarray(5,2,2),      &
+                                      childarray(6,1,2):childarray(6,2,2)) =    &
+                         tempC%array6(childarray(1,1,1):childarray(1,2,1),      &
+                                      childarray(2,1,1):childarray(2,2,1),      &
+                                      childarray(3,1,1):childarray(3,2,1),      &
+                                      childarray(4,1,1):childarray(4,2,1),      &
+                                      childarray(5,1,1):childarray(5,2,1),      &
+                                      childarray(6,1,1):childarray(6,2,1))
+                    end select
+                endif  ! < (.not.in_bc)
+            endif  ! < memberin
+!
+        endif
+
+        call Agrif_array_deallocate(tempPextend,nbdim)
+        call Agrif_array_deallocate(tempC,nbdim)
+
+    endif
+!
+!   Deallocations
+#if defined AGRIF_MPI
+    if (member) then
+        call Agrif_array_deallocate(tempP,nbdim)
+    endif
+#endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpnD
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Parentbounds
+!
+!> Calculates the bounds of the parent grid for the interpolation of the child grid
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Parentbounds ( type_interp, nbdim, indmin, indmax, &
+                                s_Parent_temp, s_Child_temp,        &
+                                s_Child, ds_Child,                  &
+                                s_Parent,ds_Parent,                 &
+                                pttruetab, cetruetab,               &
+                                pttab_Child, pttab_Parent, posvar, coords )
+!---------------------------------------------------------------------------------------------------
+    INTEGER, DIMENSION(6),     intent(in)  :: type_interp
+    INTEGER,                   intent(in)  :: nbdim
+    INTEGER, DIMENSION(nbdim), intent(out) :: indmin, indmax
+    REAL,    DIMENSION(nbdim), intent(out) :: s_Parent_temp, s_child_temp
+    REAL,    DIMENSION(nbdim), intent(in)  :: s_Child, ds_child
+    REAL,    DIMENSION(nbdim), intent(in)  :: s_Parent,ds_Parent
+    INTEGER, DIMENSION(nbdim), intent(in)  :: pttruetab, cetruetab
+    INTEGER, DIMENSION(nbdim), intent(in)  :: pttab_Child, pttab_Parent
+    INTEGER, DIMENSION(nbdim), intent(in)  :: posvar
+    INTEGER, DIMENSION(nbdim), intent(in)  :: coords
+!
+    INTEGER :: i
+    REAL,DIMENSION(nbdim) :: dim_newmin, dim_newmax
+!
+    dim_newmin = s_Child + (pttruetab - pttab_Child) * ds_Child
+    dim_newmax = s_Child + (cetruetab - pttab_Child) * ds_Child
+!
+    do i = 1,nbdim
+!
+        indmin(i) = pttab_Parent(i) + agrif_int((dim_newmin(i)-s_Parent(i))/ds_Parent(i))
+        indmax(i) = pttab_Parent(i) + agrif_ceiling((dim_newmax(i)-s_Parent(i))/ds_Parent(i))
+!
+!       Necessary for the Quadratic interpolation
+!
+        if ( (pttruetab(i) == cetruetab(i)) .and. (posvar(i) == 1) ) then
+        elseif ( coords(i) == 0 ) then  ! (interptab == 'N')
+        elseif ( (type_interp(i) == Agrif_ppm)     .or.     &
+                 (type_interp(i) == Agrif_eno)     .or.     &
+                 (type_interp(i) == Agrif_ppm_lim) .or.     &
+                 (type_interp(i) == Agrif_weno) ) then
+            indmin(i) = indmin(i) - 2
+            indmax(i) = indmax(i) + 2
+        elseif ( (type_interp(i) /= Agrif_constant) .and.   &
+                 (type_interp(i) /= Agrif_linear) ) then
+            indmin(i) = indmin(i) - 1
+            indmax(i) = indmax(i) + 1
+        endif
+!
+    enddo
+!
+    s_Parent_temp = s_Parent + (indmin - pttab_Parent) * ds_Parent
+    s_Child_temp  = s_Child + (pttruetab - pttab_Child) * ds_Child
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Parentbounds
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_1D_Recursive
+!
+!> Subroutine for the interpolation of a 1D grid variable.
+!> It calls Agrif_InterpBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_1D_recursive ( type_interp, tabin, tabout,  &
+                                       indmin, indmax,              &
+                                       pttab_child, petab_child,    &
+                                       s_child,  s_parent,          &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer,            intent(in)  :: type_interp
+    integer,            intent(in)  :: indmin, indmax
+    integer,            intent(in)  :: pttab_child, petab_child
+    real,               intent(in)  :: s_child, s_parent
+    real,               intent(in)  :: ds_child, ds_parent
+    real, dimension(            &
+        indmin:indmax           &
+    ),                  intent(in)  :: tabin
+    real, dimension(            &
+        pttab_child:petab_child &
+    ),                  intent(out) :: tabout
+!---------------------------------------------------------------------------------------------------
+    call Agrif_InterpBase(type_interp,                      &
+                          tabin(indmin:indmax),             &
+                          tabout(pttab_child:petab_child),  &
+                          indmin, indmax,                   &
+                          pttab_child, petab_child,         &
+                          s_parent,    s_child,             &
+                         ds_parent,   ds_child)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_1D_recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_2D_Recursive
+!
+!> Subroutine for the interpolation of a 2D grid variable.
+!> It calls Agrif_Interp_1D_recursive and Agrif_InterpBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_2D_recursive ( type_interp, tabin, tabout,  &
+                                       indmin, indmax,              &
+                                       pttab_child, petab_child,    &
+                                       s_child,  s_parent,          &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(2),              intent(in)  :: type_interp
+    integer, dimension(2),              intent(in)  :: indmin, indmax
+    integer, dimension(2),              intent(in)  :: pttab_child, petab_child
+    real,    dimension(2),              intent(in)  :: s_child, s_parent
+    real,    dimension(2),              intent(in)  :: ds_child, ds_parent
+    real,    dimension(                 &
+        indmin(1):indmax(1),            &
+        indmin(2):indmax(2)),           intent(in)  :: tabin
+    real,    dimension(                 &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2)), intent(out) :: tabout
+!---------------------------------------------------------------------------------------------------
+    real, dimension(                    &
+        pttab_child(1):petab_child(1),  &
+        indmin(2):indmax(2))            :: tabtemp
+    real, dimension(                    &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(1):petab_child(1))  :: tabout_trsp
+    real, dimension(                    &
+        indmin(2):indmax(2),            &
+        pttab_child(1):petab_child(1))  :: tabtemp_trsp
+    integer                             :: i, j, coeffraf
+!---------------------------------------------------------------------------------------------------
+!
+    coeffraf = nint ( ds_parent(1) / ds_child(1) )
+!
+    if ((type_interp(1) == Agrif_Linear) .and. (coeffraf /= 1)) then
+!---CDIR NEXPAND
+        if(.NOT. precomputedone(1))     &
+            call Linear1dPrecompute2d(                  &
+                    indmax(2)-indmin(2)+1,              &
+                    indmax(1)-indmin(1)+1,              &
+                    petab_child(1)-pttab_child(1)+1,    &
+                    s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+!---CDIR NEXPAND
+        call Linear1dAfterCompute(tabin,tabtemp,size(tabin),size(tabtemp),1)
+!
+    elseif ((type_interp(1) == Agrif_PPM) .and. (coeffraf /= 1)) then
+!---CDIR NEXPAND
+        if(.NOT. precomputedone(1))     &
+            call PPM1dPrecompute2d(                     &
+                    indmax(2)-indmin(2)+1,              &
+                    indmax(1)-indmin(1)+1,              &
+                    petab_child(1)-pttab_child(1)+1,        &
+                    s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+!---CDIR NEXPAND
+        call PPM1dAfterCompute(tabin,tabtemp,size(tabin),size(tabtemp),1)
+    else
+        do j = indmin(2),indmax(2)
+!
+!---CDIR NEXPAND
+            call Agrif_Interp_1D_recursive(type_interp(1),                  &
+                    tabin(indmin(1):indmax(1),j),               &
+                    tabtemp(pttab_child(1):petab_child(1),j),   &
+                    indmin(1),indmax(1),                    &
+                    pttab_child(1),petab_child(1),          &
+                    s_child(1), s_parent(1),                &
+                    ds_child(1),ds_parent(1))
+!
+        enddo
+    endif
+
+    coeffraf = nint(ds_parent(2)/ds_child(2))
+    tabtemp_trsp = TRANSPOSE(tabtemp)
+
+    if ((type_interp(2) == Agrif_Linear) .and. (coeffraf /= 1)) then
+!---CDIR NEXPAND
+        if(.NOT. precomputedone(2))     &
+            call Linear1dPrecompute2d(                  &
+                    petab_child(1)-pttab_child(1)+1,    &
+                    indmax(2)-indmin(2)+1,              &
+                    petab_child(2)-pttab_child(2)+1,    &
+                    s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+!---CDIR NEXPAND
+        call Linear1dAfterCompute(tabtemp_trsp,tabout_trsp, &
+                size(tabtemp_trsp),size(tabout_trsp),2)
+
+    elseif ((type_interp(2) == Agrif_PPM) .and. (coeffraf /= 1)) then
+!---CDIR NEXPAND
+        if(.NOT. precomputedone(2))     &
+            call PPM1dPrecompute2d(                     &
+                    petab_child(1)-pttab_child(1)+1,    &
+                    indmax(2)-indmin(2)+1,              &
+                    petab_child(2)-pttab_child(2)+1,    &
+                    s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+!---CDIR NEXPAND
+        call PPM1dAfterCompute(tabtemp_trsp, tabout_trsp,    &
+                               size(tabtemp_trsp), size(tabout_trsp), 2)
+    else
+        do i = pttab_child(1), petab_child(1)
+!
+!---CDIR NEXPAND
+            call Agrif_InterpBase(type_interp(2),                                   &
+                                  tabtemp_trsp(indmin(2):indmax(2), i),             &
+                                  tabout_trsp(pttab_child(2):petab_child(2), i),    &
+                                  indmin(2), indmax(2),                             &
+                                  pttab_child(2), petab_child(2),                   &
+                                  s_parent(2),    s_child(2),                       &
+                                 ds_parent(2),   ds_child(2) )
+        enddo
+    endif
+!
+    tabout = TRANSPOSE(tabout_trsp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_2D_recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_3D_Recursive
+!
+!> Subroutine for the interpolation of a 3D grid variable.
+!> It calls #Agrif_Interp_2D_recursive and #Agrif_InterpBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_3D_recursive ( type_interp, tabin, tabout,  &
+                                       indmin, indmax,              &
+                                       pttab_child, petab_child,    &
+                                       s_child,  s_parent,          &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(3),              intent(in)  :: type_interp
+    integer, dimension(3),              intent(in)  :: indmin, indmax
+    integer, dimension(3),              intent(in)  :: pttab_child, petab_child
+    real,    dimension(3),              intent(in)  :: s_child, s_parent
+    real,    dimension(3),              intent(in)  :: ds_child, ds_parent
+    real,    dimension(                 &
+        indmin(1):indmax(1),            &
+        indmin(2):indmax(2),            &
+        indmin(3):indmax(3)),           intent(in)  :: tabin
+    real,    dimension(                 &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3)), intent(out) :: tabout
+!---------------------------------------------------------------------------------------------------
+    real, dimension(                    &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        indmin(3):indmax(3))            :: tabtemp
+    integer                             :: i, j, k, coeffraf
+    integer                             :: locind_child_left, kdeb
+!
+    coeffraf = nint ( ds_parent(1) / ds_child(1) )
+    if ( (type_interp(1) == Agrif_Linear) .and. (coeffraf/=1) ) then
+        call Linear1dPrecompute2d(indmax(2)-indmin(2)+1,            &
+                                  indmax(1)-indmin(1)+1,            &
+                                  petab_child(1)-pttab_child(1)+1,  &
+                                  s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+        precomputedone(1) = .TRUE.
+    elseif ( (type_interp(1) == Agrif_PPM) .and. (coeffraf/=1) ) then
+        call PPM1dPrecompute2d(indmax(2)-indmin(2)+1,           &
+                               indmax(1)-indmin(1)+1,           &
+                               petab_child(1)-pttab_child(1)+1, &
+                               s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+        precomputedone(1) = .TRUE.
+    endif
+
+    coeffraf = nint ( ds_parent(2) / ds_child(2) )
+    if ( (type_interp(2) == Agrif_Linear) .and. (coeffraf/=1) ) then
+        call Linear1dPrecompute2d(petab_child(1)-pttab_child(1)+1,  &
+                                  indmax(2)-indmin(2)+1,            &
+                                  petab_child(2)-pttab_child(2)+1,  &
+                                  s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+        precomputedone(2) = .TRUE.
+    elseif ( (type_interp(2) == Agrif_PPM) .and. (coeffraf/=1) ) then
+        call PPM1dPrecompute2d(petab_child(1)-pttab_child(1)+1, &
+                               indmax(2)-indmin(2)+1,           &
+                               petab_child(2)-pttab_child(2)+1, &
+                               s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+        precomputedone(2) = .TRUE.
+    endif
+!
+    do k = indmin(3), indmax(3)
+        call Agrif_Interp_2D_recursive(type_interp(1:2),                            &
+                                       tabin(indmin(1):indmax(1),                   &
+                                             indmin(2):indmax(2), k),               &
+                                       tabtemp(pttab_child(1):petab_child(1),       &
+                                               pttab_child(2):petab_child(2), k),   &
+                                       indmin(1:2), indmax(1:2),                    &
+                                       pttab_child(1:2), petab_child(1:2),          &
+                                       s_child(1:2),     s_parent(1:2),             &
+                                       ds_child(1:2),   ds_parent(1:2) )
+    enddo
+!
+    precomputedone(1) = .FALSE.
+    precomputedone(2) = .FALSE.
+    coeffraf = nint(ds_parent(3)/ds_child(3))
+!
+    if ( coeffraf == 1 ) then
+        locind_child_left = 1 + agrif_int((s_child(3)-s_parent(3))/ds_parent(3))
+        kdeb = indmin(3)+locind_child_left-2
+        do k = pttab_child(3),petab_child(3)
+            kdeb = kdeb + 1
+            do j = pttab_child(2), petab_child(2)
+            do i = pttab_child(1), petab_child(1)
+                tabout(i,j,k) = tabtemp(i,j,kdeb)
+            enddo
+            enddo
+        enddo
+    else
+        do j = pttab_child(2), petab_child(2)
+        do i = pttab_child(1), petab_child(1)
+            call Agrif_InterpBase(type_interp(3),                                   &
+                                  tabtemp(i,j,indmin(3):indmax(3)),                 &
+                                  tabout(i,j,pttab_child(3):petab_child(3)),        &
+                                  indmin(3), indmax(3),                             &
+                                  pttab_child(3), petab_child(3),                   &
+                                  s_parent(3),    s_child(3),                       &
+                                 ds_parent(3),   ds_child(3) )
+        enddo
+        enddo
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_3D_recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_4D_Recursive
+!
+!> Subroutine for the interpolation of a 4D grid variable.
+!> It calls #Agrif_Interp_3D_recursive and #Agrif_InterpBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_4D_recursive ( type_interp, tabin, tabout,  &
+                                       indmin, indmax,              &
+                                       pttab_child, petab_child,    &
+                                       s_child,  s_parent,          &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(4),              intent(in)  :: type_interp
+    integer, dimension(4),              intent(in)  :: indmin, indmax
+    integer, dimension(4),              intent(in)  :: pttab_child, petab_child
+    real,    dimension(4),              intent(in)  :: s_child, s_parent
+    real,    dimension(4),              intent(in)  :: ds_child, ds_parent
+    real,    dimension(                 &
+        indmin(1):indmax(1),            &
+        indmin(2):indmax(2),            &
+        indmin(3):indmax(3),            &
+        indmin(4):indmax(4)),           intent(in)  :: tabin
+    real,    dimension(                 &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3),  &
+        pttab_child(4):petab_child(4)), intent(out) :: tabout
+!---------------------------------------------------------------------------------------------------
+    real, dimension(                    &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3),  &
+        indmin(4):indmax(4))            :: tabtemp
+    integer                             :: i, j, k, l
+!
+    do l = indmin(4), indmax(4)
+        call Agrif_Interp_3D_recursive(type_interp(1:3),                            &
+                                       tabin(indmin(1):indmax(1),                   &
+                                             indmin(2):indmax(2),                   &
+                                             indmin(3):indmax(3), l),               &
+                                       tabtemp(pttab_child(1):petab_child(1),       &
+                                               pttab_child(2):petab_child(2),       &
+                                               pttab_child(3):petab_child(3), l),   &
+                                       indmin(1:3), indmax(1:3),                    &
+                                       pttab_child(1:3), petab_child(1:3),          &
+                                       s_child(1:3),    s_parent(1:3),              &
+                                       ds_child(1:3),  ds_parent(1:3) )
+    enddo
+!
+    do k = pttab_child(3), petab_child(3)
+    do j = pttab_child(2), petab_child(2)
+    do i = pttab_child(1), petab_child(1)
+        call Agrif_InterpBase(type_interp(4),                                       &
+                              tabtemp(i,j,k,indmin(4):indmax(4)),                   &
+                              tabout(i,j,k,pttab_child(4):petab_child(4)),          &
+                              indmin(4), indmax(4),                                 &
+                              pttab_child(4), petab_child(4),                       &
+                              s_parent(4),    s_child(4),                           &
+                             ds_parent(4),   ds_child(4) )
+    enddo
+    enddo
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_4D_recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_5D_Recursive
+!
+!> Subroutine for the interpolation of a 5D grid variable.
+!> It calls #Agrif_Interp_4D_recursive and #Agrif_InterpBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_5D_recursive ( type_interp, tabin, tabout,  &
+                                       indmin, indmax,              &
+                                       pttab_child, petab_child,    &
+                                       s_child,  s_parent,          &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(5),              intent(in)  :: type_interp
+    integer, dimension(5),              intent(in)  :: indmin, indmax
+    integer, dimension(5),              intent(in)  :: pttab_child, petab_child
+    real,    dimension(5),              intent(in)  :: s_child, s_parent
+    real,    dimension(5),              intent(in)  :: ds_child, ds_parent
+    real,    dimension(                 &
+        indmin(1):indmax(1),            &
+        indmin(2):indmax(2),            &
+        indmin(3):indmax(3),            &
+        indmin(4):indmax(4),            &
+        indmin(5):indmax(5)),           intent(in)  :: tabin
+    real,    dimension(                 &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3),  &
+        pttab_child(4):petab_child(4),  &
+        pttab_child(5):petab_child(5)), intent(out) :: tabout
+!---------------------------------------------------------------------------------------------------
+    real, dimension(                    &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3),  &
+        pttab_child(4):petab_child(4),  &
+        indmin(5):indmax(5))            :: tabtemp
+    integer                             :: i, j, k, l, m
+!
+    do m = indmin(5), indmax(5)
+        call Agrif_Interp_4D_recursive(type_interp(1:4),                            &
+                                       tabin(indmin(1):indmax(1),                   &
+                                             indmin(2):indmax(2),                   &
+                                             indmin(3):indmax(3),                   &
+                                             indmin(4):indmax(4),m),                &
+                                       tabtemp(pttab_child(1):petab_child(1),       &
+                                               pttab_child(2):petab_child(2),       &
+                                               pttab_child(3):petab_child(3),       &
+                                               pttab_child(4):petab_child(4), m),   &
+                                       indmin(1:4),indmax(1:4),                     &
+                                       pttab_child(1:4), petab_child(1:4),          &
+                                       s_child(1:4),     s_parent(1:4),             &
+                                       ds_child(1:4),   ds_parent(1:4) )
+    enddo
+!
+    do l = pttab_child(4), petab_child(4)
+    do k = pttab_child(3), petab_child(3)
+    do j = pttab_child(2), petab_child(2)
+    do i = pttab_child(1), petab_child(1)
+        call Agrif_InterpBase(type_interp(5),                                       &
+                              tabtemp(i,j,k,l,indmin(5):indmax(5)),                 &
+                              tabout(i,j,k,l,pttab_child(5):petab_child(5)),        &
+                              indmin(5), indmax(5),                                 &
+                              pttab_child(5), petab_child(5),                       &
+                              s_parent(5),   s_child(5),                            &
+                              ds_parent(5), ds_child(5) )
+    enddo
+    enddo
+    enddo
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_5D_recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Interp_6D_Recursive
+!
+!> Subroutine for the interpolation of a 6D grid variable.
+!> It calls #Agrif_Interp_5D_recursive and Agrif_InterpBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Interp_6D_recursive ( type_interp, tabin, tabout,  &
+                                       indmin, indmax,              &
+                                       pttab_child, petab_child,    &
+                                       s_child,  s_parent,          &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(6),                  intent(in)  :: type_interp
+    integer, dimension(6),                  intent(in)  :: indmin, indmax
+    integer, dimension(6),                  intent(in)  :: pttab_child, petab_child
+    real,    dimension(6),                  intent(in)  :: s_child, s_parent
+    real,    dimension(6),                  intent(in)  :: ds_child, ds_parent
+    real,    dimension(                 &
+        indmin(1):indmax(1),            &
+        indmin(2):indmax(2),            &
+        indmin(3):indmax(3),            &
+        indmin(4):indmax(4),            &
+        indmin(5):indmax(5),            &
+        indmin(6):indmax(6)),               intent(in)  :: tabin
+    real,    dimension(                 &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3),  &
+        pttab_child(4):petab_child(4),  &
+        pttab_child(5):petab_child(5),  &
+        pttab_child(6):petab_child(6)),     intent(out) :: tabout
+!---------------------------------------------------------------------------------------------------
+    real, dimension(                    &
+        pttab_child(1):petab_child(1),  &
+        pttab_child(2):petab_child(2),  &
+        pttab_child(3):petab_child(3),  &
+        pttab_child(4):petab_child(4),  &
+        pttab_child(5):petab_child(5),  &
+        indmin(6):indmax(6))            :: tabtemp
+    integer                             :: i, j, k, l, m, n
+!
+    do n = indmin(6), indmax(6)
+        call Agrif_Interp_5D_recursive(type_interp(1:5),                            &
+                                       tabin(indmin(1):indmax(1),                   &
+                                             indmin(2):indmax(2),                   &
+                                             indmin(3):indmax(3),                   &
+                                             indmin(4):indmax(4),                   &
+                                             indmin(5):indmax(5), n),               &
+                                        tabtemp(pttab_child(1):petab_child(1),      &
+                                                pttab_child(2):petab_child(2),      &
+                                                pttab_child(3):petab_child(3),      &
+                                                pttab_child(4):petab_child(4),      &
+                                                pttab_child(5):petab_child(5), n),  &
+                                        indmin(1:5),indmax(1:5),                    &
+                                        pttab_child(1:5), petab_child(1:5),         &
+                                        s_child(1:5), s_parent(1:5),                &
+                                        ds_child(1:5),ds_parent(1:5) )
+    enddo
+!
+    do m = pttab_child(5), petab_child(5)
+    do l = pttab_child(4), petab_child(4)
+    do k = pttab_child(3), petab_child(3)
+    do j = pttab_child(2), petab_child(2)
+    do i = pttab_child(1), petab_child(1)
+        call Agrif_InterpBase(type_interp(6),                                       &
+                              tabtemp(i,j,k,l,m,indmin(6):indmax(6)),               &
+                              tabout(i,j,k,l,m,pttab_child(6):petab_child(6)),      &
+                              indmin(6), indmax(6),                                 &
+                              pttab_child(6), petab_child(6),                       &
+                              s_parent(6),   s_child(6),                            &
+                              ds_parent(6), ds_child(6) )
+    enddo
+    enddo
+    enddo
+    enddo
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Interp_6D_recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_InterpBase
+!
+!> Calls the interpolation method chosen by the user (linear, lagrange, spline, etc.).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_InterpBase ( type_interp, parenttab, childtab, indmin, indmax, &
+                              pttab_child, petab_child,                         &
+                              s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    INTEGER                                                 :: type_interp
+    INTEGER                                                 :: indmin, indmax
+    INTEGER                                                 :: pttab_child, petab_child
+    REAL, DIMENSION(indmin:indmax),           INTENT(IN)    :: parenttab
+    REAL, DIMENSION(pttab_child:petab_child), INTENT(OUT)   :: childtab
+    REAL                                                    :: s_parent, s_child
+    REAL                                                    :: ds_parent,ds_child
+!
+    if ( (indmin == indmax) .and. (pttab_child == petab_child) ) then
+!
+        childtab(pttab_child) = parenttab(indmin)
+!
+    elseif (type_interp == Agrif_LINEAR) then    !       Linear interpolation
+!
+        call Agrif_basicinterp_linear1D(parenttab,childtab,                   &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif ( type_interp == Agrif_PPM ) then     !       PPM interpolation
+
+        call PPM1d(parenttab,childtab,                      &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif ( type_interp == Agrif_PPM_LIM ) then     !       PPM interpolation
+
+        call PPM1d_lim(parenttab,childtab,                      &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif (type_interp == Agrif_LAGRANGE) then  !       Lagrange interpolation
+!
+        call lagrange1D(parenttab,childtab,                 &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif (type_interp == Agrif_ENO) then       !       Eno interpolation
+!
+        call ENO1d(parenttab,childtab,                      &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif (type_interp == Agrif_WENO) then      !       Weno interpolation
+!
+        call WENO1d(parenttab,childtab,                     &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif (type_interp == Agrif_LINEARCONSERV) then !   Linear conservative interpolation
+!
+        call Linear1dConserv(parenttab,childtab,            &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif (type_interp == Agrif_LINEARCONSERVLIM) then !Linear conservative interpolation
+!
+        call Linear1dConservLim(parenttab,childtab,         &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    elseif (type_interp == Agrif_CONSTANT) then
+!
+        call Constant1d(parenttab,childtab,                 &
+                indmax-indmin+1,petab_child-pttab_child+1,  &
+                s_parent,s_child,ds_parent,ds_child)
+!
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_InterpBase
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Find_list_interp
+!---------------------------------------------------------------------------------------------------
+function Agrif_Find_list_interp ( list_interp, pttab, petab, pttab_Child, pttab_Parent,     &
+                                    nbdim, indmin, indmax, indminglob,  indmaxglob,         &
+                                    pttruetab, cetruetab, memberin                          &
+#if defined AGRIF_MPI
+                                   ,indminglob2, indmaxglob2, parentarray,                  &
+                                    member, tab4t, memberinall, sendtoproc1, recvfromproc1  &
+#endif
+    ) result(find_list_interp)
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_List_Interp_Loc),   pointer     :: list_interp
+    integer,                       intent(in)  :: nbdim
+    integer, dimension(nbdim),     intent(in)  :: pttab, petab, pttab_Child, pttab_Parent
+    integer, dimension(nbdim),     intent(out) :: indmin, indmax
+    integer, dimension(nbdim),     intent(out) :: indminglob, indmaxglob
+    integer, dimension(nbdim),     intent(out) :: pttruetab, cetruetab
+    logical,                       intent(out) :: memberin
+#if defined AGRIF_MPI
+    integer, dimension(nbdim),     intent(out) :: indminglob2, indmaxglob2
+    integer, dimension(nbdim,2,2), intent(out) :: parentarray
+    logical,                       intent(out) :: member
+    integer, dimension(nbdim,0:Agrif_Nbprocs-1,8), intent(out) :: tab4t
+    logical, dimension(0:Agrif_Nbprocs-1),         intent(out) :: memberinall
+    logical, dimension(0:Agrif_Nbprocs-1),         intent(out) :: sendtoproc1, recvfromproc1
+#endif
+    logical :: find_list_interp
+!
+    integer :: i
+    type(Agrif_List_Interp_Loc), pointer :: parcours
+    type(Agrif_Interp_Loc),      pointer :: pil
+
+    find_list_interp = .false.
+
+    if ( .not. associated(list_interp) )    return
+
+    parcours => list_interp
+    find_loop : do while ( associated(parcours) )
+
+        pil => parcours % interp_loc
+
+        do i = 1,nbdim
+            if ( (pttab(i) /= pil % pttab(i)) .or. &
+                 (petab(i) /= pil % petab(i)) .or. &
+                 (pttab_child(i)  /= pil % pttab_child(i)) .or. &
+                 (pttab_parent(i) /= pil % pttab_parent(i)) ) then
+                parcours => parcours % suiv
+                cycle find_loop
+            endif
+        enddo
+
+        indmin = pil % indmin(1:nbdim)
+        indmax = pil % indmax(1:nbdim)
+
+        pttruetab = pil % pttruetab(1:nbdim)
+        cetruetab = pil % cetruetab(1:nbdim)
+
+#if !defined AGRIF_MPI
+        indminglob  = pil % indminglob(1:nbdim)
+        indmaxglob  = pil % indmaxglob(1:nbdim)
+#else
+        indminglob  = pil % indminglob2(1:nbdim)
+        indmaxglob  = pil % indmaxglob2(1:nbdim)
+        indminglob2 = pil % indminglob2(1:nbdim)
+        indmaxglob2 = pil % indmaxglob2(1:nbdim)
+        parentarray = pil % parentarray(1:nbdim,:,:)
+        member      = pil % member
+        tab4t         = pil % tab4t(1:nbdim, 0:Agrif_Nbprocs-1, 1:8)
+        memberinall   = pil % memberinall(0:Agrif_Nbprocs-1)
+        sendtoproc1   = pil % sendtoproc1(0:Agrif_Nbprocs-1)
+        recvfromproc1 = pil % recvfromproc1(0:Agrif_Nbprocs-1)
+#endif
+        memberin = pil % memberin
+        find_list_interp = .true.
+        exit find_loop
+    enddo find_loop
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Find_list_interp
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_AddTo_list_interp
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_AddTo_list_interp ( list_interp, pttab, petab, pttab_Child, pttab_Parent,  &
+                                     indmin, indmax, indminglob, indmaxglob,                &
+                                     pttruetab, cetruetab,                                  &
+                                     memberin, nbdim                                        &
+#if defined AGRIF_MPI
+                                    ,indminglob2, indmaxglob2,                              &
+                                     parentarray,                                           &
+                                     member,                                                &
+                                     tab4t, memberinall, sendtoproc1, recvfromproc1         &
+#endif
+    )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_List_Interp_Loc), pointer    :: list_interp
+    integer                                 :: nbdim
+    integer, dimension(nbdim)               :: pttab, petab, pttab_Child, pttab_Parent
+    integer, dimension(nbdim)               :: indmin,indmax
+    integer, dimension(nbdim)               :: indminglob, indmaxglob
+    integer, dimension(nbdim)               :: pttruetab, cetruetab
+    logical                                 :: memberin
+#if defined AGRIF_MPI
+    integer, dimension(nbdim,2,2)           :: parentarray
+    logical                                 :: member
+    integer, dimension(nbdim)                       :: indminglob2,indmaxglob2
+    integer, dimension(nbdim,0:Agrif_Nbprocs-1,8)   :: tab4t
+    logical, dimension(0:Agrif_Nbprocs-1)           :: memberinall
+    logical, dimension(0:Agrif_Nbprocs-1)           :: sendtoproc1
+    logical, dimension(0:Agrif_Nbprocs-1)           :: recvfromproc1
+#endif
+!
+    type(Agrif_List_Interp_Loc), pointer    :: parcours
+    type(Agrif_Interp_Loc),      pointer    :: pil
+!
+    allocate(parcours)
+    allocate(parcours % interp_loc)
+
+    pil => parcours % interp_loc
+
+    pil % pttab(1:nbdim) = pttab(1:nbdim)
+    pil % petab(1:nbdim) = petab(1:nbdim)
+    pil % pttab_child(1:nbdim) = pttab_child(1:nbdim)
+    pil % pttab_parent(1:nbdim) = pttab_parent(1:nbdim)
+
+    pil % indmin(1:nbdim) = indmin(1:nbdim)
+    pil % indmax(1:nbdim) = indmax(1:nbdim)
+
+    pil % memberin = memberin
+#if !defined AGRIF_MPI
+    pil % indminglob(1:nbdim) = indminglob(1:nbdim)
+    pil % indmaxglob(1:nbdim) = indmaxglob(1:nbdim)
+#else
+    pil % indminglob2(1:nbdim) = indminglob2(1:nbdim)
+    pil % indmaxglob2(1:nbdim) = indmaxglob2(1:nbdim)
+    pil % parentarray(1:nbdim,:,:) = parentarray(1:nbdim,:,:)
+    pil % member = member
+    allocate(pil % tab4t(nbdim, 0:Agrif_Nbprocs-1, 8))
+    allocate(pil % memberinall(0:Agrif_Nbprocs-1))
+    allocate(pil % sendtoproc1(0:Agrif_Nbprocs-1))
+    allocate(pil % recvfromproc1(0:Agrif_Nbprocs-1))
+    pil % tab4t         = tab4t
+    pil % memberinall   = memberinall
+    pil % sendtoproc1   = sendtoproc1
+    pil % recvfromproc1 = recvfromproc1
+#endif
+
+    pil % pttruetab(1:nbdim) = pttruetab(1:nbdim)
+    pil % cetruetab(1:nbdim) = cetruetab(1:nbdim)
+
+    parcours % suiv => list_interp
+    list_interp => parcours
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Addto_list_interp
+!===================================================================================================
+!
+end module Agrif_Interpolation
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinterpbasic.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinterpbasic.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modinterpbasic.F90	(revision 9987)
@@ -0,0 +1,1464 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_InterpBasic
+!>
+!> Contains different procedures of interpolation (linear,lagrange, spline,...) used in
+!! the Agrif_Interpolation module.
+!
+module Agrif_InterpBasic
+!
+    use Agrif_Types
+!
+    implicit none
+!
+    real, dimension(5,Agrif_MaxRaff,3)      :: tabppm
+    real, dimension(Agrif_MaxRaff)          :: tabdiff2, tabdiff3
+    real, dimension(:),   allocatable       :: tabtest4
+    real, dimension(:,:), allocatable       :: coeffparent
+    integer, dimension(:,:), allocatable    :: indparent
+    integer, dimension(:,:), allocatable    :: indparentppm, indchildppm
+    integer, dimension(:), allocatable      :: indparentppm_1d, indchildppm_1d
+!
+    private :: Agrif_limiter_vanleer
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_basicinterp_linear1D
+!
+!> Linear 1D interpolation on a child grid (vector y) from its parent grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_basicinterp_linear1D ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(np), intent(in)     :: x            !< Coarse input data from parent
+    real, dimension(nc), intent(out)    :: y            !< Fine output data to child
+    integer,             intent(in)     :: np           !< Length of input array
+    integer,             intent(in)     :: nc           !< Length of output array
+    real,                intent(in)     :: s_parent     !< Parent grid position (s_root = 0)
+    real,                intent(in)     :: s_child      !< Child  grid position (s_root = 0)
+    real,                intent(in)     :: ds_parent    !< Parent grid dx (ds_root = 1)
+    real,                intent(in)     :: ds_child     !< Child  grid dx (ds_root = 1)
+!
+    integer :: i, coeffraf, locind_parent_left
+    real    :: globind_parent_left, globind_parent_right
+    real    :: invds, invds2, ypos, ypos2, diff
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if ( coeffraf == 1 ) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    endif
+!
+    ypos = s_child
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    globind_parent_left  = s_parent + (locind_parent_left - 1)*ds_parent
+    globind_parent_right = globind_parent_left + ds_parent
+!
+    invds  = 1./ds_parent
+    invds2 = ds_child/ds_parent
+    ypos2 = ypos*invds
+    globind_parent_right = globind_parent_right*invds
+!
+    do i = 1,nc-1
+!
+        if (ypos2 > globind_parent_right) then
+            locind_parent_left = locind_parent_left + 1
+            globind_parent_right = globind_parent_right + 1.
+            ypos2 = ypos*invds+(i-1)*invds2
+        endif
+!
+        diff = globind_parent_right - ypos2
+        y(i) = (diff*x(locind_parent_left) + (1.-diff)*x(locind_parent_left+1))
+        ypos2 = ypos2 + invds2
+!
+    enddo
+!
+    ypos = s_child + (nc-1)*ds_child
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+!
+    if (locind_parent_left == np) then
+        y(nc) = x(np)
+    else
+        globind_parent_left = s_parent + (locind_parent_left - 1)*ds_parent
+        y(nc) = ((globind_parent_left + ds_parent - ypos)*x(locind_parent_left)  &
+                           + (ypos - globind_parent_left)*x(locind_parent_left+1))*invds
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_basicinterp_linear1D
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Linear1dPrecompute2d
+!
+!> Computes 2D coefficients and index for a linear 1D interpolation on a child grid (vector y)
+!! from its parent grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine Linear1dPrecompute2d ( np2, np, nc, s_parent, s_child, ds_parent, ds_child, dir )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: np,nc,np2
+    real,    intent(in) :: s_parent, s_child
+    real,    intent(in) :: ds_parent, ds_child
+    integer, intent(in) :: dir
+!
+    integer :: i,coeffraf,locind_parent_left,inc,inc1,inc2
+    integer, dimension(:,:), allocatable :: indparent_tmp
+    real, dimension(:,:), allocatable :: coeffparent_tmp
+    real    :: ypos,globind_parent_left,globind_parent_right
+    real    :: invds, invds2, invds3
+    real :: ypos2,diff
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    ypos = s_child
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    globind_parent_left = s_parent + (locind_parent_left - 1)*ds_parent
+    globind_parent_right = globind_parent_left + ds_parent
+!
+    invds = 1./ds_parent
+    invds2 = ds_child/ds_parent
+    invds3 = 0.5/real(coeffraf)
+    ypos2 = ypos*invds
+    globind_parent_right=globind_parent_right*invds
+!
+    if (.not.allocated(indparent)) then
+        allocate(indparent(nc*np2,3),coeffparent(nc*np2,3))
+    else
+        if ( size(indparent,1) < nc*np2 ) then
+            allocate(coeffparent_tmp(size(indparent,1),size(indparent,2)))
+            allocate(  indparent_tmp(size(indparent,1),size(indparent,2)))
+            coeffparent_tmp = coeffparent
+            indparent_tmp   = indparent
+            deallocate(indparent,coeffparent)
+            allocate(indparent(nc*np2,3),coeffparent(nc*np2,3))
+            coeffparent(1:size(coeffparent_tmp,1),1:size(coeffparent_tmp,2)) = coeffparent_tmp
+            indparent(  1:size(indparent_tmp,  1),1:size(indparent_tmp,  2)) = indparent_tmp
+            deallocate(indparent_tmp,coeffparent_tmp)
+        endif
+    endif
+!
+    do i = 1,nc-1
+!
+        if (ypos2 > globind_parent_right) then
+            locind_parent_left = locind_parent_left + 1
+            globind_parent_right = globind_parent_right + 1.
+            ypos2 = ypos*invds+(i-1)*invds2
+        endif
+!
+        diff = globind_parent_right - ypos2
+        diff = invds3*nint(2*coeffraf*diff)
+        indparent(i,dir) = locind_parent_left
+        coeffparent(i,dir) = diff
+        ypos2 = ypos2 + invds2
+!
+    enddo
+!
+    ypos = s_child + (nc-1)*ds_child
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+
+    if (locind_parent_left == np) then
+        indparent(nc,dir) = locind_parent_left-1
+        coeffparent(nc,dir) = 0.
+    else
+        globind_parent_left = s_parent + (locind_parent_left - 1)*ds_parent
+        indparent(nc,dir) = locind_parent_left
+        diff = (globind_parent_left + ds_parent - ypos) * invds
+        diff = invds3*nint(2*coeffraf*diff)
+        coeffparent(nc,dir) = diff
+    endif
+
+    do i=2, np2
+        inc  =  i*nc
+        inc1 = (i-1)*nc
+        inc2 = (i-2)*nc
+!CDIR ALTCODE
+        indparent(1+inc1:inc,dir) = indparent(1+inc2:inc1,dir)+np
+!CDIR ALTCODE
+        coeffparent(1+inc1:inc,dir) =coeffparent(1:nc,dir)
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Linear1dPrecompute2d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Linear1dAfterCompute
+!
+!> Carries out a linear 1D interpolation on a child grid (vector y) from its parent grid (vector x)
+!! using precomputed coefficient and index.
+!---------------------------------------------------------------------------------------------------
+subroutine Linear1dAfterCompute ( x, y, np, nc, dir )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    integer,             intent(in)     :: dir
+!
+    integer :: i
+!
+!CDIR ALTCODE
+!CDIR NODEP
+    do i = 1,nc
+        y(i) = coeffparent(i,dir)  * x(MAX(indparent(i,dir),1)) + &
+           (1.-coeffparent(i,dir)) * x(indparent(i,dir)+1)
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Linear1dAfterCompute
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Lagrange1d
+!
+!> Carries out a lagrange 1D interpolation on a child grid (vector y) from its parent grid
+!! (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine Lagrange1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    integer :: i, coeffraf, locind_parent_left
+    real    :: ypos,globind_parent_left
+    real    :: deltax, invdsparent
+    real    :: t2,t3,t4,t5,t6,t7,t8
+!
+    if (np <= 2) then
+        call Agrif_basicinterp_linear1D(x,y,np,nc,s_parent,s_child,ds_parent,ds_child)
+        return
+    endif
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    endif
+!
+    invdsparent = 1./ds_parent
+    ypos = s_child
+!
+    do i = 1,nc
+!
+        locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+        globind_parent_left = s_parent + (locind_parent_left - 1)*ds_parent
+
+        deltax = invdsparent*(ypos-globind_parent_left)
+        deltax = nint(coeffraf*deltax)/real(coeffraf)
+
+        ypos = ypos + ds_child
+        if (abs(deltax) <= 0.0001) then
+            y(i)=x(locind_parent_left)
+            cycle
+        endif
+!
+        t2 = deltax - 2.
+        t3 = deltax - 1.
+        t4 = deltax + 1.
+
+        t5 = -(1./6.)*deltax*t2*t3
+        t6 = 0.5*t2*t3*t4
+        t7 = -0.5*deltax*t2*t4
+        t8 = (1./6.)*deltax*t3*t4
+
+        y(i) = t5*x(locind_parent_left-1) + t6*x(locind_parent_left)    &
+              +t7*x(locind_parent_left+1) + t8*x(locind_parent_left+2)
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Lagrange1d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Constant1d
+!
+!> Carries out a constant 1D interpolation on a child grid (vector y) from its parent grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine Constant1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    integer :: i, coeffraf, locind_parent
+    real    :: ypos
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent:locind_parent+nc-1)
+        return
+    endif
+!
+    ypos = s_child
+!
+    do i = 1,nc
+!
+        locind_parent = 1 + nint((ypos - s_parent)/ds_parent)
+        y(i) = x(locind_parent)
+        ypos = ypos + ds_child
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Constant1d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Linear1dConserv
+!
+!> Carries out a conservative linear 1D interpolation on a child grid (vector y) from its parent 
+!! grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine Linear1dConserv ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    real, dimension(:), allocatable :: ytemp
+    integer :: i,coeffraf,locind_parent_left,locind_parent_last
+    real    :: ypos,xdiffmod,xpmin,xpmax,slope
+    integer :: i1,i2,ii
+    integer :: diffmod
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    endif
+!
+    diffmod = 0
+    if (mod(coeffraf,2) == 0) diffmod = 1
+
+    xdiffmod = real(diffmod)/2.
+
+    allocate(ytemp(-2*coeffraf:nc+2*coeffraf))
+!
+    ypos = s_child
+!
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    locind_parent_last = 1 + agrif_ceiling((ypos +(nc - 1) *ds_child - s_parent)/ds_parent)
+
+    xpmin = s_parent + (locind_parent_left-1)*ds_parent
+    xpmax = s_parent + (locind_parent_last-1)*ds_parent
+
+    i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+    i2 = 1+agrif_int((xpmax-s_child)/ds_child)
+
+    i = i1
+
+    if (locind_parent_left == 1) then
+        slope = (x(locind_parent_left+1)-x(locind_parent_left))/(coeffraf)
+    else
+        slope = (x(locind_parent_left+1)-x(locind_parent_left-1))/(2.*coeffraf)
+    endif
+
+    do ii = i-coeffraf/2+diffmod,i+coeffraf/2
+        ytemp(ii) = x(locind_parent_left)+(ii-i-xdiffmod/2.)*slope
+    enddo
+
+    locind_parent_left = locind_parent_left + 1
+
+    do i = i1+coeffraf, i2-coeffraf,coeffraf
+        slope = (x(locind_parent_left+1)-x(locind_parent_left-1))/(2.*coeffraf)
+        do ii = i-coeffraf/2+diffmod,i+coeffraf/2
+            ytemp(ii) = x(locind_parent_left)+(ii-i-xdiffmod/2.)*slope
+        enddo
+        locind_parent_left = locind_parent_left + 1
+    enddo
+
+    i = i2
+
+    if (locind_parent_left == np) then
+        slope = (x(locind_parent_left)-x(locind_parent_left-1))/(coeffraf)
+    else
+        slope = (x(locind_parent_left+1)-x(locind_parent_left-1))/(2.*coeffraf)
+    endif
+
+    do ii = i-coeffraf/2+diffmod,nc
+        ytemp(ii) = x(locind_parent_left)+(ii-i-xdiffmod/2.)*slope
+    enddo
+!
+    y(1:nc)=ytemp(1:nc)
+!
+    deallocate(ytemp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Linear1dConserv
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Linear1dConservLim
+!
+!> Carries out a limited conservative linear 1D interpolation on a child grid (vector y) from
+!! its parent grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine Linear1dConservLim ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    real, dimension(:), allocatable :: ytemp
+    integer :: i,coeffraf,locind_parent_left,locind_parent_last
+    real    :: ypos,xdiffmod,xpmin,xpmax,slope
+    integer :: i1,i2,ii
+    integer :: diffmod
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    endif
+!
+    if (coeffraf /= 3) then
+        print *,'Linear1dConservLim not ready for refinement ratio = ', coeffraf
+        stop
+    endif
+!
+    diffmod = 0
+    if (mod(coeffraf,2) == 0) diffmod = 1
+
+    xdiffmod = real(diffmod)/2.
+
+    allocate(ytemp(-2*coeffraf:nc+2*coeffraf))
+!
+    ypos = s_child
+!
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    locind_parent_last = 1 + agrif_ceiling((ypos +(nc - 1) *ds_child - s_parent)/ds_parent)
+
+    xpmin = s_parent + (locind_parent_left-1)*ds_parent
+    xpmax = s_parent + (locind_parent_last-1)*ds_parent
+
+    i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+    i2 = 1+agrif_int((xpmax-s_child)/ds_child)
+
+    i = i1
+
+    if (locind_parent_left == 1) then
+        slope=0.
+    else
+        slope = Agrif_limiter_vanleer(x(locind_parent_left-1:locind_parent_left+1))
+        slope = slope / coeffraf
+    endif
+
+    do ii = i-coeffraf/2+diffmod,i+coeffraf/2
+        ytemp(ii) = x(locind_parent_left)+(ii-i-xdiffmod/2.)*slope
+    enddo
+
+    locind_parent_left = locind_parent_left + 1
+
+    do i = i1+coeffraf, i2-coeffraf,coeffraf
+        slope = Agrif_limiter_vanleer(x(locind_parent_left-1:locind_parent_left+1))
+        slope = slope / coeffraf
+        do ii=i-coeffraf/2+diffmod,i+coeffraf/2
+            ytemp(ii) = x(locind_parent_left)+(ii-i-xdiffmod/2.)*slope
+        enddo
+        locind_parent_left = locind_parent_left + 1
+    enddo
+
+    i = i2
+
+    if (locind_parent_left == np) then
+        slope=0.
+    else
+        slope = Agrif_limiter_vanleer(x(locind_parent_left-1:locind_parent_left+1))
+        slope = slope / coeffraf
+    endif
+
+    do ii=i-coeffraf/2+diffmod,nc
+        ytemp(ii) = x(locind_parent_left)+(ii-i-xdiffmod/2.)*slope
+    enddo
+!
+    y(1:nc) = ytemp(1:nc)
+!
+    deallocate(ytemp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Linear1dConservLim
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine PPM1d
+!
+!> Carries out a 1D interpolation and apply monotonicity constraints using piecewise parabolic
+!! method (PPM) on a child grid (vector y) from its parent grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine PPM1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    integer :: i,coeffraf,locind_parent_left,locind_parent_last
+    integer :: iparent,ipos,pos,nmin,nmax
+    real    :: ypos
+    integer :: i1,jj
+    real :: xpmin,a
+!
+    real, dimension(np) :: xl,delta,a6,slope
+    integer :: diffmod
+    real :: invcoeffraf
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    endif
+!
+    invcoeffraf = ds_child/ds_parent
+!
+    if( .not. allocated(tabtest4) ) then
+        allocate(tabtest4(-2*coeffraf:nc+2*coeffraf))
+    else
+        if (size(tabtest4) < nc+4*coeffraf+1) then
+            deallocate( tabtest4 )
+            allocate(tabtest4(-2*coeffraf:nc+2*coeffraf))
+        endif
+    endif
+!
+    ypos = s_child
+!
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    locind_parent_last = 1 + agrif_ceiling((ypos +(nc - 1)*ds_child - s_parent)/ds_parent)
+!
+    xpmin = s_parent + (locind_parent_left-1)*ds_parent
+    i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+!
+!CDIR NOVECTOR
+    do i=1,coeffraf
+        tabdiff2(i) = (real(i)-0.5)*invcoeffraf
+    enddo
+!
+    a = invcoeffraf**2
+    tabdiff3(1) = (1./3.)*a
+    a = 2.*a
+!CDIR NOVECTOR
+    do i=2,coeffraf
+        tabdiff3(i) = tabdiff3(i-1)+(real(i)-1)*a
+    enddo
+!
+    if      ( locind_parent_last+2 <= np ) then
+        nmax = locind_parent_last+2
+    else if ( locind_parent_last+1 <= np ) then
+        nmax = locind_parent_last+1
+    else
+        nmax = locind_parent_last
+    endif
+!
+    if (locind_parent_left-1 >= 1) then
+        nmin = locind_parent_left-1
+    else
+        nmin = locind_parent_left
+    endif
+!
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+    do i = nmin,nmax
+        slope(i) = x(i) - x(i-1)
+    enddo
+!
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+    do i = nmin+1,nmax-1
+        xl(i)= 0.5*(x(i-1)+x(i))-0.08333333333333*(slope(i+1)-slope(i-1))
+    enddo
+!
+! apply parabolic monotonicity
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+    do i = locind_parent_left,locind_parent_last
+        delta(i) = xl(i+1) - xl(i)
+        a6(i) = 6.*x(i)-3.*(xl(i) +xl(i+1))
+    enddo
+!
+    diffmod = 0
+    if (mod(coeffraf,2) == 0) diffmod = 1
+!
+    ipos = i1
+!
+    do iparent = locind_parent_left,locind_parent_last
+        pos=1
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+        do jj = ipos-coeffraf/2+diffmod,ipos+coeffraf/2
+!
+            tabtest4(jj) = xl(iparent) + tabdiff2(pos) *  (delta(iparent)+a6(iparent)) &
+                                       - tabdiff3(pos) *  a6(iparent)
+            pos = pos+1
+        enddo
+        ipos = ipos + coeffraf
+    enddo
+!
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+    y(1:nc) = tabtest4(1:nc)
+!---------------------------------------------------------------------------------------------------
+end subroutine PPM1d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine PPM1dPrecompute2d
+!
+!> Computes 2D coefficients and index for a 1D interpolation using piecewise parabolic method
+!---------------------------------------------------------------------------------------------------
+subroutine PPM1dPrecompute2d ( np2, np, nc, s_parent, s_child, ds_parent, ds_child, dir )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np2, np, nc
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+    integer,             intent(in)     :: dir
+!
+    integer, dimension(:,:), allocatable :: indparent_tmp
+    integer, dimension(:,:), allocatable :: indchild_tmp
+    integer :: i,coeffraf,locind_parent_left,locind_parent_last
+    integer :: iparent,ipos,pos
+    real    :: ypos
+    integer :: i1,jj
+    real :: xpmin,a
+!
+    integer :: diffmod
+    real :: invcoeffraf
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    invcoeffraf = ds_child/ds_parent
+!
+    if (.not.allocated(indparentppm)) then
+        allocate(indparentppm(np2*nc,3),indchildppm(np2*nc,3))
+    else
+        if (size(indparentppm,1) < np2*nc) then
+            allocate(   &
+                indparent_tmp(size(indparentppm,1),size(indparentppm,2)), &
+                indchild_tmp( size(indparentppm,1),size(indparentppm,2)))
+            indparent_tmp = indparentppm
+            indchild_tmp  = indchildppm
+            deallocate(indparentppm,indchildppm)
+            allocate(indparentppm(np2*nc,3),indchildppm(np2*nc,3))
+            indparentppm(1:size(indparent_tmp,1),1:size(indparent_tmp,2)) = indparent_tmp
+            indchildppm( 1:size(indparent_tmp,1),1:size(indparent_tmp,2)) = indchild_tmp
+            deallocate(indparent_tmp,indchild_tmp)
+        endif
+    endif
+
+    if (.not.allocated(indparentppm_1d)) then
+        allocate(indparentppm_1d(-2*coeffraf:nc+2*coeffraf),    &
+                 indchildppm_1d( -2*coeffraf:nc+2*coeffraf))
+    else
+        if (size(indparentppm_1d) < nc+4*coeffraf+1) then
+            deallocate(indparentppm_1d,indchildppm_1d)
+            allocate(indparentppm_1d(-2*coeffraf:nc+2*coeffraf),&
+                     indchildppm_1d( -2*coeffraf:nc+2*coeffraf))
+        endif
+    endif
+!
+    ypos = s_child
+!
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    locind_parent_last = 1 + agrif_ceiling((ypos +(nc - 1)*ds_child - s_parent)/ds_parent)
+!
+    xpmin = s_parent + (locind_parent_left-1)*ds_parent
+    i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+!
+    do i = 1,coeffraf
+        tabdiff2(i)=(real(i)-0.5)*invcoeffraf
+    enddo
+!
+    a = invcoeffraf**2
+    tabdiff3(1) = (1./3.)*a
+    a = 2.*a
+!CDIR ALTCODE
+    do i = 2,coeffraf
+        tabdiff3(i) = tabdiff3(i-1)+(real(i)-1)*a
+    enddo
+
+!CDIR ALTCODE
+    do i = 1,coeffraf
+        tabppm(1,i,dir) = 0.08333333333333*(-1.+4*tabdiff2(i)-3*tabdiff3(i))
+        tabppm(2,i,dir) = 0.08333333333333*(7.-26.*tabdiff2(i)+18.*tabdiff3(i))
+        tabppm(3,i,dir) = 0.08333333333333*(7.+30*tabdiff2(i)-30*tabdiff3(i))
+        tabppm(4,i,dir) = 0.08333333333333*(-1.-10.*tabdiff2(i)+18.*tabdiff3(i))
+        tabppm(5,i,dir) = 0.08333333333333*(2*tabdiff2(i)-3*tabdiff3(i))
+    enddo
+!
+    diffmod = 0
+    if (mod(coeffraf,2) == 0) diffmod = 1
+!
+    ipos = i1
+!
+    do iparent = locind_parent_left,locind_parent_last
+        pos=1
+!CDIR ALTCODE
+        do jj = ipos - coeffraf/2+diffmod,ipos + coeffraf/2
+            indparentppm_1d(jj) = iparent-2
+            indchildppm_1d(jj)  = pos
+            pos = pos+1
+        enddo
+        ipos = ipos + coeffraf
+    enddo
+!
+    do i = 1,np2
+        indparentppm(1+(i-1)*nc:i*nc,dir) = indparentppm_1d(1:nc) + (i-1)*np
+        indchildppm (1+(i-1)*nc:i*nc,dir) = indchildppm_1d (1:nc)
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine PPM1dPrecompute2d
+!===================================================================================================
+!
+!===================================================================================================
+!subroutine PPM1dPrecompute(np,nc,&
+!                    s_parent,s_child,ds_parent,ds_child)
+!!
+!!CC   Description:
+!!CC   subroutine to compute coefficient and index for  a 1D interpolation
+!!CC   using piecewise parabolic method
+!!C    Method:
+!!
+!!     Declarations:
+!!
+!      Implicit none
+!!
+!!     Arguments
+!      Integer             :: np,nc
+!!      Real, Dimension(:),Allocatable :: ytemp
+!      Real                :: s_parent,s_child,ds_parent,ds_child
+!!
+!!     Local scalars
+!      Integer :: i,coeffraf,locind_parent_left,locind_parent_last
+!      Integer :: iparent,ipos,pos,nmin,nmax
+!      Real    :: ypos
+!      integer :: i1,jj
+!      Real :: xpmin,a
+!!
+!      Real :: xrmin,xrmax,am3,s2,s1
+!      Real, Dimension(np) :: xl,delta,a6,slope
+!!      Real, Dimension(:),Allocatable  :: diff,diff2,diff3
+!      INTEGER :: diffmod
+!      REAL :: invcoeffraf
+!!
+!      coeffraf = nint(ds_parent/ds_child)
+!!
+!      If (coeffraf == 1) Then
+!          return
+!      End If
+!      invcoeffraf = ds_child/ds_parent
+!!
+!
+!      if (.not.allocated(indparentppm)) then
+!      allocate(indparentppm(-2*coeffraf:nc+2*coeffraf,1),&
+!         indchildppm(-2*coeffraf:nc+2*coeffraf,1))
+!      else
+!      if (size(indparentppm,1)<nc+4*coeffraf+1) then
+!      deallocate(indparentppm,indchildppm)
+!      allocate(indparentppm(-2*coeffraf:nc+2*coeffraf,1),&
+!         indchildppm(-2*coeffraf:nc+2*coeffraf,1))
+!      endif
+!      endif
+!
+!      ypos = s_child
+!!
+!      locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+!      locind_parent_last = 1 +&
+!      agrif_ceiling((ypos +(nc - 1)&
+!      *ds_child - s_parent)/ds_parent)
+!!
+!      xpmin = s_parent + (locind_parent_left-1)*ds_parent
+!      i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+!!
+!!
+!
+!      Do i=1,coeffraf
+!        tabdiff2(i)=(real(i)-0.5)*invcoeffraf
+!      EndDo
+!
+!      a = invcoeffraf**2
+!      tabdiff3(1) = (1./3.)*a
+!      a=2.*a
+!!CDIR ALTCODE
+!!!!CDIR SHORTLOOP
+!      Do i=2,coeffraf
+!        tabdiff3(i) = tabdiff3(i-1)+(real(i)-1)*a
+!      EndDo
+!
+!!CDIR ALTCODE
+!!!!CDIR SHORTLOOP
+!      Do i=1,coeffraf
+!      tabppm(1,i,1) = 0.08333333333333*(-1.+4*tabdiff2(i)-3*tabdiff3(i))
+!      tabppm(2,i,1) = 0.08333333333333*&
+!              (7.-26.*tabdiff2(i)+18.*tabdiff3(i))
+!      tabppm(3,i,1) =0.08333333333333*(7.+30*tabdiff2(i)-30*tabdiff3(i))
+!      tabppm(4,i,1) = 0.08333333333333*&
+!              (-1.-10.*tabdiff2(i)+18.*tabdiff3(i))
+!      tabppm(5,i,1) = 0.08333333333333*(2*tabdiff2(i)-3*tabdiff3(i))
+!      End Do
+!!
+!!
+!        diffmod = 0
+!       IF (mod(coeffraf,2) == 0) diffmod = 1
+!!
+!        ipos = i1
+!!
+!        Do iparent = locind_parent_left,locind_parent_last
+!             pos=1
+!!CDIR ALTCODE
+!!CDIR SHORTLOOP
+!             Do jj = ipos - coeffraf/2+diffmod,ipos + coeffraf/2
+!         indparentppm(jj,1) = iparent-2
+!         indchildppm(jj,1) = pos
+!               pos = pos+1
+!             End do
+!             ipos = ipos + coeffraf
+!!
+!        End do
+!
+!      Return
+!      End subroutine ppm1dprecompute
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine PPM1dAfterCompute
+!
+! Carries out a 1D interpolation and apply monotonicity constraints using piecewise parabolic
+! method (PPM) on a child grid (vector y) from its parent grid (vector x).
+! Use precomputed coefficient and index.
+!---------------------------------------------------------------------------------------------------
+subroutine PPM1dAfterCompute ( x, y, np, nc, dir )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    integer,             intent(in)     :: np, nc
+    integer,             intent(in)     :: dir
+!
+    integer :: i
+!
+    do i = 1,nc
+        y(i) = tabppm(1,indchildppm(i,dir),dir) * x(indparentppm(i,dir)  ) + &
+               tabppm(2,indchildppm(i,dir),dir) * x(indparentppm(i,dir)+1) + &
+               tabppm(3,indchildppm(i,dir),dir) * x(indparentppm(i,dir)+2) + &
+               tabppm(4,indchildppm(i,dir),dir) * x(indparentppm(i,dir)+3) + &
+               tabppm(5,indchildppm(i,dir),dir) * x(indparentppm(i,dir)+4)
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine PPM1dAfterCompute
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine weno1d
+!
+! Carries out a 1D interpolation and apply monotonicity constraints
+! using WENO method on a child grid (vector y) from its parent grid (vector x).
+!---------------------------------------------------------------------------------------------------
+!subroutine weno1dnew ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+!
+!CC   Description:
+!CC   subroutine to do a 1D interpolation and apply monotonicity constraints
+!CC   using piecewise parabolic method
+!CC   on a child grid (vector y) from its parent grid (vector x).
+!C    Method:
+!
+!     Declarations:
+!
+!      Implicit none
+!
+!     Arguments
+!      Integer             :: np,nc
+!      Real, Dimension(np) :: x
+!      Real, Dimension(nc) :: y
+!      Real, Dimension(:),Allocatable :: ytemp
+!      Real                :: s_parent,s_child,ds_parent,ds_child
+!
+!     Local scalars
+!      Integer :: i,coeffraf,locind_parent_left,locind_parent_last
+!      Integer :: iparent,ipos,pos,nmin,nmax
+!      Real    :: ypos
+!      integer :: i1,jj
+!      Real :: xpmin,cavg,a,b
+!
+!      Real :: xrmin,xrmax,am3,s2,s1
+!      Real, Dimension(np) :: xr,xl,delta,a6,slope,slope2,smooth
+!      Real, Dimension(:),Allocatable  :: diff,diff2,diff3
+!      INTEGER :: diffmod
+!      REAL :: invcoeffraf
+!      integer :: s,l,k
+!      integer :: etan, etap
+!      real :: delta0, delta1, delta2
+!      real :: epsilon
+!      parameter (epsilon = 1.D-8)
+!      real, dimension(:,:), allocatable :: ak, ck
+!
+!      coeffraf = nint(ds_parent/ds_child)
+!
+!      If (coeffraf == 1) Then
+!          locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+!          y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+!          return
+!      End If
+!      invcoeffraf = ds_child/ds_parent
+!      Allocate(ak(0:1,coeffraf))
+!      Allocate(ck(0:1,coeffraf))
+!
+!
+!      Allocate(ytemp(-2*coeffraf:nc+2*coeffraf))
+!      ypos = s_child
+!
+!      locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+!      locind_parent_last = 1 +&
+!      agrif_ceiling((ypos +(nc - 1)&
+!      *ds_child - s_parent)/ds_parent)
+!
+!      xpmin = s_parent + (locind_parent_left-1)*ds_parent
+!      i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+!
+!      Allocate( diff(coeffraf),diff2(coeffraf),diff3(coeffraf) )
+!
+!      diff(1)=0.5*invcoeffraf
+!      do i=2,coeffraf
+!         diff(i) = diff(i-1)+invcoeffraf
+!      enddo
+!
+!      ak = 0.
+!      ck = 0.
+!
+!      do i=1,coeffraf
+!         do k=0,1
+!         do s=0,2
+!         do l=0,2
+!           if (l /= s) then
+!            ak(k,i) = ak(k,i)+(diff(i)-(k-l+1.))
+!           endif
+!         enddo
+!         enddo
+!         enddo
+!
+!         etap = 0
+!         etan = 0
+!         do k=0,1
+!          if (ak(k,i) > 0) then
+!            etap = etap+1
+!          else if (ak(k,i) < 0) then
+!            etan = etan + 1
+!          endif
+!         enddo
+!
+!         do k=0,1
+!           if (ak(k,i) == 0) then
+!            Ck(k,i) = 1.
+!           else if (ak(k,i) > 0) then
+!            Ck(k,i) = 1./(etap * ak(k,i))
+!           else
+!            Ck(k,i) = -1./(etan * ak(k,i))
+!           endif
+!         enddo
+!      enddo
+!
+!
+!      a = 0.
+!      b = invcoeffraf
+!      Do i=1,coeffraf
+!         diff2(i) = 0.5*(b*b - a*a)
+!         diff3(i) = (1./3.)*(b*b*b - a*a*a)
+!         a = a + invcoeffraf
+!         b = b + invcoeffraf
+!      End do
+!
+!      if( locind_parent_last+2 <= np ) then
+!           nmax = locind_parent_last+2
+!      elseif( locind_parent_last+1 <= np ) then
+!           nmax = locind_parent_last+1
+!      else
+!           nmax = locind_parent_last
+!      endif
+!
+!      if(locind_parent_left-2 >= 1) then
+!          nmin = locind_parent_left-2
+!      elseif(locind_parent_left-1 >= 1) then
+!          nmin = locind_parent_left-1
+!      else
+!          nmin = locind_parent_left
+!      endif
+!
+!      Do i = nmin+1,nmax
+!         slope(i) = (x(i) - x(i-1))
+!      Enddo
+!      DO i=nmin+2,nmax
+!        smooth(i) = 0.5*(slope(i)**2+slope(i-1)**2)&
+!       +(slope(i)-slope(i-1))**2
+!      enddo
+!
+!        diffmod = 0
+!        IF (mod(coeffraf,2) == 0) diffmod = 1
+!
+!        ipos = i1
+!
+!        Do iparent = locind_parent_left,locind_parent_last
+!             pos=1
+!
+!            delta0=1./(epsilon+smooth(iparent  ))**3
+!            delta1=1./(epsilon+smooth(iparent+1))**3
+!            delta2=1./(epsilon+smooth(iparent+2))**3
+!
+!             Do jj = ipos - coeffraf/2+diffmod,ipos + coeffraf/2
+!
+!               pos = pos+1
+!             End do
+!             ipos = ipos + coeffraf
+!
+!        End do
+!
+!
+!        y(1:nc)=ytemp(1:nc)
+!        deallocate(ytemp)
+!        deallocate(diff, diff2, diff3)
+!
+!        deallocate(ak,ck)
+!
+!      Return
+!      End subroutine weno1dnew
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine WENO1d
+!
+!> Carries out a a 1D interpolation using WENO method on a child grid (vector y) from its parent 
+!! grid (vector x).
+!---------------------------------------------------------------------------------------------------
+subroutine WENO1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    real, dimension(:), allocatable :: ytemp
+    integer :: i,coeffraf,locind_parent_left,locind_parent_last
+    integer :: iparent,ipos,pos,nmin,nmax
+    real    :: ypos
+    integer :: i1,jj
+    real :: xpmin
+!
+    real, dimension(np) :: slope
+    real, dimension(:), allocatable  :: diff
+    integer :: diffmod
+    real :: invcoeffraf
+    real :: delta0, delta1, sumdelta
+    real, parameter :: epsilon = 1.d-8
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    endif
+!
+    invcoeffraf = ds_child/ds_parent
+!
+    allocate(ytemp(-2*coeffraf:nc+2*coeffraf))
+    ypos = s_child
+!
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    locind_parent_last = 1 + agrif_ceiling((ypos +(nc - 1) *ds_child - s_parent)/ds_parent)
+!
+    xpmin = s_parent + (locind_parent_left-1)*ds_parent
+    i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+!
+    allocate(diff(coeffraf))
+    diff(1) = 0.5*invcoeffraf
+    do i = 2,coeffraf
+        diff(i) = diff(i-1)+invcoeffraf
+    enddo
+!
+    if ( locind_parent_last+2 <= np ) then
+        nmax = locind_parent_last+2
+    else if ( locind_parent_last+1 <= np ) then
+        nmax = locind_parent_last+1
+      else
+        nmax = locind_parent_last
+    endif
+!
+    if(locind_parent_left-1 >= 1) then
+        nmin = locind_parent_left-1
+    else
+        nmin = locind_parent_left
+    endif
+!
+    do i = nmin+1,nmax
+        slope(i) = x(i) - x(i-1)
+    enddo
+!
+    diffmod = 0
+    if (mod(coeffraf,2) == 0) diffmod = 1
+!
+    ipos = i1
+!
+    do iparent = locind_parent_left,locind_parent_last
+        pos=1
+        delta0 = 1./(epsilon+slope(iparent  )**2)**2
+        delta1 = 1./(epsilon+slope(iparent+1)**2)**2
+        sumdelta = 1./(delta0+delta1)
+        do jj = ipos - coeffraf/2+diffmod,ipos + coeffraf/2
+            ytemp(jj) = x(iparent)+(diff(pos)-0.5)*( delta0*slope(iparent) + &
+                                                     delta1*slope(iparent+1))*sumdelta
+            pos = pos+1
+        enddo
+        ipos = ipos + coeffraf
+    enddo
+!
+    y(1:nc) = ytemp(1:nc)
+    deallocate(ytemp)
+    deallocate(diff)
+!---------------------------------------------------------------------------------------------------
+end subroutine WENO1d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine ENO1d
+!
+!> Carries out a 1D interpolation using piecewise polynomial ENO reconstruction technique
+!! on a child grid (vector y) from its parent grid (vector x).
+!! \see ---- p 163-164 Computational gasdynamics ----
+!---------------------------------------------------------------------------------------------------
+subroutine ENO1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: np, nc
+    real, dimension(np), intent(in)     :: x
+    real, dimension(nc), intent(out)    :: y
+    real,                intent(in)     :: s_parent, s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!
+    integer :: i,coeffraf,locind_parent_left,locind_parent_last
+    integer :: ipos, pos
+    real    :: ypos,xi
+    integer :: i1,jj
+    real :: xpmin
+!
+    real, dimension(:),   allocatable  :: ytemp
+    real, dimension(:,:), allocatable  :: xbar
+    real, dimension(1:np+1)            :: xhalf
+    real, dimension(3,np)              :: dd, c
+    integer :: diffmod, left
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    if (coeffraf == 1) then
+        locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+        y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+        return
+    end if
+
+    diffmod = 0
+    if (mod(coeffraf,2) == 0) diffmod = 1
+!
+    allocate(ytemp(-2*coeffraf:nc+2*coeffraf))
+    ypos = s_child
+!
+    locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent)
+    locind_parent_last = 1 + agrif_ceiling((ypos +(nc - 1) *ds_child - s_parent)/ds_parent)
+!
+    xpmin = s_parent + (locind_parent_left-1)*ds_parent
+    i1 = 1+agrif_int((xpmin-s_child)/ds_child)
+!
+    do i = 1,np+1
+        xhalf(i) = i - 0.5
+    enddo
+!
+! Compute divided differences
+!
+    dd(1,1:np)   = x(1:np)
+    dd(2,1:np-1) = 0.5*( dd(1,2:np) - dd(1,1:np-1) )
+    dd(3,1:np-2) = (1./3.)*( dd(2,2:np-1) - dd(2,1:np-2) )
+!
+    allocate( xbar( coeffraf,2 ) )
+    xi = 0.5
+    do i = 1,coeffraf
+        xbar(i,1) = (i-1)*ds_child/ds_parent - xi
+        xbar(i,2) =  i   *ds_child/ds_parent - xi
+    enddo
+!
+    ipos = i1
+!
+    do i = locind_parent_left,locind_parent_last
+        left = i
+        do jj = 2,3
+            if(abs(dd(jj,left)) > abs(dd(jj,left-1))) left = left-1
+        enddo
+!
+!       convert to Taylor series form
+        call taylor(i,xhalf(left:left+2),dd(1:3,left),c(1:3,i))
+    enddo
+!
+! Evaluate the reconstruction on each cell
+!
+    do i = locind_parent_left,locind_parent_last
+!
+        pos = 1
+!
+        do jj = ipos - coeffraf/2+diffmod,ipos + coeffraf/2
+            ytemp(jj) = ( c(1,i)*(xbar(pos,2)-xbar(pos,1))              &
+                        + c(2,i)*(xbar(pos,2)*xbar(pos,2) -             &
+                                  xbar(pos,1)*xbar(pos,1))              &
+                        + c(3,i)*(xbar(pos,2)*xbar(pos,2)*xbar(pos,2) - &
+                                  xbar(pos,1)*xbar(pos,1)*xbar(pos,1))  &
+                        ) * coeffraf
+            pos = pos+1
+        enddo
+        ipos = ipos + coeffraf
+!
+    enddo
+!
+    y(1:nc) = ytemp(1:nc)
+    deallocate(ytemp,xbar)
+!---------------------------------------------------------------------------------------------------
+end subroutine ENO1d
+!===================================================================================================
+!
+!     **************************************************************************  
+!CC   Subroutine ppm1d_lim
+!     ************************************************************************** 
+! 
+      Subroutine ppm1d_lim(x,y,np,nc,s_parent,s_child,ds_parent,ds_child) 
+!
+!CC   Description:
+!CC   Subroutine to do a 1D interpolation and apply monotonicity constraints
+!CC   using piecewise parabolic method  
+!CC   on a child grid (vector y) from its parent grid (vector x).
+!C    Method:
+!
+!     Declarations:
+!
+      Implicit none
+!        
+!     Arguments
+      Integer             :: np,nc      
+      Real, Dimension(np) :: x      
+      Real, Dimension(nc) :: y
+      Real, Dimension(:),Allocatable :: ytemp
+      Real                :: s_parent,s_child,ds_parent,ds_child
+!
+!     Local scalars
+      Integer :: i,coeffraf,locind_parent_left,locind_parent_last
+      Integer :: iparent,ipos,pos,nmin,nmax
+      Real    :: ypos
+      integer :: i1,jj
+      Real :: xpmin,cavg,a,b
+!      
+      Real :: xrmin,xrmax,am3,s2,s1  
+      Real, Dimension(np) :: dela,xr,xl,delta,a6,slope,slope2
+      Real, Dimension(:),Allocatable  :: diff,diff2,diff3    
+      INTEGER :: diffmod
+!      
+      coeffraf = nint(ds_parent/ds_child)
+!
+      If (coeffraf == 1) Then
+          locind_parent_left = 1 + nint((s_child - s_parent)/ds_parent)
+          y(1:nc) = x(locind_parent_left:locind_parent_left+nc-1)
+          return
+      End If
+!      
+      Allocate(ytemp(-2*coeffraf:nc+2*coeffraf))
+      ypos = s_child  
+!
+      locind_parent_left = 1 + agrif_int((ypos - s_parent)/ds_parent) 
+      locind_parent_last = 1 + &
+           agrif_ceiling((ypos +(nc - 1)  &
+           *ds_child - s_parent)/ds_parent)  
+!
+      xpmin = s_parent + (locind_parent_left-1)*ds_parent       
+      i1 = 1+agrif_int((xpmin-s_child)/ds_child)        
+!     
+      Allocate( diff(coeffraf),diff2(coeffraf),diff3(coeffraf) )
+!      
+         diff(:) = ds_child/ds_parent
+!      
+      Do i=1,coeffraf
+         a = real(i-1)*ds_child/ds_parent
+         b = real(i)*ds_child/ds_parent
+         diff2(i) = 0.5*(b*b - a*a)  
+         diff3(i) = (1./3.)*(b*b*b - a*a*a)
+      End do
+!
+      if( locind_parent_last+2 <= np ) then
+           nmax = locind_parent_last+2    
+      else if( locind_parent_last+1 <= np ) then
+           nmax = locind_parent_last+1
+      else
+           nmax = locind_parent_last 
+      endif     
+!      
+      if(locind_parent_left-1 >= 1) then
+          nmin = locind_parent_left-1
+      else 
+          nmin = locind_parent_left
+      endif    
+! 
+      Do i = nmin,nmax
+         slope(i) = x(i) - x(i-1)
+         slope2(i) = 2.*abs(slope(i))
+      Enddo
+!
+      Do i = nmin,nmax-1
+         dela(i) = 0.5 * ( slope(i) + slope(i+1) )
+! Van Leer slope limiter
+         dela(i) = min( abs(dela(i)),slope2(i), &
+                       slope2(i+1) )*sign(1.,dela(i))
+         IF( slope(i)*slope(i+1) <= 0. ) dela(i) = 0.
+      Enddo
+!
+      Do i = nmin,nmax-2
+         xr(i) = x(i) + (1./2.)*slope(i+1) + (-1./6.)*dela(i+1) &
+                                          + ( 1./6. )*dela(i)
+      Enddo
+!
+      Do i = nmin,nmax-2
+         xrmin = min(x(i),x(i+1))
+         xrmax = max(x(i),x(i+1))
+         xr(i) = min(xr(i),xrmax)
+         xr(i) = max(xr(i),xrmin)
+         xl(i+1) = xr(i)         
+      Enddo
+! apply parabolic monotonicity
+       Do i = locind_parent_left,locind_parent_last
+          If( ( (xr(i)-x(i))* (x(i)-xl(i)) ) .le. 0. ) then
+             xl(i) = x(i) 
+             xr(i) = x(i)
+          Endif          
+          delta(i) = xr(i) - xl(i)
+          am3 = 3. * x(i)
+          s1  = am3 - 2. * xr(i)
+          s2  = am3 - 2. * xl(i)
+          IF( delta(i) * (xl(i) - s1) .le. 0. ) xl(i) = s1
+          IF( delta(i) * (s2 - xr(i)) .le. 0. ) xr(i) = s2
+          delta(i) = xr(i) - xl(i)
+          a6(i) = 6.*x(i)-3.*(xl(i) +xr(i))
+!
+       End do   
+!
+        diffmod = 0
+       IF (mod(coeffraf,2) == 0) diffmod = 1           
+!
+        ipos = i1
+!               
+        Do iparent = locind_parent_left,locind_parent_last       
+             pos=1
+             cavg = 0.
+             Do jj = ipos - coeffraf/2+diffmod,ipos + coeffraf/2
+!
+               ytemp(jj) = (diff(pos)*xl(iparent)   &
+                  + diff2(pos) &
+                  *  (delta(iparent)+a6(iparent)) &
+                  - diff3(pos)*a6(iparent))*coeffraf
+                              
+               cavg = cavg + ytemp(jj)
+               pos = pos+1 
+             End do 
+             ipos = ipos + coeffraf
+!
+        End do     
+!
+!
+        y(1:nc)=ytemp(1:nc)                                 
+        deallocate(ytemp)                
+        deallocate(diff, diff2, diff3)
+      Return
+      End Subroutine ppm1d_lim
+!===================================================================================================
+!  subroutine taylor
+!---------------------------------------------------------------------------------------------------
+subroutine taylor ( ind, xhalf, dd, c )
+!---------------------------------------------------------------------------------------------------
+    integer,            intent(in)  :: ind
+    real, dimension(3), intent(in)  :: xhalf
+    real, dimension(3), intent(in)  :: dd
+    real, dimension(3), intent(out) :: c
+!
+    real, dimension(0:3,0:3) :: d
+    integer                  :: i, j
+!
+    d(0,0:3) = 1.0
+    do i = 1,3
+        d(i,0) = (ind-xhalf(i))*d(i-1,0)
+    enddo
+!
+    do i = 1,3
+        do j = 1,3-i
+            d(i,j) = d(i,j-1) + (ind-xhalf(i+j))*d(i-1,j)
+        enddo
+    enddo
+!
+    do j = 1,3
+        c(j) = 0.
+        do i=0,3-j
+            c(j) = c(j) + d(i,j)*dd(i+j)
+        enddo
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine taylor
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_limiter_vanleer
+!---------------------------------------------------------------------------------------------------
+real function Agrif_limiter_vanleer ( tab ) result(res)
+!---------------------------------------------------------------------------------------------------
+    real, dimension(3), intent(in) :: tab
+!
+    real :: p1, p2, p3
+
+    p1 =    (tab(3)-tab(1))/2.
+    p2 = 2.*(tab(2)-tab(1))
+    p3 = 2.*(tab(3)-tab(2))
+
+    if ((p1>0.).AND.(p2>0.).AND.(p3>0)) then
+        res = minval((/p1,p2,p3/))
+    elseif ((p1<0.).AND.(p2<0.).AND.(p3<0)) then
+        res = maxval((/p1,p2,p3/))
+    else
+        res=0.
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_limiter_vanleer
+!===================================================================================================
+!
+end module Agrif_InterpBasic
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modlinktomodel.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modlinktomodel.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modlinktomodel.F90	(revision 9987)
@@ -0,0 +1,181 @@
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place -  Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Link
+!>
+!> This module is used to link AGRIF files to the model.
+!
+module Agrif_Link
+!
+    interface
+!
+        subroutine Agrif_clustering_def ( )
+!
+        end subroutine Agrif_clustering_def
+!
+        subroutine Agrif_Set_numberofcells ( Agrif_Gr )
+            use Agrif_Grids, only : Agrif_Grid
+            type(Agrif_Grid), pointer :: Agrif_Gr   !< Pointer on the current grid
+        end subroutine Agrif_Set_numberofcells
+!
+        subroutine Agrif_Get_numberofcells ( Agrif_Gr )
+            use Agrif_Grids, only : Agrif_Grid
+            type(Agrif_Grid), pointer :: Agrif_Gr   !< Pointer on the current grid
+        end subroutine Agrif_Get_numberofcells
+!
+    end interface
+!
+    abstract interface
+!
+        subroutine alloc_proc ( Agrif_Gr )
+            use Agrif_Grids, only : Agrif_Grid
+            type(Agrif_Grid), pointer :: Agrif_Gr   !< Pointer on the current grid
+        end subroutine alloc_proc
+!
+        subroutine typedef_proc ( )
+            implicit none
+        end subroutine typedef_proc
+!
+    end interface
+    
+    procedure(alloc_proc)   :: Agrif_Allocationcalls
+    procedure(typedef_proc) :: Agrif_probdim_modtype_def
+!
+end module Agrif_Link
+!
+!===================================================================================================
+!  function Agrif_parent
+!        modify by conv. To use : un_parent = Agrif_Parent(un)
+!===================================================================================================
+!  function Agrif_Get_Coarse_Grid
+!        modify by conv. To use : un_Mygrid = Agrif_Get_Coarse_grid(un)
+!===================================================================================================
+!  function Agrif_Rhox
+!        modify by conv. To use : var = Agrif_Rhox()
+!                    REAL(Agrif_Curgrid % spaceref(1))
+!===================================================================================================
+!  function Agrif_Parent_Rhox
+!        modify by conv. To use : var = Agrif_Parent_Rhox()
+!                    REAL(Agrif_Curgrid % parent % spaceref(1))
+!===================================================================================================
+!  function Agrif_Irhox
+!        modify by conv. To use : var = Agrif_Parent_IRhox()
+!                    Agrif_Curgrid % spaceref(1)
+!===================================================================================================
+!  function Agrif_Parent_Irhox
+!        modify by conv. To use : var = Agrif_Parent_IRhox()
+!                    Agrif_Curgrid % parent % spaceref(1)
+!===================================================================================================
+!  function Agrif_Rhoy
+!        modify by conv. To use : var = Agrif_Rhoy()
+!                    REAL(Agrif_Curgrid % spaceref(2))
+!===================================================================================================
+!  function Agrif_Parent_Rhoy
+!        modify by conv. To use : var = Agrif_Parent_Rhoy()
+!                    REAL(Agrif_Curgrid % parent % spaceref(2))
+!===================================================================================================
+!  function Agrif_Irhoy
+!        modify by conv. To use : var = Agrif_Parent_IRhoy()
+!                    Agrif_Curgrid % spaceref(2)
+!===================================================================================================
+!  function Agrif_Parent_Irhoy
+!        modify by conv. To use : var = Agrif_Parent_IRhoy()
+!                    Agrif_Curgrid % parent % spaceref(2)
+!===================================================================================================
+!  function Agrif_Rhoz
+!        modify by conv. To use : var = Agrif_Rhoz()
+!                    REAL(Agrif_Curgrid % spaceref(3))
+!===================================================================================================
+!  function Agrif_Parent_Rhoz
+!        modify by conv. To use : var = Agrif_Parent_Rhoz()
+!                    REAL(Agrif_Curgrid % parent % spaceref(3))
+!===================================================================================================
+!  function Agrif_Irhoz
+!        modify by conv. To use : var = Agrif_Parent_IRhoz()
+!                    Agrif_Curgrid % spaceref(3)
+!===================================================================================================
+!  function Agrif_Parent_Irhoz
+!        modify by conv. To use : var = Agrif_Parent_IRhoz()
+!                    Agrif_Curgrid % parent % spaceref(3)
+!===================================================================================================
+!  function Agrif_NearCommonBorderX
+!        modify by conv. To use : var = Agrif_NearCommonBorderX()
+!                       Agrif_Curgrid % NearRootBorder(1)
+!===================================================================================================
+!  function Agrif_NearCommonBorderY
+!        modify by conv. To use : var = Agrif_NearCommonBorderY()
+!                       Agrif_Curgrid % NearRootBorder(2)
+!===================================================================================================
+!  function Agrif_NearCommonBorderZ
+!        modify by conv. To use : var = Agrif_NearCommonBorderZ()
+!                       Agrif_Curgrid % NearRootBorder(3)
+!===================================================================================================
+!  function Agrif_DistantCommonBorderX
+!        modify by conv. To use : var = Agrif_DistantCommonBorderX()
+!                       Agrif_Curgrid % DistantRootBorder(1)
+!===================================================================================================
+!  function Agrif_DistantCommonBorderY
+!        modify by conv. To use : var = Agrif_DistantCommonBorderY()
+!                       Agrif_Curgrid % DistantRootBorder(2)
+!===================================================================================================
+!  function Agrif_DistantCommonBorderZ
+!        modify by conv. To use : var = Agrif_DistantCommonBorderZ()
+!                       Agrif_Curgrid % DistantRootBorder(3)
+!===================================================================================================
+!  function Agrif_Nb_Step
+!        modify by conv. To use : var = Agrif_Nb_Step()
+!                          Agrif_Curgrid % ngridstep
+!===================================================================================================
+!  function Agrif_Nb_Fine_Grids
+!        modify by conv. To use : var = Agrif_Nb_Fine_Grids()
+!                         Agrif_nbfixedgrids
+!===================================================================================================
+!  function Agrif_Ix
+!        modify by conv. To use : var = Agrif_Ix()
+!                         Agrif_Curgrid % ix(1)
+!===================================================================================================
+!  function Agrif_Parent_Ix
+!        modify by conv. To use : var = Agrif_Parent_Ix()
+!                        Agrif_Curgrid % parent % ix(1)
+!===================================================================================================
+!  function Agrif_Iy
+!        modify by conv. To use : var = Agrif_Iy()
+!                        Agrif_Curgrid % ix(2)
+!===================================================================================================
+!  function Agrif_Parent_Iy
+!        modify by conv. To use : var = Agrif_Parent_Iy()
+!                       Agrif_Curgrid % parent % ix(2)
+!===================================================================================================
+!  function Agrif_Iz
+!        modify by conv. To use : var = Agrif_Iz()
+!                      Agrif_Curgrid % ix(3)
+!===================================================================================================
+!  function Agrif_Parent_Iz
+!        modify by conv. To use : var = Agrif_Parent_Iz()
+!                     Agrif_Curgrid % parent % ix(3)
+!===================================================================================================
+!  function Agrif_Get_grid_id
+!        modify by conv. To use : var = Agrif_Get_grid_id()
+!                    Agrif_Curgrid % grid_id
+!===================================================================================================
+!  function Agrif_Get_parent_id
+!        modify by conv. To use : var = Agrif_Get_parent_id()
+!                    Agrif_Curgrid % parent % grid_id
+!===================================================================================================
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modmask.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modmask.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modmask.F90	(revision 9987)
@@ -0,0 +1,586 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place -  Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Mask.
+!>
+!> Module for masks.
+!
+module Agrif_Mask
+!
+    use Agrif_Types
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_CheckMasknD
+!
+!> Called in the procedure #Agrif_InterpnD to recalculate the value of the parent grid variable
+!! when this one is equal to Agrif_SpecialValue.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_CheckMasknD ( tempP, parent, pbtab, petab, ppbtab, ppetab, noraftab, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), pointer   :: tempP  !< Part of the parent grid used for the interpolation of the child grid
+    type(Agrif_Variable), pointer   :: parent !< The parent grid
+    integer, dimension(nbdim)       :: pbtab  !< limits of the parent grid used
+    integer, dimension(nbdim)       :: petab  !< interpolation of the child grid
+    integer, dimension(nbdim)       :: ppbtab, ppetab
+    logical, dimension(nbdim)       :: noraftab
+    integer                         :: nbdim
+!
+    integer :: i0,j0,k0,l0,m0,n0
+!
+    select case (nbdim)
+    case (1)
+        do i0 = pbtab(1),petab(1)
+            if (tempP%array1(i0) == Agrif_SpecialValue) then
+                call CalculNewValTempP((/i0/),tempP,parent,ppbtab,ppetab,noraftab,nbdim)
+            endif
+        enddo
+    case (2)
+        do j0 = pbtab(2),petab(2)
+        do i0 = pbtab(1),petab(1)
+            if (tempP%array2(i0,j0) == Agrif_SpecialValue) then
+                call CalculNewValTempP((/i0,j0/),tempP,parent,ppbtab,ppetab, noraftab,nbdim)
+            endif
+        enddo
+        enddo
+    case (3)
+        do k0 = pbtab(3),petab(3)
+        do j0 = pbtab(2),petab(2)
+        do i0 = pbtab(1),petab(1)
+            if (tempP%array3(i0,j0,k0) == Agrif_SpecialValue) then
+!------CDIR NEXPAND
+                call CalculNewValTempP3D((/i0,j0,k0/), &
+                    tempP%array3(ppbtab(1),ppbtab(2),ppbtab(3)),  &
+                    parent%array3(ppbtab(1),ppbtab(2),ppbtab(3)), &
+                    ppbtab,ppetab,noraftab,MaxSearch,Agrif_SpecialValue)
+
+!            Call CalculNewValTempP((/i0,j0,k0/),
+!     &                             tempP,parent,
+!     &                             ppbtab,ppetab,
+!     &                             noraftab,nbdim)
+
+            endif
+        enddo
+        enddo
+        enddo
+    case (4)
+        do l0 = pbtab(4),petab(4)
+        do k0 = pbtab(3),petab(3)
+        do j0 = pbtab(2),petab(2)
+        do i0 = pbtab(1),petab(1)
+            if (tempP%array4(i0,j0,k0,l0) == Agrif_SpecialValue) then
+                call CalculNewValTempP4D((/i0,j0,k0,l0/), &
+                    tempP%array4(ppbtab(1),ppbtab(2),ppbtab(3),ppbtab(4)),  &
+                    parent%array4(ppbtab(1),ppbtab(2),ppbtab(3),ppbtab(4)), &
+                    ppbtab,ppetab,noraftab,MaxSearch,Agrif_SpecialValue)
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+    case (5)
+        do m0 = pbtab(5),petab(5)
+        do l0 = pbtab(4),petab(4)
+        do k0 = pbtab(3),petab(3)
+        do j0 = pbtab(2),petab(2)
+        do i0 = pbtab(1),petab(1)
+            if (tempP%array5(i0,j0,k0,l0,m0) == Agrif_SpecialValue) then
+                call CalculNewValTempP((/i0,j0,k0,l0,m0/), &
+                    tempP,parent,ppbtab,ppetab,noraftab,nbdim)
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+    case (6)
+        do n0 = pbtab(6),petab(6)
+        do m0 = pbtab(5),petab(5)
+        do l0 = pbtab(4),petab(4)
+        do k0 = pbtab(3),petab(3)
+        do j0 = pbtab(2),petab(2)
+        do i0 = pbtab(1),petab(1)
+            if (tempP%array6(i0,j0,k0,l0,m0,n0) == Agrif_SpecialValue) then
+                call CalculNewValTempP((/i0,j0,k0,l0,m0,n0/), &
+                    tempP,parent,ppbtab,ppetab,noraftab,nbdim)
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+        enddo
+    end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CheckMasknD
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine CalculNewValTempP
+!
+!> Called in the procedure #Agrif_InterpnD to recalculate the value of the parent grid variable
+!! when this one is equal to Agrif_SpecialValue.
+!---------------------------------------------------------------------------------------------------
+subroutine CalculNewValTempP ( indic, tempP, parent, ppbtab, ppetab, noraftab, nbdim )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(nbdim)       :: indic
+    type(Agrif_Variable), pointer   :: tempP  !< Part of the parent grid used for the interpolation of the child grid
+    type(Agrif_Variable), pointer   :: parent !< The parent grid
+    integer, dimension(nbdim)       :: ppbtab, ppetab
+    logical, dimension(nbdim)       :: noraftab
+    integer                         :: nbdim
+!
+    integer                     :: i,ii,iii,jj,kk,ll,mm,nn
+    integer, dimension(nbdim)   :: imin,imax,idecal
+    integer                     :: nbvals
+    real                        :: res
+    real                        :: valparent
+    integer                     :: ValMax
+    logical                     :: firsttest
+!
+    ValMax = 1
+    do iii = 1,nbdim
+        if (.NOT.noraftab(iii)) then
+            ValMax = max(ValMax,ppetab(iii)-indic(iii))
+            ValMax = max(ValMax,indic(iii)-ppbtab(iii))
+        endif
+    enddo
+!
+    Valmax = min(Valmax,MaxSearch)
+!
+!CDIR NOVECTOR
+    imin = indic
+!CDIR NOVECTOR
+    imax = indic
+!
+    i = 1
+    firsttest = .TRUE.
+!
+    do while (i <= ValMax)
+!
+        if ( (i == 1).AND.(firsttest) ) i = Valmax
+!
+        do iii = 1,nbdim
+            if (.NOT.noraftab(iii)) then
+                imin(iii) = max(indic(iii) - i,ppbtab(iii))
+                imax(iii) = min(indic(iii) + i,ppetab(iii))
+                if (firsttest) then
+                    if (indic(iii) > ppbtab(iii)) then
+!CDIR NOVECTOR
+                        idecal = indic
+                        idecal(iii) = idecal(iii)-1
+                        SELECT CASE(nbdim)
+                        CASE (1)
+                            if (tempP%array1(idecal(1) &
+                                    ) == Agrif_SpecialValue) imin(iii) = imax(iii)
+                        CASE (2)
+                            if (tempP%array2(idecal(1), idecal(2) &
+                                    ) == Agrif_SpecialValue) imin(iii) = imax(iii)
+                        CASE (3)
+                            if (tempP%array3(idecal(1), &
+                                             idecal(2), idecal(3) &
+                                    ) == Agrif_SpecialValue) imin(iii) = imax(iii)
+                        CASE (4)
+                            if (tempP%array4(idecal(1), idecal(2), &
+                                             idecal(3), idecal(4)  &
+                                    ) == Agrif_SpecialValue) imin(iii) = imax(iii)
+                        CASE (5)
+                            if (tempP%array5(idecal(1), idecal(2), &
+                                             idecal(3), idecal(4), &
+                                             idecal(5)             &
+                                    ) == Agrif_SpecialValue) imin(iii) = imax(iii)
+                        CASE (6)
+                            if (tempP%array6(idecal(1), idecal(2), &
+                                             idecal(3), idecal(4), &
+                                             idecal(5), idecal(6)  &
+                                    ) == Agrif_SpecialValue) imin(iii) = imax(iii)
+                        END SELECT
+                    endif
+                endif
+            endif
+        enddo
+!
+        Res = 0.
+        Nbvals = 0
+!
+        SELECT CASE(nbdim)
+        CASE (1)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+            do ii = imin(1),imax(1)
+                ValParent = parent%array1(ii)
+                if ( ValParent /= Agrif_SpecialValue) then
+                    Res = Res + ValParent
+                    Nbvals = Nbvals + 1
+                endif
+            enddo
+!
+        CASE (2)
+            do jj = imin(2),imax(2)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+            do ii = imin(1),imax(1)
+                ValParent = parent%array2(ii,jj)
+                if ( ValParent /= Agrif_SpecialValue) then
+                    Res = Res + ValParent
+                    Nbvals = Nbvals + 1
+                endif
+            enddo
+            enddo
+
+        CASE (3)
+            do kk = imin(3),imax(3)
+            do jj = imin(2),imax(2)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+            do ii = imin(1),imax(1)
+                ValParent = parent%array3(ii,jj,kk)
+                if ( ValParent /= Agrif_SpecialValue) then
+                    Res = Res + ValParent
+                    Nbvals = Nbvals + 1
+                endif
+            enddo
+            enddo
+            enddo
+
+        CASE (4)
+            do ll = imin(4),imax(4)
+            do kk = imin(3),imax(3)
+            do jj = imin(2),imax(2)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+            do ii = imin(1),imax(1)
+                ValParent = parent%array4(ii,jj,kk,ll)
+                if ( ValParent /= Agrif_SpecialValue) then
+                    Res = Res + ValParent
+                    Nbvals = Nbvals + 1
+                endif
+            enddo
+            enddo
+            enddo
+            enddo
+
+        CASE (5)
+            do mm = imin(5),imax(5)
+            do ll = imin(4),imax(4)
+            do kk = imin(3),imax(3)
+            do jj = imin(2),imax(2)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+            do ii = imin(1),imax(1)
+                ValParent = parent%array5(ii,jj,kk,ll,mm)
+                if ( ValParent /= Agrif_SpecialValue) then
+                    Res = Res + ValParent
+                    Nbvals = Nbvals + 1
+                endif
+            enddo
+            enddo
+            enddo
+            enddo
+            enddo
+
+        CASE (6)
+            do nn = imin(6),imax(6)
+            do mm = imin(5),imax(5)
+            do ll = imin(4),imax(4)
+            do kk = imin(3),imax(3)
+            do jj = imin(2),imax(2)
+!CDIR ALTCODE
+!CDIR SHORTLOOP
+            do ii = imin(1),imax(1)
+                ValParent = parent%array6(ii,jj,kk,ll,mm,nn)
+                if ( ValParent /= Agrif_SpecialValue) then
+                    Res = Res + ValParent
+                    Nbvals = Nbvals + 1
+                endif
+            enddo
+            enddo
+            enddo
+            enddo
+            enddo
+            enddo
+
+        END SELECT
+!
+        if (Nbvals > 0) then
+            if (firsttest) then
+                firsttest = .FALSE.
+                i=1
+                cycle
+            endif
+            SELECT CASE(nbdim)
+            CASE (1)
+                tempP%array1(indic(1))           = Res/Nbvals
+            CASE (2)
+                tempP%array2(indic(1), indic(2)) = Res/Nbvals
+            CASE (3)
+                tempP%array3(indic(1), indic(2), &
+                             indic(3))           = Res/Nbvals
+            CASE (4)
+                tempP%array4(indic(1), indic(2), &
+                             indic(3), indic(4)) = Res/Nbvals
+            CASE (5)
+                tempP%array5(indic(1), indic(2), &
+                             indic(3), indic(4), &
+                             indic(5))           = Res/Nbvals
+            CASE (6)
+                tempP%array6(indic(1), indic(2), &
+                             indic(3), indic(4), &
+                             indic(5), indic(6)) = Res/Nbvals
+            END SELECT
+            exit
+        else
+            if (firsttest) exit
+            i = i + 1
+        endif
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine CalculNewValTempP
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine CalculNewValTempP3D
+!
+!> Called in the procedure #Agrif_InterpnD to recalculate the value of the parent grid variable
+!! when this one is equal to Agrif_SpecialValue.
+!---------------------------------------------------------------------------------------------------
+subroutine CalculNewValTempP3D ( indic, tempP, parent, ppbtab, ppetab, noraftab, &
+                                 MaxSearch, Agrif_SpecialValue )
+!---------------------------------------------------------------------------------------------------
+    integer, parameter          :: nbdim = 3
+    integer, dimension(nbdim)   :: indic
+    integer, dimension(nbdim)   :: ppbtab, ppetab
+    logical, dimension(nbdim)   :: noraftab
+    integer                     :: MaxSearch
+    real                        :: Agrif_SpecialValue
+    real, dimension(ppbtab(1):ppetab(1), &
+                    ppbtab(2):ppetab(2), &
+                    ppbtab(3):ppetab(3)) &
+                                :: tempP, parent  !< Part of the parent grid used for
+                                                  !< the interpolation of the child grid
+!
+    integer                     :: i,ii,iii,jj,kk
+    integer, dimension(nbdim)   :: imin,imax,idecal
+    integer                     :: Nbvals
+    real                        :: Res
+    real                        :: ValParent
+    integer                     :: ValMax
+    logical                     :: Existunmasked
+!
+    ValMax = 1
+!CDIR NOVECTOR
+    do iii = 1,nbdim
+        if (.NOT.noraftab(iii)) then
+            ValMax = max(ValMax,ppetab(iii)-indic(iii))
+            ValMax = max(ValMax,indic(iii)-ppbtab(iii))
+        endif
+    enddo
+!
+    Valmax = min(Valmax,MaxSearch)
+!
+!CDIR NOVECTOR
+    imin = indic
+!CDIR NOVECTOR
+    imax = indic
+
+!CDIR NOVECTOR
+    idecal = indic
+    i = Valmax
+!
+    do iii = 1,nbdim
+        if (.NOT.noraftab(iii)) then
+            imin(iii) = max(indic(iii) - i,ppbtab(iii))
+            imax(iii) = min(indic(iii) + i,ppetab(iii))
+
+            if (indic(iii) > ppbtab(iii)) then
+                idecal(iii) = idecal(iii)-1
+                if (tempP(idecal(1),idecal(2),idecal(3)) == Agrif_SpecialValue) then
+                    imin(iii) = imax(iii)
+                endif
+                idecal(iii) = idecal(iii)+1
+            endif
+        endif
+    enddo
+!
+    Existunmasked = .FALSE.
+!
+    do kk = imin(3),imax(3)
+    do jj = imin(2),imax(2)
+!CDIR NOVECTOR
+    do ii = imin(1),imax(1)
+        if ( parent(ii,jj,kk) /= Agrif_SpecialValue) then
+            Existunmasked = .TRUE.
+            exit
+        endif
+    enddo
+    enddo
+    enddo
+!
+    if (.Not.Existunmasked) return
+!
+    i = 1
+!
+    do while(i <= ValMax)
+!
+        do iii = 1 , nbdim
+            if (.NOT.noraftab(iii)) then
+                imin(iii) = max(indic(iii) - i,ppbtab(iii))
+                imax(iii) = min(indic(iii) + i,ppetab(iii))
+            endif
+        enddo
+!
+        Res = 0.
+        Nbvals = 0
+!
+        do kk = imin(3),imax(3)
+        do jj = imin(2),imax(2)
+!CDIR NOVECTOR
+        do ii = imin(1),imax(1)
+            ValParent = parent(ii,jj,kk)
+            if ( ValParent /= Agrif_SpecialValue) then
+                Res = Res + ValParent
+                Nbvals = Nbvals + 1
+            endif
+        enddo
+        enddo
+        enddo
+!
+        if (Nbvals > 0) then
+            tempP(indic(1),indic(2),indic(3)) = Res/Nbvals
+            exit
+        else
+            i = i + 1
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine CalculNewValTempP3D
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine CalculNewValTempP4D
+!
+!> Called in the procedure #Agrif_InterpnD to recalculate the value of the parent grid variable
+!! when this one is equal to Agrif_SpecialValue.
+!---------------------------------------------------------------------------------------------------
+subroutine CalculNewValTempP4D ( indic, tempP, parent, ppbtab, ppetab, noraftab, &
+                                 MaxSearch, Agrif_SpecialValue )
+!---------------------------------------------------------------------------------------------------
+    integer, parameter          :: nbdim = 4
+    integer, dimension(nbdim)   :: indic
+    integer, dimension(nbdim)   :: ppbtab, ppetab
+    logical, dimension(nbdim)   :: noraftab
+    integer                     :: MaxSearch
+    real                        :: Agrif_SpecialValue
+    real, dimension(ppbtab(1):ppetab(1), &
+                    ppbtab(2):ppetab(2), &
+                    ppbtab(3):ppetab(3), &
+                    ppbtab(4):ppetab(4)) &
+                                :: tempP, parent  !< Part of the parent grid used for
+                                                  !< the interpolation of the child grid
+!
+    integer                     :: i,ii,iii,jj,kk,ll
+    integer, dimension(nbdim)   :: imin,imax,idecal
+    integer                     :: Nbvals
+    real                        :: Res
+    real                        :: ValParent
+    integer                     :: ValMax
+!
+    logical                     :: firsttest
+!
+    ValMax = 1
+    do iii = 1,nbdim
+        if (.NOT.noraftab(iii)) then
+            ValMax = max(ValMax,ppetab(iii)-indic(iii))
+            ValMax = max(ValMax,indic(iii)-ppbtab(iii))
+        endif
+    enddo
+!
+    Valmax = min(Valmax,MaxSearch)
+!
+    imin = indic
+    imax = indic
+!
+    i = 1
+    firsttest = .TRUE.
+    idecal = indic
+!
+    do while (i <= ValMax)
+!
+        if ((i == 1).AND.(firsttest)) i = Valmax
+
+        do iii = 1,nbdim
+            if (.NOT.noraftab(iii)) then
+                imin(iii) = max(indic(iii) - i,ppbtab(iii))
+                imax(iii) = min(indic(iii) + i,ppetab(iii))
+                if (firsttest) then
+                    if (indic(iii) > ppbtab(iii)) then
+                        idecal(iii) = idecal(iii)-1
+                        if (tempP(idecal(1),idecal(2),idecal(3),idecal(4)) == Agrif_SpecialValue) then
+                            imin(iii) = imax(iii)
+                        endif
+                        idecal(iii) = idecal(iii)+1
+                    endif
+                endif
+            endif
+        enddo
+!
+        Res = 0.
+        Nbvals = 0
+!
+        do ll = imin(4),imax(4)
+        do kk = imin(3),imax(3)
+        do jj = imin(2),imax(2)
+        do ii = imin(1),imax(1)
+            ValParent = parent(ii,jj,kk,ll)
+            if ( ValParent /= Agrif_SpecialValue) then
+                Res = Res + ValParent
+                Nbvals = Nbvals + 1
+            endif
+        enddo
+        enddo
+        enddo
+        enddo
+!
+        if (Nbvals > 0) then
+            if (firsttest) then
+                firsttest = .FALSE.
+                i=1
+                cycle
+            endif
+
+            tempP(indic(1),indic(2),indic(3),indic(4)) = Res/Nbvals
+            exit
+        else
+            if (firsttest) exit
+            i = i + 1
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine CalculNewValTempP4D
+!===================================================================================================
+!
+end module Agrif_Mask
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modmpp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modmpp.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modmpp.F90	(revision 9987)
@@ -0,0 +1,634 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+module Agrif_Mpp
+!
+    use Agrif_Arrays
+    use Agrif_Grids
+!
+    implicit none
+!
+    interface
+        subroutine Agrif_get_proc_info ( imin, imax, jmin, jmax )
+            integer, intent(out) :: imin, imax
+            integer, intent(out) :: jmin, jmax
+        end subroutine Agrif_get_proc_info
+    end interface
+!
+    integer, private :: Agrif_MPI_prec
+!
+    private :: Agrif_get_proc_info
+!
+contains
+!
+#if defined AGRIF_MPI
+!===================================================================================================
+!  subroutine Agrif_MPI_Init
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_MPI_Init ( comm )
+!---------------------------------------------------------------------------------------------------
+    integer, optional, intent(in) :: comm    !< MPI communicator to be attached to the root grid.
+!
+    include 'mpif.h'
+    integer :: code, ierr
+    logical :: mpi_was_called
+    integer :: current_mpi_prec
+!
+    call MPI_INITIALIZED( mpi_was_called, code )
+    if( code /= MPI_SUCCESS ) then
+        write(*,*) ': Error in routine mpi_initialized'
+        call MPI_ABORT( MPI_COMM_WORLD, code, ierr )
+    endif
+    if( .not. mpi_was_called ) then
+        write(*,*) '### AGRIF Error : you should call Agrif_MPI_Init *after* MPI_Init.'
+        stop
+    endif
+
+    current_mpi_prec = KIND(1.0)
+    if (current_mpi_prec == 4) then
+      Agrif_MPI_prec = MPI_REAL4
+    else
+      Agrif_MPI_prec = MPI_REAL8
+    endif
+!
+    if ( present(comm) ) then
+        call Agrif_MPI_switch_comm(comm)
+    else
+        call Agrif_MPI_switch_comm(MPI_COMM_WORLD)
+    endif
+!
+    Agrif_Mygrid % communicator = Agrif_mpi_comm
+!
+    if ( Agrif_Parallel_sisters ) then
+        call Agrif_Init_ProcList( Agrif_Mygrid % proc_def_list, Agrif_Nbprocs )
+        call Agrif_pl_copy( Agrif_Mygrid % proc_def_list, Agrif_Mygrid % required_proc_list )
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_MPI_Init
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_MPI_switch_comm ( comm )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: comm    !< MPI communicator you want to switch to.
+!
+    include 'mpif.h'
+    integer :: code
+    logical :: mpi_was_called
+!
+    call MPI_INITIALIZED( mpi_was_called, code )
+    if ( .not. mpi_was_called ) return
+!
+    call MPI_COMM_SIZE(comm, Agrif_Nbprocs, code)
+    call MPI_COMM_RANK(comm, Agrif_ProcRank, code)
+    Agrif_mpi_comm = comm
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_MPI_switch_comm
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_MPI_get_grid_comm ( ) result ( comm )
+!---------------------------------------------------------------------------------------------------
+    integer :: comm
+    comm = Agrif_Curgrid % communicator
+!---------------------------------------------------------------------------------------------------
+end function Agrif_MPI_get_grid_comm
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_MPI_set_grid_comm ( comm )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in) :: comm
+    Agrif_Curgrid % communicator = comm
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_MPI_set_grid_comm
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_Init_ProcList ( proclist, nbprocs )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(inout) :: proclist
+    integer,               intent(in)    :: nbprocs
+!
+    include 'mpif.h'
+    type(Agrif_Proc), pointer     :: new_proc
+    integer                       :: p, ierr
+    integer                       :: imin, imax, jmin, jmax
+    integer, dimension(5)         :: local_proc_grid_info
+    integer, dimension(5,nbprocs) :: all_procs_grid_info
+!
+    call Agrif_get_proc_info(imin, imax, jmin, jmax)
+!
+    local_proc_grid_info(:) = (/Agrif_Procrank, imin, jmin, imax, jmax/)
+!
+    call MPI_ALLGATHER(local_proc_grid_info, 5, MPI_INTEGER, &
+                       all_procs_grid_info,  5, MPI_INTEGER, Agrif_mpi_comm, ierr)
+!
+    do p = 1,nbprocs
+!
+        allocate(new_proc)
+        new_proc % pn = all_procs_grid_info(1,p)
+        new_proc % imin(1) = all_procs_grid_info(2,p)
+        new_proc % imin(2) = all_procs_grid_info(3,p)
+        new_proc % imax(1) = all_procs_grid_info(4,p)
+        new_proc % imax(2) = all_procs_grid_info(5,p)
+        call Agrif_pl_append( proclist, new_proc )
+!
+    enddo
+!
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Init_ProcList
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Get_External_Data_first
+!---------------------------------------------------------------------------------------------------
+subroutine Get_External_Data_first ( pttruetab, cetruetab, pttruetabwhole, cetruetabwhole,  &
+                                     nbdim, memberoutall, coords, sendtoproc, recvfromproc, &
+                                     imin, imax, imin_recv, imax_recv )
+!---------------------------------------------------------------------------------------------------
+    include 'mpif.h'
+!
+    integer,                                     intent(in)  :: nbdim
+    integer, dimension(nbdim,0:Agrif_NbProcs-1), intent(in)  :: pttruetab,     cetruetab
+    integer, dimension(nbdim,0:Agrif_NbProcs-1), intent(in)  :: pttruetabwhole,cetruetabwhole
+    logical, dimension(0:Agrif_Nbprocs-1),       intent(in)  :: memberoutall
+    integer, dimension(nbdim),                   intent(in)  :: coords
+    logical, dimension(0:Agrif_Nbprocs-1),       intent(out) :: sendtoproc
+    logical, dimension(0:Agrif_Nbprocs-1),       intent(out) :: recvfromproc
+    integer, dimension(nbdim,0:Agrif_NbProcs-1), intent(out) :: imin,imax
+    integer, dimension(nbdim,0:Agrif_NbProcs-1), intent(out) :: imin_recv,imax_recv
+!
+    integer :: imintmp, imaxtmp, i, j, k, i1
+    integer :: imin1,imax1
+    logical :: tochange,tochangebis
+    integer, dimension(nbdim,0:Agrif_NbProcs-1)    :: pttruetab2,cetruetab2
+!
+! pttruetab2 and cetruetab2 are modified arrays in order to always
+! send the most inner points
+!
+    pttruetab2(:,Agrif_Procrank) = pttruetab(:,Agrif_Procrank)
+    cetruetab2(:,Agrif_Procrank) = cetruetab(:,Agrif_Procrank)
+!
+    do k = 0,Agrif_Nbprocs-1
+    do i = 1,nbdim
+        tochangebis = .TRUE.
+        DO i1 = 1,nbdim
+            IF (i /= i1) THEN
+                IF ( (pttruetab(i1,Agrif_Procrank) /= pttruetab(i1,k))  .OR. &
+                     (cetruetab(i1,Agrif_Procrank) /= cetruetab(i1,k))) THEN
+                    tochangebis = .FALSE.
+                    EXIT
+                ENDIF
+            ENDIF
+        ENDDO
+        IF (tochangebis) THEN
+            imin1 = max(pttruetab(i,Agrif_Procrank), pttruetab(i,k))
+            imax1 = min(cetruetab(i,Agrif_Procrank), cetruetab(i,k))
+! Always send the most interior points
+
+            tochange = .false.
+            IF (cetruetab(i,Agrif_Procrank) > cetruetab(i,k)) THEN
+                DO j=imin1,imax1
+                    IF ((cetruetab(i,k)-j) > (j-pttruetab(i,Agrif_Procrank))) THEN
+                        imintmp = j+1
+                        tochange = .TRUE.
+                    ELSE
+                        EXIT
+                    ENDIF
+                ENDDO
+            ENDIF
+
+            if (tochange) then
+                pttruetab2(i,Agrif_Procrank) = imintmp
+            endif
+
+            tochange = .FALSE.
+            imaxtmp=0
+            IF (pttruetab(i,Agrif_Procrank) < pttruetab(i,k)) THEN
+                DO j=imax1,imin1,-1
+                    IF ((j-pttruetab(i,k)) > (cetruetab(i,Agrif_Procrank)-j)) THEN
+                        imaxtmp = j-1
+                        tochange = .TRUE.
+                    ELSE
+                        EXIT
+                    ENDIF
+                ENDDO
+            ENDIF
+
+            if (tochange) then
+                cetruetab2(i,Agrif_Procrank) = imaxtmp
+            endif
+        ENDIF
+    enddo
+    enddo
+
+    do k = 0,Agrif_NbProcs-1
+!
+        sendtoproc(k) = .true.
+!
+!CDIR SHORTLOOP
+        do i = 1,nbdim
+            imin(i,k) = max(pttruetab2(i,Agrif_Procrank), pttruetabwhole(i,k))
+            imax(i,k) = min(cetruetab2(i,Agrif_Procrank), cetruetabwhole(i,k))
+!
+            if ( (imin(i,k) > imax(i,k)) .and. (coords(i) /= 0) ) then
+                sendtoproc(k) = .false.
+            endif
+        enddo
+        IF ( .not. memberoutall(k) ) THEN
+            sendtoproc(k) = .false.
+        ENDIF
+    enddo
+!
+    call Exchangesamelevel_first(sendtoproc,nbdim,imin,imax,recvfromproc,imin_recv,imax_recv)
+!---------------------------------------------------------------------------------------------------
+end subroutine Get_External_Data_first
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine ExchangeSameLevel_first
+!---------------------------------------------------------------------------------------------------
+subroutine ExchangeSameLevel_first ( sendtoproc, nbdim, imin, imax, recvfromproc, &
+                                     imin_recv, imax_recv )
+!---------------------------------------------------------------------------------------------------
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),       intent(in)  :: sendtoproc
+    INTEGER,                                     intent(in)  :: nbdim
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(in)  :: imin
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(in)  :: imax
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),       intent(out) :: recvfromproc
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(out) :: imin_recv
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(out) :: imax_recv
+!
+    include 'mpif.h'
+    INTEGER :: k
+    INTEGER :: etiquette = 100
+    INTEGER :: code
+    LOGICAL :: res
+    INTEGER, DIMENSION(MPI_STATUS_SIZE)   :: statut
+    INTEGER, DIMENSION(nbdim,2,0:Agrif_Nbprocs-1)    :: iminmax_temp
+
+    do k = 0,Agrif_ProcRank-1
+!
+        call MPI_SEND(sendtoproc(k),1,MPI_LOGICAL,k,etiquette,Agrif_mpi_comm,code)
+!
+        if (sendtoproc(k)) then
+            iminmax_temp(:,1,k) = imin(:,k)
+            iminmax_temp(:,2,k) = imax(:,k)
+            call MPI_SEND(iminmax_temp(:,:,k),2*nbdim,MPI_INTEGER,k,etiquette,Agrif_mpi_comm,code)
+        endif
+!
+    enddo
+!
+!   Reception from others processors of the necessary part of the parent grid
+    do k = Agrif_ProcRank+1,Agrif_Nbprocs-1
+!
+        call MPI_RECV(res,1,MPI_LOGICAL,k,etiquette,Agrif_mpi_comm,statut,code)
+        recvfromproc(k) = res
+!
+        if (recvfromproc(k)) then
+            call MPI_RECV(iminmax_temp(:,:,k),2*nbdim,MPI_INTEGER,k,etiquette, &
+                    Agrif_mpi_comm,statut,code)
+            imin_recv(:,k) = iminmax_temp(:,1,k)
+            imax_recv(:,k) = iminmax_temp(:,2,k)
+        endif
+!
+    enddo
+
+!   Reception from others processors of the necessary part of the parent grid
+    do k = Agrif_ProcRank+1,Agrif_Nbprocs-1
+!
+        call MPI_SEND(sendtoproc(k),1,MPI_LOGICAL,k,etiquette,Agrif_mpi_comm,code)
+!
+        if (sendtoproc(k)) then
+!
+            iminmax_temp(:,1,k) = imin(:,k)
+            iminmax_temp(:,2,k) = imax(:,k)
+
+            call MPI_SEND(iminmax_temp(:,:,k),2*nbdim,MPI_INTEGER,k,etiquette, &
+                    Agrif_mpi_comm,code)
+        endif
+!
+    enddo
+!
+!
+!   Reception from others processors of the necessary part of the parent grid
+    do k = Agrif_ProcRank-1,0,-1
+!
+        call MPI_RECV(res,1,MPI_LOGICAL,k,etiquette,Agrif_mpi_comm,statut,code)
+        recvfromproc(k) = res
+!
+        if (recvfromproc(k)) then
+!
+            call MPI_RECV(iminmax_temp(:,:,k),2*nbdim,MPI_INTEGER,k,etiquette, &
+                    Agrif_mpi_comm,statut,code)
+
+            imin_recv(:,k) = iminmax_temp(:,1,k)
+            imax_recv(:,k) = iminmax_temp(:,2,k)
+        endif
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine ExchangeSamelevel_first
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine ExchangeSameLevel
+!---------------------------------------------------------------------------------------------------
+subroutine ExchangeSameLevel ( sendtoproc, recvfromproc, nbdim,    &
+                               pttruetabwhole, cetruetabwhole,     &
+                               imin, imax, imin_recv, imax_recv,   &
+                               memberout, tempC, tempCextend )
+!---------------------------------------------------------------------------------------------------
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),       intent(in)    :: sendtoproc
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),       intent(in)    :: recvfromproc
+    INTEGER,                                     intent(in)    :: nbdim
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(in)    :: pttruetabwhole
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(in)    :: cetruetabwhole
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(in)    :: imin,      imax
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1), intent(in)    :: imin_recv, imax_recv
+    LOGICAL,                                     intent(in)    :: memberout
+    TYPE(Agrif_Variable), pointer,               intent(inout) :: tempC, tempCextend
+!
+    include 'mpif.h'
+    INTEGER :: i,k
+    INTEGER :: etiquette = 100
+    INTEGER :: code, datasize
+    INTEGER, DIMENSION(MPI_STATUS_SIZE)   :: statut
+    TYPE(Agrif_Variable), pointer, SAVE   :: temprecv
+!
+    IF (memberout) THEN
+        call Agrif_array_allocate(tempCextend, pttruetabwhole(:,Agrif_ProcRank),  &
+                                               cetruetabwhole(:,Agrif_ProcRank),nbdim)
+        call Agrif_var_set_array_tozero(tempCextend,nbdim)
+    ENDIF
+!
+    IF (sendtoproc(Agrif_ProcRank)) THEN
+        call Agrif_var_copy_array(tempCextend,imin(:,Agrif_Procrank),imax(:,Agrif_Procrank), &
+                                  tempC,      imin(:,Agrif_Procrank),imax(:,Agrif_Procrank), &
+                                  nbdim)
+    ENDIF
+!
+    do k = 0,Agrif_ProcRank-1
+!
+        if (sendtoproc(k)) then
+!
+            datasize = 1
+!
+!CDIR SHORTLOOP
+            do i = 1,nbdim
+                datasize = datasize * (imax(i,k)-imin(i,k)+1)
+            enddo
+!
+            SELECT CASE(nbdim)
+            CASE(1)
+                call MPI_SEND(tempC%array1(imin(1,k):imax(1,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(2)
+                call MPI_SEND(tempC%array2(imin(1,k):imax(1,k),     &
+                                           imin(2,k):imax(2,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(3)
+                call Agrif_Send_3Darray(tempC%array3,lbound(tempC%array3),imin(:,k),imax(:,k),k)
+            CASE(4)
+                call MPI_SEND(tempC%array4(imin(1,k):imax(1,k),     &
+                                           imin(2,k):imax(2,k),     &
+                                           imin(3,k):imax(3,k),     &
+                                           imin(4,k):imax(4,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(5)
+                call MPI_SEND(tempC%array5(imin(1,k):imax(1,k),     &
+                                           imin(2,k):imax(2,k),     &
+                                           imin(3,k):imax(3,k),     &
+                                           imin(4,k):imax(4,k),     &
+                                           imin(5,k):imax(5,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(6)
+                call MPI_SEND(tempC%array6(imin(1,k):imax(1,k),     &
+                                           imin(2,k):imax(2,k),     &
+                                           imin(3,k):imax(3,k),     &
+                                           imin(4,k):imax(4,k),     &
+                                           imin(5,k):imax(5,k),     &
+                                           imin(6,k):imax(6,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            END SELECT
+!
+        endif
+    enddo
+!
+!   Reception from others processors of the necessary part of the parent grid
+    do k = Agrif_ProcRank+1,Agrif_Nbprocs-1
+!
+        if (recvfromproc(k)) then
+!
+            datasize = 1
+!
+!CDIR SHORTLOOP
+            do i = 1,nbdim
+                datasize = datasize * (imax_recv(i,k)-imin_recv(i,k)+1)
+            enddo
+
+            if (.not.associated(temprecv)) allocate(temprecv)
+            call Agrif_array_allocate(temprecv,imin_recv(:,k),imax_recv(:,k),nbdim)
+
+            SELECT CASE(nbdim)
+            CASE(1)
+                call MPI_RECV(temprecv%array1,datasize,Agrif_MPI_prec,k,etiquette, &
+                        Agrif_mpi_comm,statut,code)
+            CASE(2)
+                call MPI_RECV(temprecv%array2,datasize,Agrif_MPI_prec,k,etiquette, &
+                        Agrif_mpi_comm,statut,code)
+            CASE(3)
+                call MPI_RECV(temprecv%array3,datasize,Agrif_MPI_prec,k,etiquette, &
+                        Agrif_mpi_comm,statut,code)
+            CASE(4)
+                call MPI_RECV(temprecv%array4,datasize,Agrif_MPI_prec,k,etiquette, &
+                        Agrif_mpi_comm,statut,code)
+            CASE(5)
+                call MPI_RECV(temprecv%array5,datasize,Agrif_MPI_prec,k,etiquette, &
+                        Agrif_mpi_comm,statut,code)
+            CASE(6)
+                call MPI_RECV(temprecv%array6,datasize,Agrif_MPI_prec,k,etiquette, &
+                        Agrif_mpi_comm,statut,code)
+            END SELECT
+
+            call Agrif_var_replace_value(tempCextend,temprecv,imin_recv(:,k),imax_recv(:,k),0.,nbdim)
+            call Agrif_array_deallocate(temprecv,nbdim)
+!
+        endif
+    enddo
+
+!   Reception from others processors of the necessary part of the parent grid
+    do k = Agrif_ProcRank+1,Agrif_Nbprocs-1
+!
+        if (sendtoproc(k)) then
+!
+            SELECT CASE(nbdim)
+            CASE(1)
+                datasize=SIZE(tempC%array1(imin(1,k):imax(1,k)))
+                call MPI_SEND(tempC%array1(imin(1,k):imax(1,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(2)
+                datasize=SIZE(tempC%array2(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k)))
+                call MPI_SEND(tempC%array2(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(3)
+                datasize=SIZE(tempC%array3(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k)))
+                call MPI_SEND(tempC%array3(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(4)
+                datasize=SIZE(tempC%array4(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k),     &
+                                               imin(4,k):imax(4,k)))
+                call MPI_SEND(tempC%array4(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k),     &
+                                               imin(4,k):imax(4,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(5)
+                datasize=SIZE(tempC%array5(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k),     &
+                                               imin(4,k):imax(4,k),     &
+                                               imin(5,k):imax(5,k)))
+                call MPI_SEND(tempC%array5(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k),     &
+                                               imin(4,k):imax(4,k),     &
+                                               imin(5,k):imax(5,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            CASE(6)
+                datasize=SIZE(tempC%array6(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k),     &
+                                               imin(4,k):imax(4,k),     &
+                                               imin(5,k):imax(5,k),     &
+                                               imin(6,k):imax(6,k)))
+                call MPI_SEND(tempC%array6(imin(1,k):imax(1,k),     &
+                                               imin(2,k):imax(2,k),     &
+                                               imin(3,k):imax(3,k),     &
+                                               imin(4,k):imax(4,k),     &
+                                               imin(5,k):imax(5,k),     &
+                                               imin(6,k):imax(6,k)),    &
+                        datasize,Agrif_MPI_prec,k,etiquette,      &
+                        Agrif_mpi_comm,code)
+            END SELECT
+!
+        endif
+!
+    enddo
+!
+!   Reception from others processors of the necessary part of the parent grid
+    do k = Agrif_ProcRank-1,0,-1
+!
+        if (recvfromproc(k)) then
+!
+            if (.not.associated(temprecv)) allocate(temprecv)
+            call Agrif_array_allocate(temprecv,imin_recv(:,k),imax_recv(:,k),nbdim)
+
+            SELECT CASE(nbdim)
+            CASE(1)
+                datasize=SIZE(temprecv%array1)
+                call MPI_RECV(temprecv%array1,datasize,Agrif_MPI_prec,k,etiquette,&
+                        Agrif_mpi_comm,statut,code)
+            CASE(2)
+                datasize=SIZE(temprecv%array2)
+                call MPI_RECV(temprecv%array2,datasize,Agrif_MPI_prec,k,etiquette,&
+                        Agrif_mpi_comm,statut,code)
+            CASE(3)
+                datasize=SIZE(temprecv%array3)
+                call MPI_RECV(temprecv%array3,datasize,Agrif_MPI_prec,k,etiquette,&
+                        Agrif_mpi_comm,statut,code)
+            CASE(4)
+                datasize=SIZE(temprecv%array4)
+                call MPI_RECV(temprecv%array4,datasize,Agrif_MPI_prec,k,etiquette,&
+                          Agrif_mpi_comm,statut,code)
+            CASE(5)
+                datasize=SIZE(temprecv%array5)
+                call MPI_RECV(temprecv%array5,datasize,Agrif_MPI_prec,k,etiquette,&
+                         Agrif_mpi_comm,statut,code)
+            CASE(6)
+                datasize=SIZE(temprecv%array6)
+                call MPI_RECV(temprecv%array6,datasize,Agrif_MPI_prec,k,etiquette,&
+                        Agrif_mpi_comm,statut,code)
+            END SELECT
+
+            call Agrif_var_replace_value(tempCextend,temprecv,imin_recv(:,k),imax_recv(:,k),0.,nbdim)
+            call Agrif_array_deallocate(temprecv,nbdim)
+!
+        endif
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine ExchangeSamelevel
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Send_3Darray
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Send_3Darray ( tab3D, bounds, imin, imax, k )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(3),                                     intent(in) :: bounds
+    real, dimension(bounds(1):,bounds(2):,bounds(3):), target, intent(in) :: tab3D
+    integer, dimension(3),                                     intent(in) :: imin, imax
+    integer,                                                   intent(in) :: k
+!
+    integer :: etiquette = 100
+    integer :: datasize, code
+    include 'mpif.h'
+
+    datasize = SIZE(tab3D(imin(1):imax(1),  &
+                          imin(2):imax(2),  &
+                          imin(3):imax(3)))
+
+    call MPI_SEND( tab3D( imin(1):imax(1),  &
+                          imin(2):imax(2),  &
+                          imin(3):imax(3)), &
+                          datasize,Agrif_MPI_prec,k,etiquette,Agrif_mpi_comm,code)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Send_3Darray
+!===================================================================================================
+!
+#else
+    subroutine dummy_Agrif_Mpp ()
+    end subroutine dummy_Agrif_Mpp
+#endif
+!
+end Module Agrif_Mpp
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modprocs.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modprocs.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modprocs.F90	(revision 9987)
@@ -0,0 +1,208 @@
+module Agrif_Procs
+!
+    implicit none
+!
+    type Agrif_Proc
+        integer               :: pn       !< Proc index in coarse grid
+        integer               :: pi       !< Proc index in x-direction (informative only, could be removed)
+        integer               :: pj       !< Proc index in y-direction (informative only, could be removed)
+        integer, dimension(3) :: imin
+        integer, dimension(3) :: imax
+        integer               :: nb_seqs = 0  !< Number of integration sequences the proc is attached to.
+        integer               :: grid_id = 0  !< Grid id the proc is attached to.
+    end type Agrif_Proc
+!
+    type Agrif_Proc_p
+        type(Agrif_Proc),   pointer   :: proc => NULL()  !< Pointer to the actual proc structure
+        type(Agrif_Proc_p), pointer   :: next => NULL()  !< Next proc in the list
+    end type Agrif_Proc_p
+!
+    type Agrif_Proc_List
+        integer                       :: nitems = 0      !< Number of elements in the list
+        type(Agrif_Proc_p), pointer   :: first => NULL() !< First proc in the list
+        type(Agrif_Proc_p), pointer   :: last  => NULL() !< Last proc inserted in the list
+    end type Agrif_Proc_List
+!
+contains
+!
+!===================================================================================================
+subroutine Agrif_pl_append ( proclist, proc )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List),     intent(inout)  :: proclist
+    type(Agrif_Proc), pointer, intent(in)     :: proc
+!
+    type(Agrif_Proc_p), pointer   :: new_pp
+!
+    allocate( new_pp )
+!
+    new_pp % proc => proc
+    new_pp % next => NULL()
+!
+    if ( associated(proclist % last) ) then
+        ! the list is not empty, let 'proc' be the next after the last (ie. the last one).
+        proclist % last % next => new_pp
+    else
+        ! the list has just been initialized. Let 'proc' be the first one.
+        proclist % first => new_pp
+    endif
+    ! anyway, for next time 'proc' will be the last one. 
+    proclist % last => new_pp
+    proclist % nitems = proclist % nitems + 1
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_append
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_pl_print_array ( proclist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(in) :: proclist
+!
+    type(Agrif_Proc_p), pointer :: pp
+    type(Agrif_Proc),   pointer :: proc
+!
+    pp => proclist % first
+!
+    write(*,'("/-------+-----+-----+------+------+------+------+------\")')
+    write(*,'("| iproc | ipx | ipy | imin | imax | jmin | jmax | grid |")')
+    write(*,'("|-------+-----+-----+------+------+------+------+------|")')
+    do while ( associated(pp) )
+        proc => pp % proc
+        write(*,'("|",i6," |",i4," |",i4," |",i5," :",i5," |",i5," :",i5," | ",i4," |")') &
+            proc % pn, proc % pi, proc % pj, proc % imin(1), proc % imax(1), proc % imin(2), proc % imax(2), &
+            proc % grid_id
+        pp => pp % next
+    enddo
+    write(*,'("\-------+-----+-----+------+------+------+------+------/")')
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_print_array
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_pl_print ( proclist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(in) :: proclist
+!
+    type(Agrif_Proc_p), pointer :: pp
+!
+    pp => proclist % first
+    do while ( associated(pp) )
+        write(*,'(i0,",")',advance='no') pp % proc % pn
+        pp => pp % next
+    enddo
+    write(*,*)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_print
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_pl_copy ( proclist, copy )
+!
+!< Carries out a copy of 'proclist' into 'copy'
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(in)    :: proclist
+    type(Agrif_Proc_List), intent(out)   :: copy
+!
+    type(Agrif_Proc_p),    pointer    :: pp
+!
+    call Agrif_pl_clear(copy)
+!
+    pp => proclist % first
+    do while ( associated(pp) )
+        call Agrif_pl_append( copy, pp % proc )
+        pp => pp % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_copy
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_pl_deep_copy ( proclist, copy )
+!
+!< Carries out a deep copy of 'proclist' into 'copy'
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(in)    :: proclist
+    type(Agrif_Proc_List), intent(out)   :: copy
+!
+    type(Agrif_Proc_p), pointer :: pp
+    type(Agrif_Proc),   pointer :: new_proc
+!
+    call Agrif_pl_clear(copy)
+!
+    pp => proclist % first
+    do while ( associated(pp) )
+        allocate( new_proc )
+        new_proc = pp % proc
+        call Agrif_pl_append( copy, new_proc )
+        pp => pp % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_deep_copy
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_pl_clear ( proclist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(inout)  :: proclist
+!
+    type(Agrif_Proc_p), pointer    :: pp, ppd
+!
+    pp => proclist % first
+!    
+    do while( associated(pp) )
+        ppd => pp
+        pp  => pp % next
+        deallocate(ppd)
+    enddo
+    
+    proclist % first => NULL()
+    proclist % last  => NULL()
+    proclist % nitems = 0
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_clear
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_pl_to_array ( proclist, procarray )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List),                       intent(in)   :: proclist
+    type(Agrif_Proc), dimension(:), allocatable, intent(out)  :: procarray
+!
+    type(Agrif_Proc_p), pointer   :: pp
+!
+    allocate( procarray(1:proclist % nitems) )
+!
+    pp => proclist % first
+    do while ( associated(pp) )
+        procarray(pp%proc%pn+1) = pp % proc
+        pp => pp % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_pl_to_array
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_pl_search_proc ( proclist, rank ) result ( proc )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Proc_List), intent(in)   :: proclist
+    integer,               intent(in)   :: rank
+!
+    type(Agrif_Proc_p), pointer :: pp
+    type(Agrif_Proc),   pointer :: proc
+    logical :: found
+!
+    found = .false.
+    proc => NULL()
+    pp => proclist % first
+    do while ( .not.found .and. associated(pp) )
+        if ( pp % proc % pn == rank ) then
+            proc => pp % proc
+            return
+        else
+            pp => pp % next
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_pl_search_proc
+!===================================================================================================
+!
+end module Agrif_Procs
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modsauv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modsauv.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modsauv.F90	(revision 9987)
@@ -0,0 +1,663 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!> Module Agrif_Save
+!!
+!! Module for the initialization by copy of the grids created by clustering.
+!
+module Agrif_Save
+!
+    use Agrif_Types
+    use Agrif_Link
+    use Agrif_Arrays
+    use Agrif_Variables
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+! subroutine Agrif_deallocate_Arrays
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_deallocate_Arrays ( var )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), pointer :: var
+!
+    if (allocated(var%array1))  deallocate(var%array1)
+    if (allocated(var%array2))  deallocate(var%array2)
+    if (allocated(var%array3))  deallocate(var%array3)
+    if (allocated(var%array4))  deallocate(var%array4)
+    if (allocated(var%array5))  deallocate(var%array5)
+    if (allocated(var%array6))  deallocate(var%array6)
+!
+    if (allocated(var%darray1)) deallocate(var%darray1)
+    if (allocated(var%darray2)) deallocate(var%darray2)
+    if (allocated(var%darray3)) deallocate(var%darray3)
+    if (allocated(var%darray4)) deallocate(var%darray4)
+    if (allocated(var%darray5)) deallocate(var%darray5)
+    if (allocated(var%darray6)) deallocate(var%darray6)
+!
+    if (allocated(var%sarray1)) deallocate(var%sarray1)
+    if (allocated(var%sarray2)) deallocate(var%sarray2)
+    if (allocated(var%sarray3)) deallocate(var%sarray3)
+    if (allocated(var%sarray4)) deallocate(var%sarray4)
+    if (allocated(var%sarray5)) deallocate(var%sarray5)
+    if (allocated(var%sarray6)) deallocate(var%sarray6)
+!
+!
+    if (associated(var%oldvalues2D))    deallocate(var%oldvalues2D)
+    if (allocated(var%posvar))          deallocate(var%posvar)
+    if (allocated(var%interptab))       deallocate(var%interptab)
+    if (allocated(var%coords))          deallocate(var%coords)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_deallocate_Arrays
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_deallocate_Arrays_c ( var_c )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable_c), pointer :: var_c
+!
+    if (allocated(var_c%carray1)) deallocate(var_c%carray1)
+    if (allocated(var_C%carray2)) deallocate(var_c%carray2)
+!
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_deallocate_Arrays_c
+!===================================================================================================
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_deallocate_Arrays_l ( var_l )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable_l), pointer :: var_l
+!
+!
+    if (allocated(var_l%larray1)) deallocate(var_l%larray1)
+    if (allocated(var_l%larray2)) deallocate(var_l%larray2)
+    if (allocated(var_l%larray3)) deallocate(var_l%larray3)
+    if (allocated(var_l%larray4)) deallocate(var_l%larray4)
+    if (allocated(var_l%larray5)) deallocate(var_l%larray5)
+    if (allocated(var_l%larray6)) deallocate(var_l%larray6)
+!
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_deallocate_Arrays_l
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_deallocate_Arrays_i ( var_i )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable_i), pointer :: var_i
+!
+!
+    if (allocated(var_i%iarray1)) deallocate(var_i%iarray1)
+    if (allocated(var_i%iarray2)) deallocate(var_i%iarray2)
+    if (allocated(var_i%iarray3)) deallocate(var_i%iarray3)
+    if (allocated(var_i%iarray4)) deallocate(var_i%iarray4)
+    if (allocated(var_i%iarray5)) deallocate(var_i%iarray5)
+    if (allocated(var_i%iarray6)) deallocate(var_i%iarray6)
+!
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_deallocate_Arrays_i
+!
+!===================================================================================================
+!  subroutine Agrif_Free_data_before
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Free_data_before ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: Agrif_Gr ! Pointer on the current grid
+!
+    integer :: i
+    type(Agrif_Variables_List), pointer :: parcours
+    type(Agrif_Variable),       pointer :: var
+    type(Agrif_Variable_c),     pointer :: var_c
+    type(Agrif_Variable_r),     pointer :: var_r
+    type(Agrif_Variable_l),     pointer :: var_l
+    type(Agrif_Variable_i),     pointer :: var_i
+!
+    do i = 1,Agrif_NbVariables(0)
+!
+        var => Agrif_Gr % tabvars(i)
+!
+        if ( .NOT. Agrif_Mygrid % tabvars(i) % restore ) then
+            call Agrif_deallocate_Arrays(var)
+        endif
+!
+        if (associated(var%list_interp)) then
+            call Agrif_Free_list_interp(var%list_interp)
+        endif
+!
+    enddo
+    do i=1,Agrif_NbVariables(1)
+        var_c => Agrif_Gr % tabvars_c(i)
+        call Agrif_deallocate_Arrays_c(var_c)
+    enddo
+    do i=1,Agrif_NbVariables(3)
+        var_l => Agrif_Gr % tabvars_l(i)
+        call Agrif_deallocate_Arrays_l(var_l)
+    enddo
+    do i=1,Agrif_NbVariables(4)
+        var_i => Agrif_Gr % tabvars_i(i)
+        call Agrif_deallocate_Arrays_i(var_i)
+    enddo
+
+    parcours => Agrif_Gr % variables
+
+    do i = 1,Agrif_Gr%NbVariables
+!
+        if ( .NOT. parcours%var%root_var % restore ) then
+            call Agrif_deallocate_Arrays(parcours%var)
+        endif
+!
+        if (associated(parcours%var%list_interp)) then
+            call Agrif_Free_list_interp(parcours%var%list_interp)
+        endif
+!
+        if ( .NOT. parcours%var%root_var % restore ) then
+            deallocate(parcours%var)
+        endif
+!
+        parcours => parcours % next
+!
+    enddo
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) then
+        if ( Agrif_Probdim == 1 ) deallocate(Agrif_Gr%tabpoint1D)
+        if ( Agrif_Probdim == 2 ) deallocate(Agrif_Gr%tabpoint2D)
+        if ( Agrif_Probdim == 3 ) deallocate(Agrif_Gr%tabpoint3D)
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Free_data_before
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Free_list_interp
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Free_list_interp ( list_interp )
+!---------------------------------------------------------------------------------------------------
+      type(Agrif_List_Interp_Loc), pointer :: list_interp
+!
+      if (associated(list_interp%suiv)) call Agrif_Free_list_interp(list_interp%suiv)
+
+#if defined AGRIF_MPI
+       deallocate(list_interp%interp_loc%tab4t)
+       deallocate(list_interp%interp_loc%memberinall)
+       deallocate(list_interp%interp_loc%sendtoproc1)
+       deallocate(list_interp%interp_loc%recvfromproc1)
+#endif
+       deallocate(list_interp%interp_loc)
+       deallocate(list_interp)
+       nullify(list_interp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Free_list_interp
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Free_data_after
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Free_data_after ( Agrif_Gr )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: Agrif_Gr  !< Pointer on the current grid
+!
+    integer :: i
+    type(Agrif_Variables_List), pointer :: parcours, rootparcours
+    type(Agrif_Variable),       pointer :: var
+!
+    do i = 1,Agrif_NbVariables(0)
+        if ( Agrif_Mygrid % tabvars(i) % restore ) then
+            var => Agrif_Gr%tabvars(i)
+            call Agrif_deallocate_Arrays(var)
+        endif
+    enddo
+!
+    parcours => Agrif_Gr%variables
+    rootparcours => Agrif_Mygrid%variables
+!
+    do i = 1,Agrif_Gr%NbVariables
+        if (rootparcours%var % restore ) then
+            call Agrif_deallocate_Arrays(parcours%var)
+            deallocate(parcours%var)
+        endif
+        parcours => parcours % next
+        rootparcours => rootparcours % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Free_data_after
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_CopyFromOld_All
+!
+!> Called in Agrif_Clustering#Agrif_Init_Hierarchy.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_CopyFromOld_All ( g, oldchildlist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer, intent(inout) :: g   !< Pointer on the current grid
+    type(Agrif_Grid_List),     intent(in)    :: oldchildlist
+!
+    type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive procedure
+    real    :: g_eps, eps, oldgrid_eps
+    integer :: out
+    integer :: iii
+!
+    out = 0
+!
+    parcours => oldchildlist % first
+!
+    do while (associated(parcours))
+!
+        if ((.NOT. g % fixed) .AND. (parcours % gr %oldgrid)) then
+!
+            g_eps = huge(1.)
+            oldgrid_eps = huge(1.)
+            do iii = 1,Agrif_Probdim
+                g_eps = min(g_eps,g % Agrif_dx(iii))
+                oldgrid_eps = min(oldgrid_eps, parcours % gr % Agrif_dx(iii))
+            enddo
+!
+            eps = min(g_eps,oldgrid_eps)/100.
+!
+            do iii = 1,Agrif_Probdim
+                if (g % Agrif_dx(iii) < (parcours % gr % Agrif_dx(iii) - eps)) then
+                    parcours => parcours % next
+                    out = 1
+                    exit
+                endif
+            enddo
+!
+            if ( out == 1 ) cycle
+!
+            call Agrif_CopyFromOld(g,parcours%gr)
+!
+        endif
+!
+        call Agrif_CopyFromOld_All(g,parcours % gr % child_list)
+!
+        parcours => parcours % next
+!
+      enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CopyFromOld_All
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_CopyFromOld
+!
+!> Call to the Agrif_Copy procedure.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_CopyFromOld ( new_gr, old_gr )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer, intent(inout) :: new_gr  !< Pointer on the current grid
+    type(Agrif_Grid), pointer, intent(inout) :: old_gr  !< Pointer on an old grid
+!
+    type(Agrif_Variable), pointer   :: new_var
+    type(Agrif_Variable), pointer   :: old_var
+    integer :: i
+!
+    do i = 1,Agrif_NbVariables(0)
+        if ( Agrif_Mygrid % tabvars(i) % restore ) then
+            old_var => old_gr % tabvars(i)
+            new_var => new_gr % tabvars(i)
+            call Agrif_Copy(new_gr, old_gr, new_var, old_var )
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CopyFromOld
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_CopyFromOld_AllOneVar
+!
+!> Called in Agrif_Clustering#Agrif_Init_Hierarchy.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_CopyFromOld_AllOneVar ( g, oldchildlist, indic )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer, intent(inout) :: g            !< Pointer on the current grid
+    type(Agrif_Grid_List),     intent(in)    :: oldchildlist
+    integer,                   intent(in)    :: indic
+!
+    type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive procedure
+    real    :: g_eps,eps,oldgrid_eps
+    integer :: out
+    integer :: iii
+!
+    out = 0
+!
+    parcours => oldchildlist % first
+!
+    do while (associated(parcours))
+!
+        if ((.NOT. g % fixed) .AND. (parcours % gr %oldgrid)) then
+!
+            g_eps = huge(1.)
+            oldgrid_eps = huge(1.)
+            do iii = 1,Agrif_Probdim
+                g_eps = min(g_eps,g % Agrif_dx(iii))
+                oldgrid_eps = min(oldgrid_eps,parcours % gr % Agrif_dx(iii))
+            enddo
+!
+            eps = min(g_eps,oldgrid_eps)/100.
+!
+            do iii = 1,Agrif_Probdim
+                if (g % Agrif_dx(iii) < (parcours % gr % Agrif_dx(iii) - eps)) then
+                    parcours => parcours % next
+                    out = 1
+                    exit
+                endif
+            enddo
+
+            if ( out == 1 ) cycle
+!
+            call Agrif_CopyFromOldOneVar(g,parcours%gr,indic)
+!
+        endif
+!
+        call Agrif_CopyFromOld_AllOneVar(g,parcours%gr % child_list,indic)
+!
+        parcours => parcours % next
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CopyFromOld_AllOneVar
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_CopyFromOldOneVar
+!
+!> Call to Agrif_Copy
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_CopyFromOldOneVar ( new_gr, old_gr, indic )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer, intent(inout) :: new_gr     !< Pointer on the current grid
+    type(Agrif_Grid), pointer, intent(in)    :: old_gr     !< Pointer on an old grid
+    integer,                   intent(in)    :: indic
+!
+    type(Agrif_Variable),  pointer  :: new_var, old_var
+!
+    new_var => Agrif_Search_Variable(new_gr, -indic)
+    old_var => Agrif_Search_Variable(old_gr, -indic)
+!
+    call Agrif_array_allocate(new_var,new_var%lb,new_var%ub,new_var%nbdim)
+    call Agrif_Copy(new_gr, old_gr, new_var,old_var)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CopyFromOldOneVar
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Copy
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Copy ( new_gr, old_gr, new_var, old_var )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid),     pointer, intent(in)       :: new_gr !< Pointer on the current grid
+    type(Agrif_Grid),     pointer, intent(in)       :: old_gr !< Pointer on an old grid
+    type(Agrif_Variable), pointer, intent(inout)    :: new_var
+    type(Agrif_Variable), pointer, intent(in)       :: old_var
+!
+    type(Agrif_Variable), pointer :: root ! Pointer on the variable of the root grid
+    integer               :: nbdim     ! Number of dimensions of the current grid
+    integer, dimension(6) :: pttabnew  ! Indexes of the first point in the domain
+    integer, dimension(6) :: petabnew  ! Indexes of the first point in the domain
+    integer, dimension(6) :: pttabold  ! Indexes of the first point in the domain
+    integer, dimension(6) :: petabold  ! Indexes of the first point in the domain
+    integer, dimension(6) :: nbtabold  ! Number of cells in each direction
+    integer, dimension(6) :: nbtabnew  ! Number of cells in each direction
+    real,    dimension(6) :: snew,sold
+    real,    dimension(6) :: dsnew,dsold
+    real    :: eps
+    integer :: n
+!
+    root => new_var % root_var
+    nbdim = root % nbdim
+!
+    do n = 1,nbdim
+!
+        select case(root % interptab(n))
+!
+        case('x')
+!
+            pttabnew(n) = root % point(n)
+            pttabold(n) = root % point(n)
+            snew(n)  = new_gr % Agrif_x(1)
+            sold(n)  = old_gr % Agrif_x(1)
+            dsnew(n) = new_gr % Agrif_dx(1)
+            dsold(n) = old_gr % Agrif_dx(1)
+!
+            if (root % posvar(n) == 1) then
+                petabnew(n) = pttabnew(n) + new_gr % nb(1)
+                petabold(n) = pttabold(n) + old_gr % nb(1)
+            else
+                petabnew(n) = pttabnew(n) + new_gr % nb(1) - 1
+                petabold(n) = pttabold(n) + old_gr % nb(1) - 1
+                snew(n) = snew(n) + dsnew(n)/2.
+                sold(n) = sold(n) + dsold(n)/2.
+            endif
+!
+        case('y')
+!
+            pttabnew(n) = root % point(n)
+            pttabold(n) = root % point(n)
+            snew(n) = new_gr % Agrif_x(2)
+            sold(n) = old_gr % Agrif_x(2)
+            dsnew(n) = new_gr % Agrif_dx(2)
+            dsold(n) = old_gr % Agrif_dx(2)
+!
+            if (root % posvar(n) == 1) then
+                petabnew(n) = pttabnew(n) + new_gr % nb(2)
+                petabold(n) = pttabold(n) + old_gr % nb(2)
+            else
+                petabnew(n) = pttabnew(n) + new_gr % nb(2) - 1
+                petabold(n) = pttabold(n) + old_gr % nb(2) - 1
+                snew(n) = snew(n) + dsnew(n)/2.
+                sold(n) = sold(n) + dsold(n)/2.
+            endif
+!
+        case('z')
+!
+            pttabnew(n) = root % point(n)
+            pttabold(n) = root % point(n)
+            snew(n)  = new_gr % Agrif_x(3)
+            sold(n)  = old_gr % Agrif_x(3)
+            dsnew(n) = new_gr % Agrif_dx(3)
+            dsold(n) = old_gr % Agrif_dx(3)
+!
+            if (root % posvar(n) == 1) then
+                petabnew(n) = pttabnew(n) + new_gr % nb(3)
+                petabold(n) = pttabold(n) + old_gr % nb(3)
+            else
+                petabnew(n) = pttabnew(n) + new_gr % nb(3) - 1
+                petabold(n) = pttabold(n) + old_gr % nb(3) - 1
+                snew(n) = snew(n) + dsnew(n)/2.
+                sold(n) = sold(n) + dsold(n)/2.
+            endif
+!
+        case('N')
+!
+            call Agrif_get_var_bounds(new_var,pttabnew(n),petabnew(n),n)
+!
+            pttabold(n) = pttabnew(n)
+            petabold(n) = petabnew(n)
+            snew(n) = 0.
+            sold(n) = 0.
+            dsnew(n) = 1.
+            dsold(n) = 1.
+!
+        end select
+!
+    enddo
+!
+    do n = 1,nbdim
+        nbtabnew(n) = petabnew(n) - pttabnew(n)
+        nbtabold(n) = petabold(n) - pttabold(n)
+    enddo
+!
+    eps = min(minval(dsnew(1:nbdim)),minval(dsold(1:nbdim))) / 100.
+!
+    do n = 1,nbdim
+        if (snew(n) > (sold(n)+dsold(n)*nbtabold(n)+eps)) return
+        if ((snew(n)+dsnew(n)*nbtabnew(n)-eps) < sold(n)) return
+    enddo
+!
+    call Agrif_CopynD(new_var,old_var,pttabold,petabold,pttabnew,petabnew,  &
+                      sold,snew,dsold,dsnew,nbdim)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Copy
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_CopynD
+!
+!> Copy from the nD variable Old_Var the nD variable New_Var
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_CopynD ( new_var, old_var, pttabold, petabold, pttabnew, petabnew, &
+                          sold, snew, dsold, dsnew, nbdim )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable), pointer, intent(inout) :: new_var
+    type(Agrif_Variable), pointer, intent(in)    :: old_var
+    integer, dimension(nbdim),     intent(in)    :: pttabnew
+    integer, dimension(nbdim),     intent(in)    :: petabnew
+    integer, dimension(nbdim),     intent(in)    :: pttabold
+    integer, dimension(nbdim),     intent(in)    :: petabold
+    real,    dimension(nbdim),     intent(in)    :: snew, sold
+    real,    dimension(nbdim),     intent(in)    :: dsnew,dsold
+    integer,                       intent(in)    :: nbdim
+!
+    integer :: i,j,k,l,m,n,i0,j0,k0,l0,m0,n0
+!
+    real,    dimension(nbdim) :: dim_gmin,   dim_gmax
+    real,    dimension(nbdim) :: dim_newmin, dim_newmax
+    real,    dimension(nbdim) :: dim_min
+    integer, dimension(nbdim) :: ind_gmin,ind_newmin, ind_newmax
+!
+    do i = 1,nbdim
+!
+        dim_gmin(i) = sold(i)
+        dim_gmax(i) = sold(i) + (petabold(i)-pttabold(i)) * dsold(i)
+!
+        dim_newmin(i) = snew(i)
+        dim_newmax(i) = snew(i) + (petabnew(i)-pttabnew(i)) * dsnew(i)
+!
+    enddo
+!
+    do i = 1,nbdim
+        if (dim_gmax(i) < dim_newmin(i)) return
+        if (dim_gmin(i) > dim_newmax(i)) return
+    enddo
+!
+    do i = 1,nbdim
+!
+        ind_newmin(i) = pttabnew(i) - floor(-(max(dim_gmin(i),dim_newmin(i))-dim_newmin(i))/dsnew(i))
+        dim_min(i) = snew(i) + (ind_newmin(i)-pttabnew(i))*dsnew(i)
+        ind_gmin(i)   = pttabold(i) + nint((dim_min(i)-dim_gmin(i))/dsold(i))
+        ind_newmax(i) = pttabnew(i) + int((min(dim_gmax(i),dim_newmax(i))-dim_newmin(i))/dsnew(i))
+!
+    enddo
+!
+    select case (nbdim)
+!
+    case (1)
+        i0 = ind_gmin(1)
+        do i = ind_newmin(1),ind_newmax(1)
+            new_var % array1(i)    = old_var % array1(i0)
+            new_var % restore1D(i) = 1
+            i0 = i0 + int(dsnew(1)/dsold(1))
+        enddo
+!
+    case (2)
+        i0 = ind_gmin(1) ; do i = ind_newmin(1),ind_newmax(1)
+        j0 = ind_gmin(2) ; do j = ind_newmin(2),ind_newmax(2)
+            new_var % array2(i,j)    = old_var % array2(i0,j0)
+            new_var % restore2D(i,j) = 1
+            j0 = j0 + int(dsnew(2)/dsold(2))
+        enddo
+        i0 = i0 + int(dsnew(1)/dsold(1))
+        enddo
+!
+    case (3)
+        i0 = ind_gmin(1) ; do i = ind_newmin(1),ind_newmax(1)
+        j0 = ind_gmin(2) ; do j = ind_newmin(2),ind_newmax(2)
+        k0 = ind_gmin(3) ; do k = ind_newmin(3),ind_newmax(3)
+            new_var % array3(i,j,k)    =  old_var % array3(i0,j0,k0)
+            new_var % restore3D(i,j,k) = 1
+            k0 = k0 + int(dsnew(3)/dsold(3))
+        enddo
+        j0 = j0 + int(dsnew(2)/dsold(2))
+        enddo
+        i0 = i0 + int(dsnew(1)/dsold(1))
+        enddo
+!
+    case (4)
+        i0 = ind_gmin(1) ; do i = ind_newmin(1),ind_newmax(1)
+        j0 = ind_gmin(2) ; do j = ind_newmin(2),ind_newmax(2)
+        k0 = ind_gmin(3) ; do k = ind_newmin(3),ind_newmax(3)
+        l0 = ind_gmin(4) ; do l = ind_newmin(4),ind_newmax(4)
+            new_var % array4(i,j,k,l)    = old_var % array4(i0,j0,k0,l0)
+            new_var % restore4D(i,j,k,l) = 1
+            l0 = l0 + int(dsnew(4)/dsold(4))
+        enddo
+        k0 = k0 + int(dsnew(3)/dsold(3))
+        enddo
+        j0 = j0 + int(dsnew(2)/dsold(2))
+        enddo
+        i0 = i0 + int(dsnew(1)/dsold(1))
+        enddo
+!
+    case (5)
+        i0 = ind_gmin(1) ; do i = ind_newmin(1),ind_newmax(1)
+        j0 = ind_gmin(2) ; do j = ind_newmin(2),ind_newmax(2)
+        k0 = ind_gmin(3) ; do k = ind_newmin(3),ind_newmax(3)
+        l0 = ind_gmin(4) ; do l = ind_newmin(4),ind_newmax(4)
+        m0 = ind_gmin(5) ; do m = ind_newmin(5),ind_newmax(5)
+            new_var % array5(i,j,k,l,m)    = old_var % array5(i0,j0,k0,l0,m0)
+            new_var % restore5D(i,j,k,l,m) = 1
+            m0 = m0 + int(dsnew(5)/dsold(5))
+        enddo
+        l0 = l0 + int(dsnew(4)/dsold(4))
+        enddo
+        k0 = k0 + int(dsnew(3)/dsold(3))
+        enddo
+        j0 = j0 + int(dsnew(2)/dsold(2))
+        enddo
+        i0 = i0 + int(dsnew(1)/dsold(1))
+        enddo
+!
+    case (6)
+        i0 = ind_gmin(1) ; do i = ind_newmin(1),ind_newmax(1)
+        j0 = ind_gmin(2) ; do j = ind_newmin(2),ind_newmax(2)
+        k0 = ind_gmin(3) ; do k = ind_newmin(3),ind_newmax(3)
+        l0 = ind_gmin(4) ; do l = ind_newmin(4),ind_newmax(4)
+        m0 = ind_gmin(5) ; do m = ind_newmin(5),ind_newmax(5)
+        n0 = ind_gmin(6) ; do n = ind_newmin(6),ind_newmax(6)
+            new_var % array6(i,j,k,l,m,n)    = old_var % array6(i0,j0,k0,l0,m0,n0)
+            new_var % restore6D(i,j,k,l,m,n) = 1
+            n0 = n0 + int(dsnew(6)/dsold(6))
+        enddo
+        m0 = m0 + int(dsnew(5)/dsold(5))
+        enddo
+        l0 = l0 + int(dsnew(4)/dsold(4))
+        enddo
+        k0 = k0 + int(dsnew(3)/dsold(3))
+        enddo
+        j0 = j0 + int(dsnew(2)/dsold(2))
+        enddo
+        i0 = i0 + int(dsnew(1)/dsold(1))
+        enddo
+!
+      end select
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_CopynD
+!===================================================================================================
+!
+end module Agrif_Save
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modseq.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modseq.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modseq.F90	(revision 9987)
@@ -0,0 +1,640 @@
+module Agrif_seq
+!
+    use Agrif_Init
+    use Agrif_Procs
+    use Agrif_Arrays
+!
+    implicit none
+!
+contains
+!
+#if defined AGRIF_MPI
+!===================================================================================================
+function Agrif_seq_allocate_list ( nb_seqs ) result( seqlist )
+!---------------------------------------------------------------------------------------------------
+    integer, intent(in)     :: nb_seqs
+!
+    type(Agrif_Sequence_List), pointer :: seqlist
+!
+    allocate(seqlist)
+    seqlist % nb_seqs = nb_seqs
+    allocate(seqlist % sequences(1:nb_seqs))
+!---------------------------------------------------------------------------------------------------
+end function Agrif_seq_allocate_list
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_add_grid ( seqlist, seq_num, grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Sequence_List), intent(inout)    :: seqlist
+    integer,                   intent(in)       :: seq_num
+    type(Agrif_Grid), pointer, intent(in)       :: grid
+!
+    call Agrif_gl_append(seqlist % sequences(seq_num) % gridlist, grid )
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_add_grid
+!===================================================================================================
+!
+!===================================================================================================
+recursive subroutine Agrif_seq_init_sequences ( grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(inout)  :: grid
+!
+    type(Agrif_PGrid), pointer  :: gp
+!
+#if defined AGRIF_MPI
+!
+! Build list of required procs for each child grid
+    gp => grid % child_list % first
+    do while ( associated( gp ) )
+        call Agrif_seq_build_required_proclist( gp % gr )
+        gp => gp % next
+    enddo
+!
+! Create integration sequences for the current grid
+    call Agrif_seq_create_proc_sequences( grid )
+    call Agrif_seq_allocate_procs_to_childs( grid )
+!
+! Create new communicators for sequences
+    call Agrif_seq_create_communicators( grid )
+!
+#endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_init_sequences
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_build_required_proclist ( grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(inout) :: grid
+!
+    type(Agrif_Grid),      pointer  :: parent_grid
+    type(Agrif_Rectangle), pointer  :: grid_rect
+    type(Agrif_Proc_p),    pointer  :: proc_rect
+    type(Agrif_Proc),      pointer  :: proc
+    logical     :: proc_is_required
+    integer     :: i
+!
+    if ( grid % fixedrank == 0 ) then
+!       grid is the Root
+        if ( grid % required_proc_list % nitems == 0 ) then
+            print*, "### Error Agrif_seq_build_required_proclist: empty proc list."
+            print*, "# -> You should check if Agrif_Init_ProcList() is actually working."
+            stop
+        endif
+        return
+    endif
+!
+    parent_grid => grid % parent
+    grid_rect   => grid % rect_in_parent
+    proc_rect   => parent_grid % proc_def_list % first
+!
+
+    do while ( associated( proc_rect ) )
+
+!
+        proc => proc_rect % proc
+!
+        proc_is_required = .true.
+        do i = 1,Agrif_Probdim
+            proc_is_required = ( proc_is_required             .and. &
+                    ( grid_rect % imin(i) <= proc % imax(i) ) .and. &
+                    ( grid_rect % imax(i) >= proc % imin(i) ) )
+        enddo
+!
+        if ( proc_is_required ) then
+            call Agrif_pl_append(grid % required_proc_list, proc)
+        endif
+        proc_rect => proc_rect % next
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_build_required_proclist
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_create_proc_sequences ( grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(inout)    :: grid
+!
+    type(Agrif_Grid_List), pointer :: sorted_child_list
+    type(Agrif_PGrid),     pointer :: child_p
+    type(Agrif_PGrid),     pointer :: g1p, g2p
+    type(Agrif_Proc_p),    pointer :: pp1, pp2
+    type(Agrif_Proc),      pointer :: proc
+    integer                        :: nb_seq_max, nb_seqs, cur_seq
+!
+    nb_seq_max = 0
+!
+    if ( grid % child_list % nitems == 0 ) return
+!
+! For each required proc...
+    pp1  => grid % required_proc_list % first
+    do while ( associated(pp1) )
+        proc => pp1 % proc
+        proc % nb_seqs = 0
+!   ..loop over all child grids...
+        child_p => grid % child_list % first
+        do while ( associated(child_p) )
+!       ..and look for 'proc' in the list of procs required by 'child'
+            pp2 => child_p % gr % required_proc_list % first
+            do while ( associated(pp2) )
+                if ( proc % pn == pp2 % proc % pn ) then
+!                   'proc' is required by this child grid, so we increment its number of sequences
+                    proc % nb_seqs = proc % nb_seqs + 1
+                    pp2 => NULL()
+                else
+                    pp2 => pp2 % next
+                endif
+            enddo
+            child_p => child_p % next
+        enddo
+        nb_seq_max = max(nb_seq_max, proc % nb_seqs)
+        pp1 => pp1 % next
+    enddo
+!
+! For each grid...
+    g1p => grid % child_list % first
+    do while ( associated(g1p) )
+!     compare it with the following ones
+        g2p => g1p % next
+        do while ( associated(g2p) )
+            if ( Agrif_seq_grids_are_connected( g1p % gr, g2p % gr ) ) then
+                call Agrif_gl_append( g1p % gr % neigh_list, g2p % gr )
+                call Agrif_gl_append( g2p % gr % neigh_list, g1p % gr )
+            endif
+            g2p => g2p % next
+        enddo
+        g1p => g1p % next
+    enddo
+!
+! Colorize graph nodes
+    nb_seqs = Agrif_seq_colorize_grid_list(grid % child_list)
+    sorted_child_list => Agrif_gl_merge_sort ( grid % child_list, compare_colors )
+!
+! Create sequence structure
+    cur_seq = 0
+    grid % child_seq => Agrif_seq_allocate_list(nb_seqs)
+    child_p => sorted_child_list % first
+    do while ( associated(child_p) )
+        if ( cur_seq /= child_p % gr % seq_num ) then
+            cur_seq = child_p % gr % seq_num
+        endif
+        call Agrif_seq_add_grid(grid % child_seq,cur_seq,child_p% gr)
+        child_p => child_p % next
+    enddo
+!
+    call Agrif_gl_delete(sorted_child_list)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_create_proc_sequences
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_seq_grids_are_connected( g1, g2 ) result( connection )
+!
+!< Compare required_proc_list for g1 and g2. These are connected if they share a same proc.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(in) :: g1, g2
+!
+    logical :: connection
+    type(Agrif_Proc_p), pointer :: pp1, pp2
+!
+    connection = .false.
+!
+    pp1 => g1 % required_proc_list % first
+!
+    do while( associated(pp1) .and. (.not. connection) )
+!
+        pp2 => g2 % required_proc_list % first
+        do while ( associated(pp2) .and. (.not. connection) )
+            if ( pp1 % proc % pn == pp2 % proc % pn ) then
+            ! if pp1 and pp2 are the same proc, it means that g1 and g2 are connected. We stop here.
+                connection = .true.
+            endif
+            pp2 => pp2 % next
+        enddo
+        pp1 => pp1 % next
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end function Agrif_seq_grids_are_connected
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_seq_colorize_grid_list ( gridlist ) result ( ncolors )
+!
+!< 1.  Sort nodes in decreasing order of degree.
+!< 2.  Color the node with highest degree with color 1.
+!< 3.  Choose the node with the largest DSAT value. In case of conflict, choose the one with the
+!!       highest degree. Then the one corresponding to the largest grid.
+!< 4.  Color this node with the smallest possible color.
+!< 5.  If all nodes are colored, then stop. Otherwise, go to 3.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)    :: gridlist
+!
+    type(Agrif_Grid_List),   pointer  :: X, Y
+    type(Agrif_PGrid),       pointer  :: gridp
+    type(Agrif_Grid_List),   pointer  :: tmp_gl
+    integer                           :: ncolors
+    integer, dimension(1:gridlist%nitems)   :: colors
+!
+! Be carefull...
+    nullify(Y)
+!
+! First initialize the color of each node
+    gridp => gridlist % first
+    do while ( associated(gridp) )
+        gridp % gr % seq_num = 0
+        gridp => gridp % next
+    enddo
+!
+! Then sort the grids by decreasing degree
+    X => Agrif_gl_merge_sort( gridlist, compare_grid_degrees )
+    gridp => X % first
+!
+! Colorize the first grid in the list
+    gridp % gr % seq_num = 1
+    gridp => gridp % next
+!
+! Then for each of its neighbors...
+    do while ( associated(gridp) )
+!
+        if ( gridp % gr % neigh_list % nitems == 0 ) then
+        ! this grid is alone... let.s attach it to an existing sequence
+            call Agrif_seq_attach_grid( X, gridp % gr )
+            gridp => gridp % next
+            cycle
+        endif
+!
+!     Compute dsat value of all non-colored grids
+        tmp_gl => Agrif_gl_build_from_gp(gridp)
+        call Agrif_seq_calc_dsat(tmp_gl)
+!
+!     Sort non-colored grids by decreasing dsat value, then by size
+        call Agrif_gl_delete(Y)
+        Y => Agrif_gl_merge_sort( tmp_gl, compare_dsat_values, compare_size_values )
+!
+!     Next coloration is for the first grid in this list  TODO : maybe we could find a better choice ..?
+        gridp => Y % first
+!
+!     Assign a color to the chosen grid
+        gridp % gr % seq_num = Agrif_seq_smallest_available_color_in_neighborhood( gridp % gr % neigh_list )
+!
+        gridp => gridp % next
+        call Agrif_gl_delete(tmp_gl)
+!
+    enddo
+!
+    call Agrif_gl_delete(X)
+    call Agrif_seq_colors_in_neighborhood( gridlist, colors )
+    ncolors = maxval(colors)
+!---------------------------------------------------------------------------------------------------
+end function Agrif_seq_colorize_grid_list
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_attach_grid ( gridlist, grid )
+!
+!< 'grid' is not connected to any neighbor. Therefore, we give an existing and well chosen color.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)       :: gridlist
+    type(Agrif_Grid),      intent(inout)    :: grid
+!
+    integer, dimension(gridlist%nitems) :: colors
+    integer, dimension(:), allocatable  :: ngrids_by_color
+    integer :: i, color, ncolors
+!
+    call Agrif_seq_colors_in_neighborhood( gridlist, colors )
+    ncolors = maxval(colors)
+!
+    allocate(ngrids_by_color(ncolors))
+    ngrids_by_color = 0
+!
+    do i = 1,gridlist % nitems
+        if (colors(i) > 0)  ngrids_by_color(colors(i)) = ngrids_by_color(colors(i)) + 1
+    enddo
+!
+    color = ncolors
+    do i = 1,ncolors
+        if ( ngrids_by_color(i) < color ) color = i
+    enddo
+!
+    grid % seq_num = color
+    deallocate(ngrids_by_color)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_attach_grid
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_colors_in_neighborhood ( neigh_list, colors )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)   :: neigh_list
+    integer, dimension(:), intent(out)  :: colors
+!
+    integer                     :: i
+    type(Agrif_PGrid), pointer  :: gridp
+!
+    i = lbound(colors,1)
+    colors = 0
+    gridp => neigh_list % first
+!
+    do while ( associated(gridp) )
+!
+        if ( i > ubound(colors,1) ) then
+            print*,'Error in Agrif_seq_colors_in_neighborhood : "colors" array is too small'
+            stop
+        endif
+        colors(i) = gridp % gr % seq_num
+        gridp => gridp % next
+        i = i+1
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_colors_in_neighborhood
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_seq_smallest_available_color_in_neighborhood ( neigh_list ) result ( smallest )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)   :: neigh_list
+!
+    integer, dimension(:), allocatable :: color_is_met
+    integer     :: colors_tab(1:neigh_list%nitems)
+    integer     :: i, smallest, max_color
+!
+    call Agrif_seq_colors_in_neighborhood( neigh_list, colors_tab )
+    max_color = maxval(colors_tab)
+!
+    allocate(color_is_met(1:max_color))
+    color_is_met = 0
+!
+    do i = 1,neigh_list % nitems
+        if ( colors_tab(i) /= 0 ) then
+            color_is_met(colors_tab(i)) = 1
+        endif
+    enddo
+!
+    smallest = max_color+1
+    do i = 1,max_color
+        if ( color_is_met(i) == 0 ) then
+            smallest = i
+            exit
+        endif
+    enddo
+!
+    deallocate(color_is_met)
+!---------------------------------------------------------------------------------------------------
+end function Agrif_seq_smallest_available_color_in_neighborhood
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_calc_dsat ( gridlist )
+!< For each node 'v' :
+!<   if none of its neighbors is colored then
+!<       DSAT(v) = degree(v)  #  degree(v) := number of neighbors
+!<   else
+!<       DSAT(v) = number of different colors used in the first neighborhood of v.
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(in)   :: gridlist
+!
+    type(Agrif_PGrid), pointer          :: gridp
+    type(Agrif_Grid),  pointer          :: grid
+    integer, dimension(:), allocatable  :: colors, color_is_met
+    integer                             :: i, ncolors
+!
+    gridp => gridlist % first
+!
+    do while ( associated(gridp) )
+!
+        grid => gridp % gr
+!
+        allocate(colors(grid % neigh_list % nitems))
+        call Agrif_seq_colors_in_neighborhood( grid % neigh_list, colors )
+
+        allocate(color_is_met(1:maxval(colors)))
+        color_is_met = 0
+!
+        do i = 1,grid % neigh_list % nitems
+            if ( colors(i) /= 0 ) then
+                color_is_met(colors(i)) = 1
+            endif
+        enddo
+        ncolors = sum(color_is_met)
+!
+        if ( ncolors == 0 ) then
+            grid % dsat = grid % neigh_list % nitems
+        else
+            grid % dsat = ncolors
+        endif
+        deallocate(colors, color_is_met)
+        gridp => gridp % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_calc_dsat
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_allocate_procs_to_childs ( coarse_grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(inout) :: coarse_grid
+!
+    integer                         :: is, ip, ig, ngrids
+    type(Agrif_Grid_List), pointer  :: gridlist
+    type(Agrif_PGrid),     pointer  :: gp
+    type(Agrif_Grid),      pointer  :: grid
+    type(Agrif_Proc_List), pointer  :: proclist
+    type(Agrif_Proc),      pointer  :: proc
+    type(Agrif_Proc_p),    pointer  :: pp
+    type(Agrif_Proc), dimension(:), allocatable, target :: procarray
+    type(Agrif_Grid), dimension(:), allocatable         :: gridarray
+    type(Agrif_Sequence_List), pointer :: seqlist
+    real,dimension(:),allocatable :: grid_costs
+    integer,dimension(:), allocatable :: nbprocs_per_grid
+    integer :: i1, i2, j1, j2
+    real :: max_cost
+    integer :: max_index
+!
+    seqlist => coarse_grid % child_seq
+    if ( .not. associated(seqlist) ) return
+!
+! Initialize proc allocation
+    pp => coarse_grid % proc_def_list % first
+    do while ( associated(pp) )
+        pp % proc % grid_id = 0
+        pp => pp % next
+    enddo
+!
+! For each sequence...
+    do is = 1,seqlist % nb_seqs
+!
+        proclist => seqlist % sequences(is) % proclist
+        gridlist => seqlist % sequences(is) % gridlist
+!
+!     Copy coarse grid proc list and convert it to an array
+        call Agrif_pl_deep_copy( coarse_grid % proc_def_list, proclist )
+        call Agrif_pl_to_array ( proclist, procarray )
+!
+!     Allocate a temporary array with concerned grid numbers
+        ngrids = gridlist % nitems
+        allocate(gridarray(1:ngrids))
+        allocate(grid_costs(1:ngrids))
+        allocate(nbprocs_per_grid(1:ngrids))
+
+      nbprocs_per_grid = 0
+!
+!     Allocate required procs to each grid
+        gp => gridlist % first
+        ig = 0
+        do while ( associated(gp) )
+            grid => gp % gr
+            ig = ig+1 ; gridarray(ig) = grid
+            pp => grid % required_proc_list % first
+            do while ( associated(pp) )
+                procarray( pp % proc % pn+1 ) % grid_id = grid % fixedrank
+                nbprocs_per_grid(ig) = nbprocs_per_grid(ig) + 1
+                pp => pp % next
+            enddo
+            gp => gp % next
+        enddo
+!
+!     Add unused procs to the grids
+! TODO FIXME: This is just a dummy allocation. You should take into account grid size and more
+!             information here...
+
+! Estimate current costs
+
+        do ig = 1, ngrids
+          i1 = gridarray(ig)%ix(1)
+          i2 = gridarray(ig)%ix(1)+gridarray(ig)%nb(1)/gridarray(ig)%spaceref(1)-1
+          j1 = gridarray(ig)%ix(2)
+          j2 = gridarray(ig)%ix(2)+gridarray(ig)%nb(2)/gridarray(ig)%spaceref(2)-1
+          Call Agrif_estimate_parallel_cost(i1,i2,j1,j2,nbprocs_per_grid(ig),grid_costs(ig))
+          grid_costs(ig) = grid_costs(ig) * gridarray(ig)%timeref(1)
+        enddo
+
+        ig = 1
+        do ip = 1,proclist%nitems
+            if ( procarray( ip ) % grid_id == 0 ) then
+!             this proc is unused
+              max_cost = 0.
+              max_index = 1
+              do ig = 1,ngrids
+                 if (grid_costs(ig) > max_cost) then
+                    max_cost = grid_costs(ig)
+                    max_index = ig
+                 endif
+              enddo
+
+              ig = max_index
+              procarray( ip ) % grid_id = gridarray(ig) % fixedrank
+
+              nbprocs_per_grid(ig) =  nbprocs_per_grid(ig) + 1
+              i1 = gridarray(ig)%ix(1)
+              i2 = gridarray(ig)%ix(1)+gridarray(ig)%nb(1)/gridarray(ig)%spaceref(1)-1
+              j1 = gridarray(ig)%ix(2)
+              j2 = gridarray(ig)%ix(2)+gridarray(ig)%nb(2)/gridarray(ig)%spaceref(2)-1
+              Call Agrif_estimate_parallel_cost(i1,i2,j1,j2,nbprocs_per_grid(ig),grid_costs(ig))
+              grid_costs(ig) = grid_costs(ig) * gridarray(ig)%timeref(1)
+
+            endif
+        enddo
+!
+!     Allocate proc nums to each grid
+        gp => gridlist % first
+        do while ( associated(gp) )
+            do ip = 1,proclist%nitems
+                if ( procarray( ip ) % grid_id == gp % gr % fixedrank ) then
+                    allocate(proc)
+                    proc = procarray( ip )
+                    call Agrif_pl_append(gp % gr % proc_def_in_parent_list, proc)
+                endif
+            enddo
+            gp => gp % next
+        enddo
+!
+!     Clean up
+        deallocate(procarray, gridarray, grid_costs, nbprocs_per_grid)
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_allocate_procs_to_childs
+!===================================================================================================
+!
+!===================================================================================================
+subroutine Agrif_seq_create_communicators ( grid )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), intent(inout) :: grid
+!
+    include 'mpif.h'
+    type(Agrif_Sequence_List), pointer  :: seqlist  ! List of child sequences
+    type(Agrif_PGrid), pointer          :: gridp
+    type(Agrif_Proc),  pointer          :: proc
+    integer     :: i, ierr
+    integer     :: current_comm, comm_seq, color_seq
+!
+    seqlist => grid % child_seq
+    if ( .not. associated(seqlist) ) return
+!
+    current_comm = grid % communicator
+    color_seq = MPI_COMM_NULL
+!
+! For each sequence, split the current communicator into as many groups as needed.
+    do i = 1,seqlist % nb_seqs
+!
+!     Loop over each proclist to give a color to the current process
+        gridp => seqlist % sequences(i) % gridlist % first
+        grid_loop : do while ( associated(gridp) )
+            proc => Agrif_pl_search_proc( gridp % gr % proc_def_in_parent_list, Agrif_Procrank )
+            if ( associated(proc) ) then
+                if ( gridp % gr % fixedrank /= proc % grid_id ) then
+                    write(*,'("### Error Agrif_seq_create_communicators : ")')
+                    write(*,'("  inconsitancy on proc ",i2,":")') Agrif_Procrank
+                    write(*,'("gr % fixedrank = ",i0,", where proc % grid_id = ",i0)') &
+                            gridp % gr % fixedrank, proc % grid_id
+                    stop
+                endif
+                color_seq = gridp % gr % fixedrank
+                exit grid_loop
+            endif
+            gridp => gridp % next
+        enddo grid_loop
+!
+        call MPI_COMM_SPLIT(current_comm, color_seq, Agrif_ProcRank, comm_seq, ierr)
+        gridp % gr % communicator = comm_seq
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_seq_create_communicators
+!===================================================================================================
+!
+!===================================================================================================
+function Agrif_seq_select_child ( g, is ) result ( gridp )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer, intent(in)   :: g
+    integer,                   intent(in)   :: is
+!
+    type(Agrif_PGrid), pointer  :: gridp
+    type(Agrif_Proc),  pointer  :: proc
+!
+    call Agrif_Instance( g )
+    gridp => g % child_seq % sequences(is) % gridlist % first
+!
+    do while ( associated(gridp) )
+        proc => Agrif_pl_search_proc( gridp % gr % proc_def_in_parent_list, Agrif_Procrank )
+        if ( associated(proc) ) then
+            return
+        endif
+        gridp => gridp % next
+    enddo
+    write(*,'("### Error Agrif_seq_select_child : no grid found in sequence ",i0," (mother G",i0,") for P",i0)')&
+        is, g%fixedrank, Agrif_Procrank
+    stop
+!---------------------------------------------------------------------------------------------------
+end function Agrif_seq_select_child
+!===================================================================================================
+#else
+    subroutine dummy_Agrif_seq ()
+    end subroutine dummy_Agrif_seq
+#endif
+!
+end module Agrif_seq
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modtypes.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modtypes.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modtypes.F90	(revision 9987)
@@ -0,0 +1,425 @@
+!     Agrif (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place-Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!
+!
+!> Definition of data types used in AGRIF, of several variables and parameters
+!
+module Agrif_Types
+!
+use Agrif_Procs
+!
+implicit none
+!
+integer, parameter :: Agrif_MaxRaff = 7       !< Maximum refinement ratio
+integer, parameter :: Agrif_NbMaxGrids = 10   !< Maximum number of grids of the hierarchy
+!
+!===================================================================================================
+type Agrif_LRectangle
+!---------------------------------------------------------------------------------------------------
+!<  Data type allowing a grid to reach a grid on the same level or its child grids
+!
+    type(Agrif_Rectangle) , pointer :: r    => NULL()   !< to reach a child grid
+    type(Agrif_LRectangle), pointer :: next => NULL()   !< to reach a grid on the same level
+!
+!---------------------------------------------------------------------------------------------------
+end type Agrif_LRectangle
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Rectangle
+!---------------------------------------------------------------------------------------------------
+!<  Data type to define several characteristics of a grid (number, position, time and space
+!<  refinement factors, etc).
+!
+    integer                         :: number       !< Number of the grid
+    integer, dimension(3)           :: imin         !< Minimal position in the x,y and z direction
+    integer, dimension(3)           :: imax         !< Maximal position in the x,y and z direction
+    integer, dimension(3)           :: spaceref     !< Space refinement factor in the x,y and z direction
+    integer, dimension(3)           :: timeref      !< Time refinement factor in the x,y and z direction
+    type(Agrif_LRectangle), pointer :: childgrids => NULL()   !< Pointer to reach a grid on the same level or a child grid
+!
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Rectangle
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Variable
+!---------------------------------------------------------------------------------------------------
+!<  Data type to characterize a grid variable.
+!
+    type(Agrif_Variable), pointer  :: root_var   => NULL()  !< pointer on the variable of the root grid
+    type(Agrif_Variable), pointer  :: parent_var => NULL()  !< pointer on the parent variable
+!
+    integer,   dimension(6)              :: point           !< index of the first point in the
+                                                            !<    real domain (x,y and z direction)
+    integer,   dimension(:), allocatable :: posvar          !< position of the variable on the cell
+                                                            !<   (1 for the boarder of the edge, 2 for the center)
+    integer                            :: interpIndex = -1  !< Indication for the space interpolation (module Agrif_Boundary)
+    integer                            :: nbdim = 0         !< number of dimensions of the grid variable
+    character(1), dimension(:), allocatable :: interptab    !< Array indicating the type of dimension (space or not)
+                                                            !!   for each of them
+    integer,   dimension(:), allocatable :: coords          !< Array indicating the coordinate for each dimension
+                                                            !!   of the array that is refined :
+                                                            !!  'x' -> 1 ; 'y' -> 2 ; 'z' -> 3 ; 'N' -> 0
+
+!> @}
+!> \name Arrays containing the values of the grid variables (real)
+!> @{
+    real,    dimension(:)          , allocatable :: array1
+    real,    dimension(:,:)        , allocatable :: array2
+    real,    dimension(:,:,:)      , allocatable :: array3
+    real,    dimension(:,:,:,:)    , allocatable :: array4
+    real,    dimension(:,:,:,:,:)  , allocatable :: array5
+    real,    dimension(:,:,:,:,:,:), allocatable :: array6
+!> @}
+!> \name Arrays containing the values of the grid variables (real*8)
+!> @{
+    real(8), dimension(:)          , allocatable :: darray1
+    real(8), dimension(:,:)        , allocatable :: darray2
+    real(8), dimension(:,:,:)      , allocatable :: darray3
+    real(8), dimension(:,:,:,:)    , allocatable :: darray4
+    real(8), dimension(:,:,:,:,:)  , allocatable :: darray5
+    real(8), dimension(:,:,:,:,:,:), allocatable :: darray6
+!> @}
+!> \name Arrays containing the values of the grid variables (real*4)
+!> @{
+    real(4), dimension(:)          , allocatable :: sarray1
+    real(4), dimension(:,:)        , allocatable :: sarray2
+    real(4), dimension(:,:,:)      , allocatable :: sarray3
+    real(4), dimension(:,:,:,:)    , allocatable :: sarray4
+    real(4), dimension(:,:,:,:,:)  , allocatable :: sarray5
+    real(4), dimension(:,:,:,:,:,:), allocatable :: sarray6
+!> @}
+!> \name Arrays used to restore the values
+!> @{
+    integer, dimension(:)          , pointer :: restore1D => NULL()
+    integer, dimension(:,:)        , pointer :: restore2D => NULL()
+    integer, dimension(:,:,:)      , pointer :: restore3D => NULL()
+    integer, dimension(:,:,:,:)    , pointer :: restore4D => NULL()
+    integer, dimension(:,:,:,:,:)  , pointer :: restore5D => NULL()
+    integer, dimension(:,:,:,:,:,:), pointer :: restore6D => NULL()
+!> @}
+
+    real, dimension(:,:), pointer :: oldvalues2D => NULL() !< Array used for the time interpolation
+
+    logical :: restore = .FALSE. !< =1 if the variable should be restored
+    logical :: Interpolationshouldbemade = .FALSE. !< TRUE if the interpolation should be made in any case
+    integer                 :: bcinf !< option bc
+    integer                 :: bcsup !< option bc
+    integer, dimension(6)   :: type_interp    !< option interp
+    integer, dimension(6,6) :: type_interp_bc !< option bcinterp
+    integer, dimension(6)   :: type_update    !< option update
+
+    integer, dimension(6)   :: lb
+    integer, dimension(6)   :: ub
+
+    logical,dimension(6,2) :: memberin
+    integer,dimension(6,2,2,6,2) :: childarray
+
+    type(Agrif_List_Interp_Loc), pointer :: list_interp => NULL()
+    type(Agrif_List_Interp_Loc), pointer :: list_update => NULL()
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Variable
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Variable_c
+!---------------------------------------------------------------------------------------------------
+!<  Data type to characterize a grid variable.
+!
+    type(Agrif_Variable_c), pointer  :: root_var   => NULL()      !< pointer on the variable of the root grid
+    type(Agrif_Variable_c), pointer  :: parent_var => NULL()      !< pointer on the parent variable
+!
+    integer                          :: nbdim = 0                 !< number of dimensions of the grid variable
+!
+!> \name Arrays containing the values of the grid variables (character)
+!> @{
+    character(2400)                             :: carray0
+    character(200), dimension(:)  , allocatable :: carray1
+    character(200), dimension(:,:), allocatable :: carray2
+!> @}
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Variable_c
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Variable_r
+!---------------------------------------------------------------------------------------------------
+!<  Data type to characterize a grid variable.
+!
+    type(Agrif_Variable_r), pointer  :: root_var   => NULL()      !< pointer on the variable of the root grid
+    type(Agrif_Variable_r), pointer  :: parent_var => NULL()      !< pointer on the parent variable
+!
+    integer                          :: nbdim = 0                 !< number of dimensions of the grid variable
+!
+!> \name Arrays containing the values of the grid variables (real)
+!> @{
+    real                                         :: array0
+    real,    dimension(:)          , allocatable :: array1
+    real,    dimension(:,:)        , allocatable :: array2
+    real,    dimension(:,:,:)      , allocatable :: array3
+    real,    dimension(:,:,:,:)    , allocatable :: array4
+    real,    dimension(:,:,:,:,:)  , allocatable :: array5
+    real,    dimension(:,:,:,:,:,:), allocatable :: array6
+!> @}
+!> \name Arrays containing the values of the grid variables (real*8)
+!> @{
+    real(8)                                      :: darray0
+    real(8), dimension(:)          , allocatable :: darray1
+    real(8), dimension(:,:)        , allocatable :: darray2
+    real(8), dimension(:,:,:)      , allocatable :: darray3
+    real(8), dimension(:,:,:,:)    , allocatable :: darray4
+    real(8), dimension(:,:,:,:,:)  , allocatable :: darray5
+    real(8), dimension(:,:,:,:,:,:), allocatable :: darray6
+!> @}
+!> \name Arrays containing the values of the grid variables (real*4)
+!> @{
+    real(4)                                      :: sarray0
+    real(4), dimension(:)          , allocatable :: sarray1
+    real(4), dimension(:,:)        , allocatable :: sarray2
+    real(4), dimension(:,:,:)      , allocatable :: sarray3
+    real(4), dimension(:,:,:,:)    , allocatable :: sarray4
+    real(4), dimension(:,:,:,:,:)  , allocatable :: sarray5
+    real(4), dimension(:,:,:,:,:,:), allocatable :: sarray6
+!> @}
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Variable_r
+!===================================================================================================
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Variable_l
+!---------------------------------------------------------------------------------------------------
+!<  Data type to characterize a grid variable.
+!
+    type(Agrif_Variable_l), pointer  :: root_var   => NULL()      !< pointer on the variable of the root grid
+    type(Agrif_Variable_l), pointer  :: parent_var => NULL()      !< pointer on the parent variable
+!
+    integer                          :: nbdim = 0                 !< number of dimensions of the grid variable
+!
+!> \name Arrays containing the values of the grid variables (logical)
+!> @{
+    logical                                      :: larray0
+    logical, dimension(:)          , allocatable :: larray1
+    logical, dimension(:,:)        , allocatable :: larray2
+    logical, dimension(:,:,:)      , allocatable :: larray3
+    logical, dimension(:,:,:,:)    , allocatable :: larray4
+    logical, dimension(:,:,:,:,:)  , allocatable :: larray5
+    logical, dimension(:,:,:,:,:,:), allocatable :: larray6
+!> @}
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Variable_l
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Variable_i
+!---------------------------------------------------------------------------------------------------
+!<  Data type to characterize a grid variable.
+!
+    type(Agrif_Variable_i), pointer  :: root_var   => NULL()      !< pointer on the variable of the root grid
+    type(Agrif_Variable_i), pointer  :: parent_var => NULL()      !< pointer on the parent variable
+!
+    integer                          :: nbdim = 0             !< number of dimensions of the grid variable
+!
+!> \name Arrays containing the values of the grid variables (integer)
+!> @{
+    integer                                      :: iarray0
+    integer, dimension(:)          , allocatable :: iarray1
+    integer, dimension(:,:)        , allocatable :: iarray2
+    integer, dimension(:,:,:)      , allocatable :: iarray3
+    integer, dimension(:,:,:,:)    , allocatable :: iarray4
+    integer, dimension(:,:,:,:,:)  , allocatable :: iarray5
+    integer, dimension(:,:,:,:,:,:), allocatable :: iarray6
+!> @}
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Variable_i
+!===================================================================================================
+!
+!===================================================================================================
+type Agrif_Interp_Loc
+!---------------------------------------------------------------------------------------------------
+    integer,dimension(6)              :: pttab, petab, pttab_Child, pttab_Parent = -99
+    integer,dimension(6)              :: indmin, indmax
+    integer,dimension(6)              :: pttruetab,cetruetab
+    logical :: member, memberin
+#if !defined AGRIF_MPI
+    integer,dimension(6)              :: indminglob,indmaxglob
+#else
+    integer,dimension(6)              :: indminglob2,indmaxglob2
+    integer,dimension(6,2,2)          :: parentarray
+    integer,dimension(:,:,:), pointer :: tab4t          => NULL()
+    integer,dimension(:,:,:), pointer :: tab5t          => NULL()
+    logical, dimension(:),    pointer :: memberinall    => NULL()
+    logical, dimension(:),    pointer :: memberinall2   => NULL()
+    logical, dimension(:),    pointer :: sendtoproc1    => NULL()
+    logical, dimension(:),    pointer :: sendtoproc2    => NULL()
+    logical, dimension(:),    pointer :: recvfromproc1  => NULL()
+    logical, dimension(:),    pointer :: recvfromproc2  => NULL()
+#endif
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Interp_Loc
+!===================================================================================================
+
+!===================================================================================================
+type Agrif_List_Interp_Loc
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Interp_Loc),      pointer :: interp_loc => NULL()
+    type(Agrif_List_Interp_Loc), pointer :: suiv       => NULL()
+!---------------------------------------------------------------------------------------------------
+end type Agrif_List_Interp_Loc
+!===================================================================================================
+
+!===================================================================================================
+type Agrif_Variables_List
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),       pointer :: var  => NULL()
+    type(Agrif_Variables_List), pointer :: next => NULL()
+!---------------------------------------------------------------------------------------------------
+end type Agrif_Variables_List
+!===================================================================================================
+!
+!===================================================================================================
+!> Different parameters
+!
+    type(Agrif_Variable),   dimension(:), pointer :: Agrif_tabvars => NULL()
+    type(Agrif_Variable_c), dimension(:), pointer :: Agrif_tabvars_c => NULL()
+    type(Agrif_Variable_r), dimension(:), pointer :: Agrif_tabvars_r => NULL()
+    type(Agrif_Variable_l), dimension(:), pointer :: Agrif_tabvars_l => NULL()
+    type(Agrif_Variable_i), dimension(:), pointer :: Agrif_tabvars_i => NULL()
+!
+    integer               :: Agrif_Probdim          !< Problem dimension
+    integer,dimension(0:4):: Agrif_NbVariables      !< Number of variables
+    integer               :: Agrif_nbfixedgrids     !< Number of fixed grids in the grid hierarchy
+    integer, dimension(3) :: Agrif_coeffref         !< Space refinement factor
+    integer, dimension(3) :: Agrif_coeffreft        !< Time refinement factor
+    logical               :: Agrif_UseSpecialValue          !< T if use special values on the parent grid
+    logical               :: Agrif_UseSpecialValueInUpdate  !< T if use special values on the parent grid
+    logical               :: Agrif_Update_Weights = .FALSE.
+    logical               :: Agrif_UseSpecialValueFineGrid  !< T if use special values on the current grid
+    real                  :: Agrif_SpecialValue             !< Special value on the parent grid
+    real                  :: Agrif_SpecialValueFineGrid     !< Special value on the current grid
+!>
+!> \name Clustering parameters
+!> @{
+    integer               :: Agrif_Regridding = 10
+    integer               :: Agrif_Minwidth
+    real                  :: Agrif_Efficiency = 0.7
+    integer               :: MaxSearch = 5
+    real, dimension(3)    :: Agrif_mind
+!> @}
+!> \name parameters for the interpolation of the child grids
+!> @{
+    integer, parameter    :: Agrif_linear = 1           !< linear interpolation
+    integer, parameter    :: Agrif_lagrange = 2         !< lagrange interpolation
+    integer, parameter    :: Agrif_eno = 3              !< spline interpolation
+    integer, parameter    :: Agrif_user_interp = 4      !< user defined interpolation
+    integer, parameter    :: Agrif_constant = 5         !< constant interpolation
+    integer, parameter    :: Agrif_linearconserv = 6    !< linear conservative interpolation
+    integer, parameter    :: Agrif_linearconservlim = 7 !< linear conservative interpolation
+    integer, parameter    :: Agrif_ppm = 8              !< PPM interpolation
+    integer, parameter    :: Agrif_weno = 9             !< WENO5 interpolation
+    integer, parameter    :: Agrif_ppm_lim = 10         !< PPM interpolation with monotonicity
+!> @}
+!> \name parameters for the update of the parent grids
+!> @{
+    integer, parameter    :: Agrif_Update_Copy = 1              !< copy
+    integer, parameter    :: Agrif_Update_Average = 2           !< average
+    integer, parameter    :: Agrif_Update_Full_Weighting = 3    !< full-weighting
+!> @}
+!> \name Raffinement grid switches
+!> @{
+    integer               :: Agrif_USE_ONLY_FIXED_GRIDS   !< = 1 if fixed grid mode
+    integer               :: Agrif_USE_FIXED_GRIDS        !< = 1 if AMR mode + fixed grid else only AMR mode
+!> @}
+    integer               :: Agrif_Maxlevelloc
+!
+#if defined AGRIF_MPI
+    integer :: Agrif_Nbprocs  !< Number of processors
+    integer :: Agrif_ProcRank !< Rank of the current processor
+    integer :: Agrif_Group    !< Group associated to Agrif_mpi_comm
+    integer :: Agrif_mpi_comm
+#else
+    integer :: Agrif_ProcRank = 0
+#endif
+!
+    integer :: Agrif_Extra_Boundary_Cells = 3       !< When computing integration sequences, the grid rects
+                                                    !! are expanded to this number of cells.
+    logical :: Agrif_Parallel_sisters = .FALSE.     !< When TRUE, try to compute sister grids (which have the same parent)
+                                                    !! in parallel rather than sequentially.
+    logical :: agrif_regrid_has_been_done = .FALSE. !< switch to skip Agrif_Regrid call
+!
+    real, dimension(:)          , allocatable :: parray1
+    real, dimension(:,:)        , allocatable :: parray2
+    real, dimension(:,:,:)      , allocatable :: parray3
+    real, dimension(:,:,:,:)    , allocatable :: parray4
+    real, dimension(:,:,:,:,:)  , allocatable :: parray5
+    real, dimension(:,:,:,:,:,:), allocatable :: parray6
+!
+    logical :: agrif_debug = .false.    ! may be activaded in users subroutine for debugging purposes
+
+! If a grand mother grid is present
+    logical :: agrif_coarse = .false.
+    integer, dimension(3) :: coarse_spaceref = (/1,1,1/)
+    integer, dimension(3) :: coarse_timeref  = (/1,1,1/)
+!
+contains
+!
+!===================================================================================================
+!  function Agrif_Ceiling
+!---------------------------------------------------------------------------------------------------
+integer function Agrif_Ceiling ( x )
+!---------------------------------------------------------------------------------------------------
+    real,   intent(in) :: x
+!
+    integer   :: i
+!
+    i = FLOOR(x)
+!
+    if( ABS(x - i) <= 0.0001 )then
+        Agrif_Ceiling = i
+    else
+        Agrif_Ceiling = i+1
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Ceiling
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Int
+!---------------------------------------------------------------------------------------------------
+    integer function Agrif_Int(x)
+!---------------------------------------------------------------------------------------------------
+    real,   intent(in) :: x
+!
+    integer :: i
+!
+    i = FLOOR(x) + 1
+!
+    if( ABS(x - i) <= 0.0001 )then
+        Agrif_Int = i
+    else
+        Agrif_Int = i-1
+    endif
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Int
+!===================================================================================================
+!
+end module Agrif_Types
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modupdate.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modupdate.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modupdate.F90	(revision 9987)
@@ -0,0 +1,2130 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place- Suite 330, Boston, MA 02111-1307, USA.
+!
+!> Module Agrif_Update
+!>
+!> This module  contains procedures to update a parent grid from its child grids.
+!
+module Agrif_Update
+!
+    use Agrif_UpdateBasic
+    use Agrif_Arrays
+    use Agrif_CurgridFunctions
+    use Agrif_Mask
+#if defined AGRIF_MPI
+    use Agrif_Mpp
+#endif
+!
+    implicit none
+!
+    logical, private :: precomputedone(7) = .FALSE.
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_UpdateVariable
+!
+!> subroutine to set arguments for Agrif_UpdatenD
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_UpdateVariable ( parent, child, updateinf, updatesup, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variable),  pointer      :: parent       !< Variable on the parent grid
+    type(Agrif_Variable),  pointer      :: child        !< Variable on the child grid
+    integer, dimension(6), intent(in)   :: updateinf    !< First positions where interpolations are calculated
+    integer, dimension(6), intent(in)   :: updatesup    !< Last  positions where interpolations are calculated
+    procedure()                         :: procname     !< Data recovery procedure
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(6) :: nb_child           ! Number of cells on the child grid
+    integer, dimension(6) :: lb_child
+    integer, dimension(6) :: ub_child
+    integer, dimension(6) :: lb_parent
+    real   , dimension(6) ::  s_child           ! Child  grid position (s_root = 0)
+    real   , dimension(6) ::  s_parent          ! Parent grid position (s_root = 0)
+    real   , dimension(6) :: ds_child           ! Child  grid dx (ds_root = 1)
+    real   , dimension(6) :: ds_parent          ! Parent grid dx (ds_root = 1)
+    logical, dimension(6) :: do_update          ! Indicates if we perform update for each dimension
+    integer, dimension(6) :: posvar             ! Position of the variable on the cell (1 or 2)
+    integer, dimension(6) :: oldparentlbound, oldparentubound
+    integer               :: n, nbdim
+    logical               :: wholeupdate
+    type(Agrif_Variable), pointer :: root   ! Variable on the root grid
+!
+    root => child % root_var
+    nbdim = root % nbdim
+!
+    call PreProcessToInterpOrUpdate( parent,   child,       &
+                                     nb_child, ub_child,    &
+                                     lb_child, lb_parent,   &
+                                      s_child,  s_parent,   &
+                                     ds_child, ds_parent, nbdim, interp=.false. )
+!
+    do_update(:) = .true.
+    posvar(1:nbdim) = root % posvar(1:nbdim)
+!
+    do n = 1,nbdim
+!
+        if ( root % interptab(n) == 'N' ) then
+            posvar(n) = 1
+            do_update(n) = .false.
+            oldparentlbound(n) = parent % lb(n)
+            oldparentubound(n) = parent % ub(n)
+            parent % lb(n) = child % lb(n)
+            parent % ub(n) = child % ub(n)
+        end if
+!
+    enddo
+
+    wholeupdate = .FALSE.
+!
+    do n = 1,nbdim
+        if ( do_update(n) ) then
+            if ( (updateinf(n) > updatesup(n)) .OR. &
+                ((updateinf(n) == -99) .AND. (updatesup(n) == -99)) &
+               ) then
+                wholeupdate = .TRUE.
+            endif
+        endif
+    enddo
+!
+    IF (wholeupdate) THEN
+        call Agrif_UpdateWhole(parent, child,               &
+                updateinf(1:nbdim), updatesup(1:nbdim),     &
+                lb_child(1:nbdim), lb_parent(1:nbdim),      &
+                nb_child(1:nbdim), posvar(1:nbdim),         &
+                do_update(1:nbdim),                         &
+                s_child(1:nbdim),   s_parent(1:nbdim),      &
+                ds_child(1:nbdim), ds_parent(1:nbdim), nbdim, procname)
+    ELSE
+        call Agrif_UpdateBcnD(parent, child,                &
+                updateinf(1:nbdim), updatesup(1:nbdim),     &
+                lb_child(1:nbdim), lb_parent(1:nbdim),      &
+                nb_child(1:nbdim), posvar(1:nbdim),         &
+                do_update(1:nbdim),                         &
+                s_child(1:nbdim),   s_parent(1:nbdim),      &
+                ds_child(1:nbdim), ds_parent(1:nbdim), nbdim, procname)
+    ENDIF
+!
+    do n = 1,nbdim
+!
+        if ( root % interptab(n) == 'N' ) then  ! No space DIMENSION
+            parent % lb(n) = oldparentlbound(n)
+            parent % ub(n) = oldparentubound(n)
+        end if
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_UpdateVariable
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_UpdateWhole
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_UpdateWhole ( parent, child, uinf, usup,       &
+                               lb_child, lb_parent,             &
+                               nb_child, posvar,                &
+                               do_update,                       &
+                               s_child,   s_parent,             &
+                               ds_child, ds_parent, nbdim, procname )
+!---------------------------------------------------------------------------------------------------
+#if defined AGRIF_MPI
+    include 'mpif.h'
+#endif
+!
+    type(Agrif_Variable),      pointer    :: parent         !< Variable on the parent grid
+    type(Agrif_Variable),      pointer    :: child          !< Variable on the child grid
+    integer, dimension(nbdim), intent(in) :: uinf           !< First positions where interpolations are calculated
+    integer, dimension(nbdim), intent(in) :: usup           !< Last  positions where interpolations are calculated
+    integer,                   intent(in) :: nbdim          !< Number of dimensions of the grid variable
+    integer, dimension(nbdim), intent(in) :: lb_child       !< Index of the first point inside the domain for the parent grid variable
+    integer, dimension(nbdim), intent(in) :: lb_parent      !< Index of the first point inside the domain for the child grid variable
+    integer, dimension(nbdim), intent(in) :: nb_child       !< Number of cells of the child grid
+    integer, dimension(nbdim), intent(in) :: posvar         !< Position of the variable on the cell (1 or 2)
+    logical, dimension(nbdim), intent(in) :: do_update      !< Indicates if we update for each dimension
+    real,    dimension(nbdim), intent(in) :: s_child        !< Positions of the child grid
+    real,    dimension(nbdim), intent(in) :: s_parent       !< Positions of the parent grid
+    real,    dimension(nbdim), intent(in) :: ds_child       !< Space steps of the child grid
+    real,    dimension(nbdim), intent(in) :: ds_parent      !< Space steps of the parent grid
+    procedure()                           :: procname       !< Data recovery procedure
+!
+    integer, dimension(nbdim)     :: type_update ! Type of update (copy or average)
+    integer, dimension(nbdim,2)   :: lubglob
+    integer, dimension(nbdim,2,2) :: indtab      ! limits of the child grid that will be used in the update scheme
+    integer, dimension(nbdim,2,2) :: indtruetab  ! grid variable where boundary conditions are
+    integer :: coeffraf, i
+    integer :: uinfloc, usuploc
+!
+    type_update = child % root_var % type_update(1:nbdim)
+!
+    do i = 1, nbdim
+!
+        if ( do_update(i) ) then
+!
+            coeffraf = nint(ds_parent(i)/ds_child(i))
+            uinfloc = 0
+            usuploc = nb_child(i)/coeffraf - 1
+
+            IF (posvar(i) == 1) THEN
+                usuploc = usuploc - 1
+            ENDIF
+
+            IF (uinf(i) > usup(i)) THEN
+                uinfloc = uinf(i)
+                usuploc = usuploc - uinf(i)
+            ENDIF
+
+            indtab(i,1,1) = lb_child(i) + (uinfloc + 1) * coeffraf
+            indtab(i,1,2) = lb_child(i) + (usuploc + 1) * coeffraf
+
+            IF ( posvar(i) == 1 ) THEN
+                IF ( type_update(i) == Agrif_Update_Full_Weighting ) THEN
+                    indtab(i,1,1) = indtab(i,1,1) - (coeffraf - 1)
+                    indtab(i,1,2) = indtab(i,1,2) + (coeffraf - 1)
+                ELSE IF ( type_update(i) /= Agrif_Update_Copy ) THEN
+                    indtab(i,1,1) = indtab(i,1,1) - coeffraf / 2
+                    indtab(i,1,2) = indtab(i,1,2) + coeffraf / 2
+                ENDIF
+            ELSE
+                indtab(i,1,1) = indtab(i,1,1) - coeffraf
+                indtab(i,1,2) = indtab(i,1,2) - 1
+    ! at this point, indices are OK for an average
+                IF ( type_update(i) == Agrif_Update_Full_Weighting ) THEN
+                    indtab(i,1,1) = indtab(i,1,1) - coeffraf / 2
+                    indtab(i,1,2) = indtab(i,1,2) + coeffraf / 2
+                ENDIF
+            ENDIF
+!
+        else    ! IF ( .not.do_update(i) ) THEN
+!
+            if ( posvar(i) == 1 ) then
+                indtab(i,1,1) = lb_child(i)
+                indtab(i,1,2) = lb_child(i) + nb_child(i)
+            else
+                indtab(i,1,1) = lb_child(i)
+                indtab(i,1,2) = lb_child(i) + nb_child(i) - 1
+            endif
+!
+        endif
+    enddo
+
+! lubglob contains the global lbound and ubound of the child array
+! lubglob(:,1) : global lbound for each dimension
+! lubglob(:,2) : global lbound for each dimension
+!
+    call Agrif_get_var_global_bounds(child, lubglob, nbdim)
+!
+    indtruetab(1:nbdim,1,1) = max(indtab(1:nbdim,1,1), lubglob(1:nbdim,1))
+    indtruetab(1:nbdim,1,2) = min(indtab(1:nbdim,1,2), lubglob(1:nbdim,2))
+!
+    call Agrif_UpdatenD(type_update, parent, child,                         &
+                        indtruetab(1:nbdim,1,1), indtruetab(1:nbdim,1,2),   &
+                        lb_child(1:nbdim), lb_parent(1:nbdim),              &
+                        s_child(1:nbdim), s_parent(1:nbdim),                &
+                        ds_child(1:nbdim), ds_parent(1:nbdim),              &
+#if defined AGRIF_MPI
+                        posvar, do_update,                                  &
+#endif
+                        nbdim, procname)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_UpdateWhole
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_UpdateBcnd
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_UpdateBcnd ( parent, child, uinf, usup,        &
+                              lb_child, lb_parent,              &
+                              nb_child, posvar,                 &
+                              do_update,                        &
+                              s_child,  s_parent,               &
+                              ds_child, ds_parent, nbdim, procname )
+!---------------------------------------------------------------------------------------------------
+#if defined AGRIF_MPI
+    include 'mpif.h'
+#endif
+!
+    type(Agrif_Variable), pointer           :: parent       !< Variable on the parent grid
+    type(Agrif_Variable), pointer           :: child        !< Variable on the child grid
+    integer, dimension(nbdim), intent(in)   :: uinf         !< First positions where interpolations are calculated
+    integer, dimension(nbdim), intent(in)   :: usup         !< Last  positions where interpolations are calculated
+    integer                                 :: nbdim        !< Number of dimensions of the grid variable
+    integer, dimension(nbdim), intent(in)   :: lb_child     !< Index of the first point inside the domain for
+                                                            !!   the parent grid variable
+    integer, dimension(nbdim), intent(in)   :: lb_parent    !< Index of the first point inside the domain for
+                                                            !!   the child grid variable
+    integer, dimension(nbdim), intent(in)   :: nb_child     !< Number of cells of the child grid
+    integer, dimension(nbdim), intent(in)   :: posvar       !< Position of the variable on the cell (1 or 2)
+    logical, dimension(nbdim), intent(in)   :: do_update    !< Indicates if we update for each dimension
+    real,    dimension(nbdim), intent(in)   :: s_child      !< Positions of the child grid
+    real,    dimension(nbdim), intent(in)   :: s_parent     !< Positions of the parent grid
+    real,    dimension(nbdim), intent(in)   :: ds_child     !< Space steps of the child grid
+    real,    dimension(nbdim), intent(in)   :: ds_parent    !< Space steps of the parent grid
+    procedure()                             :: procname     !< Data recovery procedure
+!
+    integer,dimension(nbdim)     :: type_update ! Type of update (copy or average)
+    integer,dimension(nbdim,2)   :: lubglob
+    integer                      :: i
+    integer,dimension(nbdim,2,2) :: indtab         ! Arrays indicating the limits of the child
+    integer,dimension(nbdim,2,2) :: indtruetab     ! grid variable where boundary conditions are
+    integer,dimension(nbdim,2,2,nbdim)   :: ptres  ! calculated
+    integer                      :: nb, ndir
+    integer :: coeffraf
+!
+    type_update = child % root_var % type_update(1:nbdim)
+!
+    DO i = 1, nbdim
+        coeffraf = nint(ds_parent(i)/ds_child(i))
+        indtab(i,1,1) = lb_child(i) + (uinf(i) + 1) * coeffraf
+        indtab(i,1,2) = lb_child(i) + (usup(i) + 1) * coeffraf
+
+        indtab(i,2,1) = lb_child(i) + nb_child(i) - (usup(i)+1) *  coeffraf
+        indtab(i,2,2) = lb_child(i) + nb_child(i) - (uinf(i)+1) *  coeffraf
+
+        IF (posvar(i) == 1) THEN
+            IF (type_update(i) == Agrif_Update_Full_Weighting) THEN
+                indtab(i,:,1) = indtab(i,:,1) - (coeffraf - 1)
+                indtab(i,:,2) = indtab(i,:,2) + (coeffraf - 1)
+            ELSE IF (type_update(i) /= Agrif_Update_Copy) THEN
+                indtab(i,:,1) = indtab(i,:,1) - coeffraf / 2
+                indtab(i,:,2) = indtab(i,:,2) + coeffraf / 2
+            ENDIF
+        ELSE
+            indtab(i,1,1) = indtab(i,1,1) - coeffraf
+            indtab(i,1,2) = indtab(i,1,2) - 1
+            indtab(i,2,2) = indtab(i,2,2) + coeffraf - 1
+            IF (type_update(i) == Agrif_Update_Full_Weighting) THEN
+                indtab(i,1,1) = indtab(i,1,1) - coeffraf/2
+                indtab(i,1,2) = indtab(i,1,2) + coeffraf/2
+                indtab(i,2,1) = indtab(i,2,1) - coeffraf/2
+                indtab(i,2,2) = indtab(i,2,2) + coeffraf/2
+            ENDIF
+        ENDIF
+    ENDDO
+!
+    call Agrif_get_var_global_bounds(child,lubglob,nbdim)
+!
+    indtruetab(1:nbdim,1,1) = max(indtab(1:nbdim,1,1),lubglob(1:nbdim,1))
+    indtruetab(1:nbdim,1,2) = max(indtab(1:nbdim,1,2),lubglob(1:nbdim,1))
+    indtruetab(1:nbdim,2,1) = min(indtab(1:nbdim,2,1),lubglob(1:nbdim,2))
+    indtruetab(1:nbdim,2,2) = min(indtab(1:nbdim,2,2),lubglob(1:nbdim,2))
+!
+    do nb = 1,nbdim
+        if ( do_update(nb) ) then
+            do ndir = 1,2
+                ptres(nb,1,ndir,nb) = indtruetab(nb,ndir,1)
+                ptres(nb,2,ndir,nb) = indtruetab(nb,ndir,2)
+                do i = 1,nbdim
+                    if ( i /= nb ) then
+                        if ( do_update(i) ) then
+                            ptres(i,1,ndir,nb) = indtruetab(i,1,1)
+                            ptres(i,2,ndir,nb) = indtruetab(i,2,2)
+                        else
+                            if (posvar(i) == 1) then
+                                ptres(i,1,ndir,nb) = lb_child(i)
+                                ptres(i,2,ndir,nb) = lb_child(i) + nb_child(i)
+                            else
+                                ptres(i,1,ndir,nb) = lb_child(i)
+                                ptres(i,2,ndir,nb) = lb_child(i) + nb_child(i) - 1
+                            endif
+                        endif
+                    endif
+                enddo
+            enddo
+        endif
+    enddo
+!
+    do nb = 1,nbdim
+        if ( do_update(nb) ) then
+            do ndir = 1,2
+                call Agrif_UpdatenD(type_update, parent, child,             &
+                        ptres(1:nbdim,1,ndir,nb),ptres(1:nbdim,2,ndir,nb),  &
+                        lb_child(1:nbdim),lb_parent(1:nbdim),               &
+                        s_child(1:nbdim),s_parent(1:nbdim),                 &
+                        ds_child(1:nbdim),ds_parent(1:nbdim),               &
+#if defined AGRIF_MPI
+                        posvar,do_update,                                   &
+#endif
+                        nbdim,procname,nb,ndir)
+            enddo
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_UpdateBcnd
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_UpdatenD
+!
+!> updates a 2D grid variable on the parent grid of the current grid
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_UpdatenD ( type_update, parent, child,     &
+                            pttab, petab,                   &
+                            lb_child, lb_parent,            &
+                            s_child,  s_parent,             &
+                            ds_child, ds_parent,            &
+#if defined AGRIF_MPI
+                            posvar, do_update,              &
+#endif
+                            nbdim, procname, nb, ndir )
+!---------------------------------------------------------------------------------------------------
+#if defined AGRIF_MPI
+    include 'mpif.h'
+#endif
+!
+    integer, dimension(6),     intent(in)   :: type_update  !< Type of update (copy or average)
+    type(Agrif_Variable), pointer           :: parent       !< Variable of the parent grid
+    type(Agrif_Variable), pointer           :: child        !< Variable of the child grid
+    integer,                   intent(in)   :: nbdim
+    integer, dimension(nbdim), intent(in)   :: pttab        !< Index of the first point inside the domain
+    integer, dimension(nbdim), intent(in)   :: petab        !< Index of the first point inside the domain
+    integer, dimension(nbdim), intent(in)   :: lb_child  !< Index of the first point inside the domain for the child
+                                                            !!    grid variable
+    integer, dimension(nbdim), intent(in)   :: lb_parent !< Index of the first point inside the domain for the parent
+                                                            !!    grid variable
+    real,    dimension(nbdim), intent(in)   :: s_child      !< Positions of the child grid
+    real,    dimension(nbdim), intent(in)   :: s_parent     !< Positions of the parent grid
+    real,    dimension(nbdim), intent(in)   :: ds_child     !< Space steps of the child grid
+    real,    dimension(nbdim), intent(in)   :: ds_parent    !< Space steps of the parent grid
+    procedure()                             :: procname     !< Data recovery procedure
+    integer, optional,         intent(in)   :: nb, ndir
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(nbdim)       :: pttruetab, cetruetab
+#if defined AGRIF_MPI
+    integer, dimension(nbdim)       :: posvar  !< Position of the variable on the cell (1 or 2)
+    logical, dimension(nbdim)       :: do_update
+#endif
+    integer, dimension(nbdim)       :: coords
+    integer, dimension(nbdim)       :: indmin, indmax
+    integer, dimension(nbdim)       :: indminglob, indmaxglob
+    real   , dimension(nbdim)       :: s_Child_temp, s_Parent_temp
+    integer, dimension(nbdim)       :: lowerbound,upperbound
+    integer, dimension(nbdim)       :: pttruetabwhole, cetruetabwhole
+    integer, dimension(nbdim,2,2)   :: childarray
+    integer, dimension(nbdim,2,2)   :: parentarray
+    integer,dimension(nbdim)     :: type_update_temp
+    logical :: memberin, member
+    integer :: nbin, ndirin
+!
+#if defined AGRIF_MPI
+!
+    integer,dimension(nbdim)    :: indminglob2,indmaxglob2
+    logical, dimension(0:Agrif_Nbprocs-1) :: sendtoproc1,recvfromproc1
+    logical, dimension(0:Agrif_Nbprocs-1) :: sendtoproc2,recvfromproc2
+    integer                               :: code, local_proc
+    integer                               :: i,j,k
+    integer, dimension(nbdim,4)           :: tab3
+    integer, dimension(nbdim,4,0:Agrif_Nbprocs-1) :: tab4
+    integer, dimension(nbdim,0:Agrif_Nbprocs-1,8) :: tab4t
+    integer, dimension(nbdim,0:Agrif_Nbprocs-1,8) :: tab5t
+    logical :: find_list_update
+    logical, dimension(0:Agrif_Nbprocs-1) :: memberinall, memberinall2
+    logical, dimension(1) :: memberin1
+!
+#endif
+!
+    type(Agrif_Variable), pointer, save :: tempC => NULL()       ! Temporary child grid variable
+    type(Agrif_Variable), pointer, save :: tempP => NULL()       ! Temporary parent grid variable
+    type(Agrif_Variable), pointer, save :: tempCextend => NULL() ! Temporary child
+    type(Agrif_Variable), pointer, save :: tempPextend => NULL() ! Temporary parent
+    type(Agrif_Variable), pointer :: tempP_indic, tempP_average
+    type(Agrif_Variable), pointer :: tempC_indic
+    logical :: compute_average
+    real :: coeff_multi
+    integer :: nb_dimensions
+!
+!   Get local lower and upper bound of the child variable
+    call Agrif_get_var_bounds_array(child, lowerbound, upperbound, nbdim)
+
+! here pttab and petab corresponds to the (global) indices of the points needed in the update
+! pttruetab and cetruetab contains only indices that are present on the local processor
+!
+    coords = child % root_var % coords
+!
+    call Agrif_Childbounds( nbdim, lowerbound, upperbound, pttab, petab, Agrif_Procrank,    &
+                            coords, pttruetab, cetruetab, memberin )
+    call Agrif_Prtbounds( nbdim, indminglob, indmaxglob, s_Parent_temp, s_Child_temp,       &
+                         s_child, ds_child, s_parent, ds_parent,                            &
+                         pttab, petab, lb_child, lb_parent                                  &
+#if defined AGRIF_MPI
+                       , posvar, type_update, do_update, pttruetabwhole, cetruetabwhole     &
+#endif
+            )
+
+#if defined AGRIF_MPI
+!
+    IF (memberin) THEN
+        call Agrif_GlobalToLocalBounds(childarray,lowerbound,upperbound,    &
+                                       pttruetab,cetruetab, coords,         &
+                                       nbdim, Agrif_Procrank, member)
+    ENDIF
+
+    call Agrif_Prtbounds(nbdim, indmin, indmax,                     &
+                         s_Parent_temp, s_Child_temp,               &
+                         s_child, ds_child, s_parent, ds_parent,    &
+                         pttruetab, cetruetab, lb_child, lb_parent, &
+                         posvar, type_update, do_update,            &
+                         pttruetabwhole, cetruetabwhole)
+!
+#else
+    indmin = indminglob
+    indmax = indmaxglob
+    pttruetabwhole = pttruetab
+    cetruetabwhole = cetruetab
+    childarray(:,1,2) = pttruetab
+    childarray(:,2,2) = cetruetab
+#endif
+
+    IF (.not.present(nb)) THEN
+        nbin=0
+        ndirin=0
+    ELSE
+        nbin = nb
+        ndirin = ndir
+    ENDIF
+
+    IF (memberin) THEN
+!
+        IF ( .not.associated(tempC) )  allocate(tempC)
+!
+        call Agrif_array_allocate(tempC,pttruetab,cetruetab,nbdim)
+        call Agrif_var_set_array_tozero(tempC,nbdim)
+
+        SELECT CASE (nbdim)
+        CASE(1)
+            CALL procname(tempC%array1,                 &
+                      childarray(1,1,2),childarray(1,2,2),.TRUE.,nbin,ndirin)
+        CASE(2)
+            CALL procname(tempC%array2,                 &
+                      childarray(1,1,2),childarray(1,2,2),  &
+                      childarray(2,1,2),childarray(2,2,2),.TRUE.,nbin,ndirin)
+        CASE(3)
+            CALL procname(tempC%array3,                 &
+                      childarray(1,1,2),childarray(1,2,2),  &
+                      childarray(2,1,2),childarray(2,2,2),  &
+                      childarray(3,1,2),childarray(3,2,2),.TRUE.,nbin,ndirin)
+        CASE(4)
+            CALL procname(tempC%array4,                 &
+                      childarray(1,1,2),childarray(1,2,2),  &
+                      childarray(2,1,2),childarray(2,2,2),  &
+                      childarray(3,1,2),childarray(3,2,2),  &
+                      childarray(4,1,2),childarray(4,2,2),.TRUE.,nbin,ndirin)
+        CASE(5)
+            CALL procname(tempC%array5,                 &
+                      childarray(1,1,2),childarray(1,2,2),  &
+                      childarray(2,1,2),childarray(2,2,2),  &
+                      childarray(3,1,2),childarray(3,2,2),  &
+                      childarray(4,1,2),childarray(4,2,2),  &
+                      childarray(5,1,2),childarray(5,2,2),.TRUE.,nbin,ndirin)
+        CASE(6)
+            CALL procname(tempC%array6,                 &
+                      childarray(1,1,2),childarray(1,2,2),  &
+                      childarray(2,1,2),childarray(2,2,2),  &
+                      childarray(3,1,2),childarray(3,2,2),  &
+                      childarray(4,1,2),childarray(4,2,2),  &
+                      childarray(5,1,2),childarray(5,2,2),  &
+                      childarray(6,1,2),childarray(6,2,2),.TRUE.,nbin,ndirin)
+        END SELECT
+!
+    ENDIF
+!
+#if defined AGRIF_MPI
+!
+!     tab2 contains the necessary limits of the parent grid for each processor
+
+    if (Associated(child%list_update)) then
+        call Agrif_Find_list_update(child%list_update,pttab,petab,                      &
+                                    lb_child,lb_parent,nbdim,                         &
+                                    find_list_update,tab4t,tab5t,memberinall,memberinall2,  &
+                                    sendtoproc1,recvfromproc1,sendtoproc2,recvfromproc2)
+    else
+        find_list_update = .FALSE.
+    endif
+
+    if (.not.find_list_update) then
+        tab3(:,1) = pttruetab(:)
+        tab3(:,2) = cetruetab(:)
+        tab3(:,3) = pttruetabwhole(:)
+        tab3(:,4) = cetruetabwhole(:)
+!
+        call MPI_ALLGATHER(tab3,4*nbdim,MPI_INTEGER,tab4,4*nbdim,MPI_INTEGER,Agrif_mpi_comm,code)
+
+        if ( .not.associated(tempCextend) ) allocate(tempCextend)
+        do k=0,Agrif_Nbprocs-1
+            do j=1,4
+                do i=1,nbdim
+                    tab4t(i,k,j) = tab4(i,j,k)
+                enddo
+            enddo
+        enddo
+
+        memberin1(1) = memberin
+        call MPI_ALLGATHER(memberin1,1,MPI_LOGICAL,memberinall,1,MPI_LOGICAL,Agrif_mpi_comm,code)
+
+        call Get_External_Data_first(tab4t(:,:,1),tab4t(:,:,2),tab4t(:,:,3),tab4t(:,:,4),   &
+                                     nbdim, memberinall, coords,                            &
+                                     sendtoproc1,recvfromproc1,                             &
+                                     tab4t(:,:,5),tab4t(:,:,6),tab4t(:,:,7),tab4t(:,:,8))
+    endif
+
+    call ExchangeSameLevel(sendtoproc1,recvfromproc1,nbdim,         &
+            tab4t(:,:,3),tab4t(:,:,4),tab4t(:,:,5),tab4t(:,:,6),    &
+            tab4t(:,:,7),tab4t(:,:,8),memberin,tempC,tempCextend)
+
+#else
+    tempCextend => tempC
+#endif
+!
+!     Update of the parent grid (tempP) from the child grid (tempC)
+!
+    IF (memberin) THEN
+!
+        IF ( .not.associated(tempP) ) allocate(tempP)
+!
+        call Agrif_array_allocate(tempP,indmin,indmax,nbdim)
+!
+        if ( nbdim == 1 ) then
+            tempP % array1 = 0.
+            call Agrif_Update_1D_Recursive( type_update(1),  &
+                                            tempP%array1,   &
+                                            tempCextend%array1, &
+                                            indmin(1), indmax(1),   &
+                                            pttruetabwhole(1), cetruetabwhole(1),   &
+                                            s_Child_temp(1), s_Parent_temp(1),      &
+                                            ds_child(1), ds_parent(1) )
+                                            
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+            allocate(tempC_indic)
+            allocate(tempP_indic)
+            call Agrif_array_allocate(tempC_indic,lbound(tempCextend%array1),ubound(tempCextend%array1),nbdim)
+            call Agrif_array_allocate(tempP_indic,lbound(tempP%array1),ubound(tempP%array1),nbdim)
+
+            compute_average = .FALSE.
+            type_update_temp(1:nbdim) = type_update(1:nbdim)
+            IF (ANY(type_update(1:nbdim) == Agrif_Update_Full_Weighting)) THEN
+              compute_average = .TRUE.
+              allocate(tempP_average)
+              call Agrif_array_allocate(tempP_average,lbound(tempP%array1),ubound(tempP%array1),nbdim)
+              WHERE (type_update(1:nbdim) == Agrif_Update_Full_Weighting)
+                type_update_temp(1:nbdim) = Agrif_Update_Average
+              END WHERE
+              call Agrif_Update_1D_Recursive( type_update_temp(1),   &
+                                            tempP_average%array1,       &
+                                            tempCextend%array1, &
+                                            indmin(1), indmax(1),   &
+                                            pttruetabwhole(1), cetruetabwhole(1),   &
+                                            s_Child_temp(1), s_Parent_temp(1),      &
+                                            ds_child(1), ds_parent(1) )
+              coeff_multi = 1.
+              do nb_dimensions=1,nbdim
+                coeff_multi = coeff_multi * nint(ds_parent(nb_dimensions)/ds_child(nb_dimensions))
+              enddo
+            ENDIF
+            
+            WHERE (tempCextend%array1 == Agrif_SpecialValueFineGrid)
+              tempC_indic%array1 = 0.
+            ELSEWHERE
+              tempC_indic%array1 = 1.
+            END WHERE
+            
+            Agrif_UseSpecialValueInUpdate = .FALSE.
+            Agrif_Update_Weights = .TRUE.
+ 
+             call Agrif_Update_1D_Recursive( type_update_temp(1),   &
+                                            tempP_indic%array1,       &
+                                            tempC_indic%array1, &
+                                            indmin(1), indmax(1),   &
+                                            pttruetabwhole(1), cetruetabwhole(1),   &
+                                            s_Child_temp(1), s_Parent_temp(1),      &
+                                            ds_child(1), ds_parent(1) )
+
+           Agrif_UseSpecialValueInUpdate = .TRUE.
+           Agrif_Update_Weights = .FALSE.
+
+           IF (compute_average) THEN
+               WHERE (tempP_indic%array1 == 0.)
+                  tempP%array1 = Agrif_SpecialValueFineGrid
+               ELSEWHERE ((tempP_indic%array1 == coeff_multi).AND.(tempP%array1 /= Agrif_SpecialValueFineGrid))
+                  tempP%array1 = tempP%array1 /tempP_indic%array1
+               ELSEWHERE
+                  tempP%array1 = tempP_average%array1 /tempP_indic%array1
+               END WHERE
+
+           ELSE
+               WHERE (tempP_indic%array1 == 0.)
+                  tempP%array1 = Agrif_SpecialValueFineGrid
+               ELSEWHERE
+                  tempP%array1 = tempP%array1 /tempP_indic%array1
+               END WHERE
+            ENDIF
+           
+            deallocate(tempP_indic%array1)
+            deallocate(tempC_indic%array1)
+            deallocate(tempC_indic)
+            deallocate(tempP_indic)
+            IF (compute_average) THEN
+              deallocate(tempP_average%array1)
+              deallocate(tempP_average)
+            ENDIF
+            ENDIF
+            
+        endif
+        if ( nbdim == 2 ) then
+            call Agrif_Update_2D_Recursive( type_update(1:2),   &
+                                            tempP%array2,       &
+                                            tempCextend%array2, &
+                                            indmin(1:2), indmax(1:2),   &
+                                            pttruetabwhole(1:2), cetruetabwhole(1:2),   &
+                                            s_Child_temp(1:2), s_Parent_temp(1:2),      &
+                                            ds_child(1:2), ds_parent(1:2) )
+
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+            allocate(tempC_indic)
+            allocate(tempP_indic)
+            call Agrif_array_allocate(tempC_indic,lbound(tempCextend%array2),ubound(tempCextend%array2),nbdim)
+            call Agrif_array_allocate(tempP_indic,lbound(tempP%array2),ubound(tempP%array2),nbdim)
+ 
+            compute_average = .FALSE.
+            type_update_temp(1:nbdim) = type_update(1:nbdim)
+            IF (ANY(type_update == Agrif_Update_Full_Weighting)) THEN
+              compute_average = .TRUE.
+              allocate(tempP_average)
+              call Agrif_array_allocate(tempP_average,lbound(tempP%array2),ubound(tempP%array2),nbdim)
+              WHERE (type_update(1:nbdim) == Agrif_Update_Full_Weighting)
+                type_update_temp(1:nbdim) = Agrif_Update_Average
+              END WHERE
+              call Agrif_Update_2D_Recursive( type_update_temp(1:2),   &
+                                            tempP_average%array2,       &
+                                            tempCextend%array2, &
+                                            indmin(1:2), indmax(1:2),   &
+                                            pttruetabwhole(1:2), cetruetabwhole(1:2),   &
+                                            s_Child_temp(1:2), s_Parent_temp(1:2),      &
+                                            ds_child(1:2), ds_parent(1:2) )
+              coeff_multi = 1.
+              do nb_dimensions=1,nbdim
+                coeff_multi = coeff_multi * nint(ds_parent(nb_dimensions)/ds_child(nb_dimensions))
+              enddo
+            ENDIF
+            
+            WHERE (tempCextend%array2 == Agrif_SpecialValueFineGrid)
+              tempC_indic%array2 = 0.
+            ELSEWHERE
+              tempC_indic%array2 = 1.
+            END WHERE
+            
+            Agrif_UseSpecialValueInUpdate = .FALSE.
+            Agrif_Update_Weights = .TRUE.
+            
+            call Agrif_Update_2D_Recursive( type_update_temp(1:2),   &
+                                            tempP_indic%array2,       &
+                                            tempC_indic%array2, &
+                                            indmin(1:2), indmax(1:2),   &
+                                            pttruetabwhole(1:2), cetruetabwhole(1:2),   &
+                                            s_Child_temp(1:2), s_Parent_temp(1:2),      &
+                                            ds_child(1:2), ds_parent(1:2) )
+
+           Agrif_UseSpecialValueInUpdate = .TRUE.
+           Agrif_Update_Weights = .FALSE.
+
+           IF (compute_average) THEN
+               WHERE (tempP_indic%array2 == 0.)
+                  tempP%array2 = Agrif_SpecialValueFineGrid
+               ELSEWHERE ((tempP_indic%array2 == coeff_multi).AND.(tempP%array2 /= Agrif_SpecialValueFineGrid))
+                  tempP%array2 = tempP%array2 /tempP_indic%array2
+               ELSEWHERE
+                  tempP%array2 = tempP_average%array2 /tempP_indic%array2
+               END WHERE
+
+           ELSE
+               WHERE (tempP_indic%array2 == 0.)
+                  tempP%array2 = Agrif_SpecialValueFineGrid
+               ELSEWHERE
+                  tempP%array2 = tempP%array2 /tempP_indic%array2
+               END WHERE
+            ENDIF
+           
+            deallocate(tempP_indic%array2)
+            deallocate(tempC_indic%array2)
+            deallocate(tempC_indic)
+            deallocate(tempP_indic)
+            IF (compute_average) THEN
+              deallocate(tempP_average%array2)
+              deallocate(tempP_average)
+            ENDIF
+            ENDIF
+            
+        endif
+        if ( nbdim == 3 ) then
+            call Agrif_Update_3D_Recursive( type_update(1:3),   &
+                                            tempP%array3,       &
+                                            tempCextend%array3, &
+                                            indmin(1:3), indmax(1:3),   &
+                                            pttruetabwhole(1:3), cetruetabwhole(1:3),   &
+                                            s_Child_temp(1:3), s_Parent_temp(1:3),      &
+                                            ds_child(1:3), ds_parent(1:3) )
+                                            
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+            allocate(tempC_indic)
+            allocate(tempP_indic)
+            call Agrif_array_allocate(tempC_indic,lbound(tempCextend%array3),ubound(tempCextend%array3),nbdim)
+            call Agrif_array_allocate(tempP_indic,lbound(tempP%array3),ubound(tempP%array3),nbdim)
+
+            compute_average = .FALSE.
+            type_update_temp(1:nbdim) = type_update(1:nbdim)
+            IF (ANY(type_update == Agrif_Update_Full_Weighting)) THEN
+              compute_average = .TRUE.
+              allocate(tempP_average)
+              call Agrif_array_allocate(tempP_average,lbound(tempP%array3),ubound(tempP%array3),nbdim)
+              WHERE (type_update(1:nbdim) == Agrif_Update_Full_Weighting)
+                type_update_temp(1:nbdim) = Agrif_Update_Average
+              END WHERE
+              call Agrif_Update_3D_Recursive( type_update_temp(1:3),   &
+                                            tempP_average%array3,       &
+                                            tempCextend%array3, &
+                                            indmin(1:3), indmax(1:3),   &
+                                            pttruetabwhole(1:3), cetruetabwhole(1:3),   &
+                                            s_Child_temp(1:3), s_Parent_temp(1:3),      &
+                                            ds_child(1:3), ds_parent(1:3) )
+              coeff_multi = 1.
+              do nb_dimensions=1,nbdim
+                coeff_multi = coeff_multi * nint(ds_parent(nb_dimensions)/ds_child(nb_dimensions))
+              enddo
+            ENDIF
+            
+            WHERE (tempCextend%array3 == Agrif_SpecialValueFineGrid)
+              tempC_indic%array3 = 0.
+            ELSEWHERE
+              tempC_indic%array3 = 1.
+            END WHERE
+            
+            Agrif_UseSpecialValueInUpdate = .FALSE.
+            Agrif_Update_Weights = .TRUE.
+ 
+             call Agrif_Update_3D_Recursive( type_update_temp(1:3),   &
+                                            tempP_indic%array3,       &
+                                            tempC_indic%array3, &
+                                            indmin(1:3), indmax(1:3),   &
+                                            pttruetabwhole(1:3), cetruetabwhole(1:3),   &
+                                            s_Child_temp(1:3), s_Parent_temp(1:3),      &
+                                            ds_child(1:3), ds_parent(1:3) )
+
+           Agrif_UseSpecialValueInUpdate = .TRUE.
+           Agrif_Update_Weights = .FALSE.
+
+           IF (compute_average) THEN
+               WHERE (tempP_indic%array3 == 0.)
+                  tempP%array3 = Agrif_SpecialValueFineGrid
+               ELSEWHERE ((tempP_indic%array3 == coeff_multi).AND.(tempP%array3 /= Agrif_SpecialValueFineGrid))
+                  tempP%array3 = tempP%array3 /tempP_indic%array3
+               ELSEWHERE
+                  tempP%array3 = tempP_average%array3 /tempP_indic%array3
+               END WHERE
+
+           ELSE
+               WHERE (tempP_indic%array3 == 0.)
+                  tempP%array3 = Agrif_SpecialValueFineGrid
+               ELSEWHERE
+                  tempP%array3 = tempP%array3 /tempP_indic%array3
+               END WHERE
+            ENDIF
+           
+            deallocate(tempP_indic%array3)
+            deallocate(tempC_indic%array3)
+            deallocate(tempC_indic)
+            deallocate(tempP_indic)
+            IF (compute_average) THEN
+              deallocate(tempP_average%array3)
+              deallocate(tempP_average)
+            ENDIF
+            ENDIF
+            
+        endif
+        if ( nbdim == 4 ) then
+            call Agrif_Update_4D_Recursive( type_update(1:4),   &
+                                            tempP%array4,       &
+                                            tempCextend%array4, &
+                                            indmin(1:4), indmax(1:4),   &
+                                            pttruetabwhole(1:4), cetruetabwhole(1:4),   &
+                                            s_Child_temp(1:4), s_Parent_temp(1:4),      &
+                                            ds_child(1:4), ds_parent(1:4) )
+                                            
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+            
+            allocate(tempC_indic)
+            allocate(tempP_indic)
+            call Agrif_array_allocate(tempC_indic,lbound(tempCextend%array4),ubound(tempCextend%array4),nbdim)
+            call Agrif_array_allocate(tempP_indic,lbound(tempP%array4),ubound(tempP%array4),nbdim)
+           
+            compute_average = .FALSE.
+            type_update_temp(1:nbdim) = type_update(1:nbdim)
+            IF (ANY(type_update == Agrif_Update_Full_Weighting)) THEN
+              compute_average = .TRUE.
+              allocate(tempP_average)
+              call Agrif_array_allocate(tempP_average,lbound(tempP%array4),ubound(tempP%array4),nbdim)
+              WHERE (type_update(1:nbdim) == Agrif_Update_Full_Weighting)
+                type_update_temp(1:nbdim) = Agrif_Update_Average
+              END WHERE
+              call Agrif_Update_4D_Recursive( type_update_temp(1:4),   &
+                                            tempP_average%array4,       &
+                                            tempCextend%array4, &
+                                            indmin(1:4), indmax(1:4),   &
+                                            pttruetabwhole(1:4), cetruetabwhole(1:4),   &
+                                            s_Child_temp(1:4), s_Parent_temp(1:4),      &
+                                            ds_child(1:4), ds_parent(1:4) )
+              coeff_multi = 1.
+              do nb_dimensions=1,nbdim
+                coeff_multi = coeff_multi * nint(ds_parent(nb_dimensions)/ds_child(nb_dimensions))
+              enddo
+            ENDIF
+            
+            WHERE (tempCextend%array4 == Agrif_SpecialValueFineGrid)
+              tempC_indic%array4 = 0.
+            ELSEWHERE
+              tempC_indic%array4 = 1.
+            END WHERE
+            
+            Agrif_UseSpecialValueInUpdate = .FALSE.
+            Agrif_Update_Weights = .TRUE.
+ 
+             call Agrif_Update_4D_Recursive( type_update_temp(1:4),   &
+                                            tempP_indic%array4,       &
+                                            tempC_indic%array4, &
+                                            indmin(1:4), indmax(1:4),   &
+                                            pttruetabwhole(1:4), cetruetabwhole(1:4),   &
+                                            s_Child_temp(1:4), s_Parent_temp(1:4),      &
+                                            ds_child(1:4), ds_parent(1:4) )
+
+           Agrif_UseSpecialValueInUpdate = .TRUE.
+           Agrif_Update_Weights = .FALSE.
+           
+           IF (compute_average) THEN
+               WHERE (tempP_indic%array4 == 0.)
+                  tempP%array4 = Agrif_SpecialValueFineGrid
+               ELSEWHERE ((tempP_indic%array4 == coeff_multi).AND.(tempP%array4 /= Agrif_SpecialValueFineGrid))
+                  tempP%array4 = tempP%array4 /tempP_indic%array4
+               ELSEWHERE
+                  tempP%array4 = tempP_average%array4 /tempP_indic%array4
+               END WHERE
+
+           ELSE
+               WHERE (tempP_indic%array4 == 0.)
+                  tempP%array4 = Agrif_SpecialValueFineGrid
+               ELSEWHERE
+                  tempP%array4 = tempP%array4 /tempP_indic%array4
+               END WHERE
+            ENDIF
+            deallocate(tempP_indic%array4)
+            deallocate(tempC_indic%array4)
+            deallocate(tempC_indic)
+            deallocate(tempP_indic)
+            IF (compute_average) THEN
+              deallocate(tempP_average%array4)
+              deallocate(tempP_average)
+            ENDIF
+            ENDIF
+            
+        endif
+        if ( nbdim == 5 ) then
+            call Agrif_Update_5D_Recursive( type_update(1:5),   &
+                                            tempP%array5,       &
+                                            tempCextend%array5, &
+                                            indmin(1:5), indmax(1:5),   &
+                                            pttruetabwhole(1:5), cetruetabwhole(1:5),   &
+                                            s_Child_temp(1:5), s_Parent_temp(1:5),      &
+                                            ds_child(1:5), ds_parent(1:5) )
+                                            
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+            allocate(tempC_indic)
+            allocate(tempP_indic)
+            call Agrif_array_allocate(tempC_indic,lbound(tempCextend%array5),ubound(tempCextend%array5),nbdim)
+            call Agrif_array_allocate(tempP_indic,lbound(tempP%array5),ubound(tempP%array5),nbdim)
+
+            compute_average = .FALSE.
+            type_update_temp(1:nbdim) = type_update(1:nbdim)
+            IF (ANY(type_update == Agrif_Update_Full_Weighting)) THEN
+              compute_average = .TRUE.
+              allocate(tempP_average)
+              call Agrif_array_allocate(tempP_average,lbound(tempP%array5),ubound(tempP%array5),nbdim)
+              WHERE (type_update(1:nbdim) == Agrif_Update_Full_Weighting)
+                type_update_temp(1:nbdim) = Agrif_Update_Average
+              END WHERE
+              call Agrif_Update_5D_Recursive( type_update_temp(1:5),   &
+                                            tempP_average%array5,       &
+                                            tempCextend%array5, &
+                                            indmin(1:5), indmax(1:5),   &
+                                            pttruetabwhole(1:5), cetruetabwhole(1:5),   &
+                                            s_Child_temp(1:5), s_Parent_temp(1:5),      &
+                                            ds_child(1:5), ds_parent(1:5) )
+              coeff_multi = 1.
+              do nb_dimensions=1,nbdim
+                coeff_multi = coeff_multi * nint(ds_parent(nb_dimensions)/ds_child(nb_dimensions))
+              enddo
+            ENDIF
+            
+            WHERE (tempCextend%array5 == Agrif_SpecialValueFineGrid)
+              tempC_indic%array5 = 0.
+            ELSEWHERE
+              tempC_indic%array5 = 1.
+            END WHERE
+            
+            Agrif_UseSpecialValueInUpdate = .FALSE.
+            Agrif_Update_Weights = .TRUE.
+ 
+             call Agrif_Update_5D_Recursive( type_update_temp(1:5),   &
+                                            tempP_indic%array5,       &
+                                            tempC_indic%array5, &
+                                            indmin(1:5), indmax(1:5),   &
+                                            pttruetabwhole(1:5), cetruetabwhole(1:5),   &
+                                            s_Child_temp(1:5), s_Parent_temp(1:5),      &
+                                            ds_child(1:5), ds_parent(1:5) )
+
+           Agrif_UseSpecialValueInUpdate = .TRUE.
+           Agrif_Update_Weights = .FALSE.
+
+           IF (compute_average) THEN
+               WHERE (tempP_indic%array5 == 0.)
+                  tempP%array5 = Agrif_SpecialValueFineGrid
+               ELSEWHERE ((tempP_indic%array5 == coeff_multi).AND.(tempP%array5 /= Agrif_SpecialValueFineGrid))
+                  tempP%array5 = tempP%array5 /tempP_indic%array5
+               ELSEWHERE
+                  tempP%array5 = tempP_average%array5 /tempP_indic%array5
+               END WHERE
+
+           ELSE
+               WHERE (tempP_indic%array5 == 0.)
+                  tempP%array5 = Agrif_SpecialValueFineGrid
+               ELSEWHERE
+                  tempP%array5 = tempP%array5 /tempP_indic%array5
+               END WHERE
+            ENDIF
+           
+            deallocate(tempP_indic%array5)
+            deallocate(tempC_indic%array5)
+            deallocate(tempC_indic)
+            deallocate(tempP_indic)
+            IF (compute_average) THEN
+              deallocate(tempP_average%array5)
+              deallocate(tempP_average)
+            ENDIF
+            ENDIF
+            
+        endif
+        if ( nbdim == 6 ) then
+            call Agrif_Update_6D_Recursive( type_update(1:6),   &
+                                            tempP%array6,       &
+                                            tempCextend%array6, &
+                                            indmin(1:6), indmax(1:6),   &
+                                            pttruetabwhole(1:6), cetruetabwhole(1:6),   &
+                                            s_Child_temp(1:6), s_Parent_temp(1:6),      &
+                                            ds_child(1:6), ds_parent(1:6) )
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+            allocate(tempC_indic)
+            allocate(tempP_indic)
+            call Agrif_array_allocate(tempC_indic,lbound(tempCextend%array6),ubound(tempCextend%array6),nbdim)
+            call Agrif_array_allocate(tempP_indic,lbound(tempP%array6),ubound(tempP%array6),nbdim)
+
+            compute_average = .FALSE.
+            type_update_temp(1:nbdim) = type_update(1:nbdim)
+            IF (ANY(type_update == Agrif_Update_Full_Weighting)) THEN
+              compute_average = .TRUE.
+              allocate(tempP_average)
+              call Agrif_array_allocate(tempP_average,lbound(tempP%array6),ubound(tempP%array6),nbdim)
+              type_update_temp(1:nbdim) = type_update
+              WHERE (type_update(1:nbdim) == Agrif_Update_Full_Weighting)
+                type_update_temp(1:nbdim) = Agrif_Update_Average
+              END WHERE
+              call Agrif_Update_6D_Recursive( type_update_temp(1:6),   &
+                                            tempP_average%array6,       &
+                                            tempCextend%array6, &
+                                            indmin(1:6), indmax(1:6),   &
+                                            pttruetabwhole(1:6), cetruetabwhole(1:6),   &
+                                            s_Child_temp(1:6), s_Parent_temp(1:6),      &
+                                            ds_child(1:6), ds_parent(1:6) )
+              coeff_multi = 1.
+              do nb_dimensions=1,nbdim
+                coeff_multi = coeff_multi * nint(ds_parent(nb_dimensions)/ds_child(nb_dimensions))
+              enddo
+            ENDIF
+
+           IF (compute_average) THEN
+               WHERE (tempP_indic%array6 == 0.)
+                  tempP%array6 = Agrif_SpecialValueFineGrid
+               ELSEWHERE ((tempP_indic%array6 == coeff_multi).AND.(tempP%array6 /= Agrif_SpecialValueFineGrid))
+                  tempP%array6 = tempP%array6 /tempP_indic%array6
+               ELSEWHERE
+                  tempP%array6 = tempP_average%array6 /tempP_indic%array6
+               END WHERE
+
+           ELSE
+               WHERE (tempP_indic%array6 == 0.)
+                  tempP%array6 = Agrif_SpecialValueFineGrid
+               ELSEWHERE
+                  tempP%array6 = tempP%array6 /tempP_indic%array6
+               END WHERE
+            ENDIF
+            
+            Agrif_UseSpecialValueInUpdate = .FALSE.
+            Agrif_Update_Weights = .TRUE.
+ 
+             call Agrif_Update_6D_Recursive( type_update_temp(1:6),   &
+                                            tempP_indic%array6,       &
+                                            tempC_indic%array6, &
+                                            indmin(1:6), indmax(1:6),   &
+                                            pttruetabwhole(1:6), cetruetabwhole(1:6),   &
+                                            s_Child_temp(1:6), s_Parent_temp(1:6),      &
+                                            ds_child(1:6), ds_parent(1:6) )
+
+           Agrif_UseSpecialValueInUpdate = .TRUE.
+           Agrif_Update_Weights = .FALSE.
+           
+            WHERE (tempP_indic%array6 == 0.)
+              tempP%array6 = Agrif_SpecialValueFineGrid
+            ELSEWHERE
+              tempP%array6 = tempP%array6 /tempP_indic%array6
+            END WHERE
+           
+            deallocate(tempP_indic%array6)
+            deallocate(tempC_indic%array6)
+            deallocate(tempC_indic)
+            deallocate(tempP_indic)
+            IF (compute_average) THEN
+              deallocate(tempP_average%array6)
+              deallocate(tempP_average)
+            ENDIF
+            ENDIF
+        endif
+!
+        call Agrif_array_deallocate(tempCextend,nbdim)
+!
+    ENDIF
+
+#if defined AGRIF_MPI
+    local_proc = Agrif_Procrank
+    call Agrif_get_var_bounds_array(parent,lowerbound,upperbound,nbdim)
+    call Agrif_ChildGrid_to_ParentGrid()
+    call Agrif_Childbounds(nbdim, lowerbound, upperbound,                   &
+                           indminglob,  indmaxglob,  local_proc, coords,    &
+                           indminglob2, indmaxglob2, member)
+!
+    IF (member) THEN
+        call Agrif_GlobalToLocalBounds(parentarray, lowerbound, upperbound, &
+                                       indminglob2, indmaxglob2, coords,    &
+                                       nbdim, local_proc, member)
+    ENDIF
+
+    call Agrif_ParentGrid_to_ChildGrid()
+
+    if (.not.find_list_update) then
+        tab3(:,1) = indmin(:)
+        tab3(:,2) = indmax(:)
+        tab3(:,3) = indminglob2(:)
+        tab3(:,4) = indmaxglob2(:)
+!
+        call MPI_ALLGATHER(tab3,4*nbdim,MPI_INTEGER,tab4,4*nbdim,MPI_INTEGER,Agrif_mpi_comm,code)
+
+        IF ( .not.associated(tempPextend) ) allocate(tempPextend)
+        DO k=0,Agrif_Nbprocs-1
+            do j=1,4
+                do i=1,nbdim
+                    tab5t(i,k,j) = tab4(i,j,k)
+                enddo
+            enddo
+        enddo
+
+        memberin1(1) = member
+        call MPI_ALLGATHER(memberin1,1,MPI_LOGICAL,memberinall2,1,MPI_LOGICAL,Agrif_mpi_comm,code)
+        call Get_External_Data_first(tab5t(:,:,1),tab5t(:,:,2),tab5t(:,:,3),tab5t(:,:,4),   &
+                                     nbdim, memberinall2, coords,                           &
+                                     sendtoproc2, recvfromproc2,                            &
+                                     tab5t(:,:,5),tab5t(:,:,6),tab5t(:,:,7),tab5t(:,:,8))
+
+        call Agrif_Addto_list_update(child%list_update,pttab,petab,lb_child,lb_parent,      &
+                                     nbdim,tab4t,tab5t,memberinall,memberinall2,            &
+                                     sendtoproc1,recvfromproc1,sendtoproc2,recvfromproc2)
+
+    endif
+
+    call ExchangeSameLevel(sendtoproc2,recvfromproc2,nbdim,                     &
+                            tab5t(:,:,3),tab5t(:,:,4),tab5t(:,:,5),tab5t(:,:,6),&
+                            tab5t(:,:,7),tab5t(:,:,8),member,tempP,tempPextend)
+#else
+    tempPextend => tempP
+    parentarray(:,1,1) = indmin
+    parentarray(:,2,1) = indmax
+    parentarray(:,1,2) = indmin
+    parentarray(:,2,2) = indmax
+    member = .TRUE.
+#endif
+!
+!   Special values on the child grid
+    if ( Agrif_UseSpecialValueFineGrid ) then
+!
+!cc         noraftab(1:nbdim) =
+!cc     &    child % root_var % interptab(1:nbdim) == 'N'
+!
+#if defined AGRIF_MPI
+!
+!          allocate(childvalues% var)
+!
+!          Call Agrif_array_allocate(childvalues%var,
+!     &                      pttruetab,cetruetab,nbdim)
+!          Call Agrif_var_full_copy_array(childvalues% var,
+!     &                                tempC,
+!     &                                nbdim)
+!          Call Agrif_CheckMasknD(tempC,childvalues,
+!     &                           pttruetab(1:nbdim),cetruetab(1:nbdim),
+!     &                           pttruetab(1:nbdim),cetruetab(1:nbdim),
+!     &                           noraftab(1:nbdim),nbdim)
+!          Call Agrif_array_deallocate(childvalues% var,nbdim)
+!         Deallocate(childvalues % var)
+!
+#else
+!
+!          Call Agrif_get_var_bounds_array(child,
+!     &                              lowerbound,upperbound,nbdim)
+!          Call Agrif_CheckMasknD(tempC,child,
+!     &                           pttruetab(1:nbdim),cetruetab(1:nbdim),
+!     &                           lowerbound,
+!     &                           upperbound,
+!     &                           noraftab(1:nbdim),nbdim)
+!
+#endif
+!
+    endif
+!
+!   Special values on the parent grid
+    if (Agrif_UseSpecialValue) then
+!
+#if defined AGRIF_MPI
+!
+!          Call GiveAgrif_SpecialValueToTab_mpi(parent,tempP,
+!     &                 parentarray,
+!     &                 Agrif_SpecialValue,nbdim)
+!
+!
+#else
+!
+!          Call GiveAgrif_SpecialValueToTab(parent,tempP,
+!     &                  indmin,indmax,
+!     &                  Agrif_SpecialValue,nbdim)
+!
+#endif
+!
+    endif
+!
+    IF (member) THEN
+
+        call Agrif_ChildGrid_to_ParentGrid()
+!
+        SELECT CASE(nbdim)
+        CASE(1)
+            call procname( tempPextend % array1(            &
+                    parentarray(1,1,1):parentarray(1,2,1)), &
+                    parentarray(1,1,2),parentarray(1,2,2),.FALSE.,nbin,ndirin)
+        CASE(2)
+            call procname( tempPextend % array2(            &
+                    parentarray(1,1,1):parentarray(1,2,1),  &
+                    parentarray(2,1,1):parentarray(2,2,1)), &
+                    parentarray(1,1,2),parentarray(1,2,2),  &
+                    parentarray(2,1,2),parentarray(2,2,2),.FALSE.,nbin,ndirin)
+        CASE(3)
+            call procname( tempPextend % array3(            &
+                    parentarray(1,1,1):parentarray(1,2,1),  &
+                    parentarray(2,1,1):parentarray(2,2,1),  &
+                    parentarray(3,1,1):parentarray(3,2,1)), &
+                    parentarray(1,1,2),parentarray(1,2,2),  &
+                    parentarray(2,1,2),parentarray(2,2,2),  &
+                    parentarray(3,1,2),parentarray(3,2,2),.FALSE.,nbin,ndirin)
+        CASE(4)
+            call procname( tempPextend % array4(            &
+                    parentarray(1,1,1):parentarray(1,2,1),  &
+                    parentarray(2,1,1):parentarray(2,2,1),  &
+                    parentarray(3,1,1):parentarray(3,2,1),  &
+                    parentarray(4,1,1):parentarray(4,2,1)), &
+                    parentarray(1,1,2),parentarray(1,2,2),  &
+                    parentarray(2,1,2),parentarray(2,2,2),  &
+                    parentarray(3,1,2),parentarray(3,2,2),  &
+                    parentarray(4,1,2),parentarray(4,2,2),.FALSE.,nbin,ndirin)
+        CASE(5)
+            call procname( tempPextend % array5(            &
+                    parentarray(1,1,1):parentarray(1,2,1),  &
+                    parentarray(2,1,1):parentarray(2,2,1),  &
+                    parentarray(3,1,1):parentarray(3,2,1),  &
+                    parentarray(4,1,1):parentarray(4,2,1),  &
+                    parentarray(5,1,1):parentarray(5,2,1)), &
+                    parentarray(1,1,2),parentarray(1,2,2),  &
+                    parentarray(2,1,2),parentarray(2,2,2),  &
+                    parentarray(3,1,2),parentarray(3,2,2),  &
+                    parentarray(4,1,2),parentarray(4,2,2),  &
+                    parentarray(5,1,2),parentarray(5,2,2),.FALSE.,nbin,ndirin)
+        CASE(6)
+            call procname( tempPextend % array6(            &
+                    parentarray(1,1,1):parentarray(1,2,1),  &
+                    parentarray(2,1,1):parentarray(2,2,1),  &
+                    parentarray(3,1,1):parentarray(3,2,1),  &
+                    parentarray(4,1,1):parentarray(4,2,1),  &
+                    parentarray(5,1,1):parentarray(5,2,1),  &
+                    parentarray(6,1,1):parentarray(6,2,1)), &
+                    parentarray(1,1,2),parentarray(1,2,2),  &
+                    parentarray(2,1,2),parentarray(2,2,2),  &
+                    parentarray(3,1,2),parentarray(3,2,2),  &
+                    parentarray(4,1,2),parentarray(4,2,2),  &
+                    parentarray(5,1,2),parentarray(5,2,2),  &
+                    parentarray(6,1,2),parentarray(6,2,2),.FALSE.,nbin,ndirin)
+        END SELECT
+!
+        call Agrif_ParentGrid_to_ChildGrid()
+!
+        call Agrif_array_deallocate(tempPextend,nbdim)
+!
+    ENDIF
+!
+#if defined AGRIF_MPI
+    IF (memberin) THEN
+        call Agrif_array_deallocate(tempP,nbdim)
+        call Agrif_array_deallocate(tempC,nbdim)
+    ENDIF
+#endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_UpdatenD
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Prtbounds
+!
+!> calculates the bounds of the parent grid to be updated by the child grid
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Prtbounds ( nbdim, indmin, indmax, s_Parent_temp, s_Child_temp,        &
+                             s_child, ds_child, s_parent, ds_parent,                    &
+                             pttruetab, cetruetab, lb_child, lb_parent            &
+#if defined AGRIF_MPI
+                            ,posvar, type_update, do_update,                &
+                             pttruetabwhole, cetruetabwhole                             &
+#endif
+                )
+!---------------------------------------------------------------------------------------------------
+    integer,                   intent(in)   :: nbdim
+    integer, dimension(nbdim), intent(out)  :: indmin, indmax
+    real,    dimension(nbdim), intent(out)  :: s_Parent_temp, s_Child_temp
+    real,    dimension(nbdim), intent(in)   :: s_child,  ds_child
+    real,    dimension(nbdim), intent(in)   :: s_parent, ds_parent
+    integer, dimension(nbdim), intent(in)   :: pttruetab, cetruetab
+    integer, dimension(nbdim), intent(in)   :: lb_child, lb_parent
+#if defined AGRIF_MPI
+    integer, dimension(nbdim), intent(in)   :: posvar   !< Position of the variable on the cell (1 or 2)
+    integer, dimension(nbdim), intent(in)   :: type_update
+    logical, dimension(nbdim), intent(in)   :: do_update
+    integer,dimension(nbdim), intent(out)   :: pttruetabwhole, cetruetabwhole
+#endif
+!
+    real,dimension(nbdim) :: dim_newmin,dim_newmax
+    integer :: i
+#if defined AGRIF_MPI
+    real    :: positionmin, positionmax
+    integer :: imin, imax
+    integer :: coeffraf
+#endif
+!
+    do i = 1,nbdim
+!
+        dim_newmin(i) = s_child(i) + (pttruetab(i) - lb_child(i)) * ds_child(i)
+        dim_newmax(i) = s_child(i) + (cetruetab(i) - lb_child(i)) * ds_child(i)
+!
+        indmin(i) = lb_parent(i) + agrif_ceiling((dim_newmin(i)-s_parent(i))/ds_parent(i))
+        indmax(i) = lb_parent(i) + agrif_int(    (dim_newmax(i)-s_parent(i))/ds_parent(i))
+!
+#if defined AGRIF_MPI
+        positionmin = s_parent(i) + (indmin(i)-lb_parent(i))*ds_parent(i)
+        IF ( do_update(i) ) THEN
+            IF (posvar(i) == 1) THEN
+                IF      (type_update(i) == Agrif_Update_Average) THEN
+                    positionmin = positionmin - ds_parent(i)/2.
+                ELSE IF (type_update(i) == Agrif_Update_Full_Weighting) THEN
+                    positionmin = positionmin - (ds_parent(i)-ds_child(i))
+                ENDIF
+            ELSE
+                IF (type_update(i) /= Agrif_Update_Full_Weighting) THEN
+                    positionmin = positionmin - ds_parent(i)/2.
+                ELSE
+                    coeffraf = nint(ds_parent(i)/ds_child(i))
+                    if (mod(coeffraf,2) == 1) then
+                        positionmin = positionmin - (ds_parent(i)-ds_child(i))
+                    else
+                        positionmin = positionmin - (ds_parent(i)-ds_child(i))-ds_child(i)/2.
+                    endif
+                ENDIF
+            ENDIF
+        ENDIF
+!
+        imin = lb_child(i) + agrif_ceiling((positionmin-s_child(i))/ds_child(i))
+        positionmin = s_child(i)  + (imin - lb_child(i)) * ds_child(i)
+        positionmax = s_parent(i) + (indmax(i)-lb_parent(i))*ds_parent(i)
+        pttruetabwhole(i) = imin
+
+        IF ( do_update(i) ) THEN
+            IF (posvar(i) == 1) THEN
+                IF      (type_update(i) == Agrif_Update_Average) THEN
+                    positionmax = positionmax  + ds_parent(i)/2.
+                ELSE IF (type_update(i) == Agrif_Update_Full_Weighting) THEN
+                    positionmax = positionmax  + (ds_parent(i)-ds_child(i))
+                ENDIF
+            ELSE
+                IF (type_update(i) /= Agrif_Update_Full_Weighting) THEN
+                    positionmax = positionmax  + ds_parent(i)/2.
+                ELSE
+                    coeffraf = nint(ds_parent(i)/ds_child(i))
+                    if (mod(coeffraf,2) == 1) then
+                        positionmax = positionmax + (ds_parent(i)-ds_child(i))
+                    else
+                        positionmax = positionmax + (ds_parent(i)-ds_child(i)) + ds_child(i)/2.
+                    endif
+                ENDIF
+            ENDIF
+        ENDIF
+
+        imax = lb_child(i) +agrif_int((positionmax-s_child(i))/ds_child(i))
+        positionmax = s_child(i) + (imax - lb_child(i)) * ds_child(i)
+        cetruetabwhole(i) = imax
+#endif
+!
+        s_Parent_temp(i) = s_parent(i) + (indmin(i) - lb_parent(i)) * ds_parent(i)
+        s_Child_temp(i)  = dim_newmin(i)
+
+#if defined AGRIF_MPI
+        s_Child_temp(i) = positionmin
+#endif
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Prtbounds
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Update_1D_Recursive
+!
+!> Updates a 1D grid variable on the parent grid
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_1D_Recursive ( type_update,         &
+                                       tempP, tempC,        &
+                                       indmin, indmax,      &
+                                       lb_child, ub_child,  &
+                                       s_child,  s_parent,  &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer,                            intent(in)  :: type_update            !< Type of update (copy or average)
+    integer,                            intent(in)  :: indmin, indmax
+    integer,                            intent(in)  :: lb_child, ub_child
+    real,                               intent(in)  ::  s_child,  s_parent
+    real,                               intent(in)  :: ds_child, ds_parent
+    real, dimension(indmin:indmax),     intent(out) :: tempP
+    real, dimension(lb_child:ub_child), intent(in)  :: tempC
+!---------------------------------------------------------------------------------------------------
+    call Agrif_UpdateBase(type_update,              &
+                          tempP(indmin:indmax),     &
+                          tempC(lb_child:ub_child), &
+                          indmin, indmax,           &
+                          lb_child, ub_child,       &
+                          s_parent, s_child,        &
+                          ds_parent, ds_child)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_1D_Recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Update_2D_Recursive
+!
+!> updates a 2D grid variable on the parent grid.
+!! Calls #Agrif_Update_1D_Recursive and #Agrif_UpdateBase
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_2D_Recursive ( type_update,         &
+                                       tempP, tempC,        &
+                                       indmin, indmax,      &
+                                       lb_child, ub_child,  &
+                                        s_child,  s_parent, &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(2),          intent(in)  :: type_update            !< Type of update (copy or average)
+    integer, dimension(2),          intent(in)  :: indmin, indmax
+    integer, dimension(2),          intent(in)  :: lb_child, ub_child
+    real,    dimension(2),          intent(in)  ::  s_child,  s_parent
+    real,    dimension(2),          intent(in)  :: ds_child, ds_parent
+    real,    dimension(          &
+        indmin(1):indmax(1),     &
+        indmin(2):indmax(2)),       intent(out) :: tempP
+    real,    dimension(:,:),        intent(in)  :: tempC
+!---------------------------------------------------------------------------------------------------
+    real, dimension(indmin(1):indmax(1), lb_child(2):ub_child(2)) :: tabtemp
+    real, dimension(indmin(2):indmax(2), indmin(1):indmax(1))     :: tempP_trsp
+    real, dimension(lb_child(2):ub_child(2), indmin(1):indmax(1)) :: tabtemp_trsp
+    integer :: i, j
+    integer :: coeffraf
+!
+    tabtemp = 0.
+    coeffraf = nint ( ds_parent(1) / ds_child(1) )
+!
+    IF((type_update(1) == Agrif_Update_Average) .AND. (coeffraf /= 1 )) THEN
+!---CDIR NEXPAND
+        if ( .NOT. precomputedone(1) ) then
+            call Average1dPrecompute( ub_child(2)-lb_child(2)+1,    &
+                                      indmax(1)-indmin(1)+1,              &
+                                      ub_child(1)-lb_child(1)+1,    &
+                                      s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+!            precomputedone(1) = .TRUE.
+        endif
+!---CDIR NEXPAND
+        call Average1dAfterCompute( tabtemp, tempC, size(tabtemp), size(tempC), &
+                    s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+!
+    ELSE IF ((type_update(1) == Agrif_Update_Copy) .AND. (coeffraf /= 1 ))THEN
+!---CDIR NEXPAND
+         if ( .NOT. precomputedone(1) ) then
+            call Agrif_basicupdate_copy1d_before( ub_child(2)-lb_child(2)+1, &
+                                   indmax(1)-indmin(1)+1,           &
+                                   ub_child(1)-lb_child(1)+1, &
+                                   s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+!            precomputedone(1) = .TRUE.
+        endif
+!---CDIR NEXPAND
+        call Agrif_basicupdate_copy1d_after(tabtemp,tempC,size(tabtemp),size(tempC),1)
+!
+    ELSE
+        do j = lb_child(2),ub_child(2)
+!
+!---CDIR NEXPAND
+            call Agrif_Update_1D_Recursive( type_update(1),             &
+                                            tabtemp(:,j),               &
+                                            tempC(:,j-lb_child(2)+1),   &
+                                            indmin(1), indmax(1),       &
+                                            lb_child(1),ub_child(1),    &
+                                            s_child(1),  s_parent(1),   &
+                                            ds_child(1),ds_parent(1))
+        enddo
+    ENDIF
+!
+    tabtemp_trsp = TRANSPOSE(tabtemp)
+    coeffraf = nint(ds_parent(2)/ds_child(2))
+!
+    tempP_trsp = 0.
+!
+    IF((type_update(2) == Agrif_Update_Average) .AND. (coeffraf /= 1 )) THEN
+!---CDIR NEXPAND
+        if ( .NOT. precomputedone(2) ) then
+            call Average1dPrecompute( indmax(1)-indmin(1)+1,          &
+                                      indmax(2)-indmin(2)+1,          &
+                                      ub_child(2)-lb_child(2)+1,&
+                                      s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+!            precomputedone(2) = .TRUE.
+        endif
+!---CDIR NEXPAND
+        call Average1dAfterCompute( tempP_trsp, tabtemp_trsp, size(tempP_trsp), size(tabtemp_trsp),&
+                s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+!
+    ELSE IF ((type_update(2) == Agrif_Update_Copy) .AND. (coeffraf /= 1 )) THEN
+!---CDIR NEXPAND
+        if ( .NOT. precomputedone(2) ) then
+            call Agrif_basicupdate_copy1d_before( indmax(1)-indmin(1)+1,             &
+                                   indmax(2)-indmin(2)+1,             &
+                                   ub_child(2)-lb_child(2)+1,   &
+                                   s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+!            precomputedone(2) = .TRUE.
+        endif
+!---CDIR NEXPAND
+        call Agrif_basicupdate_copy1d_after( tempP_trsp, tabtemp_trsp, size(tempP_trsp), size(tabtemp_trsp),2)
+!
+    ELSE
+        do i = indmin(1),indmax(1)
+!
+!---CDIR NEXPAND
+            call Agrif_UpdateBase(type_update(2),                                       &
+                                  tempP_trsp(indmin(2):indmax(2),i),            &
+                                  tabtemp_trsp(lb_child(2):ub_child(2),i),&
+                                  indmin(2),indmax(2),                          &
+                                  lb_child(2),ub_child(2),                &
+                                  s_parent(2),s_child(2),                       &
+                                  ds_parent(2),ds_child(2))
+!
+        enddo
+    ENDIF
+!
+    tempP = TRANSPOSE(tempP_trsp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_2D_Recursive
+!===================================================================================================
+!
+subroutine Agrif_Update_2D_Recursive_ok ( type_update, &
+                                        tempP, tempC, &
+                                        indmin, indmax,   &
+                                       lb_child, ub_child,                    &
+                                       s_child, s_parent, ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    INTEGER, DIMENSION(2), intent(in)   :: type_update            !< Type of update (copy or average)
+    INTEGER, DIMENSION(2), intent(in)   :: indmin, indmax
+    INTEGER, DIMENSION(2), intent(in)   :: lb_child, ub_child
+    REAL,    DIMENSION(2), intent(in)   :: s_child,  s_parent
+    REAL,    DIMENSION(2), intent(in)   :: ds_child, ds_parent
+    REAL,    DIMENSION(                 &
+                indmin(1):indmax(1),    &
+                indmin(2):indmax(2)),           intent(out) :: tempP
+    REAL, DIMENSION(                            &
+                lb_child(1):ub_child(1),  &
+                lb_child(2):ub_child(2)), intent(in)  :: tempC
+!
+    REAL, DIMENSION(indmin(1):indmax(1), lb_child(2):ub_child(2)) :: tabtemp
+    INTEGER :: i
+!
+    do i = lb_child(2),ub_child(2)
+        call Agrif_Update_1D_Recursive(type_update(1),                              &
+                                       tabtemp(:, i),          &
+                                       tempC(:,i),  &
+                                       indmin(1),indmax(1),                 &
+                                       lb_child(1),ub_child(1),       &
+                                       s_child(1), s_parent(1),             &
+                                      ds_child(1),ds_parent(1))
+    enddo
+!
+    tempP = 0.
+!
+    do i = indmin(1),indmax(1)
+        call Agrif_UpdateBase(type_update(2),                                       &
+                              tempP(i,:),             &
+                              tabtemp(i,:), &
+                              indmin(2),indmax(2),                          &
+                              lb_child(2),ub_child(2),                &
+                              s_parent(2),s_child(2),                       &
+                             ds_parent(2),ds_child(2))
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_2D_Recursive_ok
+!===================================================================================================
+
+!
+!===================================================================================================
+!  subroutine Agrif_Update_3D_Recursive
+!
+!> Updates a 3D grid variable on the parent grid.
+!! Calls #Agrif_Update_2D_Recursive and #Agrif_UpdateBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_3D_Recursive ( type_update,         &
+                                       tempP, tempC,        &
+                                       indmin, indmax,      &
+                                       lb_child, ub_child,  &
+                                        s_child,  s_parent, &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(3),          intent(in)  :: type_update            !< Type of update (copy or average)
+    integer, dimension(3),          intent(in)  :: indmin, indmax
+    integer, dimension(3),          intent(in)  :: lb_child, ub_child
+    real,    dimension(3),          intent(in)  ::  s_child,  s_parent
+    real,    dimension(3),          intent(in)  :: ds_child, ds_parent
+    real,    dimension(          &
+        indmin(1):indmax(1),     &
+        indmin(2):indmax(2),     &
+        indmin(3):indmax(3)),       intent(out) :: tempP
+    real, dimension(             &
+        lb_child(1):ub_child(1), &
+        lb_child(2):ub_child(2), &
+        lb_child(3):ub_child(3)),   intent(in)  :: tempC
+!---------------------------------------------------------------------------------------------------
+    real, dimension(            &
+        indmin(1):indmax(1),    &
+        indmin(2):indmax(2),    &
+        lb_child(3):ub_child(3))    :: tabtemp
+    integer :: i,j,k
+    integer :: coeffraf,locind_child_left
+    integer :: kuinf
+!
+    coeffraf = nint ( ds_parent(1) / ds_child(1) )
+!
+    if ((type_update(1) == Agrif_Update_Average) .AND. (coeffraf /= 1 )) then
+!---CDIR NEXPAND
+        call Average1dPrecompute(ub_child(2)-lb_child(2)+1,&
+                                 indmax(1)-indmin(1)+1,&
+                                 ub_child(1)-lb_child(1)+1,&
+                                 s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+        precomputedone(1) = .TRUE.
+    else if ((type_update(1) == Agrif_Update_Copy) .AND. (coeffraf /= 1 )) then
+!---CDIR NEXPAND
+         call Agrif_basicupdate_copy1d_before(ub_child(2)-lb_child(2)+1, &
+                               indmax(1)-indmin(1)+1,           &
+                               ub_child(1)-lb_child(1)+1, &
+                               s_parent(1),s_child(1),ds_parent(1),ds_child(1),1)
+        precomputedone(1) = .TRUE.
+    endif
+!
+    coeffraf = nint ( ds_parent(2) / ds_child(2) )
+!
+    if ((type_update(2) == Agrif_Update_Average) .AND. (coeffraf /= 1 )) then
+!---CDIR NEXPAND
+        call Average1dPrecompute(indmax(1)-indmin(1)+1,&
+                                 indmax(2)-indmin(2)+1,&
+                                 ub_child(2)-lb_child(2)+1,&
+                                 s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+        precomputedone(2) = .TRUE.
+    else if ((type_update(2) == Agrif_Update_Copy) .AND. (coeffraf /= 1 )) then
+!---CDIR NEXPAND
+        call Agrif_basicupdate_copy1d_before( indmax(1)-indmin(1)+1,           &
+                               indmax(2)-indmin(2)+1,           &
+                               ub_child(2)-lb_child(2)+1, &
+                               s_parent(2),s_child(2),ds_parent(2),ds_child(2),2)
+        precomputedone(2) = .TRUE.
+    endif
+!
+    do k = lb_child(3),ub_child(3)
+        call Agrif_Update_2D_Recursive( type_update(1:2),tabtemp(:,:,k),tempC(:,:,k), &
+                                        indmin(1:2),indmax(1:2),                &
+                                        lb_child(1:2),ub_child(1:2),      &
+                                        s_child(1:2),s_parent(1:2),             &
+                                        ds_child(1:2),ds_parent(1:2) )
+    enddo
+!
+    precomputedone(1) = .FALSE.
+    precomputedone(2) = .FALSE.
+!
+    coeffraf = nint ( ds_parent(3) / ds_child(3) )
+    locind_child_left = 1 + agrif_int((s_parent(3)-s_child(3))/ds_child(3))
+!
+    if (coeffraf == 1) then
+        kuinf = lb_child(3)+locind_child_left-2
+        do k=indmin(3),indmax(3)
+            kuinf = kuinf + 1
+            do j = indmin(2),indmax(2)
+            do i = indmin(1),indmax(1)
+                tempP(i,j,k) = tabtemp(i,j,kuinf)
+            enddo
+            enddo
+        enddo
+    else
+        tempP = 0.
+        do j = indmin(2),indmax(2)
+        do i = indmin(1),indmax(1)
+            call Agrif_UpdateBase(type_update(3),tempP(i,j,:),tabtemp(i,j,:),   &
+                                  indmin(3),indmax(3),                  &
+                                  lb_child(3),ub_child(3),        &
+                                  s_parent(3),s_child(3),               &
+                                  ds_parent(3),ds_child(3))
+!
+        enddo
+        enddo
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_3D_Recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Update_4D_Recursive
+!
+!> Updates a 4D grid variable on the parent grid.
+!! Calls #Agrif_Update_3D_Recursive and #Agrif_UpdateBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_4D_Recursive ( type_update,         &
+                                       tempP, tempC,        &
+                                       indmin, indmax,      &
+                                       lb_child, ub_child,  &
+                                        s_child,  s_parent, &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(4),          intent(in)  :: type_update            !< Type of update (copy or average)
+    integer, dimension(4),          intent(in)  :: indmin, indmax
+    integer, dimension(4),          intent(in)  :: lb_child, ub_child
+    real,    dimension(4),          intent(in)  ::  s_child,  s_parent
+    real,    dimension(4),          intent(in)  :: ds_child, ds_parent
+    real,    dimension(          &
+        indmin(1):indmax(1),     &
+        indmin(2):indmax(2),     &
+        indmin(3):indmax(3),     &
+        indmin(4):indmax(4)),       intent(out) :: tempP
+    real, dimension(             &
+        lb_child(1):ub_child(1), &
+        lb_child(2):ub_child(2), &
+        lb_child(3):ub_child(3), &
+        lb_child(4):ub_child(4)),   intent(in)  :: tempC
+!---------------------------------------------------------------------------------------------------
+    real, dimension(:,:,:,:), allocatable       :: tabtemp
+    integer :: i,j,k,l
+!
+    allocate(tabtemp(indmin(1):indmax(1), &
+                     indmin(2):indmax(2), &
+                     indmin(3):indmax(3), &
+                     lb_child(4):ub_child(4)))
+!
+    do l = lb_child(4), ub_child(4)
+        call Agrif_Update_3D_Recursive(type_update(1:3),                    &
+                                       tabtemp(indmin(1):indmax(1),         &
+                                               indmin(2):indmax(2),         &
+                                               indmin(3):indmax(3), l),     &
+                                       tempC(lb_child(1):ub_child(1),       &
+                                             lb_child(2):ub_child(2),       &
+                                             lb_child(3):ub_child(3), l),   &
+                                       indmin(1:3), indmax(1:3),            &
+                                       lb_child(1:3), ub_child(1:3),        &
+                                        s_child(1:3),  s_parent(1:3),       &
+                                       ds_child(1:3), ds_parent(1:3))
+    enddo
+!
+    tempP = 0.
+!
+    do k = indmin(3), indmax(3)
+    do j = indmin(2), indmax(2)
+    do i = indmin(1), indmax(1)
+        call Agrif_UpdateBase(type_update(4),                               &
+                              tempP(i,j,k,indmin(4):indmax(4)),             &
+                              tabtemp(i,j,k,lb_child(4):ub_child(4)),       &
+                              indmin(4), indmax(4),                         &
+                              lb_child(4), ub_child(4),                     &
+                               s_parent(4), s_child(4),                     &
+                              ds_parent(4),ds_child(4) )
+    enddo
+    enddo
+    enddo
+!
+    deallocate(tabtemp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_4D_Recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Update_5D_Recursive
+!
+!> Updates a 5D grid variable on the parent grid.
+!! Calls #Agrif_Update_4D_Recursive and #Agrif_UpdateBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_5D_Recursive ( type_update,         &
+                                       tempP, tempC,        &
+                                       indmin, indmax,      &
+                                       lb_child, ub_child,  &
+                                        s_child,  s_parent, &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(5),          intent(in)  :: type_update            !< Type of update (copy or average)
+    integer, dimension(5),          intent(in)  :: indmin, indmax
+    integer, dimension(5),          intent(in)  :: lb_child, ub_child
+    real,    dimension(5),          intent(in)  ::  s_child,  s_parent
+    real,    dimension(5),          intent(in)  :: ds_child, ds_parent
+    real,    dimension(          &
+        indmin(1):indmax(1),     &
+        indmin(2):indmax(2),     &
+        indmin(3):indmax(3),     &
+        indmin(4):indmax(4),     &
+        indmin(5):indmax(5)),       intent(out) :: tempP
+    real, dimension(             &
+        lb_child(1):ub_child(1), &
+        lb_child(2):ub_child(2), &
+        lb_child(3):ub_child(3), &
+        lb_child(4):ub_child(4), &
+        lb_child(5):ub_child(5)),   intent(in)  :: tempC
+!---------------------------------------------------------------------------------------------------
+    real, dimension(:,:,:,:,:), allocatable     :: tabtemp
+    integer :: i,j,k,l,m
+!
+    allocate(tabtemp(indmin(1):indmax(1), &
+                     indmin(2):indmax(2), &
+                     indmin(3):indmax(3), &
+                     indmin(4):indmax(4), &
+                     lb_child(5):ub_child(5)))
+!
+    do m = lb_child(5), ub_child(5)
+        call Agrif_Update_4D_Recursive(type_update(1:4),                    &
+                                       tabtemp(indmin(1):indmax(1),         &
+                                               indmin(2):indmax(2),         &
+                                               indmin(3):indmax(3),         &
+                                               indmin(4):indmax(4), m),     &
+                                       tempC(lb_child(1):ub_child(1),       &
+                                             lb_child(2):ub_child(2),       &
+                                             lb_child(3):ub_child(3),       &
+                                             lb_child(4):ub_child(4), m),   &
+                                       indmin(1:4),indmax(1:4),             &
+                                       lb_child(1:4), ub_child(1:4),        &
+                                        s_child(1:4), s_parent(1:4),        &
+                                       ds_child(1:4), ds_parent(1:4))
+    enddo
+!
+    tempP = 0.
+!
+    do l = indmin(4), indmax(4)
+    do k = indmin(3), indmax(3)
+    do j = indmin(2), indmax(2)
+    do i = indmin(1), indmax(1)
+        call Agrif_UpdateBase( type_update(5),                              &
+                               tempP(i,j,k,l,indmin(5):indmax(5)),          &
+                               tabtemp(i,j,k,l,lb_child(5):ub_child(5)),    &
+                               indmin(5), indmax(5),                        &
+                               lb_child(5), ub_child(5),                    &
+                                s_parent(5), s_child(5),                    &
+                               ds_parent(5),ds_child(5) )
+    enddo
+    enddo
+    enddo
+    enddo
+!
+    deallocate(tabtemp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_5D_Recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Update_6D_Recursive
+!
+!> Updates a 6D grid variable on the parent grid.
+!! Calls #Agrif_Update_5D_Recursive and #Agrif_UpdateBase.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Update_6D_Recursive ( type_update,         &
+                                       tempP, tempC,        &
+                                       indmin, indmax,      &
+                                       lb_child, ub_child,  &
+                                        s_child,  s_parent, &
+                                       ds_child, ds_parent )
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(6),          intent(in)  :: type_update            !< Type of update (copy or average)
+    integer, dimension(6),          intent(in)  :: indmin, indmax
+    integer, dimension(6),          intent(in)  :: lb_child, ub_child
+    real,    dimension(6),          intent(in)  ::  s_child,  s_parent
+    real,    dimension(6),          intent(in)  :: ds_child, ds_parent
+    real,    dimension(          &
+        indmin(1):indmax(1),     &
+        indmin(2):indmax(2),     &
+        indmin(3):indmax(3),     &
+        indmin(4):indmax(4),     &
+        indmin(5):indmax(5),     &
+        indmin(6):indmax(6)),       intent(out) :: tempP
+    real, dimension(             &
+        lb_child(1):ub_child(1), &
+        lb_child(2):ub_child(2), &
+        lb_child(3):ub_child(3), &
+        lb_child(4):ub_child(4), &
+        lb_child(5):ub_child(5), &
+        lb_child(6):ub_child(6)),   intent(in)  :: tempC
+!---------------------------------------------------------------------------------------------------
+    real, dimension(:,:,:,:,:,:), allocatable   :: tabtemp
+    integer :: i,j,k,l,m,n
+!
+    allocate(tabtemp(indmin(1):indmax(1), &
+                     indmin(2):indmax(2), &
+                     indmin(3):indmax(3), &
+                     indmin(4):indmax(4), &
+                     indmin(5):indmax(5), &
+                     lb_child(6):ub_child(6)))
+!
+    do n = lb_child(6),ub_child(6)
+        call Agrif_Update_5D_Recursive(type_update(1:5),                    &
+                                       tabtemp(indmin(1):indmax(1),         &
+                                               indmin(2):indmax(2),         &
+                                               indmin(3):indmax(3),         &
+                                               indmin(4):indmax(4),         &
+                                               indmin(5):indmax(5), n),     &
+                                       tempC(lb_child(1):ub_child(1),       &
+                                             lb_child(2):ub_child(2),       &
+                                             lb_child(3):ub_child(3),       &
+                                             lb_child(4):ub_child(4),       &
+                                             lb_child(5):ub_child(5), n),   &
+                                       indmin(1:5), indmax(1:5),            &
+                                       lb_child(1:5),ub_child(1:5),         &
+                                       s_child(1:5), s_parent(1:5),         &
+                                      ds_child(1:5),ds_parent(1:5))
+    enddo
+!
+    tempP = 0.
+!
+    do m = indmin(5), indmax(5)
+    do l = indmin(4), indmax(4)
+    do k = indmin(3), indmax(3)
+    do j = indmin(2), indmax(2)
+    do i = indmin(1), indmax(1)
+        call Agrif_UpdateBase( type_update(6),                              &
+                               tempP(i,j,k,l,m,indmin(6):indmax(6)),        &
+                               tabtemp(i,j,k,l,m,lb_child(6):ub_child(6)),  &
+                               indmin(6), indmax(6),                        &
+                               lb_child(6),  ub_child(6),                   &
+                                s_parent(6),  s_child(6),                   &
+                               ds_parent(6), ds_child(6) )
+    enddo
+    enddo
+    enddo
+    enddo
+    enddo
+!
+    deallocate(tabtemp)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Update_6D_Recursive
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_UpdateBase
+!
+!> Calls the updating method chosen by the user (copy, average or full-weighting).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_UpdateBase ( type_update,              &
+                              parent_tab, child_tab,    &
+                              indmin, indmax,           &
+                              lb_child, ub_child,       &
+                              s_parent, s_child,        &
+                              ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    integer,                            intent(in) :: type_update
+    integer,                            intent(in) :: indmin, indmax
+    integer,                            intent(in) :: lb_child, ub_child
+    real, dimension(indmin:indmax),     intent(out):: parent_tab
+    real, dimension(lb_child:ub_child), intent(in) :: child_tab
+    real,                               intent(in) :: s_parent,  s_child
+    real,                               intent(in) :: ds_parent, ds_child
+!---------------------------------------------------------------------------------------------------
+    integer :: np       ! Length of parent array
+    integer :: nc       ! Length of child  array
+!
+    np = indmax - indmin + 1
+    nc = ub_child - lb_child + 1
+!
+    if     ( type_update == Agrif_Update_Copy ) then
+!
+        call Agrif_basicupdate_copy1d(              &
+                    parent_tab, child_tab,          &
+                    np,         nc,                 &
+                    s_parent,  s_child,             &
+                    ds_parent, ds_child )
+!
+    elseif ( type_update == Agrif_Update_Average ) then
+!
+        call Agrif_basicupdate_average1d(           &
+                    parent_tab, child_tab,          &
+                    np,         nc,                 &
+                     s_parent,  s_child,            &
+                    ds_parent, ds_child )
+!
+    elseif ( type_update == Agrif_Update_Full_Weighting ) then
+!
+        call Agrif_basicupdate_full_weighting1D(    &
+                    parent_tab, child_tab,          &
+                    np,         nc,                 &
+                    s_parent,  s_child,             &
+                    ds_parent, ds_child )
+!
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_UpdateBase
+!===================================================================================================
+!
+#if defined AGRIF_MPI
+!===================================================================================================
+!  subroutine Agrif_Find_list_update
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Find_list_update ( list_update, pttab, petab, lb_child, lb_parent, nbdim, &
+                                    find_list_update, tab4t, tab5t, memberinall, memberinall2,   &
+                                    sendtoproc1, recvfromproc1, sendtoproc2, recvfromproc2 )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_List_Interp_Loc),                   pointer     :: list_update
+    INTEGER,                                       intent(in)  :: nbdim
+    INTEGER, DIMENSION(nbdim),                     intent(in)  :: pttab, petab
+    INTEGER, DIMENSION(nbdim),                     intent(in)  :: lb_child, lb_parent
+    LOGICAL,                                       intent(out) :: find_list_update
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1,8), intent(out) :: tab4t
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1,8), intent(out) :: tab5t
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1), intent(out) :: memberinall,memberinall2
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1), intent(out) :: sendtoproc1,recvfromproc1
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1), intent(out) :: sendtoproc2,recvfromproc2
+!
+    Type(Agrif_List_Interp_Loc), Pointer :: parcours
+    INTEGER :: i
+!
+    find_list_update = .FALSE.
+!
+    parcours => list_update
+
+    Find_loop :  do while ( associated(parcours) )
+        do i = 1,nbdim
+            IF ((pttab(i) /= parcours%interp_loc%pttab(i)) .OR. &
+                (petab(i) /= parcours%interp_loc%petab(i)) .OR. &
+                (lb_child(i)  /= parcours%interp_loc%pttab_child(i)) .OR. &
+                (lb_parent(i) /= parcours%interp_loc%pttab_parent(i))) THEN
+                parcours => parcours%suiv
+                cycle Find_loop
+            ENDIF
+        enddo
+!
+        tab4t = parcours%interp_loc%tab4t(1:nbdim,0:Agrif_Nbprocs-1,1:8)
+        tab5t = parcours%interp_loc%tab5t(1:nbdim,0:Agrif_Nbprocs-1,1:8)
+        memberinall  =  parcours%interp_loc%memberinall(0:Agrif_Nbprocs-1)
+        memberinall2 =  parcours%interp_loc%memberinall2(0:Agrif_Nbprocs-1)
+        sendtoproc1 =   parcours%interp_loc%sendtoproc1(0:Agrif_Nbprocs-1)
+        sendtoproc2 =   parcours%interp_loc%sendtoproc2(0:Agrif_Nbprocs-1)
+        recvfromproc1 = parcours%interp_loc%recvfromproc1(0:Agrif_Nbprocs-1)
+        recvfromproc2 = parcours%interp_loc%recvfromproc2(0:Agrif_Nbprocs-1)
+!
+        find_list_update = .TRUE.
+        exit Find_loop
+!
+    enddo Find_loop
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Find_list_update
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_AddTo_list_update
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_AddTo_list_update ( list_update, pttab, petab, lb_child, lb_parent,  &
+                                     nbdim, tab4t, tab5t, memberinall, memberinall2,        &
+                                     sendtoproc1, recvfromproc1, sendtoproc2, recvfromproc2 )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_List_Interp_Loc), pointer :: list_update
+    INTEGER,                                        intent(in) :: nbdim
+    INTEGER, DIMENSION(nbdim),                      intent(in) :: pttab, petab
+    INTEGER, DIMENSION(nbdim),                      intent(in) :: lb_child, lb_parent
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1,8),  intent(in) :: tab4t
+    INTEGER, DIMENSION(nbdim,0:Agrif_Nbprocs-1,8),  intent(in) :: tab5t
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),          intent(in) :: memberinall, memberinall2
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),          intent(in) :: sendtoproc1, recvfromproc1
+    LOGICAL, DIMENSION(0:Agrif_Nbprocs-1),          intent(in) :: sendtoproc2, recvfromproc2
+!
+    Type(Agrif_List_Interp_Loc), pointer :: parcours
+!
+    allocate(parcours)
+    allocate(parcours%interp_loc)
+
+    parcours%interp_loc%pttab(1:nbdim) = pttab(1:nbdim)
+    parcours%interp_loc%petab(1:nbdim) = petab(1:nbdim)
+    parcours%interp_loc%pttab_child(1:nbdim)  = lb_child(1:nbdim)
+    parcours%interp_loc%pttab_parent(1:nbdim) = lb_parent(1:nbdim)
+
+    allocate(parcours%interp_loc%tab4t(nbdim,0:Agrif_Nbprocs-1,8))
+    allocate(parcours%interp_loc%tab5t(nbdim,0:Agrif_Nbprocs-1,8))
+
+    allocate(parcours%interp_loc%memberinall (0:Agrif_Nbprocs-1))
+    allocate(parcours%interp_loc%memberinall2(0:Agrif_Nbprocs-1))
+
+    allocate(parcours%interp_loc%recvfromproc1(0:Agrif_Nbprocs-1))
+    allocate(parcours%interp_loc%recvfromproc2(0:Agrif_Nbprocs-1))
+    allocate(parcours%interp_loc%sendtoproc1(0:Agrif_Nbprocs-1))
+    allocate(parcours%interp_loc%sendtoproc2(0:Agrif_Nbprocs-1))
+
+    parcours%interp_loc%tab4t = tab4t
+    parcours%interp_loc%tab5t = tab5t
+    parcours%interp_loc%memberinall   = memberinall
+    parcours%interp_loc%memberinall2  = memberinall2
+    parcours%interp_loc%sendtoproc1   = sendtoproc1
+    parcours%interp_loc%sendtoproc2   = sendtoproc2
+    parcours%interp_loc%recvfromproc1 = recvfromproc1
+    parcours%interp_loc%recvfromproc2 = recvfromproc2
+
+    parcours%suiv => list_update
+    list_update => parcours
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Addto_list_update
+!===================================================================================================
+#endif
+!
+end module Agrif_Update
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modupdatebasic.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modupdatebasic.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modupdatebasic.F90	(revision 9987)
@@ -0,0 +1,434 @@
+!
+! $Id$
+!
+!     AGRIF (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place -  Suite 330, Boston, MA 02111-1307, USA.
+!
+!
+!
+!> Module containing different procedures of update (copy, average, full_weighting)
+!! used in the #Agrif_Update module.
+!===================================================================================================
+!
+module Agrif_UpdateBasic
+!
+    use Agrif_Types
+
+    implicit none
+
+    integer, dimension(:,:), allocatable :: indchildcopy
+    integer, dimension(:,:), allocatable :: indchildaverage
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_basicupdate_copy1d
+!
+!> Carries out a copy on a parent grid (vector x) from its child grid (vector y).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_basicupdate_copy1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(np), intent(out)    :: x            !< Coarse output data to parent
+    real, dimension(nc), intent(in)     :: y            !< Fine input data from child
+    integer,             intent(in)     :: np           !< Length of parent array
+    integer,             intent(in)     :: nc           !< Length of child  array
+    real,                intent(in)     :: s_parent     !< Parent grid position (s_root = 0)
+    real,                intent(in)     :: s_child      !< Child  grid position (s_root = 0)
+    real,                intent(in)     :: ds_parent    !< Parent grid dx (ds_root = 1)
+    real,                intent(in)     :: ds_child     !< Child  grid dx (ds_root = 1)
+!---------------------------------------------------------------------------------------------------
+    integer :: i, locind_child_left, coeffraf
+!
+    coeffraf = nint(ds_parent/ds_child)
+    locind_child_left = 1 + nint((s_parent - s_child)/ds_child)
+!
+    if ( coeffraf == 1 ) then
+!CDIR ALTCODE
+        x(1:np) = y(locind_child_left:locind_child_left+np-1)
+        return
+    endif
+!
+!CDIR ALTCODE
+    do i = 1,np
+        x(i) = y(locind_child_left)
+        locind_child_left = locind_child_left + coeffraf
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_basicupdate_copy1d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_basicupdate_copy1d_before
+!
+!> Precomputes index for a copy on a parent grid (vector x) from its child grid (vector y).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_basicupdate_copy1d_before ( nc2, np, nc, s_parent, s_child, ds_parent, ds_child, dir )
+!---------------------------------------------------------------------------------------------------
+    integer,             intent(in)     :: nc2          !< Length of parent array
+    integer,             intent(in)     :: np           !< Length of parent array
+    integer,             intent(in)     :: nc           !< Length of child  array
+    real,                intent(in)     :: s_parent     !< Parent grid position (s_root = 0)
+    real,                intent(in)     :: s_child      !< Child  grid position (s_root = 0)
+    real,                intent(in)     :: ds_parent    !< Parent grid dx (ds_root = 1)
+    real,                intent(in)     :: ds_child     !< Child  grid dx (ds_root = 1)
+    integer,             intent(in)     :: dir          !< Direction
+!---------------------------------------------------------------------------------------------------
+    integer, dimension(:,:), allocatable    :: indchildcopy_tmp
+    integer :: i, n_old, locind_child_left, coeffraf
+!
+    coeffraf = nint(ds_parent/ds_child)
+!
+    locind_child_left = 1 + nint((s_parent - s_child)/ds_child)
+
+    if ( .not.allocated(indchildcopy) ) then
+        allocate(indchildcopy(np*nc2, 3))
+    else
+        n_old = size(indchildcopy,1)
+        if ( n_old < np*nc2 ) then
+            allocate( indchildcopy_tmp(1:n_old, 3))
+            indchildcopy_tmp = indchildcopy
+            deallocate(indchildcopy)
+            allocate(indchildcopy(np*nc2, 3))
+            indchildcopy(1:n_old,:) = indchildcopy_tmp
+            deallocate(indchildcopy_tmp)
+        endif
+    endif
+!
+    do i = 1,np
+        indchildcopy(i,dir) = locind_child_left
+        locind_child_left = locind_child_left + coeffraf
+    enddo
+!
+    do i = 2,nc2
+        indchildcopy(1+(i-1)*np:i*np,dir) = indchildcopy(1+(i-2)*np:(i-1)*np,dir) + nc
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_basicupdate_copy1d_before
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_basicupdate_copy1d_after
+!
+!> Carries out a copy on a parent grid (vector x) from its child grid (vector y)
+!! using precomputed index.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_basicupdate_copy1d_after ( x, y, np, nc, dir )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(np), intent(out)    :: x            !< Coarse output data to parent
+    real, dimension(nc), intent(in)     :: y            !< Fine input data from child
+    integer,             intent(in)     :: np           !< Length of parent array
+    integer,             intent(in)     :: nc           !< Length of child  array
+    integer,             intent(in)     :: dir          !< Direction
+!---------------------------------------------------------------------------------------------------
+    integer :: i
+!
+!CDIR ALTCODE
+    do i = 1,np
+        x(i) = y(indchildcopy(i,dir))
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_basicupdate_copy1d_after
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_basicupdate_average1d
+!
+!> Carries out an update by average on a parent grid (vector x)from its child grid (vector y).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_basicupdate_average1d ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    REAL, DIMENSION(np), intent(out)    :: x
+    REAL, DIMENSION(nc), intent(in)     :: y
+    INTEGER,             intent(in)     :: np,nc
+    REAL,                intent(in)     :: s_parent,  s_child
+    REAL,                intent(in)     :: ds_parent, ds_child
+!
+    INTEGER :: i, ii, locind_child_left, coeffraf
+    REAL    :: xpos, invcoeffraf
+    INTEGER :: nbnonnuls
+    INTEGER :: diffmod
+!
+    coeffraf = nint(ds_parent/ds_child)
+    invcoeffraf = 1./coeffraf
+!
+    if (coeffraf == 1) then
+        locind_child_left = 1 + nint((s_parent - s_child)/ds_child)
+        x(1:np) = y(locind_child_left:locind_child_left+np-1)
+        return
+    endif
+!
+    xpos = s_parent
+    x = 0.
+!
+    diffmod = 0
+!
+    IF ( mod(coeffraf,2) == 0 ) diffmod = 1
+!
+    locind_child_left = 1 + agrif_int((xpos - s_child)/ds_child)
+!
+    IF (Agrif_UseSpecialValueInUpdate) THEN
+        do i = 1,np
+            nbnonnuls = 0
+!CDIR NOVECTOR
+            do ii = -coeffraf/2+locind_child_left+diffmod, &
+                     coeffraf/2+locind_child_left
+                IF (y(ii) /= Agrif_SpecialValueFineGrid) THEN
+!                    nbnonnuls = nbnonnuls + 1
+                    x(i) = x(i) + y(ii)
+                ENDIF
+            enddo
+!            IF (nbnonnuls /= 0) THEN
+!                x(i) = x(i)/nbnonnuls
+!            ELSE
+!                x(i) = Agrif_SpecialValueFineGrid
+!            ENDIF
+            locind_child_left = locind_child_left + coeffraf
+        enddo
+    ELSE
+!
+!CDIR ALTCODE
+        do i = 1,np
+!CDIR NOVECTOR
+            do ii = -coeffraf/2+locind_child_left+diffmod, &
+                     coeffraf/2+locind_child_left
+                x(i) = x(i) + y(ii)
+            enddo
+!            x(i) = x(i)*invcoeffraf
+            locind_child_left = locind_child_left + coeffraf
+        enddo
+        IF (.not.Agrif_Update_Weights) THEN
+           x = x * invcoeffraf
+        ENDIF
+    ENDIF
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_basicupdate_average1d
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Average1dPrecompute
+!
+!> Carries out an update by average on a parent grid (vector x)from its child grid (vector y).
+!---------------------------------------------------------------------------------------------------
+subroutine Average1dPrecompute ( nc2, np, nc, s_parent, s_child, ds_parent, ds_child, dir )
+!---------------------------------------------------------------------------------------------------
+    INTEGER, intent(in) :: nc2, np, nc
+    REAL,    intent(in) :: s_parent,  s_child
+    REAL,    intent(in) :: ds_parent, ds_child
+    INTEGER, intent(in) :: dir
+!
+    INTEGER, DIMENSION(:,:), ALLOCATABLE :: indchildaverage_tmp
+    INTEGER :: i, locind_child_left, coeffraf
+    REAL    :: xpos
+    INTEGER :: diffmod
+!
+    coeffraf = nint(ds_parent/ds_child)
+    xpos = s_parent
+    diffmod = 0
+!
+    IF ( mod(coeffraf,2) == 0 ) diffmod = 1
+!
+    locind_child_left = 1 + agrif_int((xpos - s_child)/ds_child)
+!
+    if (.not.allocated(indchildaverage)) then
+        allocate(indchildaverage(np*nc2,3))
+    else
+        if (size(indchildaverage,1)<np*nc2) then
+            allocate( indchildaverage_tmp(size(indchildaverage,1),size(indchildaverage,2)))
+            indchildaverage_tmp = indchildaverage
+            deallocate(indchildaverage)
+            allocate(indchildaverage(np*nc2,3))
+            indchildaverage(1:size(indchildaverage_tmp,1),1:size(indchildaverage_tmp,2)) = indchildaverage_tmp
+            deallocate(indchildaverage_tmp)
+        endif
+    endif
+!
+    do i = 1,np
+        indchildaverage(i,dir)= -coeffraf/2+locind_child_left+diffmod
+        locind_child_left = locind_child_left + coeffraf
+    enddo
+!
+    do i = 2,nc2
+        indchildaverage(1+(i-1)*np:i*np,dir) = indchildaverage(1+(i-2)*np:(i-1)*np,dir) + nc
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Average1dPrecompute
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Average1dAfterCompute
+!
+!> Carries out an update by average on a parent grid (vector x) from its child grid (vector y).
+!---------------------------------------------------------------------------------------------------
+subroutine Average1dAfterCompute ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child, dir )
+!---------------------------------------------------------------------------------------------------
+    REAL, DIMENSION(np), intent(inout)  :: x
+    REAL, DIMENSION(nc), intent(in)     :: y
+    INTEGER,             intent(in)     :: np, nc
+    REAL,                intent(in)     :: s_parent,  s_child
+    REAL,                intent(in)     :: ds_parent, ds_child
+    INTEGER,             intent(in)     :: dir
+!
+    REAL    :: invcoeffraf
+    INTEGER :: i, j, coeffraf
+    INTEGER, DIMENSION(np) :: nbnonnuls
+    REAL, DIMENSION(0:7), parameter :: invcoeff = (/1.,1.,0.5,1./3.,0.25,0.2,1./6.,1./7./)
+!
+    coeffraf = nint(ds_parent/ds_child)
+    invcoeffraf = 1./coeffraf
+!
+    IF (Agrif_UseSpecialValueInUpdate) THEN
+!
+!        nbnonnuls = 0
+        do  j = 1,coeffraf
+            do i = 1,np
+                IF (y(indchildaverage(i,dir) + j -1) /= Agrif_SpecialValueFineGrid) THEN
+!                    nbnonnuls(i) = nbnonnuls(i) + 1
+                    x(i) = x(i) +  y(indchildaverage(i,dir) + j-1 )
+                ENDIF
+            enddo
+        enddo
+        do i=1,np
+  !          x(i) = x(i)*invcoeff(nbnonnuls(i))
+  !          if (nbnonnuls(i) == 0) x(i) = Agrif_SpecialValueFineGrid
+        enddo
+!
+    ELSE
+!
+!CDIR NOLOOPCHG
+        do  j = 1,coeffraf
+!CDIR VECTOR
+            do i= 1,np
+                x(i) = x(i) + y(indchildaverage(i,dir) + j-1 )
+            enddo
+        enddo
+        IF (.not.Agrif_Update_Weights) THEN
+           x = x * invcoeffraf
+        ENDIF
+!
+    ENDIF
+
+!---------------------------------------------------------------------------------------------------
+end subroutine Average1dAfterCompute
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_basicupdate_full_weighting1D
+!
+!> Carries out an update by full_weighting on a parent grid (vector x) from its child grid (vector y).
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_basicupdate_full_weighting1D ( x, y, np, nc, s_parent, s_child, ds_parent, ds_child )
+!---------------------------------------------------------------------------------------------------
+    real, dimension(np), intent(out)    :: x
+    real, dimension(nc), intent(in)     :: y
+    integer,             intent(in)     :: np, nc
+    real,                intent(in)     :: s_parent,  s_child
+    real,                intent(in)     :: ds_parent, ds_child
+!---------------------------------------------------------------------------------------------------
+    REAL    :: xpos, xposfin
+    INTEGER :: i, ii, diffmod
+    INTEGER :: it1, it2
+    INTEGER :: i1,  i2
+    INTEGER :: coeffraf
+    INTEGER :: locind_child_left
+    REAL    :: sumweight, invsumweight
+    REAL    :: weights(-Agrif_MaxRaff:Agrif_MaxRaff)
+
+    coeffraf = nint(ds_parent/ds_child)
+    locind_child_left = 1 + agrif_int((s_parent-s_child)/ds_child)
+!
+    if (coeffraf == 1) then
+        x(1:np) = y(locind_child_left:locind_child_left+np-1)
+        return
+    endif
+!
+    xpos = s_parent
+    x = 0.
+!
+    xposfin = s_child + ds_child * (locind_child_left - 1)
+    IF (abs(xposfin - xpos) < 0.001) THEN
+        diffmod = 0
+    ELSE
+        diffmod = 1
+    ENDIF
+!
+    if (diffmod == 1) THEN
+        invsumweight=1./(2.*coeffraf**2)
+        do i = -coeffraf,-1
+            weights(i) = invsumweight*(2*(coeffraf+i)+1)
+        enddo
+        do i = 0,coeffraf-1
+            weights(i) = weights(-(i+1))
+        enddo
+        it1 = -coeffraf
+        i1 = -(coeffraf-1)+locind_child_left
+        i2 = 2*coeffraf - 1
+        
+    else
+        invsumweight=1./coeffraf**2
+        do i = -(coeffraf-1),0
+            weights(i) = invsumweight*(coeffraf + i)
+        enddo
+        do i=1,coeffraf-1
+            weights(i) = invsumweight*(coeffraf - i)
+        enddo
+        it1 = -(coeffraf-1)
+        i1 = -(coeffraf-1)+locind_child_left
+        i2 = 2*coeffraf - 2
+
+    endif
+!
+    sumweight = 0.
+    MYLOOP : do i = 1,np
+!
+        it2 = it1
+
+!    sumweight = 0.
+    
+        do ii = i1,i1+i2
+!
+            IF (Agrif_UseSpecialValueInUpdate) THEN
+                IF (y(ii) /= Agrif_SpecialValueFineGrid) THEN
+                    x(i) = x(i) + weights(it2)*y(ii)
+!                    sumweight = sumweight+weights(it2)
+                ELSE
+                    x(i) = Agrif_SpecialValueFineGrid
+                    i1=i1+coeffraf
+                    CYCLE MYLOOP
+                ENDIF
+            ELSE
+                x(i) = x(i) + weights(it2)*y(ii)
+            ENDIF
+
+            it2 = it2+1
+!
+        enddo
+!
+        i1 = i1 + coeffraf
+!
+        enddo MYLOOP
+        
+        IF (Agrif_UseSpecialValueInUpdate) THEN
+          x = x * coeffraf ! x will be divided by coeffraf later in modupdate.F90
+        ENDIF
+        
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_basicupdate_full_weighting1D
+!===================================================================================================
+!
+end module Agrif_UpdateBasic
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modutil.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modutil.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modutil.F90	(revision 9987)
@@ -0,0 +1,1108 @@
+!
+! $Id$
+!
+!     Agrif (Adaptive Grid Refinement In Fortran)
+!
+!     Copyright (C) 2003 Laurent Debreu (Laurent.Debreu@imag.fr)
+!                        Christophe Vouland (Christophe.Vouland@imag.fr)
+!
+!     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., 59 Temple Place-  Suite 330, Boston, MA 02111-1307, USA.
+!
+!> Module Agrif_Util
+!!
+!! This module contains the two procedures called in the main program :
+!! - #Agrif_Init_Grids allows the initialization of the root coarse grid
+!! - #Agrif_Step allows the creation of the grid hierarchy and the management of the time integration.
+!
+module Agrif_Util
+!
+    use Agrif_Clustering
+    use Agrif_BcFunction
+    use Agrif_seq
+!
+    implicit none
+!
+    abstract interface
+        subroutine step_proc()
+        end subroutine step_proc
+    end interface
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_Step
+!
+!> Creates the grid hierarchy and manages the time integration procedure.
+!> It is called in the main program.
+!> Calls subroutines #Agrif_Regrid and #Agrif_Integrate.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Step ( procname )
+!---------------------------------------------------------------------------------------------------
+    procedure(step_proc)    :: procname     !< subroutine to call on each grid
+    type(agrif_grid), pointer :: ref_grid
+!
+! Set the clustering variables
+    call Agrif_clustering_def()
+!
+! Creation and initialization of the grid hierarchy
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 1 ) then
+!
+        if ( (Agrif_Mygrid % ngridstep == 0) .AND. (.not. Agrif_regrid_has_been_done) ) then
+            call Agrif_Regrid()
+            Agrif_regrid_has_been_done = .TRUE.
+        endif
+!
+    else
+!
+        if (mod(Agrif_Mygrid % ngridstep,Agrif_Regridding) == 0) then
+            call Agrif_Regrid()
+        endif
+!
+    endif
+!
+! Time integration of the grid hierarchy
+    if (agrif_coarse) then
+      ref_grid => agrif_coarsegrid
+    else
+      ref_grid => agrif_mygrid
+    endif
+    if ( Agrif_Parallel_sisters ) then
+        call Agrif_Integrate_Parallel(ref_grid,procname)
+    else
+        call Agrif_Integrate(ref_grid,procname)
+    endif
+!
+    if ( ref_grid%child_list%nitems > 0 ) call Agrif_Instance(ref_grid)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Step
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Step_Child
+!
+!> Apply 'procname' to each grid of the hierarchy
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Step_Child ( procname )
+!---------------------------------------------------------------------------------------------------
+    procedure(step_proc)    :: procname     !< subroutine to call on each grid
+!
+    if ( Agrif_Parallel_sisters ) then
+        call Agrif_Integrate_Child_Parallel(Agrif_Mygrid,procname)
+    else
+        call Agrif_Integrate_Child(Agrif_Mygrid,procname)
+    endif
+!
+    if ( Agrif_Mygrid%child_list%nitems > 0 ) call Agrif_Instance(Agrif_Mygrid)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Step_Child
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Regrid
+!
+!> Creates the grid hierarchy from fixed grids and adaptive mesh refinement.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Regrid ( procname )
+!---------------------------------------------------------------------------------------------------
+    procedure(init_proc), optional    :: procname     !< Initialisation subroutine (Default: Agrif_InitValues)
+!
+    type(Agrif_Rectangle), pointer     :: coarsegrid_fixed
+    type(Agrif_Rectangle), pointer     :: coarsegrid_moving
+    integer                            :: i, j
+    integer :: nunit
+    logical :: BEXIST
+    TYPE(Agrif_Rectangle)            :: newrect    ! Pointer on a new grid
+    integer :: is_coarse, rhox, rhoy, rhoz, rhot
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) &
+        call Agrif_detect_all(Agrif_Mygrid)     ! Detection of areas to be refined
+!
+    allocate(coarsegrid_fixed)
+    allocate(coarsegrid_moving)
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) &
+        call Agrif_Cluster_All(Agrif_Mygrid,coarsegrid_moving) ! Clustering
+!
+    if ( Agrif_USE_FIXED_GRIDS == 1 .OR. Agrif_USE_ONLY_FIXED_GRIDS == 1 ) then
+!
+        if (Agrif_Mygrid % ngridstep == 0) then
+!            
+            nunit = Agrif_Get_Unit()
+            open(nunit, file='AGRIF_FixedGrids.in', form='formatted', status="old", ERR=99)
+            if (agrif_coarse) then ! SKIP the coarse grid declaration
+                if (Agrif_Probdim == 3) then
+                    read(nunit,*) is_coarse, rhox, rhoy, rhoz, rhot
+                elseif (Agrif_Probdim == 2) then
+                    read(nunit,*) is_coarse, rhox, rhoy, rhot
+                elseif (Agrif_Probdim == 2) then
+                    read(nunit,*) is_coarse, rhox, rhot
+                endif
+            endif
+!           Creation of the grid hierarchy from the Agrif_FixedGrids.in file
+            do i = 1,Agrif_Probdim
+                coarsegrid_fixed % imin(i) = 1
+                coarsegrid_fixed % imax(i) = Agrif_Mygrid % nb(i) + 1
+            enddo
+            j = 1
+            call Agrif_Read_Fix_Grd(coarsegrid_fixed,j,nunit)
+            close(nunit)
+!
+            call Agrif_gl_clear(Agrif_oldmygrid)
+!
+!           Creation of the grid hierarchy from coarsegrid_fixed
+            call Agrif_Create_Grids(Agrif_Mygrid,coarsegrid_fixed)
+            
+        else
+            call Agrif_gl_copy(Agrif_oldmygrid, Agrif_Mygrid % child_list)
+        endif
+    else
+        call Agrif_gl_copy(Agrif_oldmygrid, Agrif_Mygrid % child_list)
+        call Agrif_gl_clear(Agrif_Mygrid % child_list)
+    endif
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) then
+!
+        call Agrif_Save_All(Agrif_oldmygrid)
+        call Agrif_Free_before_All(Agrif_oldmygrid)
+!
+!       Creation of the grid hierarchy from coarsegrid_moving
+        call Agrif_Create_Grids(Agrif_Mygrid,coarsegrid_moving)
+!
+    endif
+!
+!   Initialization of the grid hierarchy by copy or interpolation
+!
+#if defined AGRIF_MPI
+    if ( Agrif_Parallel_sisters ) then
+        call Agrif_Init_Hierarchy_Parallel_1(Agrif_Mygrid)
+        call Agrif_Init_Hierarchy_Parallel_2(Agrif_Mygrid,procname)
+    else
+        call Agrif_Init_Hierarchy(Agrif_Mygrid,procname)
+    endif
+#else
+        call Agrif_Init_Hierarchy(Agrif_Mygrid,procname)
+#endif
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS == 0 ) call Agrif_Free_after_All(Agrif_oldmygrid)
+!
+    Agrif_regrid_has_been_done = .TRUE.
+!
+    call Agrif_Instance( Agrif_Mygrid )
+!
+    deallocate(coarsegrid_fixed)
+    deallocate(coarsegrid_moving)
+!
+    return
+!
+!     Opening error
+!
+99  INQUIRE(FILE='AGRIF_FixedGrids.in',EXIST=BEXIST)
+    if (.not. BEXIST) then
+        print*,'ERROR : File AGRIF_FixedGrids.in not found.'
+        STOP
+    else
+        print*,'Error opening file AGRIF_FixedGrids.in'
+        STOP
+    endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Regrid
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_detect_All
+!
+!> Detects areas to be refined.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_detect_all ( g )
+!---------------------------------------------------------------------------------------------------
+    TYPE(Agrif_Grid),  pointer  :: g        !< Pointer on the current grid
+!
+    Type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive procedure
+    integer, DIMENSION(3)       :: size
+    integer                     :: i
+    real                        :: g_eps
+!
+    parcours => g % child_list % first
+!
+!   To be positioned on the finer grids of the grid hierarchy
+!
+    do while (associated(parcours))
+        call Agrif_detect_all(parcours % gr)
+        parcours => parcours % next
+    enddo
+!
+    g_eps = huge(1.)
+    do i = 1,Agrif_Probdim
+        g_eps = min(g_eps, g % Agrif_dx(i))
+    enddo
+!
+    g_eps = g_eps / 100.
+!
+    if ( Agrif_Probdim == 1 ) g%tabpoint1D = 0
+    if ( Agrif_Probdim == 2 ) g%tabpoint2D = 0
+    if ( Agrif_Probdim == 3 ) g%tabpoint3D = 0
+!
+    do i = 1,Agrif_Probdim
+        if ( g%Agrif_dx(i)/Agrif_coeffref(i) < (Agrif_mind(i)-g_eps) ) return
+    enddo
+!
+    call Agrif_instance(g)
+!
+!   Detection (Agrif_detect is a users routine)
+!
+    do i = 1,Agrif_Probdim
+        size(i) = g % nb(i) + 1
+    enddo
+!
+    SELECT CASE (Agrif_Probdim)
+    CASE (1)
+        call Agrif_detect(g%tabpoint1D,size)
+    CASE (2)
+        call Agrif_detect(g%tabpoint2D,size)
+    CASE (3)
+        call Agrif_detect(g%tabpoint3D,size)
+    END SELECT
+!
+!   Addition of the areas detected on the child grids
+!
+    parcours => g % child_list % first
+!
+    do while (associated(parcours))
+        call Agrif_Add_detected_areas(g,parcours % gr)
+        parcours => parcours % next
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_detect_all
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Add_detected_areas
+!
+!> Adds on the parent grid the areas detected on its child grids
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Add_detected_areas ( parentgrid, childgrid )
+!---------------------------------------------------------------------------------------------------
+    Type(Agrif_Grid), pointer   :: parentgrid
+    Type(Agrif_Grid), pointer   :: childgrid
+!
+    integer :: i,j,k
+!
+    do i = 1,childgrid%nb(1)+1
+        if ( Agrif_Probdim == 1 ) then
+            if (childgrid%tabpoint1D(i)==1) then
+                parentgrid%tabpoint1D(childgrid%ix(1)+(i-1)/Agrif_Coeffref(1)) = 1
+            endif
+        else
+            do j=1,childgrid%nb(2)+1
+                if (Agrif_Probdim==2) then
+                    if (childgrid%tabpoint2D(i,j)==1) then
+                        parentgrid%tabpoint2D(                       &
+                            childgrid%ix(1)+(i-1)/Agrif_Coeffref(1), &
+                            childgrid%ix(2)+(j-1)/Agrif_Coeffref(2)) = 1
+                    endif
+                else
+                    do k=1,childgrid%nb(3)+1
+                        if (childgrid%tabpoint3D(i,j,k)==1) then
+                            parentgrid%tabpoint3D(                       &
+                                childgrid%ix(1)+(i-1)/Agrif_Coeffref(1), &
+                                childgrid%ix(2)+(j-1)/Agrif_Coeffref(2), &
+                                childgrid%ix(3)+(k-1)/Agrif_Coeffref(3)) = 1
+                        endif
+                    enddo
+                endif
+            enddo
+        endif
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Add_detected_areas
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Free_before_All
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Free_before_All ( gridlist )
+!---------------------------------------------------------------------------------------------------
+    Type(Agrif_Grid_List), intent(inout)    :: gridlist !< Grid list
+!
+    Type(Agrif_PGrid), pointer   :: parcours ! Pointer for the recursive procedure
+!
+    parcours => gridlist % first
+!
+    do while (associated(parcours))
+!
+        if (.not. parcours%gr%fixed) then
+            call Agrif_Free_data_before(parcours%gr)
+            parcours % gr % oldgrid = .TRUE.
+        endif
+!
+        call Agrif_Free_before_all (parcours % gr % child_list)
+!
+        parcours => parcours % next
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Free_before_All
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Save_All
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Save_All ( gridlist )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid_List), intent(inout)    :: gridlist !< Grid list
+!
+    type(Agrif_PGrid), pointer   :: parcours ! Pointer for the recursive procedure
+!
+    parcours => gridlist % first
+!
+    do while (associated(parcours))
+!
+        if (.not. parcours%gr%fixed) then
+            call Agrif_Instance(parcours%gr)
+            call Agrif_Before_Regridding()
+            parcours % gr % oldgrid = .TRUE.
+        endif
+!
+        call Agrif_Save_All(parcours % gr % child_list)
+!
+        parcours => parcours % next
+!
+      enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Save_All
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Free_after_All
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Free_after_All ( gridlist )
+!---------------------------------------------------------------------------------------------------
+    Type(Agrif_Grid_List), intent(inout)    :: gridlist       !< Grid list to free
+!
+    Type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive proced
+    Type(Agrif_PGrid), pointer  :: preparcours
+    Type(Agrif_PGrid), pointer  :: preparcoursini
+!
+    allocate(preparcours)
+!
+    preparcoursini => preparcours
+!
+    nullify(preparcours % gr)
+!
+    preparcours % next => gridlist % first
+    parcours => gridlist % first
+!
+    do while (associated(parcours))
+!
+        if ( (.NOT. parcours%gr % fixed) .AND. (parcours%gr % oldgrid) ) then
+            call Agrif_Free_data_after(parcours%gr)
+        endif
+!
+        call Agrif_Free_after_all( parcours%gr % child_list )
+!
+        if (parcours % gr % oldgrid) then
+            deallocate(parcours % gr)
+            preparcours % next => parcours % next
+            deallocate(parcours)
+            parcours => preparcours % next
+        else
+            preparcours => preparcours % next
+            parcours => parcours % next
+        endif
+!
+    enddo
+!
+    deallocate(preparcoursini)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Free_after_All
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Integrate
+!
+!> Manages the time integration of the grid hierarchy.
+!! Recursive subroutine and call on subroutines Agrif_Init::Agrif_Instance and #Agrif_Step
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: g        !< Pointer on the current grid
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+    type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive procedure
+    integer                     :: nbt      ! Number of time steps of the current grid
+    integer                     :: i, k
+!
+!   Instanciation of the variables of the current grid
+!    if ( g % fixedrank /= 0 ) then
+        call Agrif_Instance(g)
+!    endif
+!
+!   One step on the current grid
+!
+    call procname ()
+!
+!   Number of time steps on the current grid
+!
+    g%ngridstep = g % ngridstep + 1
+    parcours => g % child_list % first
+!
+!   Recursive procedure for the time integration of the grid hierarchy
+    do while (associated(parcours))
+!
+!       Instanciation of the variables of the current grid
+        call Agrif_Instance(parcours % gr)
+!
+!       Number of time steps
+        nbt = 1
+        do i = 1,Agrif_Probdim
+            nbt = max(nbt, parcours % gr % timeref(i))
+        enddo
+!
+        do k = 1,nbt
+            call Agrif_Integrate(parcours % gr, procname)
+        enddo
+!
+        parcours => parcours % next
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Integrate
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Integrate_Parallel
+!
+!> Manages the time integration of the grid hierarchy in parallel
+!! Recursive subroutine and call on subroutines Agrif_Init::Agrif_Instance and #Agrif_Step
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate_Parallel ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: g        !< Pointer on the current grid
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+#if defined AGRIF_MPI
+    type(Agrif_PGrid), pointer  :: gridp    ! Pointer for the recursive procedure
+    integer                     :: nbt      ! Number of time steps of the current grid
+    integer                     :: i, k, is
+!
+!   Instanciation of the variables of the current grid
+    if ( g % fixedrank /= 0 ) then
+        call Agrif_Instance(g)
+    endif
+!
+! One step on the current grid
+    call procname ()
+!
+! Number of time steps on the current grid
+    g % ngridstep = g % ngridstep + 1
+!
+! Continue only if the grid has defined sequences of child integrations.
+    if ( .not. associated(g % child_seq) ) return
+!
+    do is = 1, g % child_seq % nb_seqs
+!
+!     For each sequence, a given processor does integrate only on grid.
+        gridp => Agrif_seq_select_child(g,is)
+!
+!     Instanciation of the variables of the current grid
+        call Agrif_Instance(gridp % gr)
+!
+!     Number of time steps
+        nbt = 1
+        do i = 1,Agrif_Probdim
+            nbt = max(nbt, gridp % gr % timeref(i))
+        enddo
+!
+        do k = 1,nbt
+            call Agrif_Integrate_Parallel(gridp % gr, procname)
+        enddo
+!
+    enddo
+#else
+    call Agrif_Integrate( g, procname )
+#endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Integrate_Parallel
+!===================================================================================================
+!
+!
+!===================================================================================================
+!  subroutine Agrif_Integrate_ChildGrids
+!
+!> Manages the time integration of the grid hierarchy.
+!! Call the subroutine procname on each child grid of the current grid
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate_ChildGrids ( procname )
+!---------------------------------------------------------------------------------------------------
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+    type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive procedure
+    integer                     :: nbt      ! Number of time steps of the current grid
+    integer                     :: i, k, is
+    type(Agrif_Grid)                    , pointer :: save_grid
+    type(Agrif_PGrid), pointer  :: gridp    ! Pointer for the recursive procedure
+    
+    save_grid => Agrif_Curgrid
+
+! Number of time steps on the current grid
+    save_grid % ngridstep = save_grid % ngridstep + 1
+    
+#ifdef AGRIF_MPI
+    if ( .not. Agrif_Parallel_sisters ) then
+#endif
+    parcours => save_grid % child_list % first
+!
+!   Recursive procedure for the time integration of the grid hierarchy
+    do while (associated(parcours))
+!
+!       Instanciation of the variables of the current grid
+        call Agrif_Instance(parcours % gr)
+!
+!       Number of time steps
+        nbt = 1
+        do i = 1,Agrif_Probdim
+            nbt = max(nbt, parcours % gr % timeref(i))
+        enddo
+!
+        do k = 1,nbt
+            call procname()
+        enddo
+!
+        parcours => parcours % next
+!
+    enddo
+
+#ifdef AGRIF_MPI
+    else
+#endif    
+! Continue only if the grid has defined sequences of child integrations.
+    if ( .not. associated(save_grid % child_seq) ) return
+!
+    do is = 1, save_grid % child_seq % nb_seqs
+!
+!     For each sequence, a given processor does integrate only on grid.
+        gridp => Agrif_seq_select_child(save_grid,is)
+!
+!     Instanciation of the variables of the current grid
+        call Agrif_Instance(gridp % gr)
+!
+!     Number of time steps
+        nbt = 1
+        do i = 1,Agrif_Probdim
+            nbt = max(nbt, gridp % gr % timeref(i))
+        enddo
+!
+        do k = 1,nbt
+            call procname()
+        enddo
+!
+    enddo
+#ifdef AGRIF_MPI
+    endif
+#endif 
+
+    call Agrif_Instance(save_grid)
+    
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Integrate_ChildGrids
+!===================================================================================================
+!===================================================================================================
+!  subroutine Agrif_Integrate_Child
+!
+!> Manages the time integration of the grid hierarchy.
+!! Recursive subroutine and call on subroutines Agrif_Instance & Agrif_Step.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate_Child ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: g        !< Pointer on the current grid
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+    type(Agrif_PGrid), pointer  :: parcours ! Pointer for the recursive procedure
+!
+!   One step on the current grid
+!
+    call procname ()
+!
+!   Number of time steps on the current grid
+!
+    parcours => g % child_list % first
+!
+!   Recursive procedure for the time integration of the grid hierarchy
+    do while (associated(parcours))
+!
+!       Instanciation of the variables of the current grid
+        call Agrif_Instance(parcours % gr)
+        call Agrif_Integrate_Child (parcours % gr, procname)
+        parcours => parcours % next
+!
+    enddo
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Integrate_Child
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Integrate_Child_Parallel
+!
+!> Manages the time integration of the grid hierarchy.
+!! Recursive subroutine and call on subroutines Agrif_Instance & Agrif_Step.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate_Child_Parallel ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: g        !< Pointer on the current grid
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+#if defined AGRIF_MPI
+    type(Agrif_PGrid), pointer  :: gridp    ! Pointer for the recursive procedure
+    integer                     :: is
+!
+! Instanciation of the variables of the current grid
+    call Agrif_Instance(g)
+!
+! One step on the current grid
+    call procname ()
+!
+! Continue only if the grid has defined sequences of child integrations.
+    if ( .not. associated(g % child_seq) ) return
+!
+    do is = 1, g % child_seq % nb_seqs
+!
+!     For each sequence, a given processor does integrate only on grid.
+        gridp => Agrif_seq_select_child(g,is)
+        call Agrif_Integrate_Child_Parallel(gridp % gr, procname)
+!
+    enddo
+!
+    call Agrif_Instance(g)
+#else
+    call Agrif_Integrate_Child( g, procname )
+#endif
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Integrate_Child_Parallel
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Init_Grids
+!
+!> Initializes the root coarse grid pointed by Agrif_Mygrid. It is called in the main program.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Init_Grids ( procname1, procname2 )
+!---------------------------------------------------------------------------------------------------
+    procedure(typedef_proc), optional   :: procname1 !< (Default: Agrif_probdim_modtype_def)
+    procedure(alloc_proc),   optional   :: procname2 !< (Default: Agrif_Allocationcalls)
+!
+    integer :: i, ierr_allocate, nunit
+    integer :: is_coarse, rhox,rhoy,rhoz,rhot
+    logical :: BEXIST
+!
+    if (present(procname1)) Then
+        call procname1()
+    else
+        call Agrif_probdim_modtype_def()
+    endif
+!
+
+! TEST FOR COARSE GRID (GRAND MOTHER GRID) in AGRIF_FixedGrids.in
+    nunit = Agrif_Get_Unit()
+    open(nunit, file='AGRIF_FixedGrids.in', form='formatted', status="old", ERR=98)
+    if (Agrif_Probdim == 3) then
+       read(nunit,*) is_coarse, rhox, rhoy, rhoz, rhot
+    elseif (Agrif_Probdim == 2) then
+       read(nunit,*) is_coarse, rhox, rhoy, rhot
+    elseif (Agrif_Probdim == 2) then
+       read(nunit,*) is_coarse, rhox, rhot
+    endif
+    if (is_coarse == -1) then
+       agrif_coarse = .TRUE.
+       if (Agrif_Probdim == 3) then
+          coarse_spaceref(1:3)=(/rhox,rhoy,rhoz/)
+       elseif (Agrif_Probdim == 2) then
+          coarse_spaceref(1:2)=(/rhox,rhoy/)
+       elseif (Agrif_Probdim == 2) then
+          coarse_spaceref(1:1)=(/rhox/)
+       endif
+       coarse_timeref(1:Agrif_Probdim) = rhot
+    endif
+    close(nunit)
+    
+    Agrif_UseSpecialValue = .FALSE.
+    Agrif_UseSpecialValueFineGrid = .FALSE.
+    Agrif_SpecialValue = 0.
+    Agrif_SpecialValueFineGrid = 0.
+!
+    allocate(Agrif_Mygrid)
+    allocate(Agrif_OldMygrid)
+!
+!   Space and time refinement factors are set to 1 on the root grid
+!
+    do i = 1,Agrif_Probdim
+        Agrif_Mygrid % spaceref(i) = coarse_spaceref(i)
+        Agrif_Mygrid % timeref(i)  = coarse_timeref(i)
+    enddo
+!
+!   Initialization of the number of time steps
+    Agrif_Mygrid % ngridstep = 0
+    Agrif_Mygrid % grid_id   = 0
+!
+!   No parent grid for the root coarse grid
+    nullify(Agrif_Mygrid % parent)
+!
+!   Initialization of the minimum positions, global abscissa and space steps
+    do i = 1, Agrif_Probdim
+        Agrif_Mygrid % ix(i) = 1
+        Agrif_Mygrid % Agrif_x(i)  = 0.
+        Agrif_Mygrid % Agrif_dx(i) = 1./Agrif_Mygrid % spaceref(i)
+        Agrif_Mygrid % Agrif_dt(i) = 1./Agrif_Mygrid % timeref(i)
+!       Borders of the root coarse grid
+        Agrif_Mygrid % NearRootBorder(i) = .true.
+        Agrif_Mygrid % DistantRootBorder(i) = .true.
+    enddo
+!
+!   The root coarse grid is a fixed grid
+    Agrif_Mygrid % fixed = .TRUE.
+!   Level of the root grid
+    Agrif_Mygrid % level = 0
+!   Maximum level in the hierarchy
+    Agrif_MaxLevelLoc = 0
+!
+!   Number of the grid pointed by Agrif_Mygrid (root coarse grid)
+    Agrif_Mygrid % rank = 1
+!
+!   Number of the root grid as a fixed grid
+    Agrif_Mygrid % fixedrank = 0
+!
+!   Initialization of some fields of the root grid variables
+    ierr_allocate = 0
+    if( Agrif_NbVariables(0) > 0 ) allocate(Agrif_Mygrid % tabvars(Agrif_NbVariables(0)),stat=ierr_allocate)
+    if( Agrif_NbVariables(1) > 0 ) allocate(Agrif_Mygrid % tabvars_c(Agrif_NbVariables(1)),stat=ierr_allocate)
+    if( Agrif_NbVariables(2) > 0 ) allocate(Agrif_Mygrid % tabvars_r(Agrif_NbVariables(2)),stat=ierr_allocate)
+    if( Agrif_NbVariables(3) > 0 ) allocate(Agrif_Mygrid % tabvars_l(Agrif_NbVariables(3)),stat=ierr_allocate)
+    if( Agrif_NbVariables(4) > 0 ) allocate(Agrif_Mygrid % tabvars_i(Agrif_NbVariables(4)),stat=ierr_allocate)
+    if (ierr_allocate /= 0) THEN
+      STOP "*** ERROR WHEN ALLOCATING TABVARS ***"
+    endif
+!
+!   Initialization of the other fields of the root grid variables (number of
+!   cells, positions, number and type of its dimensions, ...)
+    call Agrif_Instance(Agrif_Mygrid)
+    call Agrif_Set_numberofcells(Agrif_Mygrid)
+!
+!   Allocation of the array containing the values of the grid variables
+    call Agrif_Allocation(Agrif_Mygrid, procname2)
+    call Agrif_initialisations(Agrif_Mygrid)
+!
+!   Total number of fixed grids
+    Agrif_nbfixedgrids = 0
+    
+! If a grand mother grid is declared
+
+    if (agrif_coarse) then
+      allocate(Agrif_Coarsegrid)
+
+      Agrif_Coarsegrid % ngridstep = 0
+      Agrif_Coarsegrid % grid_id   = -9999
+      
+    do i = 1, Agrif_Probdim
+        Agrif_Coarsegrid%spaceref(i) = coarse_spaceref(i)
+        Agrif_Coarsegrid%timeref(i) = coarse_timeref(i)
+        Agrif_Coarsegrid % ix(i) = 1
+        Agrif_Coarsegrid % Agrif_x(i)  = 0.
+        Agrif_Coarsegrid % Agrif_dx(i) = 1.
+        Agrif_Coarsegrid % Agrif_dt(i) = 1.
+!       Borders of the root coarse grid
+        Agrif_Coarsegrid % NearRootBorder(i) = .true.
+        Agrif_Coarsegrid % DistantRootBorder(i) = .true.
+        Agrif_Coarsegrid % nb(i) =Agrif_mygrid%nb(i) / coarse_spaceref(i)
+    enddo      
+
+!   The root coarse grid is a fixed grid
+    Agrif_Coarsegrid % fixed = .TRUE.
+!   Level of the root grid
+    Agrif_Coarsegrid % level = -1
+    
+    Agrif_Coarsegrid % grand_mother_grid = .true.
+
+!   Number of the grid pointed by Agrif_Mygrid (root coarse grid)
+    Agrif_Coarsegrid % rank = -9999
+!
+!   Number of the root grid as a fixed grid
+    Agrif_Coarsegrid % fixedrank = -9999
+    
+      Agrif_Mygrid%parent => Agrif_Coarsegrid
+      
+! Not used but required to prevent seg fault
+      Agrif_Coarsegrid%parent => Agrif_Mygrid
+      
+      call Agrif_Create_Var(Agrif_Coarsegrid)
+
+! Reset to null
+      Nullify(Agrif_Coarsegrid%parent)
+      
+      Agrif_Coarsegrid%child_list%nitems = 1
+      allocate(Agrif_Coarsegrid%child_list%first)
+      allocate(Agrif_Coarsegrid%child_list%last)
+      Agrif_Coarsegrid%child_list%first%gr => Agrif_Mygrid
+      Agrif_Coarsegrid%child_list%last%gr => Agrif_Mygrid
+
+    endif
+    
+    return
+
+98  INQUIRE(FILE='AGRIF_FixedGrids.in',EXIST=BEXIST)
+    if (.not. BEXIST) then
+        print*,'ERROR : File AGRIF_FixedGrids.in not found.'
+        STOP
+    else
+        print*,'Error opening file AGRIF_FixedGrids.in'
+        STOP
+    endif
+    
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Init_Grids
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Deallocation
+!
+!> Deallocates all data arrays.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Deallocation
+!---------------------------------------------------------------------------------------------------
+    integer                         :: nb
+    type(Agrif_Variable), pointer   :: var
+    type(Agrif_Variable_c), pointer   :: var_c
+    type(Agrif_Variable_l), pointer   :: var_l
+    type(Agrif_Variable_i), pointer   :: var_i
+!
+    do nb = 1,Agrif_NbVariables(0)
+!
+        var => Agrif_Mygrid % tabvars(nb)
+!
+        if ( allocated(var % array1) ) deallocate(var % array1)
+        if ( allocated(var % array2) ) deallocate(var % array2)
+        if ( allocated(var % array3) ) deallocate(var % array3)
+        if ( allocated(var % array4) ) deallocate(var % array4)
+        if ( allocated(var % array5) ) deallocate(var % array5)
+        if ( allocated(var % array6) ) deallocate(var % array6)
+!
+        if ( allocated(var % sarray1) ) deallocate(var % sarray1)
+        if ( allocated(var % sarray2) ) deallocate(var % sarray2)
+        if ( allocated(var % sarray3) ) deallocate(var % sarray3)
+        if ( allocated(var % sarray4) ) deallocate(var % sarray4)
+        if ( allocated(var % sarray5) ) deallocate(var % sarray5)
+        if ( allocated(var % sarray6) ) deallocate(var % sarray6)
+!
+        if ( allocated(var % darray1) ) deallocate(var % darray1)
+        if ( allocated(var % darray2) ) deallocate(var % darray2)
+        if ( allocated(var % darray3) ) deallocate(var % darray3)
+        if ( allocated(var % darray4) ) deallocate(var % darray4)
+        if ( allocated(var % darray5) ) deallocate(var % darray5)
+        if ( allocated(var % darray6) ) deallocate(var % darray6)
+!
+    enddo
+!
+    do nb = 1,Agrif_NbVariables(1)
+!
+        var_c => Agrif_Mygrid % tabvars_c(nb)
+!
+        if ( allocated(var_c % carray1) ) deallocate(var_c % carray1)
+        if ( allocated(var_c % carray2) ) deallocate(var_c % carray2)
+!
+    enddo
+
+    do nb = 1,Agrif_NbVariables(3)
+!
+        var_l => Agrif_Mygrid % tabvars_l(nb)
+!
+        if ( allocated(var_l % larray1) ) deallocate(var_l % larray1)
+        if ( allocated(var_l % larray2) ) deallocate(var_l % larray2)
+        if ( allocated(var_l % larray3) ) deallocate(var_l % larray3)
+        if ( allocated(var_l % larray4) ) deallocate(var_l % larray4)
+        if ( allocated(var_l % larray5) ) deallocate(var_l % larray5)
+        if ( allocated(var_l % larray6) ) deallocate(var_l % larray6)
+!
+    enddo
+!
+    do nb = 1,Agrif_NbVariables(4)
+!
+        var_i => Agrif_Mygrid % tabvars_i(nb)
+!
+        if ( allocated(var_i % iarray1) ) deallocate(var_i % iarray1)
+        if ( allocated(var_i % iarray2) ) deallocate(var_i % iarray2)
+        if ( allocated(var_i % iarray3) ) deallocate(var_i % iarray3)
+        if ( allocated(var_i % iarray4) ) deallocate(var_i % iarray4)
+        if ( allocated(var_i % iarray5) ) deallocate(var_i % iarray5)
+        if ( allocated(var_i % iarray6) ) deallocate(var_i % iarray6)
+!
+    enddo
+!
+    if ( allocated(Agrif_Mygrid % tabvars) )   deallocate(Agrif_Mygrid % tabvars)
+    if ( allocated(Agrif_Mygrid % tabvars_c) ) deallocate(Agrif_Mygrid % tabvars_c)
+    if ( allocated(Agrif_Mygrid % tabvars_r) ) deallocate(Agrif_Mygrid % tabvars_r)
+    if ( allocated(Agrif_Mygrid % tabvars_l) ) deallocate(Agrif_Mygrid % tabvars_l)
+    if ( allocated(Agrif_Mygrid % tabvars_i) ) deallocate(Agrif_Mygrid % tabvars_i)
+    deallocate(Agrif_Mygrid)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Deallocation
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Step_adj
+!
+!> creates the grid hierarchy and manages the backward time integration procedure.
+!> It is called in the main program.
+!> calls subroutines #Agrif_Regrid and #Agrif_Integrate_adj.
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Step_adj ( procname )
+!---------------------------------------------------------------------------------------------------
+    procedure(step_proc)    :: procname     !< Subroutine to call on each grid
+!
+!   Creation and initialization of the grid hierarchy
+!
+!   Set the clustering variables
+    call Agrif_clustering_def()
+!
+    if ( Agrif_USE_ONLY_FIXED_GRIDS .EQ. 1 ) then
+!
+        if (Agrif_Mygrid % ngridstep == 0) then
+            if (.not.Agrif_regrid_has_been_done ) then
+                call Agrif_Regrid()
+            endif
+            call Agrif_Instance(Agrif_Mygrid)
+        endif
+!
+    else
+!
+        if (mod(Agrif_Mygrid % ngridstep, Agrif_Regridding) == 0) then
+            call Agrif_Regrid()
+            call Agrif_Instance(Agrif_Mygrid)
+        endif
+!
+    endif
+!
+!   Time integration of the grid hierarchy
+!
+    call Agrif_Integrate_adj (Agrif_Mygrid,procname)
+!
+    if ( Agrif_Mygrid % child_list % nitems > 0 ) call Agrif_Instance(Agrif_Mygrid)
+!
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Step_adj
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Integrate_adj
+!
+!> Manages the backward time integration of the grid hierarchy.
+!! Recursive subroutine and call on subroutines Agrif_Init::Agrif_Instance and #Agrif_Step_adj
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate_adj ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer   :: g        !< Pointer on the current grid
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+    type(Agrif_pgrid), pointer :: parcours ! pointer for the recursive procedure
+    integer                    :: nbt      ! Number of time steps of the current grid
+    integer                    :: k
+!
+!   Instanciation of the variables of the current grid
+    if ( g%fixedrank /= 0 ) then
+        call Agrif_Instance(g)
+    endif
+!
+!   Number of time steps on the current grid
+!
+    g%ngridstep = g % ngridstep + 1
+    parcours => g % child_list % first
+!
+!   Recursive procedure for the time integration of the grid hierarchy
+    do while (associated(parcours))
+!
+!   Instanciation of the variables of the current grid
+        call Agrif_Instance(parcours % gr)
+!
+!       Number of time steps
+        nbt = 1
+        do k = 1,Agrif_Probdim
+            nbt = max(nbt, parcours % gr % timeref(k))
+        enddo
+!
+        do k = nbt,1,-1
+            call Agrif_Integrate_adj(parcours % gr, procname)
+        enddo
+!
+        parcours => parcours % next
+!
+    enddo
+!
+    if ( g % child_list % nitems > 0 )  call Agrif_Instance(g)
+!
+!   One step on the current grid
+    call procname ()
+!
+end subroutine Agrif_Integrate_adj
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Step_Child_adj
+!
+!> Apply 'procname' to each grid of the hierarchy from Child to Parent
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Step_Child_adj ( procname )
+!---------------------------------------------------------------------------------------------------
+    procedure(step_proc)        :: procname !< Subroutine to call on each grid
+!
+    call Agrif_Integrate_Child_adj(Agrif_Mygrid,procname)
+!
+    if ( Agrif_Mygrid % child_list % nitems > 0 ) call Agrif_Instance(Agrif_Mygrid)
+!
+end subroutine Agrif_Step_Child_adj
+!===================================================================================================
+!
+!===================================================================================================
+!  subroutine Agrif_Integrate_Child_adj
+!
+!> Manages the backward time integration of the grid hierarchy.
+!! Recursive subroutine and call on subroutines Agrif_Init::Agrif_Instance & Agrif_Step_adj.
+!---------------------------------------------------------------------------------------------------
+recursive subroutine Agrif_Integrate_Child_adj ( g, procname )
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid),pointer   :: g          !< Pointer on the current grid
+    procedure(step_proc)       :: procname   !< Subroutine to call on each grid
+!
+    type(Agrif_PGrid),pointer  :: parcours   !< Pointer for the recursive procedure
+!
+    parcours => g % child_list % first
+!
+!   Recursive procedure for the time integration of the grid hierarchy
+    do while (associated(parcours))
+!
+!       Instanciation of the variables of the current grid
+        call Agrif_Instance(parcours % gr)
+        call Agrif_Integrate_Child_adj(parcours % gr, procname)
+!
+       parcours => parcours % next
+!
+    enddo
+    if ( g % child_list % nitems > 0 )  call Agrif_Instance(g)
+!
+!   One step on the current grid
+    call procname()
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Integrate_Child_adj
+!===================================================================================================
+!
+!===================================================================================================
+
+end module Agrif_Util
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modvariables.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modvariables.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/AGRIF_FILES/modvariables.F90	(revision 9987)
@@ -0,0 +1,146 @@
+module Agrif_Variables
+!
+    use Agrif_CurgridFunctions
+!
+    implicit none
+!
+contains
+!
+!===================================================================================================
+!  subroutine Agrif_Declare_Variable
+!
+!> Declare a new variable profile
+!---------------------------------------------------------------------------------------------------
+subroutine Agrif_Declare_Variable ( posvar, firstpoint, raf, lb, ub, varid, torestore )
+!---------------------------------------------------------------------------------------------------
+    integer,      dimension(:), intent(in)  :: posvar     !< position of the variable on the cell
+                                                          !! (1 for the border of the edge, 2 for the center)
+    integer,      dimension(:), intent(in)  :: firstpoint !< index of the first point in the real domain
+    character(1), dimension(:), intent(in)  :: raf        !< Array indicating the type of dimension (space or not)
+                                                          !!   for each of them
+    integer,      dimension(:), intent(in)  :: lb         !< Lower bounds of the array
+    integer,      dimension(:), intent(in)  :: ub         !< Upper bounds of the array
+    integer,                    intent(out) :: varid      !< Id number of the newly created variable
+    logical,      optional,     intent(in)  :: torestore  !< Indicates if the array restore is used
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Variables_List), pointer :: new_varlist
+    type(Agrif_Variable),       pointer :: var
+    integer                             :: nbdim, i
+    logical                             :: restore
+
+    restore = .FALSE.
+    if ( Agrif_Mygrid % ngridstep /= 0 ) then
+        if (present(torestore)) restore = torestore
+    endif
+!
+    nbdim = SIZE(posvar)
+!
+    allocate(new_varlist)
+    allocate(new_varlist % var)
+
+    var => new_varlist % var
+
+    allocate(var % posvar(nbdim))
+    allocate(var % interptab(nbdim))
+    allocate(var % coords(nbdim))
+!
+    var % nbdim          = nbdim
+    var % interptab      = raf(1:nbdim)
+    var % posvar         = posvar(1:nbdim)
+    var % point(1:nbdim) = firstpoint(1:nbdim)
+    var % restore = restore
+!
+    do i = 1,nbdim
+        select case( raf(i) )
+            case('x')    ; var % coords(i) = 1
+            case('y')    ; var % coords(i) = 2
+            case('z')    ; var % coords(i) = 3
+            case('N')    ; var % coords(i) = 0
+            case default ; var % coords(i) = 0
+        end select
+    enddo
+!
+    var % lb(1:nbdim) = lb(1:nbdim)
+    var % ub(1:nbdim) = ub(1:nbdim)
+
+    if ( restore ) then
+        select case(nbdim)
+        case(1)
+            allocate(var % Restore1D(lb(1):ub(1)))
+            var % Restore1D = 0
+        case(2)
+            allocate(var % Restore2D(lb(1):ub(1),   &
+                                     lb(2):ub(2)))
+            var % Restore2D = 0
+        case(3)
+            allocate(var % Restore3D(lb(1):ub(1),   &
+                                     lb(2):ub(2),   &
+                                     lb(3):ub(3)))
+            var % Restore3D = 0
+        case(4)
+            allocate(var % Restore4D(lb(1):ub(1),   &
+                                     lb(2):ub(2),   &
+                                     lb(3):ub(3),   &
+                                     lb(4):ub(4)))
+            var % Restore4D = 0
+        case(5)
+            allocate(var % Restore5D(lb(1):ub(1),   &
+                                     lb(2):ub(2),   &
+                                     lb(3):ub(3),   &
+                                     lb(4):ub(4),   &
+                                     lb(5):ub(5)))
+            var % Restore5D = 0
+        end select
+    endif
+
+    new_varlist % next => Agrif_Curgrid % variables
+
+    Agrif_Curgrid % variables => new_varlist
+    Agrif_Curgrid % Nbvariables = Agrif_Curgrid % Nbvariables + 1
+
+    varid = -Agrif_Curgrid % Nbvariables
+
+    var % parent_var => Agrif_Search_Variable(Agrif_Curgrid % parent, Agrif_Curgrid % nbvariables)
+    var % root_var   => Agrif_Search_Variable(Agrif_Mygrid, Agrif_Curgrid % nbvariables)
+!---------------------------------------------------------------------------------------------------
+end subroutine Agrif_Declare_Variable
+!===================================================================================================
+!
+!===================================================================================================
+!  function Agrif_Search_Variable
+!
+!> Returns a pointer to the variable varid for the grid grid.
+!---------------------------------------------------------------------------------------------------
+function Agrif_Search_Variable ( grid, varid ) result(outvar)
+!---------------------------------------------------------------------------------------------------
+    type(Agrif_Grid), pointer       :: grid     !< Pointer on the current grid.
+    integer,          intent(in)    :: varid    !< ID number of the variable we are looking for.
+!
+    type(Agrif_Variable),       pointer :: outvar
+    type(Agrif_Variables_List), pointer :: parcours
+    integer :: nb, varidinv
+!
+    if ( .not.associated(grid) ) then
+        outvar => NULL()
+        return
+    endif
+!
+    parcours => grid % variables
+
+    if (.not. associated(parcours)) then   ! can occur on the grand mother grid
+           outvar => NULL()                ! during the first call by agrif_mygrid
+           return
+    endif
+
+    varidinv = 1 + grid % nbvariables - varid
+
+    do nb = 1,varidinv-1
+        parcours => parcours % next
+    enddo
+
+    outvar => parcours % var
+!---------------------------------------------------------------------------------------------------
+end function Agrif_Search_variable
+!===================================================================================================
+!
+end module Agrif_Variables
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/Makefile.lex
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/Makefile.lex	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/Makefile.lex	(revision 9987)
@@ -0,0 +1,31 @@
+LEX		= flex -i
+YACC	= bison -t -v -g
+
+all: main.c fortran.c
+
+main.c : convert.tab.c convert.yy.c
+	cat   convert.tab.c convert.yy.c > ../LIB/main.c
+	$(RM) convert.tab.c convert.yy.c
+
+fortran.c : fortran.tab.c fortran.yy.c
+	cat   fortran.tab.c fortran.yy.c > ../LIB/fortran.c
+	$(RM) fortran.tab.c fortran.yy.c
+
+convert.tab.c : convert.y decl.h
+	$(YACC) -p convert_ convert.y
+
+fortran.tab.c : fortran.y decl.h
+	$(YACC) -p fortran_ fortran.y
+
+convert.yy.c : convert.lex
+	$(LEX) -P convert_ -o convert.yy.c convert.lex
+
+fortran.yy.c : fortran.lex
+	$(LEX) -P fortran_ -o fortran.yy.c fortran.lex
+
+clean:
+	$(RM) convert.yy.c convert.tab.c convert.output convert.vcg convert.dot	\
+		  fortran.yy.c fortran.tab.c fortran.output fortran.vcg fortran.dot
+
+clean-all: clean
+	$(RM) ../LIB/main.c ../LIB/fortran.c
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/convert.lex
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/convert.lex	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/convert.lex	(revision 9987)
@@ -0,0 +1,69 @@
+/******************************************************************************/
+/*                                                                            */
+/*     CONV (converter) for Agrif (Adaptive Grid Refinement In Fortran)       */
+/*                                                                            */
+/* Copyright or   or Copr. Laurent Debreu (Laurent.Debreu@imag.fr)            */
+/*                        Cyril Mazauric (Cyril_Mazauric@yahoo.fr)            */
+/* This software is governed by the CeCILL-C license under French law and     */
+/* abiding by the rules of distribution of free software.  You can  use,      */
+/* modify and/ or redistribute the software under the terms of the CeCILL-C   */
+/* license as circulated by CEA, CNRS and INRIA at the following URL          */
+/* "http://www.cecill.info".                                                  */
+/*                                                                            */
+/* As a counterpart to the access to the source code and  rights to copy,     */
+/* modify and redistribute granted by the license, users are provided only    */
+/* with a limited warranty  and the software's author,  the holder of the     */
+/* economic rights,  and the successive licensors  have only  limited         */
+/* liability.                                                                 */
+/*                                                                            */
+/* In this respect, the user's attention is drawn to the risks associated     */
+/* with loading,  using,  modifying and/or developing or reproducing the      */
+/* software by the user in light of its specific status of free software,     */
+/* that may mean  that it is complicated to manipulate,  and  that  also      */
+/* therefore means  that it is reserved for developers  and  experienced      */
+/* professionals having in-depth computer knowledge. Users are therefore      */
+/* encouraged to load and test the software's suitability as regards their    */
+/* requirements in conditions enabling the security of their systems and/or   */
+/* data to be ensured and,  more generally, to use and operate it in the      */
+/* same conditions as regards security.                                       */
+/*                                                                            */
+/* The fact that you are presently reading this means that you have had       */
+/* knowledge of the CeCILL-C license and that you accept its terms.           */
+/******************************************************************************/
+/* version 1.7                                                                */
+/******************************************************************************/
+%option warn
+%option noyywrap
+
+%s character
+%{
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define YY_NO_INPUT
+%}
+
+SEPARATEUR      "::"
+COMMENTS        "%".*"%"
+PROBTYPE        "1D"|"2D"|"3D"
+USEITEM         "FIXED_GRIDS"|"ONLY_FIXED_GRIDS"|"F77"
+NAME            [a-zA-Z\_][a-zA-Z0-9\_]*
+INTEGER         [0-9]+
+NEXTLINE        \n+[ \t]+"$"|\n+[ \t]+"&"
+%%
+parammodule         { return TOK_MODULEMAIN; } /* name of the module                      */
+notgriddep          { return TOK_NOTGRIDDEP; } /* variable which are not grid dependent   */
+use                 { return TOK_USE; }
+{COMMENTS}          { }
+{SEPARATEUR}        { return TOK_SEP; }
+KIND                { return TOK_KIND; }
+\=                  { return TOK_EQUAL; }
+{USEITEM}           { strcpy(yylval.na,yytext); return TOK_USEITEM;  }
+{PROBTYPE}          { strcpy(yylval.na,yytext); return TOK_PROBTYPE; }  /* dimension of the problem */
+{NAME}              { strcpy(yylval.na,yytext); return TOK_NAME; }
+{INTEGER}           { strcpy(yylval.na,yytext); return TOK_CSTINT; }
+;|\,|\(|\)|:|\[|\]  { return (int) *yytext; }
+\n                  { line_num++; return (int) *yytext; }
+[ \t]+ ;
+%%
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/convert.y
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/convert.y	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/convert.y	(revision 9987)
@@ -0,0 +1,463 @@
+/******************************************************************************/
+/*                                                                            */
+/*     CONV (converter) for Agrif (Adaptive Grid Refinement In Fortran)       */
+/*                                                                            */
+/* Copyright or   or Copr. Laurent Debreu (Laurent.Debreu@imag.fr)            */
+/*                        Cyril Mazauric (Cyril_Mazauric@yahoo.fr)            */
+/* This software is governed by the CeCILL-C license under French law and     */
+/* abiding by the rules of distribution of free software.  You can  use,      */
+/* modify and/ or redistribute the software under the terms of the CeCILL-C   */
+/* license as circulated by CEA, CNRS and INRIA at the following URL          */
+/* "http://www.cecill.info".                                                  */
+/*                                                                            */
+/* As a counterpart to the access to the source code and  rights to copy,     */
+/* modify and redistribute granted by the license, users are provided only    */
+/* with a limited warranty  and the software's author,  the holder of the     */
+/* economic rights,  and the successive licensors  have only  limited         */
+/* liability.                                                                 */
+/*                                                                            */
+/* In this respect, the user's attention is drawn to the risks associated     */
+/* with loading,  using,  modifying and/or developing or reproducing the      */
+/* software by the user in light of its specific status of free software,     */
+/* that may mean  that it is complicated to manipulate,  and  that  also      */
+/* therefore means  that it is reserved for developers  and  experienced      */
+/* professionals having in-depth computer knowledge. Users are therefore      */
+/* encouraged to load and test the software's suitability as regards their    */
+/* requirements in conditions enabling the security of their systems and/or   */
+/* data to be ensured and,  more generally, to use and operate it in the      */
+/* same conditions as regards security.                                       */
+/*                                                                            */
+/* The fact that you are presently reading this means that you have had       */
+/* knowledge of the CeCILL-C license and that you accept its terms.           */
+/******************************************************************************/
+/* version 1.7                                                                */
+/******************************************************************************/
+%{
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include "decl.h"
+
+int line_num=1;
+extern FILE * convert_in;
+
+int convert_error(const char *s)
+{
+    printf("##\n## ERROR in conv: '%s' (line %d, file: %s)\n##\n", s, line_num, config_file);
+    exit(0);
+}
+
+%}
+
+%union {
+    char na[LONG_M];
+}
+
+%token TOK_SEP
+%token TOK_KIND
+%token TOK_EQUAL
+%token TOK_USE
+%token TOK_MODULEMAIN      /* name of the module                              */
+%token TOK_NOTGRIDDEP      /* Variable which are not grid dependent           */
+%token <na> TOK_USEITEM
+%token <na> TOK_NAME
+%token <na> TOK_CSTINT
+%token <na> TOK_PROBTYPE   /* dimension of the problem                        */
+%token ','
+%token ';'
+
+%%
+
+input :
+    | input line ;
+
+line :
+      '\n'
+    | TOK_PROBTYPE TOK_NAME ';'                             { initdimprob(1,$2,"0","0"); }
+    | TOK_PROBTYPE TOK_NAME ',' TOK_NAME ';'                { initdimprob(2,$2, $4,"0"); }
+    | TOK_PROBTYPE TOK_NAME ',' TOK_NAME ',' TOK_NAME ';'   { initdimprob(3,$2, $4, $6); }
+    | TOK_MODULEMAIN TOK_NAME ';'
+        {
+            listofmodules = Addtolistnom($2,listofmodules,0);
+            Addmoduletothelist($2);
+        }
+    | TOK_KIND TOK_NAME TOK_EQUAL TOK_CSTINT ';'
+        {
+            if (!strcasecmp($4,"4"))
+            {
+                listofkind = Addtolistnom($2,listofkind,4);
+            }
+            else if (!strcasecmp($4,"8"))
+            {
+                listofkind = Addtolistnom($2,listofkind,8);
+            }
+            else
+            {
+                printf("##\n## Unknown kind type : %s (must be 4 or 8)\n##",$4);
+                exit(0);
+            }
+        }
+    | TOK_NOTGRIDDEP TOK_SEP TOK_NAME ';'
+        {
+            Add_NotGridDepend_Var_1($3);
+        }
+    | TOK_USE TOK_USEITEM ';'
+        {
+            if (!strcasecmp($2,"FIXED_GRIDS"))      fixedgrids = 1;
+            if (!strcasecmp($2,"ONLY_FIXED_GRIDS")) onlyfixedgrids = 1;
+        }
+    ;
+%%
+
+void print_usage()
+{
+    printf("usage : conv <config_file> -convfile  <FILENAME>\n");
+    printf(" [-workdir <directory>] [-incdir <directory>]\n");
+    printf(" [-comdirin   <directory>] [-comdirout <directory>]\n");
+    printf(" [-convfile  <FILENAME>] [-SubloopScalar] [-SubloopScalar1] \n");
+    printf(" [-free|-fixed]\n");
+    exit(0);
+}
+
+int main(int argc,char *argv[])
+{
+    extern FILE * convert_in ;
+    FILE *dependglobaloutput;
+    int i;
+    listnom *parcours;
+    listvar *newvar;
+    int stylegiven = 0;
+    int infreegiven ;
+    int infixedgiven ;
+    int lengthmainfile;
+
+    char filetoparse[LONG_FNAME];
+
+/******************************************************************************/
+/*  1-  Variables initialization                                              */
+/******************************************************************************/
+    List_Global_Var = (listvar *) NULL;
+    List_GlobalParameter_Var = (listvar *) NULL;
+    List_Common_Var = (listvar *) NULL;
+    List_Allocate_Var = (listallocate *) NULL;
+    List_SubroutineWhereAgrifUsed = (listnom *) NULL;
+    List_Subroutine_For_Alloc = (listnom *) NULL;
+    List_Include = (listusemodule *) NULL;
+    List_NameOfModuleUsed = (listusemodule *) NULL;
+    listofmoduletmp = (listusemodule *) NULL;
+    List_SubroutineDeclaration_Var = (listvar *) NULL;
+    List_UsedInSubroutine_Var = (listvar *) NULL;
+    List_NotGridDepend_Var = (listvar *) NULL;
+    Listofavailableindices = (listindice *) NULL;
+    Listofavailableindices_glob = (listindice **) calloc(NB_CAT_VARIABLES,sizeof(listindice *));
+    List_CouplePointed_Var = (listvarpointtovar *) NULL;
+    List_ModuleUsed_Var = (listvar *) NULL;
+    List_ModuleUsedInModuleUsed_Var = (listvar *) NULL;
+    List_GlobParamModuleUsed_Var = (listparameter *) NULL;
+    List_GlobParamModuleUsedInModuleUsed_Var = (listparameter *) NULL;
+    List_SubroutineArgument_Var = (listvar *) NULL;
+    List_FunctionType_Var = (listvar *) NULL;
+    tmpuselocallist = (listusemodule *) NULL;
+    List_ContainsSubroutine = (listnom *) NULL;
+    oldfortran_out = (FILE *) NULL;
+
+    if (argc < 2) print_usage();
+    
+    strcpy(config_file, argv[1]);
+    strcpy(work_dir, ".");
+    strcpy(input_dir, ".");
+    strcpy(output_dir, "AGRIF_MODELFILES");
+    strcpy(include_dir, "AGRIF_INC");
+    strcpy(filetoparse, "");
+    strcpy(subofagrifinitgrids, "");
+    strcpy(meetagrifinitgrids, "");
+    strcpy(mpiinitvar, "");
+
+    length_last = 0 ;
+    length_first = 0 ;
+    length_v_vallengspec = 0 ;
+    length_v_commoninfile = 0 ;
+    length_v_precision = 0 ;
+    length_v_IntentSpec = 0 ;
+    length_v_initialvalue = 0 ;
+    length_v_readedlistdimension = 0 ;
+    length_a_nomvar = 0 ;
+    length_toprintglob = 0 ;
+    length_tmpvargridname = 0 ;
+    length_ligne_Subloop = 0 ;
+    length_toprint_utilagrif = 0 ;
+    length_toprinttmp_utilchar = 0 ;
+    length_ligne_writedecl = 0 ;
+    length_newname_toamr = 0 ;
+    length_newname_writedecl = 0 ;
+    length_ligne_toamr = 0 ;
+    length_tmpligne_writedecl = 0 ;
+    value_char_size = 0 ;
+    value_char_size1 = 0 ;
+    value_char_size2 = 0 ;
+    value_char_size3 = 0 ;
+    inallocate = 0;
+    infixed = 1;
+    infree  = 0;
+
+    onlyfixedgrids=0;
+    fixedgrids=0;
+    InAgrifParentDef = 0;
+    IndicenbmaillesX=0;
+    IndicenbmaillesY=0;
+    IndicenbmaillesZ=0;
+    created_dimensionlist = 1;
+    /* current indice in the table tabvars             */
+    for ( i=0 ; i<NB_CAT_VARIABLES ; i++)
+    {
+        indicemaxtabvars[i] = 0;
+    }
+    SubloopScalar = 0;
+    todebug = 0;
+    retour77 = 1 ;
+    shouldincludempif = 0 ;
+
+    Read_val_max();
+
+/******************************************************************************/
+/*  2-  Program arguments                                                     */
+/******************************************************************************/
+
+    if ( (convert_in=fopen(config_file,"r")) == NULL )
+    {
+        printf("##\n## ERROR: the configuration file '%s' doesn't exist.\n##\n", config_file);
+        print_usage();
+    }
+
+    i=2;
+    while ( i < argc )
+    {
+        if (!strcasecmp(argv[i], "-workdir"))
+        {
+            strcpy(work_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-incdir"))
+        {
+            strcpy(include_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-comdirin")) /* input directory           */
+        {
+            strcpy(input_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-comdirout")) /* output directory         */
+        {
+            strcpy(output_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-convfile")) /* file to parse             */
+        {
+            strcpy(filetoparse, argv[i+1]);
+            i++;
+            lengthmainfile = strlen(filetoparse);
+            if (!strcasecmp(&filetoparse[lengthmainfile-4], ".f90"))
+            {
+                infixed = 0;
+                infree = 1;
+            }
+            else
+            {
+                infixed = 1;
+                infree = 0;
+            }
+        }
+        else if (!strcasecmp(argv[i], "-free"))
+        {
+            stylegiven = 1;
+            infreegiven  = 1 ;
+            infixedgiven = 0;
+        }
+        else if (!strcasecmp(argv[i], "-fixed"))
+        {
+            stylegiven = 1;
+            infreegiven  = 0;
+            infixedgiven = 1;
+        }
+        else if (!strcasecmp(argv[i], "-SubloopScalar"))
+        {
+            SubloopScalar = 1 ;
+        }
+        else if (!strcasecmp(argv[i], "-SubloopScalar1"))
+        {
+            SubloopScalar = 2 ;
+        }
+        else if (!strcasecmp(argv[i], "-todebug"))
+        {
+            todebug = 1 ;
+        }
+        else if (!strcasecmp(argv[i],"-rm")) { }
+        else
+        {
+            printf("##\n## Unkwon option : %s\n##\n", argv[i]);
+            exit(0);
+        }
+        i++;
+    }
+    // Check input file
+    if ( strlen(filetoparse) == 0 )         // -convfile has not been specified
+    {
+        printf("##\n## ERROR: please provide a file to parse with -convfile.\n##\n");
+        print_usage();
+    }
+    // Setup input & output directories
+    if ( strcasecmp(work_dir, ".") != 0 )   // -workdir has been changed...
+    {
+        if ( strcasecmp(input_dir,  ".") == 0 )                 // ...and -comdirin  has NOT been changed
+        {
+            strcpy(input_dir, work_dir);
+        }
+        if ( strcasecmp(output_dir, "AGRIF_MODELFILES") == 0 )  // ...and -comdirout has NOT been changed
+        {
+            sprintf(output_dir, "%s/%s", work_dir, "AGRIF_MODELFILES");
+        }
+        if ( strcasecmp(include_dir, "AGRIF_INC") == 0 )        // ...and -incdir    has NOT been changed
+        {
+            sprintf(include_dir, "%s/%s", work_dir, "AGRIF_INC");
+        }
+    }
+    if (stylegiven == 1)
+    {
+        infree  = infreegiven;
+        infixed = infixedgiven;
+    }
+
+/******************************************************************************/
+/*  3-  Parsing of the conv file <name>.in                                    */
+/******************************************************************************/
+
+    if ( strstr(filetoparse, ".f90") || strstr(filetoparse, ".F90") ) retour77 = 0;
+
+    convert_parse();
+
+/******************************************************************************/
+/*  4-  Preparation of the file parsing                                       */
+/******************************************************************************/
+
+    sprintf(dependfilename, "%s/.dependglobal_agrif", work_dir);
+    /*                                                                         */
+    if ( (dependglobaloutput=fopen(dependfilename, "r")) != NULL )
+    {
+        for (i=0;i<NB_CAT_VARIABLES;i++)
+        {
+            fscanf(dependglobaloutput,"%d\n",&indicemaxtabvars[i]);
+        }
+        fclose(dependglobaloutput);
+    }
+    Readthedependavailablefile();
+    /* Read the .dependnbxnby file which contains indices of nbmaillsX, nbmailleY and nbmailleZ */
+    Readthedependnbxnbyfile();
+    Read_Subroutine_For_Alloc();
+
+/******************************************************************************/
+/*  5-  Parsing of the input file (2 times)                                   */
+/******************************************************************************/
+
+    /* Record all variables in list                                            */
+    firstpass = 1;
+    process_fortran(filetoparse);
+
+    CompleteThelistvarindoloop();
+    /* Read list of module used                                                */
+    RecordUseModulesVariables();
+    /* Read list of module used in module used                                 */
+    RecordUseModulesUseModulesVariables();
+    /* Save variables are considered as globals ones                           */
+    Update_List_Global_Var_From_List_Save_Var();
+    /* Update all lists                                                        */
+    ListUpdate();
+
+    Clean_List_Global_Var();
+    /* Indice tabvars identification                                           */
+    IndiceTabvarsIdentification();
+    /* Update all lists                                                        */
+    ListUpdate();
+    /* The allocation subroutine is necessary ????                             */
+    New_Allocate_Subroutine_Is_Necessary();
+    /* The allocation subroutine is necessary for common list                  */
+    New_Allocate_Subroutine_For_Common_Is_Necessary();
+    /* Sort List_SubroutineArgument_Var                                        */
+    Sort_List_SubroutineArgument_Var();
+    /* Clean all lists                                                         */
+    ListClean();
+    /* Update Indice of List_UsedInSubroutine_Var from module used             */
+    List_UsedInSubroutine_Var_Update_From_Module_Used();
+    /* Update List_SubroutineWhereAgrifUsed                                    */
+    UpdateList_SubroutineWhereAgrifUsed();
+    /* Update List_UsedInSubroutine_Var with v_readedlistdimension             */
+    UpdateList_UsedInSubroutine_With_dimension();
+
+    ModifyThelistvarindoloop();
+    UpdateListDeclarationWithDimensionList();
+    GiveTypeOfVariables();
+
+    /* Build new subroutines                                                   */
+    firstpass = 0;
+    process_fortran(filetoparse);
+
+    newvar = (listvar *) NULL;
+
+    while ( newvar )
+    {
+        printf("++++ %s %d %s %s %s\n",
+            newvar->var->v_nomvar,
+            newvar->var->v_nbdim,
+            newvar->var->v_subroutinename,
+            newvar->var->v_modulename,
+            newvar->var->v_typevar);
+        newvar = newvar->suiv;
+    }
+
+/******************************************************************************/
+/*  6-  Write informations in output files                                    */
+/******************************************************************************/
+
+    /* Write the .dependglobal_agrif file which contain the max indice         */
+    /*    of the tabvars table                                                 */
+    sprintf(dependfilename, "%s/.dependglobal_agrif", work_dir);
+    dependglobaloutput = fopen(dependfilename, "w");
+    for (i=0;i<NB_CAT_VARIABLES;i++)
+    {
+        fprintf(dependglobaloutput,"%d\n",indicemaxtabvars[i]);
+    }
+    fclose(dependglobaloutput);
+    /* Write the list of available indice                                      */
+    Writethedependavailablefile();
+    /* Write the .dependnbxnby file which contains indices of nbmaillsX,       */
+    /*    nbmailleY and nbmailleZ                                              */
+    Writethedependnbxnbyfile();
+    /* Write the .depend<namefile> file which contain general informations     */
+    /*    about variable of this file                                          */
+    parcours = List_NameOfModule;
+    while( parcours )
+    {
+        Writethedependlistofmoduleused(parcours->o_nom);
+        WritedependParameterList(parcours->o_nom);
+        Writethedependfile(parcours->o_nom,List_Global_Var);
+        parcours=parcours->suiv;
+    }
+    parcours = List_NameOfCommon;
+    while( parcours )
+    {
+        Writethedependfile(parcours->o_nom,List_Common_Var);
+        parcours=parcours->suiv;
+    }
+    Write_Subroutine_For_Alloc();
+
+/******************************************************************************/
+/*  7-  Create files in AGRIF_INC directory                                   */
+/******************************************************************************/
+
+    creefichieramr();
+
+    Write_val_max();
+
+    if ( todebug == 1 ) printf("Out of CONV \n");
+    return 0;
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/decl.h
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/decl.h	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/decl.h	(revision 9987)
@@ -0,0 +1,662 @@
+/******************************************************************************/
+/*                                                                            */
+/*     CONV (converter) for Agrif (Adaptive Grid Refinement In Fortran)       */
+/*                                                                            */
+/* Copyright or   or Copr. Laurent Debreu (Laurent.Debreu@imag.fr)            */
+/*                        Cyril Mazauric (Cyril_Mazauric@yahoo.fr)            */
+/* This software is governed by the CeCILL-C license under French law and     */
+/* abiding by the rules of distribution of free software.  You can  use,      */
+/* modify and/ or redistribute the software under the terms of the CeCILL-C   */
+/* license as circulated by CEA, CNRS and INRIA at the following URL          */
+/* "http://www.cecill.info".                                                  */
+/*                                                                            */
+/* As a counterpart to the access to the source code and  rights to copy,     */
+/* modify and redistribute granted by the license, users are provided only    */
+/* with a limited warranty  and the software's author,  the holder of the     */
+/* economic rights,  and the successive licensors  have only  limited         */
+/* liability.                                                                 */
+/*                                                                            */
+/* In this respect, the user's attention is drawn to the risks associated     */
+/* with loading,  using,  modifying and/or developing or reproducing the      */
+/* software by the user in light of its specific status of free software,     */
+/* that may mean  that it is complicated to manipulate,  and  that  also      */
+/* therefore means  that it is reserved for developers  and  experienced      */
+/* professionals having in-depth computer knowledge. Users are therefore      */
+/* encouraged to load and test the software's suitability as regards their    */
+/* requirements in conditions enabling the security of their systems and/or   */
+/* data to be ensured and,  more generally, to use and operate it in the      */
+/* same conditions as regards security.                                       */
+/*                                                                            */
+/* The fact that you are presently reading this means that you have had       */
+/* knowledge of the CeCILL-C license and that you accept its terms.           */
+/******************************************************************************/
+/* version 1.7                                                                */
+/******************************************************************************/
+#define LONG_VNAME 80		// Max length for a variable name
+#define LONG_FNAME 1000		// Max length for a file name
+#define LONG_C     200
+#define LONG_M     1500
+
+#define NB_CAT_VARIABLES 5
+
+/******************************************************************************/
+/*********** Declaration of structures used in conv ***************************/
+/******************************************************************************/
+
+typedef struct
+{
+   char first[LONG_M];
+   char last[LONG_M];
+} typedim ;                /* fortran dimension as 'ndeb:nfin'                */
+
+typedef struct listdim
+{
+   typedim dim;
+   struct listdim *suiv;
+} listdim;                 /* list of the dimensions of a variable            */
+
+typedef struct variable
+{
+   char v_typevar[LONG_VNAME];
+   char v_nomvar[LONG_VNAME] ;
+   char v_oldname[LONG_VNAME] ;
+   char v_dimchar[LONG_VNAME];
+   char v_modulename[LONG_VNAME];
+   char v_commonname[LONG_VNAME];
+   char v_vallengspec[LONG_VNAME];
+   char v_nameinttypename[LONG_VNAME];
+   char v_commoninfile[LONG_FNAME];
+   char v_subroutinename[LONG_VNAME];
+   char v_precision[LONG_C];
+   char v_initialvalue[LONG_M];
+   char v_IntentSpec[LONG_M];
+   char v_readedlistdimension[LONG_M];
+   int  v_nbdim;
+   int  v_common;
+   int  v_positioninblock;
+   int  v_module;
+   int  v_save;
+   int  v_catvar;
+   int  v_VariableIsParameter;
+   int  v_PublicDeclare;
+   int  v_PrivateDeclare;
+   int  v_ExternalDeclare;
+   int  v_pointedvar;
+   int  v_notgrid;
+   int  v_dimensiongiven;
+   int  v_c_star;
+   int  v_indicetabvars;
+   int  v_pointerdeclare;
+   int  v_optionaldeclare;
+   int  v_allocatable;
+   int  v_target;
+   int  v_dimsempty;
+   listdim *v_dimension;
+} variable ;               /* type of a variable                              */
+                           /* v_typevar : type (integer, real, ...)           */
+                           /* v_nomvar : name of the variable                 */
+                           /* v_dimension : list of dimensions of the variable*/
+                           /* v_nbdim: 1 if the variable is 1d, etc ...       */
+                           /* precision : Name of the variable which          */
+                           /* determine the precision. example : wp in the    */
+                           /* case where REAL(wp)                             */
+
+typedef struct listvar
+{
+   variable *var ;
+   struct listvar * suiv;
+} listvar ;                /* list of variables                               */
+
+
+typedef struct listusemodule
+{
+   char u_usemodule[LONG_VNAME];
+   char u_charusemodule[LONG_VNAME];
+   char u_cursubroutine[LONG_VNAME];
+   char u_modulename[LONG_VNAME];
+   int  u_firstuse;
+   struct listusemodule * suiv;
+} listusemodule;           /* list of names                                   */
+
+typedef struct listparameter
+{
+   char p_name[LONG_M];
+   char p_modulename[LONG_M];
+   struct listparameter * suiv;
+} listparameter ;           /* list of names                                  */
+
+typedef struct listname
+{
+   char n_name[LONG_VNAME];
+   struct  listname* suiv;
+} listname ;            /* list of names                                  */
+
+typedef struct listcouple
+{
+   char c_namevar[LONG_VNAME];
+   char c_namepointedvar[LONG_VNAME];
+   struct listcouple * suiv;
+} listcouple;              /* list of names                                   */
+
+
+typedef struct listnom
+{
+   char o_nom[LONG_C];
+   char o_module[LONG_VNAME];
+   char o_subroutinename[LONG_M];
+   int  o_val;
+   listcouple *couple;
+   struct listnom * suiv;
+} listnom;                 /* list of names                                   */
+
+
+typedef struct listallocate
+{
+   char a_nomvar[LONG_C];
+   char a_subroutine[LONG_VNAME];
+   char a_module[LONG_VNAME];
+   struct listallocate * suiv;
+} listallocate ;
+
+
+typedef struct listvarpointtovar
+{
+   char t_usemodule[LONG_VNAME];
+   char t_cursubroutine[LONG_VNAME];
+   listcouple *t_couple;
+   struct  listvarpointtovar* suiv;
+}listvarpointtovar ;       /* list of names                                   */
+
+
+typedef struct listindice
+{
+   int i_indice;
+   struct  listindice * suiv;
+} listindice;              /* list of indiced                                 */
+
+ variable *curvar;
+
+ listvar *List_ModuleUsedInModuleUsed_Var;
+ listvar *List_ModuleUsed_Var;
+ listvar *listduplicated;
+
+ listvar *List_GlobalParameter_Var;
+ listvar *List_Global_Var;
+ listvar *List_Data_Var;
+ listvar *List_Data_Var_Cur;
+ listvar *List_Save_Var;
+ listvar *List_SubroutineArgument_Var;
+ listvar *List_SubroutineDeclaration_Var;
+ listvar *List_UsedInSubroutine_Var;
+ listvar *List_Parameter_Var;
+ listvar *List_Dimension_Var;
+ listvar *List_FunctionType_Var;
+ listvar *List_NotGridDepend_Var;
+ listvar *List_Common_Var;
+
+
+ listname *List_Pointer_Var;
+ listname *List_ImplicitNoneSubroutine;
+
+ listusemodule *List_NameOfModuleUsed;
+ listusemodule *List_Include;
+ listusemodule *listofmoduletmp;
+ listusemodule *tmpuselocallist;
+
+ listparameter *List_GlobParamModuleUsedInModuleUsed_Var;
+ listparameter *List_GlobParamModuleUsed_Var;
+
+ listnom *List_ContainsSubroutine;
+ listnom *List_Subroutine_For_Alloc;
+ listnom *listofmodules;
+ listnom *listofkind;
+ listnom *List_NameOfModule;
+ listnom *List_NameOfCommon;
+ listnom *List_SubroutineWhereAgrifUsed;
+
+ listallocate *List_Allocate_Var;
+
+ listvarpointtovar *List_CouplePointed_Var;
+                           /*  variables which are pointed to an other one    */
+
+ listindice *Listofavailableindices;
+                           /* List of available indices in the tabvars table  */
+ listindice **Listofavailableindices_glob;
+
+ listdim *curdim;
+ listdim *commondim;
+
+/******************************************************************************/
+/****************   *** COMMON Variables ***  *********************************/
+/******************************************************************************/
+
+ int positioninblock;
+ char commonvar[LONG_VNAME];
+ char commonblockname[LONG_VNAME];
+
+/******************************************************************************/
+/****************   *** AGRIF Variables ***   *********************************/
+/******************************************************************************/
+ int inagrifcallargument;
+ int afterpercent;
+ int sameagrifargument;
+ int InAgrifParentDef;
+ char sameagrifname[LONG_VNAME];
+/******************************************************************************/
+/****************   *** VAR DEF Variables ***   *******************************/
+/******************************************************************************/
+ int indicemaxtabvars[NB_CAT_VARIABLES];     /* Number of variables in the model i.e. last      */
+                           /*    indice used in  the tabvars table            */
+ int PublicDeclare;        /* Variable has been declared as PUBLIC */
+ int PrivateDeclare;       /* Variable has been declared as PRIVATE */
+ int ExternalDeclare;      /* Variable has been declared as EXTERNAL */
+ int InitialValueGiven;    /* An initial value has been given */
+ int Allocatabledeclare;
+ int Targetdeclare;
+ int SaveDeclare;
+ int functiondeclarationisdone;
+ int pointerdeclare;
+ int optionaldeclare;
+ int inside_type_declare;
+ int VariableIsParameter;
+ int dimsgiven;
+ int shouldincludempif;
+ int c_star;
+ char DeclType[LONG_VNAME];
+ char nameinttypename[LONG_VNAME];
+ char nameinttypenameback[LONG_VNAME];
+ int GlobalDeclaration;
+ int GlobalDeclarationType;
+ char InitValue[LONG_M];
+ char IntentSpec[LONG_M];
+ char NamePrecision[LONG_C];
+ char CharacterSize[LONG_VNAME];
+ char vallengspec[LONG_VNAME];
+ int isrecursive;
+ int is_result_present;
+
+/******************************************************************************/
+/****************   *** CONV Variables ***   **********************************/
+/******************************************************************************/
+ int dimprob ;             /* dimension of the problem : 1 for 1D,2 for 2D,   */
+                           /*    3 for 3D                                     */
+ int onlyfixedgrids;       /* = 1 if onlyfixedgrids is true                   */
+ int todebug;
+ int fixedgrids;           /* = 1 if fixedgrids is true                       */
+ char nbmaillesX[LONG_VNAME];	// number of cells in the x direction
+ char nbmaillesY[LONG_VNAME];	// number of cells in the y direction
+ char nbmaillesZ[LONG_VNAME];	// number of cells in the z direction
+ int IndicenbmaillesX;
+ int IndicenbmaillesY;
+ int IndicenbmaillesZ;
+
+ int inmodulemeet;
+ int incalldeclare;
+ int aftercontainsdeclare; /* Signale si l'on vient d'un contains ou non */
+ int retour77;
+ int callagrifinitgrids;
+ int callmpiinit;
+ int firstpass;
+ int pointedvar;
+ int NbMailleXDefined;
+ int agrif_parentcall;
+ int didvariableadded;
+ int SubloopScalar;        /* = 1 we should put in argument of sub_loop       */
+                           /*    only                                         */
+                           /*    scalar and not table u(1,1,1) in place of u  */
+ int inprogramdeclare;
+ int insubroutinedeclare;
+ int inmoduledeclare;
+ int dimsempty;
+ int created_dimensionlist;
+ int incontainssubroutine;
+
+ char meetagrifinitgrids[LONG_M];
+ char mpiinitvar[LONG_M];
+ char toprintglob[LONG_M];
+ char tmpvargridname[LONG_M];
+ char dependfilename[LONG_FNAME];
+ char charusemodule[LONG_VNAME];
+ char subofagrifinitgrids[LONG_M];
+ char curmodulename[LONG_VNAME];
+ char subroutinename[LONG_VNAME];
+ char cur_filename[LONG_FNAME];		// Name of the current parsed Fortran file
+ char config_file[LONG_FNAME];		// Name of conv configuration file (ex: amr.in)
+ char work_dir[LONG_FNAME];			// Work directory         (default: './')
+ char include_dir[LONG_FNAME];		// Include directory      (default: './AGRIF_INC')
+ char output_dir[LONG_FNAME];		// output directory       (default: './AGRIF_MODELFILES')
+ char input_dir[LONG_FNAME];		// source input directory (default: './')
+
+ FILE *fortran_out;          /* Output File                                    */
+ FILE *fortran_in;           /* Input File                                     */
+ FILE *oldfortran_out;
+ FILE *subloop;
+ FILE *module_declar;
+ FILE *allocationagrif;
+
+ long int pos_cur;         /* current position in the output file             */
+ long int pos_curagrifparent;
+                           /* current position in the output file             */
+ long int pos_curcall;     /* current position in the output file             */
+ long int pos_curuse;      /* current position in the output file             */
+ long int pos_curuseold;   /* current position in the output file             */
+ long int pos_curfunction; /* current position in the output file             */
+ long int pos_cur_decl;    /* current position in the output file             */
+ long int pos_curdata;     /* current position in the output file             */
+ long int pos_curparameter;/* current position in the output file             */
+ long int pos_curcommon;   /* current position in the output file             */
+ long int pos_cursave;     /* current position in the output file             */
+ long int pos_curdimension;/* current position in the output file             */
+ long int pos_curinclude;  /* final position of a line in file                */
+ long int pos_end;         /* final position of a line in file                */
+ long int pos_endsubroutine;
+                           /* final position of a line in file                */
+
+size_t length_last;
+size_t length_first;
+size_t length_v_vallengspec;
+size_t length_v_commoninfile;
+size_t length_v_precision;
+size_t length_v_IntentSpec;
+size_t length_v_initialvalue;
+size_t length_v_readedlistdimension;
+size_t length_a_nomvar;
+size_t length_toprintglob;
+size_t length_tmpvargridname;
+size_t length_ligne_Subloop;
+size_t length_toprint_utilagrif;
+size_t length_toprinttmp_utilchar;
+size_t length_ligne_writedecl;
+size_t length_newname_toamr;
+size_t length_newname_writedecl;
+size_t length_ligne_toamr;
+size_t length_tmpligne_writedecl;
+ int value_char_size;
+ int value_char_size1;
+ int value_char_size2;
+ int value_char_size3;
+
+
+ int inallocate;
+ int infixed;
+ int infree;
+/******************************************************************************/
+/*********** Declaration of externals subroutines *****************************/
+/***************************************************** ************************/
+extern char *fortran_text;
+/******************************************************************************/
+/*********** convert.y ********************************************************/
+/******************************************************************************/
+extern int main(int argc,char *argv[]);
+extern int convert_error(const char *s);
+/******************************************************************************/
+/*********** fortran.y ********************************************************/
+/******************************************************************************/
+extern void process_fortran(const char *input_file);
+extern int fortran_error(const char *s);
+/******************************************************************************/
+/*********** dependfile.c *****************************************************/
+/******************************************************************************/
+extern void Writethedependnbxnbyfile();
+extern void Readthedependnbxnbyfile();
+extern void Writethedependlistofmoduleused(const char *NameTampon );
+extern void Readthedependlistofmoduleused(const char *NameTampon);
+extern void WritedependParameterList(const char *NameTampon );
+extern listparameter *ReaddependParameterList(const char *NameTampon, listparameter *listout);
+extern void Writethedependfile(const char *NameTampon, listvar *input );
+extern listvar *Readthedependfile(const char *NameTampon , listvar *listout);
+extern void Write_Subroutine_For_Alloc();
+extern void Read_Subroutine_For_Alloc();
+extern void Writethedependavailablefile();
+extern void Readthedependavailablefile();
+extern int is_dependfile_created(const char *NameTampon);
+extern void Write_val_max();
+extern void Read_val_max();
+/******************************************************************************/
+/*********** DiversListe.c ****************************************************/
+/******************************************************************************/
+extern void Add_Common_var_1();
+extern listnom  *Addtolistnom(const char *nom, listnom *listin, int value);
+extern listname *Addtolistname(const char *nom, listname *input);
+extern int ModuleIsDefineInInputFile(const char *name);
+extern void Addmoduletothelisttmp(const char *name);
+extern void Add_NameOfModule_1(const char *nom);
+extern void Add_NameOfCommon_1(const char *nom, const char *cursubroutinename);
+extern void Add_CouplePointed_Var_1(const char *namemodule, listcouple *couple);
+extern void Add_Include_1(const char *name);
+extern void Add_ImplicitNoneSubroutine_1();
+extern void WriteIncludeDeclaration(FILE* tofile);
+extern void Add_Save_Var_1 (const char *name,listdim *d);
+extern void Add_Save_Var_dcl_1 (listvar *var);
+/******************************************************************************/
+/*********** SubLoopCreation.c ************************************************/
+/******************************************************************************/
+extern void WriteBeginof_SubLoop();
+extern void WriteVariablelist_subloop(char *ligne);
+extern void WriteVariablelist_subloop_Call(char **ligne, size_t line_length);
+extern void WriteVariablelist_subloop_Def(char *ligne);
+extern void WriteHeadofSubroutineLoop();
+extern void closeandcallsubloopandincludeit_0(int suborfun);
+extern void closeandcallsubloop_contains_0();
+/******************************************************************************/
+/*********** toamr.c **********************************************************/
+/******************************************************************************/
+extern void WARNING_CharSize(const variable *var);
+extern const char * tabvarsname(const variable *var);
+extern const char * variablecurgridtabvars(int which_grid);
+extern const char * vargridnametabvars(const variable *var, int iorindice);
+extern const char * vargridcurgridtabvars(const variable *var, int which_grid);
+extern const char * vargridcurgridtabvarswithoutAgrif_Gr(const variable *var);
+extern const char * vargridparam(const variable *var);
+extern void write_probdimagrif_file();
+extern void write_keysagrif_file();
+extern void write_modtypeagrif_file();
+extern void write_createvarnameagrif_file(variable *v,FILE *createvarname,int *InitEmpty);
+extern void write_initialisationsagrif_file(variable *v,FILE *initproc,int *VarnameEmpty);
+extern void write_Setnumberofcells_file();
+extern void write_Getnumberofcells_file();
+extern void Write_Alloc_Agrif_Files();
+extern int IndiceInlist(int indic, listindice *listin);
+extern void write_allocation_Common_0();
+extern void write_allocation_Global_0();
+extern void creefichieramr();
+/******************************************************************************/
+/*********** UtilAgrif.c ******************************************************/
+/******************************************************************************/
+extern int Vartonumber(const char *tokname);
+extern int Agrif_in_Tok_NAME(const char *tokname);
+extern void ModifyTheVariableName_0(const char *ident,int lengthname);
+extern void Add_SubroutineWhereAgrifUsed_1(const char *sub, const char *mod);
+extern void AddUseAgrifUtil_0(FILE *fileout);
+extern void AddUseAgrifUtilBeforeCall_0(FILE *fileout);
+extern void NotifyAgrifFunction_0(const char *ident);
+extern void ModifyTheAgrifFunction_0(const char *ident);
+extern void AgriffunctionModify_0(const char *ident,int whichone);
+extern void Instanciation_0(const char *ident);
+/******************************************************************************/
+/*********** UtilCharacter.c **************************************************/
+/******************************************************************************/
+extern void FindAndChangeNameToTabvars(const char name[LONG_M],char toprint[LONG_M],
+                                             listvar * listtosee, int whichone);
+extern const char *ChangeTheInitalvaluebyTabvarsName(const char *nom,listvar *listtoread);
+extern int IsVariableReal(const char *nom);
+extern void IsVarInUseFile(const char *nom);
+extern listnom *DecomposeTheNameinlistnom(const char *nom, listnom * listout);
+extern void DecomposeTheName(const char *nom);
+extern void convert2lower(char *lowername, const char* inputname);
+extern int convert2int(const char *name);
+/******************************************************************************/
+/*********** UtilFile.c *******************************************************/
+/******************************************************************************/
+extern FILE * open_for_write (const char *filename);
+extern FILE * open_for_append (const char *filename);
+extern long int setposcur();
+extern long int setposcurname(FILE *fileout);
+extern void copyuse_0(const char *namemodule);
+extern void copyuseonly_0(const char *namemodule);
+/******************************************************************************/
+/*********** UtilFortran.c ****************************************************/
+/******************************************************************************/
+extern void initdimprob(int dimprobmod, const char *nx, const char *ny, const char *nz);
+extern int Variableshouldberemoved(const char *nom);
+extern int variableisglobal(listvar *curvar, listvar *listin);
+extern int VariableIsInListCommon(listvar *curvar,listvar *listin);
+extern int VariableIsInList(listvar *curvar,listvar *listin);
+extern void variableisglobalinmodule(listcouple *listin, const char *module,
+                                                                 FILE *fileout,long int oldposcuruse);
+extern void Write_Word_end_module_0();
+extern void Add_Subroutine_For_Alloc(const char *nom);
+extern void Write_Closing_Module();
+extern int IsTabvarsUseInArgument_0();
+extern int ImplicitNoneInSubroutine();
+extern void Add_Pointer_Var_From_List_1(listvar *listin);
+extern void Add_Pointer_Var_1(char *nom);
+extern int varispointer_0(char *ident);
+extern int VariableIsFunction(const char *ident);
+extern int varistyped_0(char *ident);
+extern void dump_var(const variable* var);
+/******************************************************************************/
+/*********** UtilListe.c ******************************************************/
+/******************************************************************************/
+extern void Init_Variable(variable *var);
+extern listvar * AddListvarToListvar(listvar *l,listvar *glob, int ValueFirstpass);
+extern void CreateAndFillin_Curvar(const char *type, variable *curvar);
+// extern void duplicatelistvar(listvar *orig);
+extern listdim * insertdim(listdim *lin,typedim nom);
+extern void change_dim_char(listdim *lin,listvar * l);
+extern int get_num_dims(const listdim *d);
+extern variable * createvar(const char *nom, listdim *d);
+extern listvar * insertvar(listvar *lin,variable *v);
+extern listvar * settype(const char *nom,listvar *lin);
+extern void printliste(listvar * lin);
+extern int IsinListe(listvar *lin,char *nom);
+extern listname *Insertname(listname *lin,char *nom,int sens);
+extern listname *concat_listname(listname *l1, listname *l2);
+extern void createstringfromlistname(char *ligne, listname *lin);
+extern void printname(listname * lin);
+extern void removeglobfromlist(listname **lin);
+extern void writelistpublic(listname *lin);
+extern void Init_List_Data_Var();
+extern void  addprecision_derivedfromkind(variable *curvar);
+extern int get_cat_var(variable *var);
+/******************************************************************************/
+/*********** UtilNotGridDep.c *************************************************/
+/******************************************************************************/
+extern void Add_NotGridDepend_Var_1 (char *name);
+extern int VarIsNonGridDepend(char *name);
+/******************************************************************************/
+/*********** WorkWithAllocatelist.c *******************************************/
+/******************************************************************************/
+extern void Add_Allocate_Var_1(const char *nom, const char *nommodule);
+extern int IsVarAllocatable_0(const char *ident);
+/******************************************************************************/
+/*********** WorkWithglobliste.c **********************************************/
+/******************************************************************************/
+extern void Add_Globliste_1(listvar *listtoadd);
+extern void Add_SubroutineDeclarationSave_Var_1(listvar *listtoadd);
+extern void checkandchangedims(listvar *listsecondpass);
+/******************************************************************************/
+/*********** WorkWithlistdatavariable.c ***************************************/
+/******************************************************************************/
+extern void Add_Data_Var_1 (listvar **curlist,char *name,char *values);
+extern void Add_Data_Var_Names_01 (listvar **curlist,listname *l1, listname *l2);
+/******************************************************************************/
+/*********** WorkWithlistmoduleinfile.c ***************************************/
+/******************************************************************************/
+extern void Save_Length(const char *nom, int whichone);
+extern void Save_Length_int(int val, int whichone);
+/******************************************************************************/
+/*********** WorkWithlistofmodulebysubroutine.c *******************************/
+/******************************************************************************/
+extern void RecordUseModulesVariables();
+extern void  RecordUseModulesUseModulesVariables();
+extern void Add_NameOfModuleUsed_1(char *name);
+extern void Addmoduletothelist(const char *name);
+extern void WriteUsemoduleDeclaration(const char *cursubroutinename);
+/******************************************************************************/
+/*********** WorkWithlistvarindoloop.c ****************************************/
+/******************************************************************************/
+extern void Add_UsedInSubroutine_Var_1 (const char *ident);
+extern void ajoutevarindoloop_definedimension (char *name);
+extern void  ModifyThelistvarindoloop();
+extern void  CompleteThelistvarindoloop();
+extern void Merge_Variables(variable *var1,variable *var2);
+extern void Update_List_Subroutine_Var(listvar *list_to_modify);
+extern void Update_List_Global_Var_From_List_Save_Var();
+extern void Update_List_From_Common_Var(listvar *list_to_modify);
+extern void Update_List_Var(listvar *list_to_modify);
+extern void List_UsedInSubroutine_Var_Update_From_Module_Used();
+extern void Update_NotGridDepend_Var(listvar *list_to_modify);
+extern int LookingForVariableInList(listvar *listin,variable *var);
+extern int LookingForVariableInListGlobal(listvar *listin,variable *var);
+extern int LookingForVariableInListName(listvar *listin,const char *var);
+extern int LookingForVariableInListGlob(listvar *listin,variable *var);
+extern int LookingForVariableInListParamGlob(listparameter *listin, variable *var);
+extern variable *get_variable_in_list_from_name(listvar *listin, const char *name);
+extern void UpdateListDeclarationWithDimensionList();
+extern void Clean_List_UsedInSubroutine_Var();
+extern void Clean_List_ModuleUsed_Var();
+extern void Clean_List_SubroutineDeclaration_Var();
+extern void Clean_List_Global_Var();
+extern void ListClean();
+extern void ListUpdate();
+extern void GiveTypeOfVariables();
+extern void Sort_List_SubroutineArgument_Var();
+extern void IndiceTabvars_Global_Var_Treated(char *nom);
+extern void IndiceTabvars_Global_Var_No_Treated(char *nom);
+extern void UpdateTheRemainingList(listvar *record);
+extern void IndiceTabvars_Common_Var_Treated(char *nom);
+extern void IndiceTabvars_Common_Var_No_Treated(char *nom);
+extern void IndiceTabvarsIdentification();
+extern void New_Allocate_Subroutine_Is_Necessary();
+extern void New_Allocate_Subroutine_For_Common_Is_Necessary();
+extern void NewModule_Creation_0();
+extern void UpdateList_SubroutineWhereAgrifUsed();
+extern void UpdateList_UsedInSubroutine_With_dimension();
+extern void Affiche(listvar *parcours);
+extern int SubInList_ContainsSubroutine();
+extern void update_indicemaxtabvars(variable *var,listindice **Listofindices);
+/******************************************************************************/
+/*********** WorkWithParameterlist.c ******************************************/
+/******************************************************************************/
+extern void Add_GlobalParameter_Var_1(listvar *listin);
+extern void Add_Parameter_Var_1(listvar *listin);
+extern void Add_Dimension_Var_1(listvar *listin);
+/******************************************************************************/
+/*********** WorkWithvarofsubroutineliste.c ***********************************/
+/******************************************************************************/
+extern void Add_SubroutineArgument_Var_1(listvar *listtoadd);
+extern void Add_FunctionType_Var_1(const char *nom);
+// extern void Add_SubroutineDeclaration_Var_1 (listvar *listtoadd);
+/******************************************************************************/
+/*********** Writedeclarations.c **********************************************/
+/******************************************************************************/
+extern void WriteBeginDeclaration(variable *v,char ligne[LONG_M],int visibility);
+extern void WriteScalarDeclaration(variable *v,char ligne[LONG_M]);
+extern void WriteTableDeclaration(variable * v,char ligne[LONG_M],int tmpok);
+extern void WriteVarDeclaration( variable *v, FILE *fileout, int value, int visibility );
+extern void WriteLocalParamDeclaration(FILE* tofile);
+extern void WriteFunctionDeclaration(FILE* tofile, int value);
+extern void WriteSubroutineDeclaration(int value);
+extern void WriteArgumentDeclaration_beforecall();
+extern void WriteArgumentDeclaration_Sort(FILE* tofile);
+extern listnom * writedeclarationintoamr(listvar *deb_common, FILE *fileout, variable *var,
+						const char *commonname, listnom *neededparameter, const char *name_common);
+extern void writesub_loopdeclaration_scalar(listvar *deb_common, FILE *fileout);
+extern void writesub_loopdeclaration_tab(listvar *deb_common, FILE *fileout);
+extern void ReWriteDeclarationAndAddTosubroutine_01(listvar *listdecl);
+extern void ReWriteDataStatement_0(FILE * filout);
+/******************************************************************************/
+/*********** WriteInFile.c ****************************************************/
+/******************************************************************************/
+extern void tofich_reste (FILE * filout, const char *s, int do_returnline);
+extern void tofich (FILE * filout, const char *s, int do_returnline);
+extern void tofich_blanc (FILE * filout, int size);
+extern void RemoveWordSET_0(FILE * filout, long int position, int sizetoremove);
+extern void RemoveWordCUR_0(FILE * filout, int sizetoremove);
+
+/******************************************************************************/
+/*********** WorkWithlistofcoupled.c **********************************************/
+/******************************************************************************/
+extern int variscoupled_0(const char *ident) ;
+extern const char * getcoupledname_0(const char *ident);
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/fortran.lex
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/fortran.lex	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/fortran.lex	(revision 9987)
@@ -0,0 +1,294 @@
+/******************************************************************************/
+/*                                                                            */
+/*     CONV (converter) for Agrif (Adaptive Grid Refinement In Fortran)       */
+/*                                                                            */
+/* Copyright or   or Copr. Laurent Debreu (Laurent.Debreu@imag.fr)            */
+/*                        Cyril Mazauric (Cyril_Mazauric@yahoo.fr)            */
+/* This software is governed by the CeCILL-C license under French law and     */
+/* abiding by the rules of distribution of free software.  You can  use,      */
+/* modify and/ or redistribute the software under the terms of the CeCILL-C   */
+/* license as circulated by CEA, CNRS and INRIA at the following URL          */
+/* "http://www.cecill.info".                                                  */
+/*                                                                            */
+/* As a counterpart to the access to the source code and  rights to copy,     */
+/* modify and redistribute granted by the license, users are provided only    */
+/* with a limited warranty  and the software's author,  the holder of the     */
+/* economic rights,  and the successive licensors  have only  limited         */
+/* liability.                                                                 */
+/*                                                                            */
+/* In this respect, the user's attention is drawn to the risks associated     */
+/* with loading,  using,  modifying and/or developing or reproducing the      */
+/* software by the user in light of its specific status of free software,     */
+/* that may mean  that it is complicated to manipulate,  and  that  also      */
+/* therefore means  that it is reserved for developers  and  experienced      */
+/* professionals having in-depth computer knowledge. Users are therefore      */
+/* encouraged to load and test the software's suitability as regards their    */
+/* requirements in conditions enabling the security of their systems and/or   */
+/* data to be ensured and,  more generally, to use and operate it in the      */
+/* same conditions as regards security.                                       */
+/*                                                                            */
+/* The fact that you are presently reading this means that you have had       */
+/* knowledge of the CeCILL-C license and that you accept its terms.           */
+/******************************************************************************/
+/* version 1.7                                                                */
+/******************************************************************************/
+%option warn
+%option noyywrap
+
+%x parameter
+%s character
+%x donottreat
+%s fortran77style
+%s fortran90style
+%{
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+extern FILE * yyin;
+#define MAX_INCLUDE_DEPTH 30
+YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
+int line_num_input = 1;
+int newlinef90 = 0;
+char tmpc;
+#define PRINT_LINE_NUM()     // { fprintf(stderr,"== Parsing l.%4d...\n", line_num_input); }
+#define INCREMENT_LINE_NUM() { line_num_input++; PRINT_LINE_NUM(); }
+
+/******************************************************************************/
+/**************PETITS PB NON PREVUS *******************************************/
+/******************************************************************************/
+/* NEXTLINF77 un ligne fortran 77 peut commencer par -      &a=b or on        */
+/*            a prevu seulement       & a=b avec l'espace entre le symbole    */
+/*            de la 7eme et le debut de la ligne de commande                  */
+/*            le ! est aussi interdit comme symbole de la 7 eme colonne       */
+/*            Normalement NEXTLINEF77 \n+[ ]{5}[^ ]                           */
+/******************************************************************************/
+#define YY_USER_ACTION  if (firstpass == 0) ECHO;
+
+void out_of_donottreat(void);
+
+%}
+
+REAL8 "real*8"[ \t]*"(a-h,o-z)"
+
+SLASH       "/"
+DSLASH      "/"[ \t]*"/"
+HEXA        Z\'[0-9a-fA-F]+\'
+NAME        [a-zA-Z\_][a-zA-Z0-9\_]*
+INTEGER     [0-9]+
+
+EXPONENT    [edq][-+]?{INTEGER}
+
+BEG_DNT         ^[C!]"$AGRIF_DO_NOT_TREAT"[ \t]*\n
+END_DNT         ^[C!]"$AGRIF_END_DO_NOT_TREAT"[ \t]*\n
+
+BEG_INTERFACE   ^[ \t]*interface
+END_INTERFACE   ^[ \t]*end[ \t]*interface.*\n
+
+ASSIGNTYPE      "assignment"[ \t]*"("[ \t]*[-+=]+[ \t]*")"
+
+COMM_F77        ^([Cc*](([ \t]*\n)|([^AaHhOo\n].*\n)))
+COMM_F90        ^[ \t]*!.*\n
+COMM_F90_2      !.*
+NEXTLINEF90     "&".*\n+
+NEXTLINEF77     [\n \t]*\n[ \t]{5}("&"|"+"|"$"|"*"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"|"."|"#")
+
+LABEL           ^(((" "|[0-9]){1,5})|([ \t]{1,5}))[ &]+
+
+%%
+  if (infixed) BEGIN(fortran77style) ;
+  if (infree)  BEGIN(fortran90style) ;
+
+{REAL8}                     { return TOK_REAL8; }
+subroutine                  { return TOK_SUBROUTINE; }
+program                     { return TOK_PROGRAM; }
+allocate                    { inallocate = 1; return TOK_ALLOCATE; }
+nullify			            { return TOK_NULLIFY; }
+null[ ]*\([ ]*\)            { return TOK_NULL_PTR; }
+deallocate                  { inallocate = 1; return TOK_DEALLOCATE; }
+result                      { return TOK_RESULT; }
+function                    { return TOK_FUNCTION; }
+end[ \t]*program            { strcpy(yylval.na,fortran_text); return TOK_ENDPROGRAM;}
+end[ \t]*module             { strcpy(yylval.na,fortran_text); return TOK_ENDMODULE; }
+end[ \t]*subroutine         { strcpy(yylval.na,fortran_text); return TOK_ENDSUBROUTINE;}
+end[ \t]*function           { strcpy(yylval.na,fortran_text); return TOK_ENDFUNCTION;}
+end                         { strcpy(yylval.na,fortran_text); return TOK_ENDUNIT;}
+include                     { pos_curinclude = setposcur()-9; return TOK_INCLUDE;}
+^[ \t]*use[ ]+              { strcpy(yylval.na,fortran_text);
+                              tmpc = (char) input(); unput(tmpc);
+                              if ( ( tmpc >= 'a' && tmpc <= 'z' ) ||
+                                   ( tmpc >= 'A' && tmpc <= 'Z' )  )  return TOK_USE;
+                              else                                    return TOK_NAME;
+                            }
+rewind                      { return TOK_REWIND; }
+implicit                    { return TOK_IMPLICIT; }
+none                        { return TOK_NONE; }
+call                        { return TOK_CALL; }
+.true.                      { return TOK_TRUE; }
+.false.                     { return TOK_FALSE; }
+\=\>                        { return TOK_POINT_TO; }
+{ASSIGNTYPE}                { strcpy(yylval.na,fortran_text); return TOK_ASSIGNTYPE;}
+\*\*                        { strcpy(yylval.na,fortran_text); return TOK_DASTER; }
+\.[ \t]*eqv\.               { strcpy(yylval.na,fortran_text); return TOK_EQV; }
+\.[ \t]*eq\.                { strcpy(yylval.na,fortran_text); return TOK_EQ;  }
+\.[ \t]*gt\.                { strcpy(yylval.na,fortran_text); return TOK_GT;  }
+\.[ \t]*ge\.                { strcpy(yylval.na,fortran_text); return TOK_GE;  }
+\.[ \t]*lt\.                { strcpy(yylval.na,fortran_text); return TOK_LT;  }
+\.[ \t]*le\.                { strcpy(yylval.na,fortran_text); return TOK_LE;  }
+\.[ \t]*neqv\.              { strcpy(yylval.na,fortran_text); return TOK_NEQV;}
+\.[ \t]*ne\.                { strcpy(yylval.na,fortran_text); return TOK_NE;  }
+\.[ \t]*not\.               { strcpy(yylval.na,fortran_text); return TOK_NOT; }
+\.[ \t]*or\.                { strcpy(yylval.na,fortran_text); return TOK_OR;  }
+\.[ \t]*xor\.               { strcpy(yylval.na,fortran_text); return TOK_XOR; }
+\.[ \t]*and\.               { strcpy(yylval.na,fortran_text); return TOK_AND; }
+module                      { return TOK_MODULE; }
+while                       { return TOK_WHILE; }
+concurrent                  { return TOK_CONCURRENT; }
+end[ \t]*do                 { return TOK_ENDDO; }
+do                          { return TOK_PLAINDO;}
+real                        { strcpy(yylval.na,fortran_text); return TOK_REAL; }
+integer                     { strcpy(yylval.na,fortran_text); return TOK_INTEGER; }
+logical                     { strcpy(yylval.na,fortran_text); return TOK_LOGICAL; }
+character                   { strcpy(yylval.na,fortran_text); return TOK_CHARACTER; }
+{HEXA}                      { strcpy(yylval.na,fortran_text); return TOK_HEXA;}
+double[ \t]*precision       { strcpy(yylval.na,fortran_text); return TOK_DOUBLEPRECISION; }
+double[ \t]*complex         { strcpy(yylval.na,fortran_text); return TOK_DOUBLECOMPLEX; }
+complex                     { return TOK_COMPLEX; }
+allocatable                 { return TOK_ALLOCATABLE; }
+close                       { return TOK_CLOSE; }
+inquire                     { return TOK_INQUIRE; }
+dimension                   { return TOK_DIMENSION; }
+pause                       { return TOK_PAUSE; }
+equivalence                 { return TOK_EQUIVALENCE; }
+stop                        { return TOK_STOP; }
+where                       { return TOK_WHERE; }
+end[ \t]*where              { return TOK_ENDWHERE; }
+else[ \t]*where[ \t]*\(     { return TOK_ELSEWHEREPAR; }
+else[ \t]*where             { return TOK_ELSEWHERE; }
+^[ \t]*contains             { return TOK_CONTAINS; }
+only                        { return TOK_ONLY; }
+parameter                   { return TOK_PARAMETER; }
+recursive                   { return TOK_RECURSIVE; }
+common                      { return TOK_COMMON; }
+^[ \t]*global[ \t]+         { return TOK_GLOBAL; }
+external                    { return TOK_EXTERNAL; }
+intent                      { return TOK_INTENT; }
+pointer                     { return TOK_POINTER; }
+optional                    { return TOK_OPTIONAL; }
+save                        { return TOK_SAVE; }
+^[ \t]*type[ \t]*\(         { pos_cur_decl = setposcur()-5; return TOK_TYPEPAR; }
+^[ \t]*type[ \t\,]+         { return TOK_TYPE; }
+end[ \t]*type               { return TOK_ENDTYPE; }
+stat                        { if (inallocate == 1) return TOK_STAT; else { strcpy(yylval.na,fortran_text); return TOK_NAME; } }
+open                        { return TOK_OPEN; }
+return                      { return TOK_RETURN; }
+exit[^(]                    { return TOK_EXIT; }
+print                       { return TOK_PRINT; }
+module[ \t]*procedure       { return TOK_PROCEDURE; }
+read                        { return TOK_READ; }
+namelist                    { return TOK_NAMELIST; }
+write                       { return TOK_WRITE; }
+flush                       { return TOK_FLUSH; }
+target                      { return TOK_TARGET; }
+public                      { return TOK_PUBLIC; }
+private                     { return TOK_PRIVATE; }
+in                          { strcpy(yylval.na,fortran_text); return TOK_IN; }
+^[ \t]*data[ \t]+           { pos_curdata = setposcur()-strlen(fortran_text); Init_List_Data_Var(); return TOK_DATA; }
+continue                    { return TOK_CONTINUE; }
+go[ \t]*to                  { return TOK_PLAINGOTO; }
+out                         { strcpy(yylval.na,fortran_text); return TOK_OUT; }
+inout                       { strcpy(yylval.na,fortran_text); return TOK_INOUT; }
+intrinsic                   { return TOK_INTRINSIC; }
+then                        { return TOK_THEN; }
+else[ \t]*if                { return TOK_ELSEIF; }
+else                        { return TOK_ELSE; }
+end[ \t]*if                 { return TOK_ENDIF; }
+if                          { return TOK_LOGICALIF; }
+sum[ \t]*\(                 { return TOK_SUM; }
+max[ \t]*\(                 { return TOK_MAX; }
+tanh                        { return TOK_TANH; }
+maxval                      { return TOK_MAXVAL; }
+trim                        { return TOK_TRIM; }
+sqrt\(                      { return TOK_SQRT; }
+select[ \t]*case            { return TOK_SELECTCASE; }
+^[ \t]*case[ \t]*           { return TOK_CASE; }
+default                     { return TOK_DEFAULT; }
+end[ \t]*select             { return TOK_ENDSELECT; }
+file[ \t]*\=                { return TOK_FILE; }
+unit[ \t]*\=                { return TOK_UNIT; }
+fmt[ \t]*\=                 { return TOK_FMT; }
+nml[ \t]*\=                 { return TOK_NML; }
+end[ \t]*\=                 { return TOK_END; }
+eor[ \t]*\=                 { return TOK_EOR; }
+err[ \t]*\=                 { return TOK_ERR; }
+exist[ \t]*\=               { return TOK_EXIST; }
+min[ \t]*\(                 { return TOK_MIN; }
+nint                        { return TOK_NINT; }
+float                       { return TOK_FLOAT; }
+exp                         { return TOK_EXP; }
+cos                         { return TOK_COS; }
+cosh                        { return TOK_COSH; }
+acos                        { return TOK_ACOS; }
+sin                         { return TOK_SIN; }
+sinh                        { return TOK_SINH; }
+asin                        { return TOK_ASIN; }
+log                         { return TOK_LOG; }
+tan                         { return TOK_TAN; }
+atan                        { return TOK_ATAN; }
+cycle                       { return TOK_CYCLE; }
+abs[ \t]*\(                 { return TOK_ABS; }
+mod                         { return TOK_MOD; }
+sign[ \t]*\(                { return TOK_SIGN; }
+minloc                      { return TOK_MINLOC; }
+maxloc                      { return TOK_MAXLOC; }
+minval                      { return TOK_MINVAL; }
+backspace                   { return TOK_BACKSPACE; }
+::                          { return TOK_FOURDOTS;  }
+\({SLASH}                   { return TOK_LEFTAB; }
+{SLASH}\)                   { return TOK_RIGHTAB; }
+format[ \t]*\((.|{NEXTLINEF90}|{NEXTLINEF77})*\)  {
+                              return TOK_FORMAT; }
+{SLASH}                     { strcpy(yylval.na,fortran_text); return TOK_SLASH; }
+DSLASH                      { strcpy(yylval.na,fortran_text); return TOK_DSLASH; }
+(\')[^']*&{0,1}\n[ \t]*&{0,1}[^']*(\') {
+                              strcpy(yylval.na,fortran_text); return TOK_CHAR_CUT; }
+(\')[^']*(\')             { strcpy(yylval.na,fortran_text);return TOK_CHAR_CONSTANT; }
+(\")[^"]*(\")             { strcpy(yylval.na,fortran_text);return TOK_CHAR_MESSAGE; }
+{BEG_INTERFACE}             { BEGIN(donottreat); }
+<donottreat>{END_INTERFACE} { out_of_donottreat(); return '\n'; }
+{NAME}                      { strcpy(yylval.na,fortran_text); return TOK_NAME; }
+({INTEGER}\.[0-9]*)/[^"and."|"false."|"true."|"eq."|"or."|"gt."|"ge."|"lt."|"le."|"not."|"ne."] {  // REAL1
+                              strcpy(yylval.na,fortran_text); return TOK_CSTREAL; }
+(({INTEGER}\.[0-9]+|[0-9]*\.{INTEGER}){EXPONENT}?)|{INTEGER}(\.)?{EXPONENT}                     {  // REAL2
+                              strcpy(yylval.na,fortran_text); return TOK_CSTREAL; }
+{INTEGER}                   { strcpy(yylval.na,fortran_text); return TOK_CSTINT; }
+\$                          {}
+\.                          {}
+\(|\)|:|\[|\]|\+|\-|\*      { strcpy(yylval.na,fortran_text); return (int) *fortran_text; }
+\%                          { strcpy(yylval.na,fortran_text); return (int) *fortran_text; }
+\;                          { return TOK_SEMICOLON; }
+\,                          { return (int) *fortran_text; }
+\=                          { return (int) *fortran_text; }
+\<                          { return (int) *fortran_text; }
+\>                          { return (int) *fortran_text; }
+\n                          { INCREMENT_LINE_NUM() ; return '\n'; }
+^[ ]*$                      {}
+[ \t]+                      {}
+{LABEL}                     { if (newlinef90 == 0) return TOK_LABEL; else newlinef90 = 0; }
+{NEXTLINEF90}               { INCREMENT_LINE_NUM() ; newlinef90=1; }
+{NEXTLINEF77}               { INCREMENT_LINE_NUM() ; }
+
+{BEG_DNT}                   { INCREMENT_LINE_NUM() ; BEGIN(donottreat); }
+<donottreat>{END_DNT}       { out_of_donottreat(); return '\n'; }
+<donottreat>.*\n            { INCREMENT_LINE_NUM() ; }
+<fortran77style>{COMM_F77}  { INCREMENT_LINE_NUM() ; }
+{COMM_F90}                  { INCREMENT_LINE_NUM() ; }
+{COMM_F90_2}                {}
+%%
+
+void out_of_donottreat ( void )
+{
+    BEGIN(INITIAL);
+    if (infixed) BEGIN(fortran77style) ;
+    if (infree)  BEGIN(fortran90style) ;
+    INCREMENT_LINE_NUM() ;
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/fortran.y
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/fortran.y	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LEX/fortran.y	(revision 9987)
@@ -0,0 +1,2225 @@
+/******************************************************************************/
+/*                                                                            */
+/*     CONV (converter) for Agrif (Adaptive Grid Refinement In Fortran)       */
+/*                                                                            */
+/* Copyright or   or Copr. Laurent Debreu (Laurent.Debreu@imag.fr)            */
+/*                        Cyril Mazauric (Cyril_Mazauric@yahoo.fr)            */
+/* This software is governed by the CeCILL-C license under French law and     */
+/* abiding by the rules of distribution of free software.  You can  use,      */
+/* modify and/ or redistribute the software under the terms of the CeCILL-C   */
+/* license as circulated by CEA, CNRS and INRIA at the following URL          */
+/* "http ://www.cecill.info".                                                  */
+/*                                                                            */
+/* As a counterpart to the access to the source code and  rights to copy,     */
+/* modify and redistribute granted by the license, users are provided only    */
+/* with a limited warranty  and the software's author,  the holder of the     */
+/* economic rights,  and the successive licensors  have only  limited         */
+/* liability.                                                                 */
+/*                                                                            */
+/* In this respect, the user's attention is drawn to the risks associated     */
+/* with loading,  using,  modifying and/or developing or reproducing the      */
+/* software by the user in light of its specific status of free software,     */
+/* that may mean  that it is complicated to manipulate,  and  that  also      */
+/* therefore means  that it is reserved for developers  and  experienced      */
+/* professionals having in-depth computer knowledge. Users are therefore      */
+/* encouraged to load and test the software's suitability as regards their    */
+/* requirements in conditions enabling the security of their systems and/or   */
+/* data to be ensured and,  more generally, to use and operate it in the      */
+/* same conditions as regards security.                                       */
+/*                                                                            */
+/* The fact that you are presently reading this means that you have had       */
+/* knowledge of the CeCILL-C license and that you accept its terms.           */
+/******************************************************************************/
+/* version 1.7                                                                */
+/******************************************************************************/
+
+%{
+#define YYMAXDEPTH 1000
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include "decl.h"
+
+extern int line_num_input;
+extern char *fortran_text;
+
+char c_selectorname[LONG_M];
+char ligne[LONG_M];
+char truename[LONG_VNAME];
+char identcopy[LONG_VNAME];
+int c_selectorgiven=0;
+listvar *curlistvar;
+typedim c_selectordim;
+listcouple *coupletmp;
+int removeline=0;
+listvar *test;
+
+int fortran_error(const char *s)
+{
+    printf("%s line %d, file %s motclef = |%s|\n", s, line_num_input, cur_filename, fortran_text);
+    exit(1);
+}
+
+%}
+
+%union {
+    char        na[LONG_M];
+    listdim     *d;
+    listvar     *l;
+    listcouple  *lc;
+    listname    *lnn;
+    typedim     dim1;
+    variable    *v;
+}
+
+%left ','
+%nonassoc ':'
+%right '='
+%left TOK_EQV TOK_NEQV
+%left TOK_OR TOK_XOR
+%left TOK_AND
+%left TOK_NOT
+%nonassoc TOK_LT TOK_GT TOK_LE TOK_GE TOK_EQ TOK_NE
+%left TOK_DSLASH
+%left '+' '-'
+%left '*' TOK_SLASH
+%right TOK_DASTER
+
+%token TOK_SEMICOLON
+%token TOK_PARAMETER
+%token TOK_RESULT
+%token TOK_ONLY
+%token TOK_INCLUDE
+%token TOK_SUBROUTINE
+%token TOK_PROGRAM
+%token TOK_FUNCTION
+%token TOK_FORMAT
+%token TOK_MAX
+%token TOK_TANH
+%token TOK_WHERE
+%token TOK_ELSEWHEREPAR
+%token TOK_ELSEWHERE
+%token TOK_ENDWHERE
+%token TOK_MAXVAL
+%token TOK_TRIM
+%token TOK_NULL_PTR
+%token TOK_SUM
+%token TOK_SQRT
+%token TOK_CASE
+%token TOK_SELECTCASE
+%token TOK_FILE
+%token TOK_UNIT
+%token TOK_FMT
+%token TOK_NML
+%token TOK_END
+%token TOK_EOR
+%token TOK_ERR
+%token TOK_EXIST
+%token TOK_MIN
+%token TOK_FLOAT
+%token TOK_EXP
+%token TOK_COS
+%token TOK_COSH
+%token TOK_ACOS
+%token TOK_NINT
+%token TOK_CYCLE
+%token TOK_SIN
+%token TOK_SINH
+%token TOK_ASIN
+%token TOK_EQUIVALENCE
+%token TOK_BACKSPACE
+%token TOK_LOG
+%token TOK_TAN
+%token TOK_ATAN
+%token TOK_RECURSIVE
+%token TOK_ABS
+%token TOK_MOD
+%token TOK_SIGN
+%token TOK_MINLOC
+%token TOK_MAXLOC
+%token TOK_EXIT
+%token TOK_MINVAL
+%token TOK_PUBLIC
+%token TOK_PRIVATE
+%token TOK_ALLOCATABLE
+%token TOK_RETURN
+%token TOK_THEN
+%token TOK_ELSEIF
+%token TOK_ELSE
+%token TOK_ENDIF
+%token TOK_PRINT
+%token TOK_PLAINGOTO
+%token TOK_LOGICALIF
+%token TOK_PLAINDO
+%token TOK_CONTAINS
+%token TOK_ENDDO
+%token TOK_MODULE
+%token TOK_ENDMODULE
+%token TOK_WHILE
+%token TOK_CONCURRENT
+%token TOK_ALLOCATE
+%token TOK_OPEN
+%token TOK_CLOSE
+%token TOK_INQUIRE
+%token TOK_WRITE
+%token TOK_FLUSH
+%token TOK_READ
+%token TOK_REWIND
+%token TOK_DEALLOCATE
+%token TOK_NULLIFY
+%token TOK_DIMENSION
+%token TOK_ENDSELECT
+%token TOK_EXTERNAL
+%token TOK_INTENT
+%token TOK_INTRINSIC
+%token TOK_NAMELIST
+%token TOK_DEFAULT
+%token TOK_OPTIONAL
+%token TOK_POINTER
+%token TOK_CONTINUE
+%token TOK_SAVE
+%token TOK_TARGET
+%token TOK_IMPLICIT
+%token TOK_NONE
+%token TOK_CALL
+%token TOK_STAT
+%token TOK_POINT_TO
+%token TOK_COMMON
+%token TOK_GLOBAL
+%token TOK_LEFTAB
+%token TOK_RIGHTAB
+%token TOK_PAUSE
+%token TOK_PROCEDURE
+%token TOK_STOP
+%token TOK_REAL8
+%token TOK_FOURDOTS
+%token <na> TOK_HEXA
+%token <na> TOK_ASSIGNTYPE
+%token <na> TOK_OUT
+%token <na> TOK_INOUT
+%token <na> TOK_IN
+%token <na> TOK_USE
+%token <na> TOK_DSLASH
+%token <na> TOK_DASTER
+%token <na> TOK_EQ
+%token <na> TOK_EQV
+%token <na> TOK_GT
+%token <na> TOK_LT
+%token <na> TOK_GE
+%token <na> TOK_NE
+%token <na> TOK_NEQV
+%token <na> TOK_LE
+%token <na> TOK_OR
+%token <na> TOK_XOR
+%token <na> TOK_NOT
+%token <na> TOK_AND
+%token <na> TOK_TRUE
+%token <na> TOK_FALSE
+%token <na> TOK_LABEL
+%token <na> TOK_TYPE
+%token <na> TOK_TYPEPAR
+%token <na> TOK_ENDTYPE
+%token <na> TOK_REAL
+%token <na> TOK_INTEGER
+%token <na> TOK_LOGICAL
+%token <na> TOK_DOUBLEPRECISION
+%token <na> TOK_ENDSUBROUTINE
+%token <na> TOK_ENDFUNCTION
+%token <na> TOK_ENDPROGRAM
+%token <na> TOK_ENDUNIT
+%token <na> TOK_CHARACTER
+%token <na> TOK_CHAR_CONSTANT
+%token <na> TOK_CHAR_CUT
+%token <na> TOK_DATA
+%token <na> TOK_CHAR_MESSAGE
+%token <na> TOK_CSTREAL
+%token <na> TOK_COMPLEX
+%token <na> TOK_DOUBLECOMPLEX
+%token <na> TOK_NAME
+%token <na> TOK_SLASH
+%token <na> TOK_CSTINT
+%token ','
+%token ':'
+%token '('
+%token ')'
+%token '<'
+%token '>'
+%type <l> dcl
+%type <l> after_type
+%type <l> dimension
+%type <l> paramlist
+%type <l> args
+%type <l> arglist
+%type <lc> only_list
+%type <lc> only_name
+%type <lc> rename_list
+%type <lc> rename_name
+%type <d> dims
+%type <d> dimlist
+%type <dim1> dim
+%type <v> paramitem
+%type <na> comblock
+%type <na> name_routine
+%type <na> opt_name
+%type <na> type
+%type <na> word_endsubroutine
+%type <na> word_endfunction
+%type <na> word_endprogram
+%type <na> word_endunit
+%type <na> typespec
+%type <na> string_constant
+%type <na> simple_const
+%type <na> ident
+%type <na> intent_spec
+%type <na> signe
+%type <na> opt_signe
+%type <na> filename
+%type <na> attribute
+%type <na> complex_const
+%type <na> begin_array
+%type <na> clause
+%type <na> arg
+%type <na> uexpr
+%type <na> minmaxlist
+%type <na> lhs
+%type <na> vec
+%type <na> outlist
+%type <na> other
+%type <na> dospec
+%type <na> expr_data
+%type <na> structure_component
+%type <na> array_ele_substring_func_ref
+%type <na> funarglist
+%type <na> funarg
+%type <na> funargs
+%type <na> triplet
+%type <na> substring
+%type <na> opt_substring
+%type <na> opt_expr
+%type <na> optexpr
+%type <lnn> data_stmt_value_list
+%type <lnn> datanamelist
+%type <na> after_slash
+%type <na> after_equal
+%type <na> predefinedfunction
+%type <na> expr
+%type <na> ubound
+%type <na> operation
+%type <na> proper_lengspec
+%type <lnn> use_name_list
+%type <lnn> public
+
+%%
+input :
+      | input line
+      ;
+line :  line-break
+      | suite_line_list
+      | TOK_LABEL suite_line_list
+      | error {yyerrok;yyclearin;}
+      ;
+line-break:
+        '\n' fin_line
+      | TOK_SEMICOLON
+      | line-break '\n' fin_line
+      | line-break TOK_SEMICOLON
+      | line-break TOK_LABEL
+      ;
+suite_line_list :
+        suite_line
+      | suite_line_list TOK_SEMICOLON '\n'
+      | suite_line_list TOK_SEMICOLON suite_line
+      ;
+suite_line :
+        entry fin_line     /* subroutine, function, module                    */
+      | spec fin_line      /* declaration                                     */
+      | TOK_INCLUDE filename fin_line
+        {
+            if (inmoduledeclare == 0 )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_curinclude,pos_end-pos_curinclude);
+            }
+        }
+      | execution-part-construct
+      ;
+
+fin_line : { pos_cur = setposcur(); }
+      ;
+
+opt_recursive :         { isrecursive = 0; }
+      | TOK_RECURSIVE   { isrecursive = 1; }
+      ;
+
+opt_result :                                { is_result_present = 0; }
+      | TOK_RESULT arglist_after_result     { is_result_present = 1; }
+      ;
+
+entry : opt_recursive TOK_SUBROUTINE name_routine arglist
+        {
+            insubroutinedeclare = 1;
+            if ( firstpass )
+                Add_SubroutineArgument_Var_1($4);
+            else
+                WriteBeginof_SubLoop();
+        }
+      | TOK_PROGRAM name_routine
+        {
+            insubroutinedeclare = 1;
+            inprogramdeclare = 1;
+            /* in the second step we should write the head of       */
+            /*    the subroutine sub_loop_<subroutinename>          */
+            if ( ! firstpass )
+                WriteBeginof_SubLoop();
+        }
+      | opt_recursive TOK_FUNCTION name_routine arglist opt_result
+        {
+            insubroutinedeclare = 1;
+            strcpy(DeclType, "");
+            /* we should to list of the subroutine argument the  */
+            /*    name of the function which has to be defined   */
+            if ( firstpass )
+            {
+                Add_SubroutineArgument_Var_1($4);
+                if ( ! is_result_present )
+                    Add_FunctionType_Var_1($3);
+            }
+            else
+            /* in the second step we should write the head of    */
+            /*    the subroutine sub_loop_<subroutinename>       */
+                WriteBeginof_SubLoop();
+        }
+      | TOK_MODULE TOK_NAME
+        {
+            GlobalDeclaration = 0;
+            strcpy(curmodulename,$2);
+            strcpy(subroutinename,"");
+            Add_NameOfModule_1($2);
+            if ( inmoduledeclare == 0 )
+            {
+                /* To know if there are in the module declaration    */
+                inmoduledeclare = 1;
+                /* to know if a module has been met                  */
+                inmodulemeet = 1;
+                /* to know if we are after the keyword contains      */
+                aftercontainsdeclare = 0 ;
+            }
+        }
+      ;
+
+/* R312 : label */
+label: TOK_CSTINT
+     | label TOK_CSTINT
+     ;
+
+name_routine :  TOK_NAME    { strcpy($$, $1); strcpy(subroutinename, $1); }
+      ;
+filename :      TOK_CHAR_CONSTANT { Add_Include_1($1); }
+      ;
+arglist :               { if ( firstpass ) $$=NULL; }
+      | '(' ')'         { if ( firstpass ) $$=NULL; }
+      | '(' args ')'    { if ( firstpass ) $$=$2; }
+      ;
+arglist_after_result:
+      | '(' ')'
+      | '(' args ')'    { if ( firstpass ) Add_SubroutineArgument_Var_1($2); }
+      ;
+args :  arg
+        {
+            if ( firstpass == 1 )
+            {
+                strcpy(nameinttypenameback,nameinttypename);
+                strcpy(nameinttypename,"");
+                curvar = createvar($1,NULL);
+                strcpy(nameinttypename,nameinttypenameback);
+                curlistvar = insertvar(NULL,curvar);
+                $$ = settype("",curlistvar);
+            }
+        }
+      | args ',' arg
+        {
+            if ( firstpass == 1 )
+            {
+                strcpy(nameinttypenameback,nameinttypename);
+                strcpy(nameinttypename,"");
+                curvar = createvar($3,NULL);
+                strcpy(nameinttypename,nameinttypenameback);
+                $$ = insertvar($1,curvar);
+            }
+        }
+      ;
+arg : TOK_NAME  { strcpy($$,$1);  }
+      | '*'     { strcpy($$,"*"); }
+      ;
+spec :  type after_type
+      | TOK_TYPE opt_spec opt_sep opt_name  { inside_type_declare = 1; }
+      | TOK_ENDTYPE opt_name                { inside_type_declare = 0; }
+      | TOK_POINTER list_couple
+      | before_parameter '(' paramlist ')'
+        {
+            if ( ! inside_type_declare )
+            {
+                if ( firstpass )
+                {
+                    if ( insubroutinedeclare )  Add_Parameter_Var_1($3);
+                    else                        Add_GlobalParameter_Var_1($3);
+                }
+                else
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out, pos_cur_decl, pos_end-pos_cur_decl);
+                }
+            }
+            VariableIsParameter =  0 ;
+        }
+      | before_parameter paramlist
+        {
+            if ( ! inside_type_declare )
+            {
+                if ( firstpass )
+                {
+                    if ( insubroutinedeclare )  Add_Parameter_Var_1($2);
+                    else                        Add_GlobalParameter_Var_1($2);
+                }
+                else
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_cur_decl,pos_end-pos_cur_decl);
+                }
+            }
+            VariableIsParameter =  0 ;
+        }
+      | common
+      | save
+        {
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_cursave,pos_end-pos_cursave);
+        }
+      | implicit
+      | dimension
+        {
+            /* if the variable is a parameter we can suppose that is   */
+            /*    value is the same on each grid. It is not useless to */
+            /*    create a copy of it on each grid                     */
+            if ( ! inside_type_declare )
+            {
+                if ( firstpass )
+                {
+                    Add_Globliste_1($1);
+                    /* if variableparamlists has been declared in a subroutine   */
+                    if ( insubroutinedeclare )     Add_Dimension_Var_1($1);
+                }
+                else
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curdimension,pos_end-pos_curdimension);
+                }
+            }
+            PublicDeclare = 0;
+            PrivateDeclare = 0;
+            ExternalDeclare = 0;
+            strcpy(NamePrecision,"");
+            c_star = 0;
+            InitialValueGiven = 0 ;
+            strcpy(IntentSpec,"");
+            VariableIsParameter =  0 ;
+            Allocatabledeclare = 0 ;
+            Targetdeclare = 0 ;
+            SaveDeclare = 0;
+            pointerdeclare = 0;
+            optionaldeclare = 0 ;
+            dimsgiven=0;
+            c_selectorgiven=0;
+            strcpy(nameinttypename,"");
+            strcpy(c_selectorname,"");
+        }
+      | public
+        {
+            if (firstpass == 0)
+            {
+                if ($1)
+                {
+                    removeglobfromlist(&($1));
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_cur,pos_end-pos_cur);
+                    writelistpublic($1);
+                }
+            }
+        }
+      | private
+      | use_stat
+      | module_proc_stmt
+      | namelist
+      | TOK_BACKSPACE '(' expr ')'
+      | TOK_EXTERNAL opt_sep use_name_list
+      | TOK_INTRINSIC opt_sep use_intrinsic_list
+      | TOK_EQUIVALENCE list_expr_equi
+      | data_stmt '\n'
+        {
+            /* we should remove the data declaration                */
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curdata,pos_end-pos_curdata);
+
+            if ( aftercontainsdeclare == 1  && firstpass == 0 )
+            {
+                ReWriteDataStatement_0(fortran_out);
+                pos_end = setposcur();
+            }
+        }
+      ;
+opt_spec :
+      | access_spec
+        {
+            PublicDeclare = 0 ;
+            PrivateDeclare = 0 ;
+        }
+      ;
+name_intrinsic :
+        TOK_SUM
+      | TOK_TANH
+      | TOK_MAXVAL
+      | TOK_MIN
+      | TOK_MINVAL
+      | TOK_TRIM
+      | TOK_SQRT
+      | TOK_NINT
+      | TOK_FLOAT
+      | TOK_EXP
+      | TOK_COS
+      | TOK_COSH
+      | TOK_ACOS
+      | TOK_SIN
+      | TOK_SINH
+      | TOK_ASIN
+      | TOK_LOG
+      | TOK_TAN
+      | TOK_ATAN
+      | TOK_MOD
+      | TOK_SIGN
+      | TOK_MINLOC
+      | TOK_MAXLOC
+      | TOK_NAME
+      ;
+use_intrinsic_list :
+                               name_intrinsic
+      | use_intrinsic_list ',' name_intrinsic
+      ;
+list_couple :
+                        '(' list_expr ')'
+      | list_couple ',' '(' list_expr ')'
+      ;
+list_expr_equi :
+                           expr_equi
+      | list_expr_equi ',' expr_equi
+      ;
+expr_equi : '(' list_expr_equi1 ')'
+      ;
+list_expr_equi1 :
+                            ident dims
+      | list_expr_equi1 ',' ident dims
+      ;
+list_expr :
+                      expr
+      | list_expr ',' expr
+      ;
+opt_sep :
+      | TOK_FOURDOTS
+      ;
+after_type :
+        dcl nodimsgiven
+        {
+            /* if the variable is a parameter we can suppose that is*/
+            /*    value is the same on each grid. It is not useless */
+            /*    to create a copy of it on each grid               */
+            if ( ! inside_type_declare )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_cur_decl,pos_end-pos_cur_decl);
+                ReWriteDeclarationAndAddTosubroutine_01($1);
+                pos_cur_decl = setposcur();
+                if ( firstpass == 0 && GlobalDeclaration == 0
+                                    && insubroutinedeclare == 0 )
+                {
+                    fprintf(fortran_out,"\n#include \"Module_Declar_%s.h\"\n", curmodulename);
+                    sprintf(ligne, "Module_Declar_%s.h", curmodulename);
+                    module_declar = open_for_write(ligne);
+                    GlobalDeclaration = 1 ;
+                    pos_cur_decl = setposcur();
+                }
+                $$ = $1;
+
+                if ( firstpass )
+                {
+                    Add_Globliste_1($1);
+                    if ( insubroutinedeclare )
+                    {
+                        if ( pointerdeclare ) Add_Pointer_Var_From_List_1($1);
+                        Add_Parameter_Var_1($1);
+                    }
+                    else
+                        Add_GlobalParameter_Var_1($1);
+
+                    /* If there's a SAVE declaration in module's subroutines we should    */
+                    /*    remove it from the subroutines declaration and add it in the    */
+                    /*    global declarations                                             */
+                    if ( aftercontainsdeclare && SaveDeclare )
+                    {
+                        if ( inmodulemeet ) Add_SubroutineDeclarationSave_Var_1($1);
+                        else                Add_Save_Var_dcl_1($1);
+                    }
+                }
+            }
+            else
+            {
+                $$ = (listvar *) NULL;
+            }
+            PublicDeclare = 0;
+            PrivateDeclare = 0;
+            ExternalDeclare = 0;
+            strcpy(NamePrecision,"");
+            c_star = 0;
+            InitialValueGiven = 0 ;
+            strcpy(IntentSpec,"");
+            VariableIsParameter =  0 ;
+            Allocatabledeclare = 0 ;
+            Targetdeclare = 0 ;
+            SaveDeclare = 0;
+            pointerdeclare = 0;
+            optionaldeclare = 0 ;
+            dimsgiven=0;
+            c_selectorgiven=0;
+            strcpy(nameinttypename,"");
+            strcpy(c_selectorname,"");
+            GlobalDeclarationType = 0;
+        }
+      | before_function name_routine arglist
+        {
+            insubroutinedeclare = 1;
+
+            if ( firstpass )
+            {
+                Add_SubroutineArgument_Var_1($3);
+                Add_FunctionType_Var_1($2);
+            }
+            else
+                WriteBeginof_SubLoop();
+
+            strcpy(nameinttypename,"");
+        }
+      ;
+before_function :   TOK_FUNCTION    { functiondeclarationisdone = 1; }
+      ;
+before_parameter :  TOK_PARAMETER   { VariableIsParameter = 1; pos_curparameter = setposcur()-9; }
+      ;
+
+data_stmt :             /* R534 */
+        TOK_DATA data_stmt_set_list
+
+data_stmt_set_list :
+        data_stmt_set
+      | data_stmt_set_list opt_comma data_stmt_set
+
+data_stmt_set :         /* R535 */
+        TOK_NAME TOK_SLASH data_stmt_value_list TOK_SLASH
+        {
+            createstringfromlistname(ligne,$3);
+            if (firstpass == 1) Add_Data_Var_1(&List_Data_Var,$1,ligne);
+            else                Add_Data_Var_1(&List_Data_Var_Cur,$1,ligne);
+        }
+      | datanamelist TOK_SLASH data_stmt_value_list TOK_SLASH
+        {
+            if (firstpass == 1)  Add_Data_Var_Names_01(&List_Data_Var,$1,$3);
+            else                 Add_Data_Var_Names_01(&List_Data_Var_Cur,$1,$3);
+        }
+      | '(' lhs ',' dospec ')' TOK_SLASH data_stmt_value_list TOK_SLASH
+        {
+            createstringfromlistname(ligne,$7);
+            printf("###################################################################################################################\n");
+            printf("## CONV Error : data_implied_do statements (R537) are not yet supported. Please complain to the proper authorities.\n");
+            printf("l.%4d -- data_stmt_set : ( lhs , dospec ) /data_stmt_value_list/ -- lhs=|%s| dospec=|%s| data_stmt_value_list=|%s|\n",
+                line_num_input,$2,$4,ligne);
+            printf("## But, are you SURE you NEED a DATA construct ?\n");
+            printf("###################################################################################################################\n");
+            exit(1);
+        }
+      ;
+
+data_stmt_value_list :
+        expr_data                           { $$ = Insertname(NULL,$1,0); }
+      | expr_data ',' data_stmt_value_list  { $$ = Insertname($3,$1,1);   }
+      ;
+
+save :  before_save varsave
+      | before_save comblock varsave
+      | save opt_comma comblock opt_comma varsave
+      | save ',' varsave
+      ;
+before_save :
+        TOK_SAVE        { pos_cursave = setposcur()-4; }
+      ;
+varsave :
+      | TOK_NAME dims   { if ( ! inside_type_declare ) Add_Save_Var_1($1,$2); }
+      ;
+datanamelist :
+        TOK_NAME                        { $$ = Insertname(NULL,$1,0); }
+      | TOK_NAME '(' expr ')'           { printf("l.%4d -- INSTRUCTION NON TRAITEE : INITIALISATION DE DATA AVEC EXPRESSION\n",line_num_input); exit(0); }
+      | datanamelist ',' datanamelist   { $$ = concat_listname($1,$3); }
+      ;
+expr_data :
+        opt_signe simple_const      { sprintf($$,"%s%s",$1,$2);  }
+      | expr_data '+' expr_data     { sprintf($$,"%s+%s",$1,$3); }
+      | expr_data '-' expr_data     { sprintf($$,"%s-%s",$1,$3); }
+      | expr_data '*' expr_data     { sprintf($$,"%s*%s",$1,$3); }
+      | expr_data '/' expr_data     { sprintf($$,"%s/%s",$1,$3); }
+      ;
+opt_signe :     { strcpy($$,""); }
+      | signe   { strcpy($$,$1); }
+      ;
+namelist :
+        TOK_NAMELIST ident
+      | TOK_NAMELIST comblock ident
+      | namelist opt_comma comblock opt_comma ident
+      | namelist ',' ident
+      ;
+before_dimension :
+        TOK_DIMENSION
+        {
+            positioninblock = 0;
+            pos_curdimension = setposcur()-9;
+        }
+
+dimension :
+        before_dimension opt_comma TOK_NAME dims lengspec
+        {
+            printf("l.%4d -- dimension : before_dimension opt_comma TOK_NAME = |%s| -- MHCHECK\n",line_num_input,$3);
+            if ( inside_type_declare ) break;
+            curvar = createvar($3,$4);
+            CreateAndFillin_Curvar("", curvar);
+            curlistvar=insertvar(NULL, curvar);
+            $$ = settype("",curlistvar);
+            strcpy(vallengspec,"");
+        }
+      | dimension ',' TOK_NAME dims lengspec
+        {
+            printf("l.%4d -- dimension : dimension ',' TOK_NAME dims lengspec = |%s| -- MHCHECK\n",line_num_input,$3);
+            if ( inside_type_declare ) break;
+            curvar = createvar($3,$4);
+            CreateAndFillin_Curvar("", curvar);
+            curlistvar = insertvar($1, curvar);
+            $$ = curlistvar;
+            strcpy(vallengspec,"");
+        }
+      ;
+private :
+        TOK_PRIVATE '\n'
+      | TOK_PRIVATE opt_sep use_name_list
+      ;
+public :
+        TOK_PUBLIC '\n'                     { $$ = (listname *) NULL; }
+      | TOK_PUBLIC opt_sep use_name_list    { $$ = $3; }
+      ;
+use_name_list :
+        TOK_NAME                            { $$ = Insertname(NULL,$1,0); }
+      | TOK_ASSIGNTYPE                      { $$ = Insertname(NULL,$1,0); }
+      | use_name_list ',' TOK_NAME          { $$ = Insertname($1,$3,0);   }
+      | use_name_list ',' TOK_ASSIGNTYPE    { $$ = Insertname($1,$3,0);   }
+      ;
+common :
+        before_common var_common_list
+        {
+            if ( inside_type_declare ) break;
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curcommon,pos_end-pos_curcommon);
+        }
+      | before_common comblock var_common_list
+        {
+            if ( inside_type_declare ) break;
+            sprintf(charusemodule,"%s",$2);
+            Add_NameOfCommon_1($2,subroutinename);
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curcommon,pos_end-pos_curcommon);
+        }
+      | common opt_comma comblock opt_comma var_common_list
+        {
+            if ( inside_type_declare ) break;
+            sprintf(charusemodule,"%s",$3);
+            Add_NameOfCommon_1($3,subroutinename);
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curcommon,pos_end-pos_curcommon);
+        }
+      ;
+before_common :
+        TOK_COMMON              { positioninblock = 0; pos_curcommon = setposcur()-6;   }
+      | TOK_GLOBAL TOK_COMMON   { positioninblock = 0; pos_curcommon = setposcur()-6-7; }
+      ;
+var_common_list :
+        var_common                      { if ( ! inside_type_declare ) Add_Common_var_1(); }
+      | var_common_list ',' var_common  { if ( ! inside_type_declare ) Add_Common_var_1(); }
+      ;
+var_common :
+        TOK_NAME dims
+        {
+            positioninblock = positioninblock + 1 ;
+            strcpy(commonvar,$1);
+            commondim = $2;
+        }
+      ;
+comblock :
+        TOK_DSLASH
+        {
+            strcpy($$,"");
+            positioninblock=0;
+            strcpy(commonblockname,"");
+        }
+      | TOK_SLASH TOK_NAME TOK_SLASH
+        {
+            strcpy($$,$2);
+            positioninblock=0;
+            strcpy(commonblockname,$2);
+        }
+      ;
+opt_comma :
+      | ','
+      ;
+paramlist :
+        paramitem                   { $$=insertvar(NULL,$1); }
+      | paramlist ',' paramitem     { $$=insertvar($1,$3);   }
+      ;
+paramitem :
+        TOK_NAME '=' expr
+        {
+            if ( inside_type_declare ) break;
+            curvar=(variable *) calloc(1,sizeof(variable));
+            Init_Variable(curvar);
+            curvar->v_VariableIsParameter = 1;
+            strcpy(curvar->v_nomvar,$1);
+            strcpy(curvar->v_subroutinename,subroutinename);
+            strcpy(curvar->v_modulename,curmodulename);
+            strcpy(curvar->v_initialvalue,$3);
+            strcpy(curvar->v_commoninfile,cur_filename);
+            Save_Length($3,14);
+            $$ = curvar;
+        }
+      ;
+module_proc_stmt :
+        TOK_PROCEDURE proc_name_list
+      ;
+proc_name_list :
+        TOK_NAME
+      | proc_name_list ',' TOK_NAME
+      ;
+implicit :
+        TOK_IMPLICIT TOK_NONE
+        {
+            if ( insubroutinedeclare == 1 )
+            {
+                Add_ImplicitNoneSubroutine_1();
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_end-13,13);
+            }
+        }
+      | TOK_IMPLICIT TOK_REAL8
+      ;
+dcl :   options TOK_NAME dims lengspec initial_value
+        {
+            if ( ! inside_type_declare )
+            {
+                if (dimsgiven == 1) curvar = createvar($2,curdim);
+                else                curvar = createvar($2,$3);
+                CreateAndFillin_Curvar(DeclType, curvar);
+                curlistvar = insertvar(NULL, curvar);
+                if (!strcasecmp(DeclType,"character"))
+                {
+                    if (c_selectorgiven == 1)
+                    {
+                        strcpy(c_selectordim.first,"1");
+                        strcpy(c_selectordim.last,c_selectorname);
+                        Save_Length(c_selectorname,1);
+                        change_dim_char(insertdim(NULL,c_selectordim),curlistvar);
+                    }
+                }
+                $$=settype(DeclType,curlistvar);
+            }
+            strcpy(vallengspec,"");
+        }
+      | dcl ',' TOK_NAME dims lengspec initial_value
+        {
+            if ( ! inside_type_declare )
+            {
+                if (dimsgiven == 1) curvar = createvar($3, curdim);
+                else                curvar = createvar($3, $4);
+                CreateAndFillin_Curvar($1->var->v_typevar,curvar);
+                strcpy(curvar->v_typevar, $1->var->v_typevar);
+                curvar->v_catvar = get_cat_var(curvar);
+                curlistvar = insertvar($1, curvar);
+                if (!strcasecmp(DeclType,"character"))
+                {
+                    if (c_selectorgiven == 1)
+                    {
+                        strcpy(c_selectordim.first,"1");
+                        strcpy(c_selectordim.last,c_selectorname);
+                        Save_Length(c_selectorname,1);
+                        change_dim_char(insertdim(NULL,c_selectordim),curlistvar);
+                    }
+                }
+                $$=curlistvar;
+            }
+            strcpy(vallengspec,"");
+        }
+      ;
+nodimsgiven : { dimsgiven = 0; }
+      ;
+type :  typespec selector               { strcpy(DeclType,$1);  }
+      | before_character c_selector     { strcpy(DeclType,"character");  }
+      | typespec '*' TOK_CSTINT         { strcpy(DeclType,$1); strcpy(nameinttypename,$3);  }
+      | TOK_TYPEPAR attribute ')'       { strcpy(DeclType,"type"); GlobalDeclarationType = 1;  }
+      ;
+c_selector :
+      | '*' TOK_CSTINT              { c_selectorgiven = 1; strcpy(c_selectorname,$2); }
+      | '*' '(' c_attribute ')'     { c_star = 1;}
+      | '(' c_attribute ')'
+      ;
+c_attribute :
+        TOK_NAME clause opt_clause
+      | TOK_NAME '=' clause opt_clause
+      | clause opt_clause
+      ;
+before_character : TOK_CHARACTER    { pos_cur_decl = setposcur()-9; }
+      ;
+typespec :
+        TOK_INTEGER         { strcpy($$,"integer"); pos_cur_decl = setposcur()-7; }
+      | TOK_LOGICAL         { strcpy($$,"logical"); pos_cur_decl = setposcur()-7; }
+      | TOK_REAL            { strcpy($$,"real");    pos_cur_decl = setposcur()-4; }
+      | TOK_COMPLEX         { strcpy($$,"complex"); pos_cur_decl = setposcur()-7; }
+      | TOK_DOUBLECOMPLEX   { strcpy($$,"double complex"); pos_cur_decl = setposcur()-14; }
+      | TOK_DOUBLEPRECISION { pos_cur_decl = setposcur()-16; strcpy($$,"real"); strcpy(nameinttypename,"8"); }
+      ;
+lengspec :
+      | '*' proper_lengspec {strcpy(vallengspec,$2);}
+      ;
+proper_lengspec :
+        expr        { sprintf($$,"*%s",$1); }
+      | '(' '*' ')' { strcpy($$,"*(*)"); }
+      ;
+selector :
+      | '*' proper_selector
+      | '(' attribute ')'
+      ;
+proper_selector : expr
+      | '(' '*' ')'
+      ;
+attribute :
+        TOK_NAME clause
+      | TOK_NAME '=' clause
+        {
+            if ( strstr($3,"0.d0") )
+            {
+                strcpy(nameinttypename,"8");
+                strcpy(NamePrecision,"");
+            }
+            else
+                sprintf(NamePrecision,"%s = %s",$1,$3);
+        }
+      | TOK_NAME        { strcpy(NamePrecision,$1); }
+      | TOK_CSTINT      { strcpy(NamePrecision,$1); }
+      | TOK_ASSIGNTYPE  { strcpy(NamePrecision,$1); }
+      ;
+clause :
+        expr   { strcpy(CharacterSize,$1);  strcpy($$,$1);  }
+      | '*'    { strcpy(CharacterSize,"*"); strcpy($$,"*"); }
+      ;
+opt_clause :
+      | ',' TOK_NAME clause
+      ;
+options :
+      | TOK_FOURDOTS
+      | ',' attr_spec_list TOK_FOURDOTS
+      ;
+attr_spec_list : attr_spec
+      | attr_spec_list ',' attr_spec
+      ;
+attr_spec :
+        TOK_PARAMETER       { VariableIsParameter = 1; }
+      | access_spec
+      | TOK_ALLOCATABLE     { Allocatabledeclare = 1; }
+      | TOK_DIMENSION dims  { dimsgiven = 1; curdim = $2; }
+      | TOK_EXTERNAL        { ExternalDeclare = 1; }
+      | TOK_INTENT '(' intent_spec ')'
+                            { strcpy(IntentSpec,$3); }
+      | TOK_INTRINSIC
+      | TOK_OPTIONAL        { optionaldeclare = 1 ; }
+      | TOK_POINTER         { pointerdeclare = 1 ; }
+      | TOK_SAVE            { SaveDeclare = 1 ; }
+      | TOK_TARGET          { Targetdeclare = 1; }
+      ;
+intent_spec :
+        TOK_IN          { strcpy($$,$1); }
+      | TOK_OUT         { strcpy($$,$1); }
+      | TOK_INOUT       { strcpy($$,$1); }
+      ;
+access_spec :
+        TOK_PUBLIC      { PublicDeclare = 1;  }
+      | TOK_PRIVATE     { PrivateDeclare = 1; }
+      ;
+dims :  { $$ = (listdim*) NULL; }
+      | '(' dimlist ')'
+        {
+            $$ = (listdim*) NULL;
+            if ( inside_type_declare ) break;
+            if ( created_dimensionlist == 1 || agrif_parentcall == 1 )  $$=$2;
+        }
+      ;
+dimlist :
+        dim
+        {
+            $$ = (listdim*) NULL;
+            if ( inside_type_declare ) break;
+            if ( created_dimensionlist == 1 || agrif_parentcall == 1 )  $$=insertdim(NULL,$1);
+        }
+      | dimlist ',' dim
+        {
+            $$ = (listdim*) NULL;
+            if ( inside_type_declare ) break;
+            if ( (!inside_type_declare) && created_dimensionlist == 1 ) $$=insertdim($1,$3);
+        }
+      ;
+dim :   ubound              { strcpy($$.first,"1"); strcpy($$.last,$1); Save_Length($1,1); }
+      | ':'                 { strcpy($$.first,"");  strcpy($$.last,"");                    }
+      | expr ':'            { strcpy($$.first,$1);  Save_Length($1,2); strcpy($$.last,""); }
+      | ':' expr            { strcpy($$.first,"");  strcpy($$.last,$2); Save_Length($2,1); }
+      | expr ':' ubound     { strcpy($$.first,$1);  Save_Length($1,2); strcpy($$.last,$3); Save_Length($3,1); }
+      ;
+ubound :
+        '*'                 { strcpy($$,"*"); }
+      | expr                { strcpy($$,$1);  }
+      ;
+expr :  uexpr               { strcpy($$,$1); }
+      | complex_const       { strcpy($$,$1); }
+      | predefinedfunction  { strcpy($$,$1); }
+      | '(' expr ')'        { sprintf($$,"(%s)",$2); }
+      ;
+
+predefinedfunction :
+        TOK_SUM minmaxlist ')'          { sprintf($$,"SUM(%s)",$2);}
+      | TOK_MAX minmaxlist ')'          { sprintf($$,"MAX(%s)",$2);}
+      | TOK_TANH '(' minmaxlist ')'     { sprintf($$,"TANH(%s)",$3);}
+      | TOK_MAXVAL '(' minmaxlist ')'   { sprintf($$,"MAXVAL(%s)",$3);}
+      | TOK_MIN minmaxlist ')'          { sprintf($$,"MIN(%s)",$2);}
+      | TOK_MINVAL '(' minmaxlist ')'   { sprintf($$,"MINVAL(%s)",$3);}
+      | TOK_TRIM '(' expr ')'           { sprintf($$,"TRIM(%s)",$3);}
+      | TOK_SQRT expr ')'               { sprintf($$,"SQRT(%s)",$2);}
+      | TOK_REAL '(' minmaxlist ')'     { sprintf($$,"REAL(%s)",$3);}
+      | TOK_NINT '(' expr ')'           { sprintf($$,"NINT(%s)",$3);}
+      | TOK_FLOAT '(' expr ')'          { sprintf($$,"FLOAT(%s)",$3);}
+      | TOK_EXP '(' expr ')'            { sprintf($$,"EXP(%s)",$3);}
+      | TOK_COS '(' expr ')'            { sprintf($$,"COS(%s)",$3);}
+      | TOK_COSH '(' expr ')'           { sprintf($$,"COSH(%s)",$3);}
+      | TOK_ACOS '(' expr ')'           { sprintf($$,"ACOS(%s)",$3);}
+      | TOK_SIN '(' expr ')'            { sprintf($$,"SIN(%s)",$3);}
+      | TOK_SINH '(' expr ')'           { sprintf($$,"SINH(%s)",$3);}
+      | TOK_ASIN '(' expr ')'           { sprintf($$,"ASIN(%s)",$3);}
+      | TOK_LOG '(' expr ')'            { sprintf($$,"LOG(%s)",$3);}
+      | TOK_TAN '(' expr ')'            { sprintf($$,"TAN(%s)",$3);}
+      | TOK_ATAN '(' expr ')'           { sprintf($$,"ATAN(%s)",$3);}
+      | TOK_ABS expr ')'                { sprintf($$,"ABS(%s)",$2);}
+      | TOK_MOD '(' minmaxlist ')'      { sprintf($$,"MOD(%s)",$3);}
+      | TOK_SIGN minmaxlist ')'         { sprintf($$,"SIGN(%s)",$2);}
+      | TOK_MINLOC '(' minmaxlist ')'   { sprintf($$,"MINLOC(%s)",$3);}
+      | TOK_MAXLOC '(' minmaxlist ')'   { sprintf($$,"MAXLOC(%s)",$3);}
+      ;
+minmaxlist : expr {strcpy($$,$1);}
+      | minmaxlist ',' expr     { sprintf($$,"%s,%s",$1,$3); }
+      ;
+uexpr : lhs                     { strcpy($$,$1); }
+      | simple_const            { strcpy($$,$1); }
+      | vec                     { strcpy($$,$1); }
+      | expr operation          { sprintf($$,"%s%s",$1,$2); }
+      | signe expr %prec '*'    { sprintf($$,"%s%s",$1,$2); }
+      | TOK_NOT expr            { sprintf($$,"%s%s",$1,$2); }
+      ;
+signe : '+'        { strcpy($$,"+"); }
+      | '-'        { strcpy($$,"-"); }
+      ;
+
+operation :
+        '+' expr %prec '+'          { sprintf($$,"+%s",$2); }
+      | '-' expr %prec '+'          { sprintf($$,"-%s",$2); }
+      | '*' expr                    { sprintf($$,"*%s",$2); }
+      | TOK_DASTER expr             { sprintf($$,"%s%s",$1,$2); }
+      | TOK_EQ expr %prec TOK_EQ    { sprintf($$,"%s%s",$1,$2); }
+      | TOK_EQV expr %prec TOK_EQV  { sprintf($$,"%s%s",$1,$2); }
+      | TOK_GT expr %prec TOK_EQ    { sprintf($$,"%s%s",$1,$2); }
+      | '>' expr %prec TOK_EQ       { sprintf($$," > %s",$2); }
+      | '<' expr %prec TOK_EQ       { sprintf($$," < %s",$2); }
+      | '>''=' expr %prec TOK_EQ    { sprintf($$," >= %s",$3); }
+      | '<''=' expr %prec TOK_EQ    { sprintf($$," <= %s",$3); }
+      | TOK_LT expr %prec TOK_EQ    { sprintf($$,"%s%s",$1,$2); }
+      | TOK_GE expr %prec TOK_EQ    { sprintf($$,"%s%s",$1,$2); }
+      | TOK_LE expr %prec TOK_EQ    { sprintf($$,"%s%s",$1,$2); }
+      | TOK_NE expr %prec TOK_EQ    { sprintf($$,"%s%s",$1,$2); }
+      | TOK_NEQV expr %prec TOK_EQV { sprintf($$,"%s%s",$1,$2); }
+      | TOK_XOR expr                { sprintf($$,"%s%s",$1,$2); }
+      | TOK_OR expr                 { sprintf($$,"%s%s",$1,$2); }
+      | TOK_AND expr                { sprintf($$,"%s%s",$1,$2); }
+      | TOK_SLASH after_slash       { sprintf($$,"%s",$2); }
+      | '=' after_equal             { sprintf($$,"%s",$2); }
+
+after_slash :                   { strcpy($$,""); }
+      | expr                    { sprintf($$,"/%s",$1); }
+      | '=' expr %prec TOK_EQ   { sprintf($$,"/= %s",$2);}
+      | TOK_SLASH expr          { sprintf($$,"//%s",$2); }
+      ;
+after_equal :
+        '=' expr %prec TOK_EQ   { sprintf($$,"==%s",$2); }
+      | expr                    { sprintf($$,"= %s",$1); }
+      ;
+
+lhs :   ident                           { strcpy($$,$1); }
+      | structure_component             { strcpy($$,$1); }
+      | array_ele_substring_func_ref    { strcpy($$,$1); }
+      ;
+
+beforefunctionuse :
+        {
+            agrif_parentcall = 0;
+            if ( !strcasecmp(identcopy, "Agrif_Parent") )   agrif_parentcall = 1;
+            if ( Agrif_in_Tok_NAME(identcopy) )
+            {
+                inagrifcallargument = 1;
+                Add_SubroutineWhereAgrifUsed_1(subroutinename, curmodulename);
+            }
+        }
+      ;
+array_ele_substring_func_ref :
+        begin_array                                         { strcpy($$,$1); if ( incalldeclare == 0 ) inagrifcallargument = 0;   }
+      | begin_array substring                               { sprintf($$," %s %s ",$1,$2); }
+      | structure_component '(' funarglist ')'              { sprintf($$," %s ( %s )",$1,$3); }
+      | structure_component '(' funarglist ')' substring    { sprintf($$," %s ( %s ) %s ",$1,$3,$5); }
+      ;
+begin_array :
+        ident '(' funarglist ')'
+        {
+            if ( inside_type_declare ) break;
+            sprintf($$," %s ( %s )",$1,$3);
+            ModifyTheAgrifFunction_0($3);
+            agrif_parentcall = 0;
+        }
+      ;
+structure_component :
+        lhs '%' declare_after_percent lhs
+        {
+            sprintf($$," %s %% %s ",$1,$4);
+            if ( incalldeclare == 0 ) inagrifcallargument = 0;
+        }
+      ;
+vec :
+        TOK_LEFTAB outlist TOK_RIGHTAB   { sprintf($$,"(/%s/)",$2); }
+      ;
+funarglist :
+        beforefunctionuse           { strcpy($$," "); }
+      | beforefunctionuse funargs   { strcpy($$,$2); }
+      ;
+funargs :
+        funarg              {  strcpy($$,$1); }
+      | funargs ',' funarg  {  sprintf($$,"%s,%s",$1,$3); }
+      ;
+funarg :
+        expr       {strcpy($$,$1);}
+      | triplet    {strcpy($$,$1);}
+      ;
+triplet :
+        expr ':' expr           {  sprintf($$,"%s :%s",$1,$3);}
+      | expr ':' expr ':' expr  {  sprintf($$,"%s :%s :%s",$1,$3,$5);}
+      | ':' expr ':' expr       {  sprintf($$,":%s :%s",$2,$4);}
+      | ':' ':' expr            {  sprintf($$,": : %s",$3);}
+      | ':' expr                {  sprintf($$,":%s",$2);}
+      | expr ':'                {  sprintf($$,"%s :",$1);}
+      | ':'                     {  sprintf($$,":");}
+      ;
+ident : TOK_NAME
+        {
+            if ( afterpercent == 0 )
+            {
+                if ( Agrif_in_Tok_NAME($1) ) Add_SubroutineWhereAgrifUsed_1(subroutinename, curmodulename);
+                if ( !strcasecmp($1,"Agrif_Parent") )   agrif_parentcall = 1;
+                if ( VariableIsFunction($1) )
+                {
+                    if ( inagrifcallargument == 1 )
+                    {
+                        if ( !strcasecmp($1,identcopy) )
+                        {
+                            strcpy(sameagrifname,identcopy);
+                            sameagrifargument = 1;
+                        }
+                    }
+                    strcpy(identcopy,$1);
+                    pointedvar = 0;
+
+                    if (variscoupled_0($1)) strcpy(truename, getcoupledname_0($1));
+                    else                    strcpy(truename, $1);
+
+                    if ( VarIsNonGridDepend(truename) == 0 && (! Variableshouldberemoved(truename)) )
+                    {
+                        if ( inagrifcallargument == 1 || varispointer_0(truename) == 1 )
+                        {
+                            if ( (IsinListe(List_UsedInSubroutine_Var,$1) == 1) || (inagrifcallargument == 1) )
+                            {
+                                if (varistyped_0(truename) == 0)    ModifyTheVariableName_0(truename,strlen($1));
+                            }
+                        }
+                        if ( inagrifcallargument != 1 || sameagrifargument ==1 )
+                        {
+                            Add_UsedInSubroutine_Var_1(truename);
+                        }
+                    }
+                    NotifyAgrifFunction_0(truename);
+                }
+            }
+            else
+            {
+                afterpercent = 0;
+            }
+        }
+      ;
+simple_const :
+        TOK_TRUE     { strcpy($$,".TRUE.");}
+      | TOK_FALSE    { strcpy($$,".FALSE.");}
+      | TOK_NULL_PTR { strcpy($$,"NULL()"); }
+      | TOK_CSTINT   { strcpy($$,$1); }
+      | TOK_CSTREAL  { strcpy($$,$1); }
+      | TOK_HEXA     { strcpy($$,$1); }
+      | simple_const TOK_NAME
+                     { sprintf($$,"%s%s",$1,$2); }
+      | string_constant opt_substring
+      ;
+string_constant :
+        TOK_CHAR_CONSTANT                   { strcpy($$,$1);}
+      | string_constant TOK_CHAR_CONSTANT
+      | TOK_CHAR_MESSAGE                    { strcpy($$,$1);}
+      | TOK_CHAR_CUT                        { strcpy($$,$1);}
+      ;
+opt_substring :     { strcpy($$," ");}
+      | substring   { strcpy($$,$1);}
+      ;
+substring :
+        '(' optexpr ':' optexpr ')' { sprintf($$,"(%s :%s)",$2,$4);}
+      ;
+optexpr :           { strcpy($$," ");}
+      | expr        { strcpy($$,$1);}
+      ;
+opt_expr :
+        '\n'        { strcpy($$," ");}
+      | expr        { strcpy($$,$1);}
+      ;
+initial_value :     { InitialValueGiven = 0; }
+      | '=' expr
+        {
+            if ( inside_type_declare ) break;
+            strcpy(InitValue,$2);
+            InitialValueGiven = 1;
+        }
+      | TOK_POINT_TO expr
+        {
+            if ( inside_type_declare ) break;
+            strcpy(InitValue,$2);
+            InitialValueGiven = 2;
+        }
+      ;
+complex_const :
+        '(' uexpr ',' uexpr ')' {sprintf($$,"(%s,%s)",$2,$4); }
+      ;
+use_stat :
+        word_use TOK_NAME
+        {
+            /* if variables has been declared in a subroutine       */
+            sprintf(charusemodule, "%s", $2);
+            if ( firstpass )
+            {
+                Add_NameOfModuleUsed_1($2);
+            }
+            else
+            {
+                if ( insubroutinedeclare )
+                    copyuse_0($2);
+
+                if ( inmoduledeclare == 0 )
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+                }
+            }
+        }
+      | word_use TOK_NAME ',' rename_list
+        {
+            if ( firstpass )
+            {
+                if ( insubroutinedeclare )
+                {
+                    Add_CouplePointed_Var_1($2,$4);
+                    coupletmp = $4;
+                    strcpy(ligne,"");
+                    while ( coupletmp )
+                    {
+                        strcat(ligne, coupletmp->c_namevar);
+                        strcat(ligne, " => ");
+                        strcat(ligne, coupletmp->c_namepointedvar);
+                        coupletmp = coupletmp->suiv;
+                        if ( coupletmp ) strcat(ligne,",");
+                    }
+                    sprintf(charusemodule,"%s",$2);
+                }
+                Add_NameOfModuleUsed_1($2);
+            }
+            if ( inmoduledeclare == 0 )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+            }
+        }
+      | word_use TOK_NAME ',' TOK_ONLY ':' '\n'
+        {
+            /* if variables has been declared in a subroutine       */
+            sprintf(charusemodule,"%s",$2);
+            if ( firstpass )
+            {
+                Add_NameOfModuleUsed_1($2);
+            }
+            else
+            {
+                if ( insubroutinedeclare )
+                    copyuseonly_0($2);
+
+                if ( inmoduledeclare == 0 )
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+                }
+            }
+        }
+      | word_use  TOK_NAME ',' TOK_ONLY ':' only_list
+        {
+            /* if variables has been declared in a subroutine      */
+            if ( firstpass )
+            {
+                if ( insubroutinedeclare )
+                {
+                    Add_CouplePointed_Var_1($2,$6);
+                    coupletmp = $6;
+                    strcpy(ligne,"");
+                    while ( coupletmp )
+                    {
+                        strcat(ligne,coupletmp->c_namevar);
+                        if ( strcasecmp(coupletmp->c_namepointedvar,"") )   strcat(ligne," => ");
+                        strcat(ligne,coupletmp->c_namepointedvar);
+                        coupletmp = coupletmp->suiv;
+                        if ( coupletmp ) strcat(ligne,",");
+                    }
+                    sprintf(charusemodule,"%s",$2);
+                }
+                Add_NameOfModuleUsed_1($2);
+            }
+            else /* if ( firstpass == 0 ) */
+            {
+                if ( inmoduledeclare == 0 )
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+                    if (oldfortran_out)  variableisglobalinmodule($6,$2,oldfortran_out,pos_curuseold);
+                }
+                else
+                {
+                    /* if we are in the module declare and if the    */
+                    /* onlylist is a list of global variable         */
+                    variableisglobalinmodule($6, $2, fortran_out,pos_curuse);
+                }
+            }
+        }
+      ;
+word_use :
+        TOK_USE
+        {
+            pos_curuse = setposcur()-strlen($1);
+            if (firstpass == 0 && oldfortran_out) pos_curuseold = setposcurname(oldfortran_out);
+        }
+      ;
+rename_list :
+        rename_name
+        {
+            $$ = $1;
+        }
+      | rename_list ',' rename_name
+        {
+            /* insert the variable in the list $1                 */
+            $3->suiv = $1;
+            $$ = $3;
+        }
+      ;
+rename_name : TOK_NAME TOK_POINT_TO TOK_NAME
+        {
+            coupletmp = (listcouple *) calloc(1,sizeof(listcouple));
+            strcpy(coupletmp->c_namevar,$1);
+            strcpy(coupletmp->c_namepointedvar,$3);
+            coupletmp->suiv = NULL;
+            $$ = coupletmp;
+        }
+      ;
+only_list :
+        only_name   {  $$ = $1; }
+      | only_list ',' only_name
+        {
+            /* insert the variable in the list $1                 */
+            $3->suiv = $1;
+            $$ = $3;
+        }
+      ;
+only_name :
+        TOK_NAME TOK_POINT_TO TOK_NAME
+        {
+            coupletmp = (listcouple *)calloc(1,sizeof(listcouple));
+            strcpy(coupletmp->c_namevar,$1);
+            strcpy(coupletmp->c_namepointedvar,$3);
+            coupletmp->suiv = NULL;
+            $$ = coupletmp;
+            pointedvar = 1;
+            Add_UsedInSubroutine_Var_1($1);
+        }
+      | TOK_NAME
+        {
+            coupletmp = (listcouple *)calloc(1,sizeof(listcouple));
+            strcpy(coupletmp->c_namevar,$1);
+            strcpy(coupletmp->c_namepointedvar,"");
+            coupletmp->suiv = NULL;
+            $$ = coupletmp;
+        }
+      ;
+
+/* R209 : execution-part-construct */
+execution-part-construct:
+        executable-construct
+      | format-stmt
+      ;
+
+/* R213 : executable-construct */
+executable-construct:
+        action-stmt
+      | do-construct
+      | case-construct
+      | if-construct
+      | where-construct
+      ;
+
+/* R214 : action-stmt */
+action-stmt :
+        TOK_CONTINUE
+      | ident_dims after_ident_dims
+      | goto
+      | call
+      | iofctl ioctl
+      | read option_read
+      | TOK_WRITE ioctl
+      | TOK_WRITE ioctl outlist
+      | TOK_REWIND after_rewind
+      | TOK_ALLOCATE '(' allocation_list opt_stat_spec ')'          { inallocate = 0; }
+      | TOK_DEALLOCATE '(' allocate_object_list opt_stat_spec ')'   { inallocate = 0; }
+      | TOK_EXIT optexpr
+      | TOK_RETURN opt_expr
+      | TOK_CYCLE opt_expr
+      | stop opt_expr
+      | int_list
+      | TOK_NULLIFY '(' pointer_name_list ')'
+      | word_endunit
+        {
+            GlobalDeclaration = 0 ;
+            if ( firstpass == 0 && strcasecmp(subroutinename,"") )
+            {
+                if ( module_declar && insubroutinedeclare == 0 )    fclose(module_declar);
+            }
+            if ( strcasecmp(subroutinename,"") )
+            {
+                if ( inmodulemeet == 1 )
+                {
+                    /* we are in a module                                */
+                    if ( insubroutinedeclare == 1 )
+                    {
+                        /* it is like an end subroutine <name>            */
+                        insubroutinedeclare = 0 ;
+                        pos_cur = setposcur();
+                        closeandcallsubloopandincludeit_0(1);
+                        functiondeclarationisdone = 0;
+                    }
+                    else
+                    {
+                        /* it is like an end module <name>                */
+                        inmoduledeclare = 0 ;
+                        inmodulemeet = 0 ;
+                    }
+                }
+                else
+                {
+                    insubroutinedeclare = 0;
+                    pos_cur = setposcur();
+                    closeandcallsubloopandincludeit_0(2);
+                    functiondeclarationisdone = 0;
+                }
+            }
+            strcpy(subroutinename,"");
+        }
+      | word_endprogram opt_name
+        {
+            insubroutinedeclare = 0;
+            inprogramdeclare = 0;
+            pos_cur = setposcur();
+            closeandcallsubloopandincludeit_0(3);
+            functiondeclarationisdone = 0;
+            strcpy(subroutinename,"");
+        }
+      | word_endsubroutine opt_name
+        {
+            if ( strcasecmp(subroutinename,"") )
+            {
+                insubroutinedeclare = 0;
+                pos_cur = setposcur();
+                closeandcallsubloopandincludeit_0(1);
+                functiondeclarationisdone = 0;
+                strcpy(subroutinename,"");
+            }
+        }
+      | word_endfunction opt_name
+        {
+            insubroutinedeclare = 0;
+            pos_cur = setposcur();
+            closeandcallsubloopandincludeit_0(0);
+            functiondeclarationisdone = 0;
+            strcpy(subroutinename,"");
+        }
+      | TOK_ENDMODULE opt_name
+        {
+            /* if we never meet the contains keyword               */
+            if ( firstpass == 0 )
+            {
+                RemoveWordCUR_0(fortran_out, strlen($2)+11);    // Remove word "end module"
+                if ( inmoduledeclare && ! aftercontainsdeclare )
+                {
+                    Write_Closing_Module(1);
+                }
+                fprintf(fortran_out,"\n      end module %s\n", curmodulename);
+                if ( module_declar && insubroutinedeclare == 0 )
+                {
+                    fclose(module_declar);
+                }
+            }
+            inmoduledeclare = 0 ;
+            inmodulemeet = 0 ;
+            aftercontainsdeclare = 1;
+            strcpy(curmodulename, "");
+            GlobalDeclaration = 0 ;
+        }
+      | if-stmt
+      | where-stmt
+      | TOK_CONTAINS
+        {
+            if ( inside_type_declare ) break;
+            if ( inmoduledeclare )
+            {
+                if ( firstpass == 0 )
+                {
+                    RemoveWordCUR_0(fortran_out,9);   // Remove word 'contains'
+                    Write_Closing_Module(0);
+                }
+                inmoduledeclare = 0 ;
+                aftercontainsdeclare = 1;
+            }
+            else if ( insubroutinedeclare )
+            {
+                incontainssubroutine = 1;
+                insubroutinedeclare  = 0;
+                incontainssubroutine = 0;
+                functiondeclarationisdone = 0;
+
+                if ( firstpass )
+                    List_ContainsSubroutine = Addtolistnom(subroutinename, List_ContainsSubroutine, 0);
+                else
+                    closeandcallsubloop_contains_0();
+
+                strcpy(subroutinename, "");
+            }
+            else printf("l.%4d -- TOK_CONTAINS -- MHCHECK\n",line_num_input);
+        }
+      ;
+
+/* R601 : variable */
+//variable : expr
+//       ;
+
+/* R734 : assignment-stmt */
+// assignment-stmt: variable '=' expr
+//       ;
+assignment-stmt: expr
+      ;
+
+/* R741 : where-stmt */
+where-stmt: TOK_WHERE '(' mask-expr ')' where-assignment-stmt
+      ;
+
+/* R742 : where-construct */
+where-construct: where-construct-stmt line-break opt-where-body-construct opt-masked-elsewhere-construct opt-elsewhere-construct end-where-stmt
+      ;
+
+opt-where-body-construct:
+      | opt-where-body-construct where-body-construct line-break
+      ;
+
+opt-masked-elsewhere-construct :
+      | opt-masked-elsewhere-construct masked-elsewhere-stmt line-break opt-where-body-construct
+      ;
+
+opt-elsewhere-construct:
+      | opt-elsewhere-construct elsewhere-stmt line-break opt-where-body-construct
+      ;
+
+/* R743 : where-construct-stmt */
+where-construct-stmt:
+        TOK_WHERE '(' mask-expr ')'
+      ;
+
+/* R744 : where-body-construct */
+where-body-construct: where-assignment-stmt
+      | where-stmt
+      | where-construct
+      ;
+
+/* R745 : where-assignment-stmt */
+where-assignment-stmt: assignment-stmt
+      ;
+
+/* R746 : mask-expr */
+mask-expr: expr
+      ;
+
+/* R747 : masked-elsewhere-stmt */
+masked-elsewhere-stmt:
+        TOK_ELSEWHEREPAR mask-expr ')'
+      | TOK_ELSEWHEREPAR mask-expr ')' TOK_NAME
+      ;
+
+/* R748: elsewhere-stmt */
+elsewhere-stmt:
+        TOK_ELSEWHERE
+      | TOK_ELSEWHERE TOK_NAME
+      ;
+
+/* R749: end-where-stmt */
+end-where-stmt:
+        TOK_ENDWHERE
+      | TOK_ENDWHERE TOK_NAME
+      ;
+
+/* R752 : forall-header */
+forall-header :
+     ;
+
+/* R801 : block */
+block:
+      |block execution-part-construct
+      |block execution-part-construct line-break
+      ;
+
+/* R813 : do-construct */
+do-construct:
+        block-do-construct
+      ;
+
+/* R814 : block-do-construct */
+block-do-construct:
+        do-stmt line-break do-block end-do
+      ;
+
+/* R815 : do-stmt */
+do-stmt:
+        label-do-stmt
+      | nonlabel-do-stmt
+      ;
+
+/* R816 : label-do-stmt */
+label-do-stmt:
+        TOK_NAME ':' TOK_PLAINDO label
+      |              TOK_PLAINDO label
+      | TOK_NAME ':' TOK_PLAINDO label loop-control
+      |              TOK_PLAINDO label loop-control
+      ;
+
+/* R817 : nonlabel-do-stmt */
+nonlabel-do-stmt:
+        TOK_NAME ':' TOK_PLAINDO
+      |              TOK_PLAINDO
+      | TOK_NAME ':' TOK_PLAINDO loop-control
+      |              TOK_PLAINDO loop-control
+      ;
+
+/* R818 : loop-control */
+loop-control:
+        opt_comma do-variable '=' expr ',' expr
+      | opt_comma do-variable '=' expr ',' expr ',' expr
+      | opt_comma TOK_WHILE '(' expr ')'
+      | opt_comma TOK_CONCURRENT forall-header
+      ;
+
+/* R819 : do-variable */
+do-variable : ident
+     ;
+
+/* R820 : do-block */
+do-block: block
+     ;
+
+/* R821 : end-do */
+end-do: end-do-stmt
+     | continue-stmt
+     ;
+
+/* R822 : end-do-stmt */
+end-do-stmt:
+        TOK_ENDDO
+      | TOK_ENDDO TOK_NAME
+      ;
+
+/* R832 : if-construct */
+if-construct: if-then-stmt line-break block opt-else-if-stmt-block opt-else-stmt-block end-if-stmt
+      ;
+
+opt-else-if-stmt-block:
+      | else-if-stmt-block
+      | opt-else-if-stmt-block else-if-stmt-block
+      ;
+
+else-if-stmt-block:
+        else-if-stmt line-break block
+      ;
+
+opt-else-stmt-block:
+      | else-stmt-block
+      | opt-else-stmt-block else-if-stmt-block
+      ;
+
+else-stmt-block: else-stmt line-break block
+        ;
+
+/* R833 : if-then-stmt */
+if-then-stmt:
+         TOK_NAME ':' TOK_LOGICALIF '(' expr ')' TOK_THEN
+      |               TOK_LOGICALIF '(' expr ')' TOK_THEN
+      ;
+
+/* R834 : else-if-stmt */
+else-if-stmt:
+        TOK_ELSEIF '(' expr ')' TOK_THEN
+      | TOK_ELSEIF '(' expr ')' TOK_THEN TOK_NAME
+      ;
+
+/* R835 : else-stmt */
+else-stmt:
+        TOK_ELSE
+      | TOK_ELSE TOK_NAME
+      ;
+
+/* R836 : end-if-stmt */
+end-if-stmt:
+        TOK_ENDIF
+      | TOK_ENDIF TOK_NAME
+      ;
+
+/* R837 : if-stmt */
+if-stmt: TOK_LOGICALIF '(' expr ')' action-stmt
+        ;
+
+/* R838 : case-construct */
+case-construct: select-case-stmt line-break opt_case-stmt-block end-select-stmt
+        ;
+
+opt_case-stmt-block:
+        | case-stmt-block
+        | opt_case-stmt-block case-stmt-block
+        ;
+
+case-stmt-block: case-stmt line-break block
+        ;
+
+/* R839 : select-case-stmt */
+select-case-stmt :
+          TOK_NAME ':' TOK_SELECTCASE '(' expr ')'
+        |              TOK_SELECTCASE '(' expr ')'
+        ;
+
+/* R840 : case-stmt */
+case-stmt:
+          TOK_CASE case-selector
+        | TOK_CASE case-selector TOK_NAME
+        ;
+
+/* R840 : end-select-stmt */
+end-select-stmt:
+          TOK_ENDSELECT
+        | TOK_ENDSELECT TOK_NAME
+        ;
+
+/* R843 : case-selector */
+case-selector:
+          '(' case-value-range-list ')'
+        | TOK_DEFAULT
+        ;
+
+case-value-range-list:
+        case-value-range
+      | case-value-range-list ',' case-value-range
+      ;
+
+/* R844: case-value-range */
+case-value-range :
+        case-value
+      | case-value ':'
+      | ':' case-value
+      | case-value ':' case-value
+      ;
+
+/* R845 : case-value */
+case-value: expr
+        ;
+
+/* R854 : continue-stmt */
+continue-stmt: TOK_CONTINUE
+        ;
+
+/* R1001 : format-stmt */
+format-stmt: TOK_FORMAT
+        ;
+
+word_endsubroutine :
+        TOK_ENDSUBROUTINE
+        {
+            strcpy($$,$1);
+            pos_endsubroutine = setposcur()-strlen($1);
+            functiondeclarationisdone = 0;
+        }
+      ;
+word_endunit :
+        TOK_ENDUNIT
+        {
+            strcpy($$,$1);
+            pos_endsubroutine = setposcur()-strlen($1);
+        }
+      ;
+word_endprogram :
+        TOK_ENDPROGRAM
+        {
+            strcpy($$,$1);
+            pos_endsubroutine = setposcur()-strlen($1);
+        }
+      ;
+word_endfunction :
+        TOK_ENDFUNCTION
+        {
+            strcpy($$,$1);
+            pos_endsubroutine = setposcur()-strlen($1);
+        }
+      ;
+
+opt_name : '\n'  {strcpy($$,"");}
+      | TOK_NAME {strcpy($$,$1);}
+      ;
+
+before_dims : { created_dimensionlist = 0; }
+      ;
+ident_dims :
+        ident before_dims dims dims
+        {
+            created_dimensionlist = 1;
+            if ( ($3 == NULL) || ($4 == NULL) ) break;
+            if  ( agrif_parentcall == 1 )
+            {
+                ModifyTheAgrifFunction_0($3->dim.last);
+                agrif_parentcall = 0;
+                fprintf(fortran_out," = ");
+            }
+        }
+      | ident_dims '%' declare_after_percent ident before_dims dims dims
+        {
+            created_dimensionlist = 1;
+        }
+      ;
+int_list :
+        TOK_CSTINT
+      | int_list ',' TOK_CSTINT
+      ;
+after_ident_dims :
+        '=' expr
+      | TOK_POINT_TO expr
+      ;
+call :  keywordcall opt_call
+        {
+            inagrifcallargument = 0 ;
+            incalldeclare=0;
+            if ( oldfortran_out && (callagrifinitgrids == 1) && (firstpass == 0) )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_curcall,pos_end-pos_curcall);
+                strcpy(subofagrifinitgrids,subroutinename);
+            }
+            Instanciation_0(sameagrifname);
+        }
+      ;
+opt_call :
+      | '(' opt_callarglist  ')'
+      ;
+opt_callarglist :
+      | callarglist
+      ;
+keywordcall :
+        before_call TOK_FLUSH
+      | before_call TOK_NAME
+        {
+            if (!strcasecmp($2,"MPI_Init") )    callmpiinit = 1;
+            else                                callmpiinit = 0;
+
+            if (!strcasecmp($2,"Agrif_Init_Grids") )
+            {
+                callagrifinitgrids = 1;
+                strcpy(meetagrifinitgrids,subroutinename);
+            }
+            else
+            {
+                callagrifinitgrids = 0;
+            }
+            if ( Vartonumber($2) == 1 )
+            {
+                incalldeclare = 1;
+                inagrifcallargument = 1 ;
+                Add_SubroutineWhereAgrifUsed_1(subroutinename, curmodulename);
+            }
+        }
+      ;
+before_call : TOK_CALL  { pos_curcall=setposcur()-4; }
+      ;
+callarglist :
+        callarg
+      | callarglist ',' callarg
+      ;
+callarg :
+        expr
+        {
+            if ( callmpiinit == 1 )
+            {
+                strcpy(mpiinitvar,$1);
+                if ( firstpass == 1 )  Add_UsedInSubroutine_Var_1 (mpiinitvar);
+            }
+        }
+      | '*' TOK_CSTINT
+      ;
+
+stop :  TOK_PAUSE
+      | TOK_STOP
+      ;
+
+option_inlist :
+      | inlist
+      ;
+option_read :
+        ioctl option_inlist
+      | infmt opt_inlist
+      ;
+opt_inlist :
+      | ',' inlist
+      ;
+ioctl : '(' ctllist ')'
+      ;
+after_rewind :
+        '(' ident ')'
+      | '(' TOK_CSTINT ')'
+      | TOK_CSTINT
+      | '(' uexpr ')'
+      | TOK_NAME
+      ;
+ctllist :
+        ioclause
+      | ctllist ',' ioclause
+      ;
+ioclause :
+        fexpr
+      | '*'
+      | TOK_DASTER
+      | ident expr dims
+      | ident expr '%' declare_after_percent ident_dims
+      | ident '(' triplet ')'
+      | ident '*'
+      | ident TOK_DASTER
+      ;
+
+declare_after_percent:      { afterpercent = 1; }
+      ;
+iofctl :
+        TOK_OPEN
+      | TOK_CLOSE
+      | TOK_FLUSH
+      ;
+infmt :  unpar_fexpr
+      | '*'
+      ;
+
+read :  TOK_READ
+      | TOK_INQUIRE
+      | TOK_PRINT
+      ;
+
+fexpr : unpar_fexpr
+      | '(' fexpr ')'
+      ;
+unpar_fexpr :
+        lhs
+      | simple_const
+      | fexpr addop fexpr %prec '+'
+      | fexpr '*' fexpr
+      | fexpr TOK_SLASH fexpr
+      | fexpr TOK_DASTER fexpr
+      | addop fexpr %prec '*'
+      | fexpr TOK_DSLASH fexpr
+      | TOK_FILE expr
+      | TOK_UNIT expr
+      | TOK_NML expr
+      | TOK_FMT expr
+      | TOK_EXIST expr
+      | TOK_ERR expr
+      | TOK_END expr
+      | TOK_NAME '=' expr
+      | predefinedfunction
+      ;
+addop : '+'
+      | '-'
+      ;
+inlist : inelt
+      | inlist ',' inelt
+      ;
+// opt_lhs :
+//       | lhs
+//       ;
+inelt : //opt_lhs opt_operation
+        lhs opt_operation
+      | '(' inlist ')' opt_operation
+      | predefinedfunction opt_operation
+      | simple_const opt_operation
+      | '(' inlist ',' dospec ')'
+      ;
+opt_operation :
+      | operation
+      | opt_operation operation
+      ;
+outlist :
+        complex_const       { strcpy($$,$1); }
+      | predefinedfunction  { strcpy($$,$1); }
+      | uexpr               { strcpy($$,$1); }
+      | other               { strcpy($$,$1); }
+      | uexpr   ',' expr    { sprintf($$,"%s,%s",$1,$3); }
+      | uexpr   ',' other   { sprintf($$,"%s,%s",$1,$3); }
+      | other   ',' expr    { sprintf($$,"%s,%s",$1,$3); }
+      | other   ',' other   { sprintf($$,"%s,%s",$1,$3); }
+      | outlist ',' expr    { sprintf($$,"%s,%s",$1,$3); }
+      | outlist ',' other   { sprintf($$,"%s,%s",$1,$3); }
+      ;
+other :
+        '(' uexpr   ',' dospec ')'    { sprintf($$,"(%s,%s)",$2,$4); }
+      | '(' outlist ',' dospec ')'    { sprintf($$,"(%s,%s)",$2,$4); }
+      | '(' other   ',' dospec ')'    { sprintf($$,"(%s,%s)",$2,$4); }
+dospec :
+        TOK_NAME '=' expr ',' expr           { sprintf($$,"%s=%s,%s)",$1,$3,$5);}
+      | TOK_NAME '=' expr ',' expr ',' expr  { sprintf($$,"%s=%s,%s,%s)",$1,$3,$5,$7);}
+      ;
+goto :  TOK_PLAINGOTO '(' expr ',' expr ')' ',' expr
+      | TOK_PLAINGOTO TOK_CSTINT
+      ;
+allocation_list :
+        allocate_object
+      | allocation_list ',' allocate_object
+      ;
+allocate_object :
+        lhs     { Add_Allocate_Var_1($1,curmodulename); }
+      ;
+allocate_object_list :
+        allocate_object
+      | allocate_object_list ',' allocate_object
+      ;
+opt_stat_spec :
+      | ',' TOK_STAT '=' lhs
+      ;
+pointer_name_list :
+        ident
+      | pointer_name_list ',' ident
+      ;
+
+%%
+
+void process_fortran(const char *input_file)
+{
+    extern FILE *fortran_in;
+    extern FILE *fortran_out;
+
+    char output_file[LONG_FNAME];
+    char input_fullpath[LONG_FNAME];
+
+    if ( todebug == 1 ) printf("Firstpass == %d \n", firstpass);
+
+     yydebug=0;
+/******************************************************************************/
+/*  1-  Open input file                                                       */
+/******************************************************************************/
+
+    strcpy(cur_filename, input_file);
+    sprintf(input_fullpath, "%s/%s", input_dir, input_file);
+
+    fortran_in = fopen(input_fullpath, "r");
+    if (! fortran_in)
+    {
+        printf("Error : File %s does not exist\n", input_fullpath);
+        exit(1);
+    }
+
+/******************************************************************************/
+/*  2-  Variables initialization                                              */
+/******************************************************************************/
+
+    line_num_input = 1;
+    PublicDeclare = 0;
+    PrivateDeclare = 0;
+    ExternalDeclare = 0;
+    SaveDeclare = 0;
+    pointerdeclare = 0;
+    optionaldeclare = 0;
+    incalldeclare = 0;
+    inside_type_declare = 0;
+    Allocatabledeclare = 0 ;
+    Targetdeclare = 0 ;
+    VariableIsParameter =  0 ;
+    strcpy(NamePrecision,"");
+    c_star = 0 ;
+    functiondeclarationisdone = 0;
+    insubroutinedeclare = 0 ;
+    strcpy(subroutinename," ");
+    isrecursive = 0;
+    InitialValueGiven = 0 ;
+    GlobalDeclarationType = 0;
+    inmoduledeclare = 0;
+    incontainssubroutine = 0;
+    afterpercent = 0;
+    aftercontainsdeclare = 1;
+    strcpy(nameinttypename,"");
+
+/******************************************************************************/
+/*  3-  Parsing of the input file (1 time)                                    */
+/******************************************************************************/
+
+    sprintf(output_file, "%s/%s", output_dir, input_file);
+
+    if (firstpass == 0) fortran_out = fopen(output_file,"w");
+
+    fortran_parse();
+
+    if (firstpass == 0) NewModule_Creation_0();
+    if (firstpass == 0) fclose(fortran_out);
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/DiversListe.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/DiversListe.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/DiversListe.c	(revision 9987)
@@ -48,92 +48,83 @@
 void Add_Common_var_1()
 {
-   listvar *newvar;
-   listvar *newvar2;
-   variable *newvariable;
-   listdim *dims;
-   char listdimension[LONG_C];
-   char ligne[LONG_C];
-   int out;
-
-   if ( firstpass == 1 )
-   {
-
-   newvar = (listvar *)malloc(sizeof(listvar));
-   newvariable = (variable *)malloc(sizeof(variable));
-   /*                                                                         */
-   Init_Variable(newvariable);
-   /*                                                                         */
-   strcpy(newvariable->v_nomvar,commonvar);
-   Save_Length(commonvar,4);
-   strcpy(newvariable->v_commonname,commonblockname);
-   Save_Length(commonblockname,7);
-   strcpy(newvariable->v_modulename,curmodulename);
-   Save_Length(curmodulename,6);
-   strcpy(newvariable->v_subroutinename,subroutinename);
-   Save_Length(subroutinename,11);
-   newvariable->v_positioninblock= positioninblock;
-   newvariable->v_common=1;
-   strcpy(newvariable->v_commoninfile,mainfile);
-   Save_Length(mainfile,10);
-
-   newvar->var = newvariable;
-
-   if ( commondim )
-   {
-      newvariable->v_dimension=commondim;
-      newvariable->v_dimensiongiven=1;
-      newvariable->v_nbdim=num_dims(commondim);
-      /* Creation of the string for the dimension of this variable            */
-      dimsempty = 1;
-      strcpy(listdimension,"");
-
-      if ( commondim )
-      {
-         dims = commondim;
-         while (dims)
-         {
-            if ( strcasecmp(dims->dim.first,"") ||
-                 strcasecmp(dims->dim.last,""))  dimsempty = 0;
-            sprintf(ligne,"%s:%s",dims->dim.first,dims->dim.last);
-            strcat(listdimension,ligne);
-            if ( dims->suiv ) strcat(listdimension,",");
-            dims = dims->suiv;
-         }
-         if ( dimsempty == 1 ) newvariable->v_dimsempty=1;
-      }
-      strcpy(newvariable->v_readedlistdimension,listdimension);
-      Save_Length(listdimension,15);
-   }
-
-
-   newvar->suiv = NULL;
-
-   if ( !List_Common_Var )
-   {
-      List_Common_Var = newvar;
-   }
-   else
-   {
-      newvar2 = List_Common_Var;
-      out = 0 ;
-      while ( newvar2 && out == 0 )
-      {
-         if ( !strcasecmp(newvar2->var->v_nomvar,commonvar) &&
-              !strcasecmp(newvar2->var->v_commonname,commonblockname) &&
-              !strcasecmp(newvar2->var->v_subroutinename,subroutinename)
-                          ) out = 1 ;
-         else newvar2 = newvar2->suiv;
-      }
-      if ( out == 0 )
-      {
-         newvar->suiv = List_Common_Var;
-         List_Common_Var = newvar;
-      }
-      else
-      {
-         free(newvar);
-      }
-   }
-   }
+    listvar *newvar;
+    listvar *newvar2;
+    variable *newvariable;
+    listdim *dims;
+    char listdimension[LONG_M];
+    char ligne[LONG_M];
+    int out;
+
+    if ( firstpass == 1 )
+    {
+        newvar = (listvar *) calloc(1,sizeof(listvar));
+        newvariable = (variable *) calloc(1,sizeof(variable));
+
+        Init_Variable(newvariable);
+
+        strcpy(newvariable->v_nomvar,commonvar);
+        strcpy(newvariable->v_commonname,commonblockname);
+        strcpy(newvariable->v_modulename,curmodulename);
+        strcpy(newvariable->v_subroutinename,subroutinename);
+        strcpy(newvariable->v_commoninfile,cur_filename);
+        newvariable->v_positioninblock = positioninblock;
+        newvariable->v_common = 1;
+        newvar->var = newvariable;
+
+        if ( commondim )
+        {
+            newvariable->v_dimension = commondim;
+            newvariable->v_dimensiongiven = 1;
+            newvariable->v_nbdim = get_num_dims(commondim);
+
+            /* Creation of the string for the dimension of this variable            */
+            dimsempty = 1;
+            strcpy(listdimension,"");
+
+            dims = commondim;
+            while (dims)
+            {
+                if ( strcasecmp(dims->dim.first,"") ||
+                     strcasecmp(dims->dim.last,""))  dimsempty = 0;
+                sprintf(ligne,"%s:%s",dims->dim.first,dims->dim.last);
+                strcat(listdimension,ligne);
+                if ( dims->suiv ) strcat(listdimension,",");
+                dims = dims->suiv;
+            }
+            if ( dimsempty == 1 ) newvariable->v_dimsempty = 1;
+
+            strcpy(newvariable->v_readedlistdimension,listdimension);
+            Save_Length(listdimension,15);
+        }
+
+        newvar->suiv = NULL;
+
+        if ( !List_Common_Var )
+        {
+            List_Common_Var = newvar;
+        }
+        else
+        {
+            newvar2 = List_Common_Var;
+            out = 0 ;
+            while ( newvar2 && out == 0 )
+            {
+                if ( !strcasecmp(newvar2->var->v_nomvar,commonvar) &&
+                     !strcasecmp(newvar2->var->v_commonname,commonblockname) &&
+                     !strcasecmp(newvar2->var->v_subroutinename,subroutinename)
+                   ) out = 1 ;
+                else newvar2 = newvar2->suiv;
+            }
+            if ( out == 0 )
+            {
+                newvar->suiv = List_Common_Var;
+                List_Common_Var = newvar;
+            }
+            else
+            {
+                free(newvar);
+            }
+        }
+    }
 }
 
@@ -145,37 +136,39 @@
 /*                                                                            */
 /******************************************************************************/
-listnom *Addtolistnom(char *nom, listnom *listin,int value)
-{
-   listnom *newnom;
-   listnom *parcours;
-   int out;
-
-   newnom=(listnom *) malloc (sizeof (listnom));
-   strcpy(newnom->o_nom,nom);
-   Save_Length(nom,23);
-   newnom->o_val = value;
-   newnom->suiv = NULL;
-
-   if ( !listin ) listin = newnom;
-   else
-   {
-      parcours = listin;
-      out = 0 ;
-      while ( parcours && out == 0 )
-      {
-         if ( !strcasecmp(parcours->o_nom,nom) ) out = 1 ;
-         else parcours=parcours->suiv;
-      }
-      if ( out == 0 )
-      {
-          newnom->suiv = listin;
-          listin = newnom;
-      }
-      else
-      {
-         free(newnom);
-      }
-   }
-   return listin;
+listnom *Addtolistnom(const char *nom, listnom *listin, int value)
+{
+    listnom *newnom;
+    listnom *parcours;
+    int out;
+
+    newnom = (listnom*) calloc(1, sizeof(listnom));
+    strcpy(newnom->o_nom, nom);
+    newnom->o_val = value;
+    newnom->suiv = NULL;
+
+    if ( listin == NULL )
+    {
+        listin = newnom;
+    }
+    else
+    {
+        parcours = listin;
+        out = 0 ;
+        while ( parcours && out == 0 )
+        {
+            if ( !strcasecmp(parcours->o_nom, nom) ) out = 1 ;
+            else parcours = parcours->suiv;
+        }
+        if ( out == 0 )
+        {
+            newnom->suiv = listin;
+            listin = newnom;
+        }
+        else
+        {
+            free(newnom);
+        }
+    }
+    return listin;
 }
 
@@ -193,37 +186,35 @@
 /*                                                                            */
 /******************************************************************************/
-listname *Addtolistname(char *nom,listname *input)
-{
-   listname *newnom;
-   listname *parcours;
-   int out;
-
-   if ( !input )
-   {
-      newnom=(listname *) malloc (sizeof (listname));
-      strcpy(newnom->n_name,nom);
-      Save_Length(nom,20);
-      newnom->suiv = NULL;
-      input = newnom;
-   }
-   else
-   {
-      parcours = input;
-      out = 0 ;
-      while ( parcours && out == 0 )
-      {
-         if ( !strcasecmp(parcours->n_name,nom) ) out = 1;
-         else parcours=parcours->suiv;
-      }
-      if ( out == 0 )
-      {
-         newnom=(listname *) malloc (sizeof (listname));
-         strcpy(newnom->n_name,nom);
-         Save_Length(nom,20);
-         newnom->suiv = input;
-         input = newnom;
-      }
-   }
-   return input;
+listname *Addtolistname(const char *nom, listname *input)
+{
+    listname *newnom;
+    listname *parcours;
+    int out;
+
+    if ( !input )
+    {
+        newnom = (listname*) calloc(1, sizeof(listname));
+        strcpy(newnom->n_name, nom);
+        newnom->suiv = NULL;
+        input = newnom;
+    }
+    else
+    {
+        parcours = input;
+        out = 0 ;
+        while ( parcours && out == 0 )
+        {
+            if ( !strcasecmp(parcours->n_name,nom) ) out = 1;
+            else parcours=parcours->suiv;
+        }
+        if ( out == 0 )
+        {
+            newnom = (listname*) calloc(1,sizeof(listname));
+            strcpy(newnom->n_name, nom);
+            newnom->suiv = input;
+            input = newnom;
+        }
+    }
+    return input;
 }
 
@@ -236,20 +227,20 @@
 /*                                                                            */
 /******************************************************************************/
-int ModuleIsDefineInInputFile(char *name)
-{
-   listnom *newnom;
-   int out;
-
-   out = 0;
-   if ( listofmodules )
-   {
-      newnom = listofmodules;
-      while( newnom && out == 0 )
-      {
-         if ( !strcasecmp(newnom->o_nom,name) ) out = 1 ;
-         else newnom=newnom->suiv;
-      }
-   }
-   return out;
+int ModuleIsDefineInInputFile(const char *name)
+{
+    listnom *newnom;
+    int out;
+
+    out = 0;
+    if ( listofmodules )
+    {
+        newnom = listofmodules;
+        while( newnom && out == 0 )
+        {
+            if ( !strcasecmp(newnom->o_nom,name) ) out = 1 ;
+            else newnom = newnom->suiv;
+        }
+    }
+    return out;
 }
 
@@ -270,40 +261,36 @@
 /*                                                                            */
 /******************************************************************************/
-void Addmoduletothelisttmp(char *name)
-{
-  listusemodule *newmodule;
-  listusemodule *parcours;
-  int out;
-
-  if ( !listofmoduletmp)
-  {
-    newmodule =(listusemodule *)malloc(sizeof(listusemodule));
-    strcpy(newmodule->u_usemodule,name);
-    Save_Length(name,16);
-    strcpy(newmodule->u_cursubroutine,subroutinename);
-    Save_Length(subroutinename,18);
-    newmodule->suiv = NULL;
-    listofmoduletmp = newmodule ;
-  }
-  else
-  {
-    parcours = listofmoduletmp;
-    out = 0;
-    while( parcours && out == 0 )
-    {
-       if ( !strcasecmp(parcours->u_usemodule,name) ) out = 1;
-       else parcours = parcours->suiv;
-    }
-    if ( out == 0 )
-    {
-       newmodule =(listusemodule *)malloc(sizeof(listusemodule));
-       strcpy(newmodule->u_usemodule,name);
-       Save_Length(name,16);
-       strcpy(newmodule->u_cursubroutine,subroutinename);
-       Save_Length(subroutinename,18);
-       newmodule->suiv = listofmoduletmp;
-       listofmoduletmp = newmodule;
-    }
-  }
+void Addmoduletothelisttmp(const char *name)
+{
+    listusemodule *newmodule;
+    listusemodule *parcours;
+    int out;
+
+    if ( !listofmoduletmp )
+    {
+        newmodule = (listusemodule*) calloc(1, sizeof(listusemodule));
+        strcpy(newmodule->u_usemodule, name);
+        strcpy(newmodule->u_cursubroutine, subroutinename);
+        newmodule->suiv = NULL;
+        listofmoduletmp = newmodule ;
+    }
+    else
+    {
+        parcours = listofmoduletmp;
+        out = 0;
+        while( parcours && out == 0 )
+        {
+            if ( !strcasecmp(parcours->u_usemodule, name) ) out = 1;
+            else parcours = parcours->suiv;
+        }
+        if ( out == 0 )
+        {
+            newmodule = (listusemodule*) calloc(1, sizeof(listusemodule));
+            strcpy(newmodule->u_usemodule, name);
+            strcpy(newmodule->u_cursubroutine, subroutinename);
+            newmodule->suiv = listofmoduletmp;
+            listofmoduletmp = newmodule;
+        }
+    }
 }
 
@@ -321,16 +308,15 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_NameOfModule_1(char *nom)
-{
-   listnom *newnom;
-
-   if ( firstpass == 1 )
-   {
-      newnom=(listnom *) malloc (sizeof (listnom));
-      strcpy(newnom->o_nom,nom);
-      Save_Length(nom,23);
-      newnom->suiv = List_NameOfModule;
-      List_NameOfModule = newnom;
-   }
+void Add_NameOfModule_1(const char *nom)
+{
+    listnom *newnom;
+
+    if ( firstpass == 1 )
+    {
+        newnom = (listnom *) calloc(1,sizeof(listnom));
+        strcpy(newnom->o_nom,nom);
+        newnom->suiv = List_NameOfModule;
+        List_NameOfModule = newnom;
+    }
 }
 
@@ -348,24 +334,23 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_NameOfCommon_1(char *nom,char *cursubroutinename)
-{
-   listnom *newnom;
-   listnom *parcours;
-
-   if ( firstpass == 1 )
-   {
-      parcours = List_NameOfCommon;
-      while ( parcours && strcasecmp(parcours->o_nom,nom) )
-                                                      parcours = parcours->suiv;
-      if ( !parcours )
-      {
-         newnom=(listnom *) malloc (sizeof (listnom));
-         strcpy(newnom->o_nom,nom);
-         strcpy(newnom->o_subroutinename,cursubroutinename);
-         Save_Length(nom,23);
-         newnom->suiv = List_NameOfCommon;
-         List_NameOfCommon = newnom;
-      }
-   }
+void Add_NameOfCommon_1(const char *nom, const char *cursubroutinename)
+{
+    listnom *newnom;
+    listnom *parcours;
+
+    if ( firstpass == 1 )
+    {
+        parcours = List_NameOfCommon;
+        while ( parcours && strcasecmp(parcours->o_nom,nom) )
+            parcours = parcours->suiv;
+        if ( !parcours )
+        {
+            newnom = (listnom *) calloc(1,sizeof(listnom));
+            strcpy(newnom->o_nom,nom);
+            strcpy(newnom->o_subroutinename,cursubroutinename);
+            newnom->suiv = List_NameOfCommon;
+            List_NameOfCommon = newnom;
+        }
+    }
 }
 
@@ -378,28 +363,22 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_CouplePointed_Var_1(char *namemodule,listcouple *couple)
-{
-   listvarpointtovar *pointtmp;
-
-   if ( firstpass == 1 )
-   {
-      /* we should complete the List_CouplePointed_Var                        */
-      pointtmp=(listvarpointtovar *)malloc(sizeof(listvarpointtovar));
-      strcpy(pointtmp->t_usemodule,namemodule);
-      Save_Length(namemodule,28);
-      strcpy(pointtmp->t_cursubroutine,subroutinename);
-      Save_Length(subroutinename,29);
-      pointtmp->t_couple = couple;
-      if ( List_CouplePointed_Var )
-      {
-         pointtmp->suiv = List_CouplePointed_Var;
-         List_CouplePointed_Var = pointtmp;
-      }
-      else
-      {
-         pointtmp->suiv = NULL;
-         List_CouplePointed_Var = pointtmp;
-      }
-   }
+void Add_CouplePointed_Var_1(const char *namemodule, listcouple *couple)
+{
+    listvarpointtovar *pointtmp;
+
+    /* we should complete the List_CouplePointed_Var                        */
+    pointtmp = (listvarpointtovar*) calloc(1, sizeof(listvarpointtovar));
+    strcpy(pointtmp->t_usemodule, namemodule);
+    strcpy(pointtmp->t_cursubroutine, subroutinename);
+    pointtmp->t_couple = couple;
+    if ( List_CouplePointed_Var )
+    {
+        pointtmp->suiv = List_CouplePointed_Var;
+    }
+    else
+    {
+        pointtmp->suiv = NULL;
+    }
+    List_CouplePointed_Var = pointtmp;
 }
 
@@ -420,66 +399,51 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_Include_1(char *name)
+void Add_Include_1(const char *name)
+{
+    listusemodule *newinclude;
+
+    if ( firstpass == 1 )
+    {
+        newinclude = (listusemodule*) calloc(1, sizeof(listusemodule));
+        strcpy(newinclude->u_usemodule,name);
+        strcpy(newinclude->u_cursubroutine,subroutinename);
+
+        newinclude->suiv = List_Include;
+        List_Include  = newinclude ;
+    }
+}
+
+/******************************************************************************/
+/*                     Add_ImplicitNoneSubroutine_1                           */
+/******************************************************************************/
+/* This subroutine is used to add a record to a list of struct                */
+/******************************************************************************/
+/*                                                                            */
+/*                                                                            */
+/******************************************************************************/
+void Add_ImplicitNoneSubroutine_1()
+{
+    if ( firstpass == 1 )
+        List_ImplicitNoneSubroutine = Addtolistname(subroutinename,List_ImplicitNoneSubroutine);
+}
+
+/******************************************************************************/
+/*                        WriteIncludeDeclaration                             */
+/******************************************************************************/
+/* Firstpass 0                                                                */
+/******************************************************************************/
+/*                                                                            */
+/******************************************************************************/
+void WriteIncludeDeclaration(FILE* tofile)
 {
   listusemodule *newinclude;
 
-  if ( firstpass == 1 )
-  {
-  newinclude =(listusemodule *)malloc(sizeof(listusemodule));
-  strcpy(newinclude->u_usemodule,name);
-  Save_Length(name,16);
-  strcpy(newinclude->u_cursubroutine,subroutinename);
-  Save_Length(subroutinename,18);
-  newinclude->suiv = NULL;
-
-  if ( !List_Include)
-  {
-     List_Include  = newinclude ;
-  }
-  else
-  {
-    newinclude->suiv = List_Include;
-    List_Include = newinclude;
-  }
-  }
-}
-
-/******************************************************************************/
-/*                     Add_ImplicitNoneSubroutine_1                           */
-/******************************************************************************/
-/* This subroutine is used to add a record to a list of struct                */
-/******************************************************************************/
-/*                                                                            */
-/*                                                                            */
-/******************************************************************************/
-void Add_ImplicitNoneSubroutine_1()
-{
-
-  if ( firstpass == 1 )
-  {
-     List_ImplicitNoneSubroutine = Addtolistname(subroutinename,
-                                                   List_ImplicitNoneSubroutine);
-  }
-}
-
-
-/******************************************************************************/
-/*                        WriteIncludeDeclaration                             */
-/******************************************************************************/
-/* Firstpass 0                                                                */
-/******************************************************************************/
-/*                                                                            */
-/******************************************************************************/
-void WriteIncludeDeclaration()
-{
-  listusemodule *newinclude;
-
   newinclude = List_Include;
-  fprintf(fortranout,"\n");
+  fprintf(tofile,"\n");
   while ( newinclude )
   {
      if ( !strcasecmp(newinclude->u_cursubroutine,subroutinename) )
      {
-        fprintf(fortranout,"      INCLUDE %s \n",newinclude->u_usemodule);
+        fprintf(tofile, "      include %s\n",newinclude->u_usemodule);
      }
      newinclude = newinclude ->suiv;
@@ -498,109 +462,81 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_Save_Var_1 (char *name,listdim *d)
-{
-  listvar *newvar;
-  listdim *dims;
-  char ligne[LONG_C];
-  char listdimension[LONG_C];
-
-  if ( firstpass == 1 )
-  {
-     newvar=(listvar *)malloc(sizeof(listvar));
-     newvar->var=(variable *)malloc(sizeof(variable));
-     /*                                                                       */
-     Init_Variable(newvar->var);
-     /*                                                                       */
-     newvar->var->v_save=1;
-     strcpy(newvar->var->v_nomvar,name);
-     Save_Length(name,4);
-     strcpy(newvar->var->v_modulename,curmodulename);
-     Save_Length(curmodulename,6);
-     strcpy(newvar->var->v_subroutinename,subroutinename);
-     Save_Length(subroutinename,11);
-     strcpy(newvar->var->v_commoninfile,mainfile);
-     Save_Length(mainfile,10);
-
-     newvar->var->v_dimension=d;
-     /* Creation of the string for the dimension of this variable             */
-     dimsempty = 1;
-
-     if ( d )
-     {
-        newvar->var->v_dimensiongiven=1;
-        dims = d;
-        while (dims)
-        {
-           if ( strcasecmp(dims->dim.first,"") || strcasecmp(dims->dim.last,""))
-                                                                  dimsempty = 0;
-           sprintf(ligne,"%s:%s",dims->dim.first,dims->dim.last);
-           strcat(listdimension,ligne);
-           if ( dims->suiv )
-           {
-              strcat(listdimension,",");
-           }
-           dims = dims->suiv;
-        }
-        if ( dimsempty == 1 ) newvar->var->v_dimsempty=1;
-     }
-
-/*     strcpy(newvar->var->v_readedlistdimension,listdimension);
-     Save_Length(listdimension,15);*/
-     /*                                                                       */
-     newvar->suiv = NULL;
-
-     if ( !List_Save_Var )
-     {
-        List_Save_Var  = newvar ;
-     }
-     else
-     {
+void Add_Save_Var_1 (const char *name, listdim *d)
+{
+    listvar *newvar;
+    listdim *dims;
+    char ligne[LONG_M];
+    char listdimension[LONG_M];
+
+    if ( firstpass == 1 )
+    {
+        newvar = (listvar *) calloc(1,sizeof(listvar));
+        newvar->var = (variable *) calloc(1,sizeof(variable));
+
+        Init_Variable(newvar->var);
+
+        newvar->var->v_save = 1;
+        strcpy(newvar->var->v_nomvar,name);
+        strcpy(newvar->var->v_modulename,curmodulename);
+        strcpy(newvar->var->v_subroutinename,subroutinename);
+        strcpy(newvar->var->v_commoninfile,cur_filename);
+
+        newvar->var->v_dimension = d;
+
+        /* Creation of the string for the dimension of this variable             */
+        dimsempty = 1;
+
+        if ( d )
+        {
+            newvar->var->v_dimensiongiven = 1;
+            dims = d;
+            while (dims)
+            {
+                if ( strcasecmp(dims->dim.first,"") || strcasecmp(dims->dim.last,""))
+                    dimsempty = 0;
+                sprintf(ligne,"%s:%s",dims->dim.first,dims->dim.last);
+                strcat(listdimension,ligne);
+                if ( dims->suiv )   strcat(listdimension,",");
+                dims = dims->suiv;
+            }
+            if ( dimsempty == 1 ) newvar->var->v_dimsempty = 1;
+        }
+
         newvar->suiv = List_Save_Var;
         List_Save_Var = newvar;
-     }
-  }
+    }
 }
 
 void Add_Save_Var_dcl_1 (listvar *var)
 {
-  listvar *newvar;
-  listvar *parcours;
-
-  if ( firstpass == 1 )
-  {
-     parcours = var;
-     while ( parcours )
-     {
-        newvar=(listvar *)malloc(sizeof(listvar));
-        newvar->var=(variable *)malloc(sizeof(variable));
-        /*                                                                    */
-        Init_Variable(newvar->var);
-        /*                                                                    */
-        newvar->var->v_save=1;
-        strcpy(newvar->var->v_nomvar,parcours->var->v_nomvar);
-        strcpy(newvar->var->v_modulename,curmodulename);
-        Save_Length(curmodulename,6);
-        strcpy(newvar->var->v_subroutinename,subroutinename);
-        Save_Length(subroutinename,11);
-        strcpy(newvar->var->v_commoninfile,mainfile);
-        Save_Length(mainfile,10);
-        /*                                                                    */
-        strcpy(newvar->var->v_readedlistdimension,
-             parcours->var->v_readedlistdimension);
-        newvar->var->v_nbdim = parcours->var->v_nbdim;
-        newvar->var->v_dimension = parcours->var->v_dimension;
-        /*                                                                    */
-        newvar->var->v_dimensiongiven=parcours->var->v_dimensiongiven;
-        /*                                                                    */
-        newvar->suiv = NULL;
-
-        if ( !List_Save_Var ) List_Save_Var  = newvar ;
-        else
-        {
-           newvar->suiv = List_Save_Var;
-           List_Save_Var = newvar;
-        }
-        parcours = parcours->suiv;
-     }
-  }
-}
+    listvar *newvar;
+    listvar *parcours;
+
+    if ( firstpass == 1 )
+    {
+        parcours = var;
+        while ( parcours )
+        {
+            newvar = (listvar *) calloc(1,sizeof(listvar));
+            newvar->var = (variable *) calloc(1,sizeof(variable));
+
+            Init_Variable(newvar->var);
+
+            newvar->var->v_save = 1;
+            strcpy(newvar->var->v_nomvar,parcours->var->v_nomvar);
+            strcpy(newvar->var->v_modulename,curmodulename);
+            strcpy(newvar->var->v_subroutinename,subroutinename);
+            strcpy(newvar->var->v_commoninfile,cur_filename);
+            strcpy(newvar->var->v_readedlistdimension,parcours->var->v_readedlistdimension);
+
+            newvar->var->v_nbdim = parcours->var->v_nbdim;
+            newvar->var->v_catvar = parcours->var->v_catvar;
+            newvar->var->v_dimension = parcours->var->v_dimension;
+            newvar->var->v_dimensiongiven=parcours->var->v_dimensiongiven;
+            newvar->suiv = List_Save_Var;
+            List_Save_Var = newvar;
+
+            parcours = parcours->suiv;
+        }
+    }
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/Makefile
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/Makefile	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/Makefile	(revision 9987)
@@ -1,7 +1,2 @@
-#- option to debug
-C_D = -g # -g -Wall
-# Compilation:
-CC		= cc -O
-#-
 OBJS = main.o WriteInFile.o toamr.o fortran.o  \
        dependfile.o SubLoopCreation.o WorkWithlistvarindoloop.o \
@@ -14,13 +9,31 @@
        WorkWithlistofcoupled.o
 
-
 .SUFFIXES:
 .SUFFIXES: .c .o
 
-all : conv
-	@echo CONV is ok
+all: conv
+	@echo
+	@echo ===================================================
+	@echo   CONV is ok
+	@echo ===================================================
+	@echo
 
-conv :  $(OBJS)
-	@$(CC) $(OBJS) -o ../$@
+#main.c: convert.y convert.lex
+#	@echo ===================================================
+#	@echo   Rebuilding main.c ...
+#	@echo ===================================================
+#	$(MAKE) -f Makefile.lex main.c
+
+#fortran.c: fortran.y fortran.lex
+#	@echo ===================================================
+#	@echo   Rebuilding fortran.c ...
+#	@echo ===================================================
+#	$(MAKE) -f Makefile.lex fortran.c
+
+conv: $(OBJS)
+	$(CC) $(CFLAGS) -g $(OBJS) -o ../$@
+
+%.o: %.c
+	$(CC) $(CFLAGS) -g -c $< -o $@
 
 main.o : main.c
@@ -28,16 +41,16 @@
 toamr.o : toamr.c decl.h
 WriteInFile.o : WriteInFile.c decl.h
-dependfile.o : dependfile.c decl.h	
-SubLoopCreation.o : SubLoopCreation.c decl.h	
-WorkWithglobliste.o : WorkWithglobliste.c decl.h	
-WorkWithlistvarindoloop.o : WorkWithlistvarindoloop.c decl.h	
-WorkWithvarofsubroutineliste.o : WorkWithvarofsubroutineliste.c decl.h	
-Writedeclarations.o : Writedeclarations.c decl.h	
-UtilFortran.o : UtilFortran.c decl.h	
-WorkWithParameterlist.o : WorkWithParameterlist.c decl.h	
-UtilNotGridDep.o : UtilNotGridDep.c decl.h	
-WorkWithlistdatavariable.o : WorkWithlistdatavariable.c decl.h	
-DiversListe.o : DiversListe.c decl.h	
-UtilAgrif.o : UtilAgrif.c decl.h	
+dependfile.o : dependfile.c decl.h
+SubLoopCreation.o : SubLoopCreation.c decl.h
+WorkWithglobliste.o : WorkWithglobliste.c decl.h
+WorkWithlistvarindoloop.o : WorkWithlistvarindoloop.c decl.h
+WorkWithvarofsubroutineliste.o : WorkWithvarofsubroutineliste.c decl.h
+Writedeclarations.o : Writedeclarations.c decl.h
+UtilFortran.o : UtilFortran.c decl.h
+WorkWithParameterlist.o : WorkWithParameterlist.c decl.h
+UtilNotGridDep.o : UtilNotGridDep.c decl.h
+WorkWithlistdatavariable.o : WorkWithlistdatavariable.c decl.h
+DiversListe.o : DiversListe.c decl.h
+UtilAgrif.o : UtilAgrif.c decl.h
 WorkWithAllocatelist.o : WorkWithAllocatelist.c decl.h
 UtilCharacter.o : UtilCharacter.c decl.h
@@ -47,4 +60,7 @@
 WorkWithlistmoduleinfile.o : WorkWithlistmoduleinfile.c decl.h
 WorkWithlistofcoupled.o : WorkWithlistofcoupled.c decl.h
-clean : 
-	/bin/rm -f *.o y.output
+
+clean:
+#	$(MAKE) -f Makefile.lex clean
+	$(RM) *.o conv
+	
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/SubLoopCreation.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/SubLoopCreation.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/SubLoopCreation.c	(revision 9987)
@@ -45,74 +45,47 @@
 
 /******************************************************************************/
-/*                             writeheadnewsub_0                              */
-/******************************************************************************/
-/* Firstpass 0                                                                */
+/*                           WriteBeginof_SubLoop                             */
+/******************************************************************************/
 /* We should write the head of the subroutine sub_loop_<subroutinename>       */
 /******************************************************************************/
 /*                                                                            */
 /******************************************************************************/
-void writeheadnewsub_0()
-{
-   char ligne[LONG_C];
-
-   if ( firstpass == 0 && IsTabvarsUseInArgument_0() == 1 )
-   {
-      if ( todebug == 1 ) printf("Enter in writeheadnewsub_0\n");
+void WriteBeginof_SubLoop()
+{
+   if (todebug == 1) printf("##\n## Enter in HEAD SUBLOOP for |%s|\n##\n", subroutinename);
+   if ( IsTabvarsUseInArgument_0() == 1 )
+   {
+      if ( todebug == 1 ) printf("> enter in WriteBeginof_SubLoop : IsTabvarsUseInArgument_0() == 1\n");
       /* we should add the use agrif_uti l if it is necessary                 */
       WriteHeadofSubroutineLoop();
       WriteUsemoduleDeclaration(subroutinename);
-      if ( ImplicitNoneInSubroutine() == 1 ) fprintf(fortranout,
-                                                       "      IMPLICIT NONE\n");
-      WriteIncludeDeclaration();
+      if ( ImplicitNoneInSubroutine() == 1 ) fprintf(fortran_out, "      implicit none\n");
+      WriteIncludeDeclaration(fortran_out);
       /*                                                                      */
       /* We should write once the declaration of tables (extract              */
       /*    from pointer) in the new subroutine                               */
-      if ( mark == 1 ) fprintf(fortranout,"!!! 000000000000000 \n");
-
-      if ( SubInList_ContainsSubroutine() == 0 ) WriteLocalParamDeclaration();
-      if ( mark == 1 ) fprintf(fortranout,"!!! 111111111111111 \n");
-
-      sprintf(ligne,"\n#include \"ParamFile%s.h\" \n",subroutinename);
-      tofich(fortranout,ligne,1);
-
-      WriteArgumentDeclaration_Sort();
-
-      if ( mark == 1 ) fprintf(fortranout,"!!! 222222222222222 \n");
-      writesub_loopdeclaration_tab(List_UsedInSubroutine_Var,fortranout);
-      if ( mark == 1 ) fprintf(fortranout,"!!! 333333333333333 \n");
-      writesub_loopdeclaration_scalar(List_UsedInSubroutine_Var,paramout);
-      if ( mark == 1 ) fprintf(fortranout,"!!! 444444444444444 \n");
-      /* now we should write the function declaration                         */
-      /*    case if it is the                                                 */
-      WriteFunctionDeclaration(1);
-      if ( mark == 1 ) fprintf(fortranout,"!!! 555555555555555 \n");
-
-//      if ( SubInList_ContainsSubroutine() == 0 ) WriteSubroutineDeclaration(1);
-  
-      if ( mark == 1 ) fprintf(fortranout,"!!! 666666666666666 \n");
-      if ( todebug == 1 ) printf("Out of writeheadnewsub_0\n");
-   }
-   else if ( firstpass == 0 )
-   {
-      AddUseAgrifUtil_0(fortranout);
+      if ( SubInList_ContainsSubroutine() == 0 ) WriteLocalParamDeclaration(fortran_out);
+
+      writesub_loopdeclaration_scalar(List_UsedInSubroutine_Var,fortran_out);
+      writesub_loopdeclaration_tab(List_UsedInSubroutine_Var,fortran_out);
+      WriteArgumentDeclaration_Sort(fortran_out);
+      WriteFunctionDeclaration(fortran_out, 1);
+   }
+   else
+   {
+      if ( todebug == 1 ) printf("> enter in WriteBeginof_SubLoop : IsTabvarsUseInArgument_0() == 0\n");
+      AddUseAgrifUtil_0(fortran_out);
       WriteUsemoduleDeclaration(subroutinename);
-      WriteIncludeDeclaration();
-      if ( ImplicitNoneInSubroutine() == 1 ) fprintf(fortranout,
-                                                       "      IMPLICIT NONE\n");
-      if ( mark == 1 ) fprintf(fortranout,"!!! aaaaaaaaaaaaaaa \n");
-      WriteLocalParamDeclaration();
-      if ( mark == 1 ) fprintf(fortranout,"!!! bbbbbbbbbbbbbbb \n");   
+      WriteIncludeDeclaration(fortran_out);
+      if ( ImplicitNoneInSubroutine() == 1 ) fprintf(fortran_out, "      implicit none\n");
+      WriteLocalParamDeclaration(fortran_out);
       WriteArgumentDeclaration_beforecall();
-      if ( mark == 1 ) fprintf(fortranout,"!!! bbbbbbccccccccc \n");
-      if ( functiondeclarationisdone == 0 ) WriteFunctionDeclaration(1);
-/*      writesub_loopdeclaration_scalar(List_SubroutineArgument_Var,fortranout);
-      writesub_loopdeclaration_tab(List_SubroutineArgument_Var,fortranout);*/
-      if ( mark == 1 ) fprintf(fortranout,"!!! ccccccccccccccc \n");
-      if ( mark == 1 ) fprintf(fortranout,"!!! ddddddddddddddd \n");
-//      WriteSubroutineDeclaration(1);
-      if ( mark == 1 ) fprintf(fortranout,"!!! eeeeeeeeeeeeeee \n");
-   }
-}
-
+      if ( functiondeclarationisdone == 0 ) WriteFunctionDeclaration(fortran_out, 1);
+/*    writesub_loopdeclaration_scalar(List_SubroutineArgument_Var,fortran_out);
+      writesub_loopdeclaration_tab(List_SubroutineArgument_Var,fortran_out);*/
+   }
+   if ( todebug == 1 ) printf("<   out of WriteBeginof_SubLoop\n");
+   if ( todebug == 1 ) printf("## EXIT HEAD SUBLOOP (%s)\n\n", subroutinename);
+}
 
 /******************************************************************************/
@@ -129,17 +102,14 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteVariablelist_subloop(FILE *outputfile,char *ligne)
+void WriteVariablelist_subloop(char *ligne)
 {
    listvar *parcours;
-   int compteur;
-
-   if ( todebug == 1 ) printf("Enter in WriteVariablelist_subloop\n");
+
+   if ( todebug == 1 ) printf("> enter in WriteVariablelist_subloop\n");
    parcours = List_SubroutineArgument_Var;
    didvariableadded = 0;
-   compteur = 0 ;
 
    while ( parcours )
    {
-
       /* if the readed variable is a variable of the subroutine               */
       /*    subroutinename we should write the name of this variable          */
@@ -147,11 +117,8 @@
       if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) )
       {
-         if ( didvariableadded == 1 )
-         {
-            strcat(ligne,",");
-         }
+         if ( didvariableadded == 1 )   strcat(ligne,",");
          strcat(ligne,parcours->var->v_nomvar);
          didvariableadded = 1;
-            }
+      }
       parcours = parcours -> suiv;
    }
@@ -161,14 +128,11 @@
       if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) )
       {
-         if ( didvariableadded == 1 )
-         {
-            strcat(ligne,",");
-         }
+         if ( didvariableadded == 1 )   strcat(ligne,",");
          strcat(ligne,parcours->var->v_nomvar);
          didvariableadded = 1;
-            }
+      }
       parcours = parcours -> suiv;
    }
-   if ( todebug == 1 ) printf("Out of WriteVariablelist_subloop\n");
+   if ( todebug == 1 ) printf("<   out of WriteVariablelist_subloop\n");
 }
 
@@ -188,14 +152,16 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteVariablelist_subloop_Call(FILE *outputfile,char *ligne)
+void WriteVariablelist_subloop_Call(char **ligne, size_t line_length)
 {
    listvar *parcours;
-   char ligne2[10];
+   char ligne2[LONG_M];
    int i;
-   int compteur ;
-
-   if ( todebug == 1 ) printf("Enter in WriteVariablelist_subloop_Call\n");
+   size_t cur_length;
+
+   cur_length = line_length;
+
+   if ( todebug == 1 ) printf("> enter in WriteVariablelist_subloop_Call\n");
    parcours = List_UsedInSubroutine_Var;
-   compteur = 0 ;
+
    while ( parcours )
    {
@@ -207,9 +173,12 @@
          )
       {
-         if ( didvariableadded == 1 )
+         if ( didvariableadded == 1 )   strcat(*ligne,",");
+         const char *vres = vargridcurgridtabvars(parcours->var, 0);
+         if ( (strlen(*ligne)+strlen(vres)+100) > cur_length )
          {
-            strcat(ligne," , ");
+            cur_length += LONG_M;
+            *ligne = realloc( *ligne, cur_length*sizeof(char) );
          }
-         strcat(ligne,vargridcurgridtabvars(parcours->var,0));
+         strcat(*ligne, vres);
          /* if it is asked in the call of the conv we should give             */
          /* scalar in argument, so we should put (1,1,1) after the            */
@@ -223,43 +192,25 @@
              while ( i <=  parcours->var->v_nbdim )
              {
-                if ( i == 1 ) strcat(ligne,"( ");
+                if ( i == 1 ) strcat(*ligne,"( ");
                 if ( SubloopScalar == 2 )
                 {
-                   strcat(ligne,":");
-                   if ( i != parcours->var->v_nbdim ) strcat(ligne,",");
+                   strcat(*ligne,":");
+                   if ( i != parcours->var->v_nbdim ) strcat(*ligne,",");
                 }
                 else
                 {
-                   strcat(ligne," lbound( ");
-                   strcat(ligne,vargridcurgridtabvars(parcours->var,0));
-                   strcat(ligne,",");
-                   strcpy(ligne2,"");
-                   sprintf(ligne2,"%d",i);
-                   strcat(ligne,ligne2);
-                   if ( i != parcours->var->v_nbdim ) strcat(ligne,"),");
+                   sprintf(ligne2,"lbound(%s,%d",vargridcurgridtabvars(parcours->var,0),i);
+                   strcat(*ligne,ligne2);
+                   if ( i != parcours->var->v_nbdim ) strcat(*ligne,"),");
                 }
-                if ( i == parcours->var->v_nbdim ) strcat(ligne,"))");
+                if ( i == parcours->var->v_nbdim ) strcat(*ligne,"))");
                 i++;
              }
          }
          didvariableadded = 1;
-         compteur = compteur +1 ;
-         /*if ( retour77 == 0 )
-         {
-            strcat(ligne," &");
-            fprintf(outputfile,"\n");
-         }
-         else fprintf(outputfile,"\n     & ");*/
-         /*tofich(outputfile,ligne,0);*/
       }
       parcours = parcours -> suiv;
    }
-   
-//   Save_Length(ligne,41);
-//   tofich(outputfile,ligne,0);
-   /* Now we should replace the last ", &" by " &"                            */
-/*   if ( didvariableadded != 0 && retour77 == 0 ) fseek(outputfile,-1,SEEK_CUR);
-   if ( didvariableadded == 0 ) fseek(outputfile,-1,SEEK_CUR);*/
-   if ( todebug == 1 ) printf("Out of WriteVariablelist_subloop_Call\n");
+   if ( todebug == 1 ) printf("<   out of WriteVariablelist_subloop_Call\n");
 }
 
@@ -280,13 +231,11 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteVariablelist_subloop_Def(FILE *outputfile, char *ligne)
+void WriteVariablelist_subloop_Def(char *ligne)
 {
    listvar *parcours;
-/*   char ligne[LONG_40M];*/
-   int compteur;
-
-   if ( todebug == 1 ) printf("Enter in WriteVariablelist_subloop_Def\n");
+
+   if ( todebug == 1 ) printf("> enter in WriteVariablelist_subloop_Def\n");
    parcours = List_UsedInSubroutine_Var;
-   compteur = 0 ;
+
    while ( parcours )
    {
@@ -295,32 +244,15 @@
       /*    in the output file                                                */
       if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename)  &&
-           (parcours->var->v_pointerdeclare == 0 || !strcasecmp(parcours->var->v_typevar,"type"))
-         )
+           (parcours->var->v_pointerdeclare == 0 || !strcasecmp(parcours->var->v_typevar,"type")) )
       {
-         if ( didvariableadded == 1 )
-         {
-            strcat(ligne,",");
-         }
+         if ( didvariableadded == 1 )   strcat(ligne,",");
          strcat(ligne,parcours->var->v_nomvar);
          didvariableadded = 1;
-            }
+      }
       parcours = parcours -> suiv;
    }
- /*  if ( compteur != 3 && compteur != 0 )
-   {
-      if ( retour77 == 0 ) fprintf(outputfile,"\n      %s &",ligne);
-      else fprintf(outputfile,"\n     & %s",ligne);
-   }*/
    Save_Length(ligne,41);
- //  tofich(outputfile,ligne,0);
-
-   /* Now we should replace the last ", &" by " &"                            */
-  /* if ( didvariableadded != 0 && retour77 == 0 ) fseek(outputfile,-1,SEEK_CUR);
-   if ( didvariableadded == 0 ) fseek(outputfile,-1,SEEK_CUR);*/
-   if ( todebug == 1 ) printf("Out of WriteVariablelist_subloop_Def\n");
-   
-}
-
-
+   if ( todebug == 1 ) printf("<   out of WriteVariablelist_subloop_Def\n");
+}
 
 /******************************************************************************/
@@ -340,33 +272,27 @@
 void WriteHeadofSubroutineLoop()
 {
-   char ligne[LONG_40M];
+   char ligne[LONG_M];
    FILE * subloop;
 
-   if ( todebug == 1 ) printf("Enter in WriteHeadofSubroutineLoop\n");
-   tofich(fortranout,"\n",1);
+   if ( todebug == 1 ) printf("> enter in WriteHeadofSubroutineLoop\n");
+   tofich(fortran_out,"\n",1);
    /* Open this newfile                                                       */
    sprintf(ligne,"Sub_Loop_%s.h",subroutinename);
-   subloop = associate(ligne);
+   subloop = open_for_write(ligne);
    /*                                                                         */
-   if (isrecursive) 
-   {
-   sprintf(ligne,"      recursive subroutine Sub_Loop_%s(",subroutinename);
-   }
-   else
-   {
-   sprintf(ligne,"      subroutine Sub_Loop_%s(",subroutinename);
-   }
+   if (isrecursive) sprintf(ligne,"recursive subroutine Sub_Loop_%s(",subroutinename);
+   else             sprintf(ligne,"subroutine Sub_Loop_%s(",subroutinename);
    /*                                                                         */
-   WriteVariablelist_subloop(subloop,ligne);
-   WriteVariablelist_subloop_Def(subloop,ligne);
+   WriteVariablelist_subloop(ligne);
+   WriteVariablelist_subloop_Def(ligne);
    /*                                                                         */
-     strcat(ligne,")");
+   strcat(ligne,")");
    tofich(subloop,ligne,1);
    /* if USE agrif_Uti l should be add                                        */
    AddUseAgrifUtil_0(subloop);
    /*                                                                         */
-   oldfortranout = fortranout;
-   fortranout = subloop;
-   if ( todebug == 1 ) printf("Out of WriteHeadofSubroutineLoop\n");
+   oldfortran_out = fortran_out;
+   fortran_out = subloop;
+   if ( todebug == 1 ) printf("<   out of WriteHeadofSubroutineLoop\n");
 }
 
@@ -386,107 +312,93 @@
 void closeandcallsubloopandincludeit_0(int suborfun)
 {
-   char ligne[LONG_40M];
-
-   if ( firstpass == 0 )
-   {
-
-   if ( todebug == 1 ) printf("Enter in closeandcallsubloopandincludeit_0\n");
+   char *ligne;
+
+   if ( firstpass == 1 )    return;
+   if ( todebug == 1 ) printf("> enter in closeandcallsubloopandincludeit_0\n");
+
+   ligne = (char*) calloc(LONG_M, sizeof(char));
+
    if ( IsTabvarsUseInArgument_0() == 1 )
    {
       /* We should remove the key word end subroutine                         */
-      RemoveWordCUR_0(fortranout,(long)(-(pos_cur-pos_endsubroutine)),
-                                          pos_cur-pos_endsubroutine);
+      RemoveWordCUR_0(fortran_out,setposcur()-pos_endsubroutine);
       /* We should close the loop subroutine                                  */
-      sprintf(ligne,"\n      end subroutine Sub_Loop_%s",subroutinename);
-      tofich(fortranout,ligne,1);
-      fclose(fortranout);
-      fortranout = oldfortranout;
-
-
-      AddUseAgrifUtilBeforeCall_0(fortranout);
+      tofich(fortran_out,"\n",1);
+      sprintf(ligne,"end subroutine Sub_Loop_%s\n",subroutinename);
+      tofich(fortran_out,ligne,1);
+      fclose(fortran_out);
+      fortran_out = oldfortran_out;
+
+      AddUseAgrifUtilBeforeCall_0(fortran_out);
       WriteArgumentDeclaration_beforecall();
-      if ( functiondeclarationisdone == 0 ) WriteFunctionDeclaration(0);
+      if ( functiondeclarationisdone == 0 ) WriteFunctionDeclaration(fortran_out, 0);
       if ( !strcasecmp(subofagrifinitgrids,subroutinename) )
-                     fprintf(oldfortranout,"      Call Agrif_Init_Grids () \n");
+            fprintf(fortran_out,"      call Agrif_Init_Grids()\n");
       /* Now we add the call af the new subroutine                            */
-      sprintf(ligne,"\n      Call Sub_Loop_%s( ",subroutinename);
+      tofich(fortran_out,"\n",1);
+      sprintf(ligne,"  call Sub_Loop_%s(",subroutinename);
       /* Write the list of the local variables used in this new subroutine    */
-      WriteVariablelist_subloop(fortranout,ligne);
+      WriteVariablelist_subloop(ligne);
       /* Write the list of the global tables used in this new subroutine      */
       /*    in doloop                                                         */
-      WriteVariablelist_subloop_Call(fortranout,ligne);
+      WriteVariablelist_subloop_Call(&ligne, LONG_M);
       /* Close the parenthesis of the new subroutine called                   */
-       strcat(ligne,")");
-      
-      tofich(fortranout,ligne,1);
+      strcat(ligne,")\n");
+      tofich(fortran_out,ligne,1);
+      /* we should include the above file in the original code                */
 
       /* We should close the original subroutine                              */
-      if ( suborfun == 3 ) sprintf(ligne,"\n      end program %s"
-                                                               ,subroutinename);
-      if ( suborfun == 2 ) sprintf(ligne,"\n      end");
-      if ( suborfun == 1 ) sprintf(ligne,"\n      end subroutine %s"
-                                                               ,subroutinename);
-      if ( suborfun == 0 ) sprintf(ligne,"\n      end function %s"
-                                                               ,subroutinename);
-      tofich(fortranout,ligne,1);
-      /* we should include the above file in the original code                */
-      sprintf(ligne,"\n#include \"Sub_Loop_%s.h\" \n",subroutinename);
-      tofich(fortranout,ligne,1);
-      }
-    oldfortranout = (FILE *)NULL;      
-   if ( todebug == 1 ) printf("Out of closeandcallsubloopandincludeit_0\n");
-   }
-   
-}
-
-
-
+      if ( suborfun == 3 ) fprintf(fortran_out, "      end program %s\n"   , subroutinename);
+      if ( suborfun == 2 ) fprintf(fortran_out, "      end\n");
+      if ( suborfun == 1 ) fprintf(fortran_out, "      end subroutine %s\n", subroutinename);
+      if ( suborfun == 0 ) fprintf(fortran_out, "      end function %s\n"  , subroutinename);
+
+      fprintf(fortran_out,"\n\n#include \"Sub_Loop_%s.h\"\n",subroutinename);
+    }
+    oldfortran_out = (FILE *)NULL;
+    if ( todebug == 1 ) printf("<   out of closeandcallsubloopandincludeit_0\n");
+}
 
 void closeandcallsubloop_contains_0()
 {
-   char ligne[LONG_40M];
-
-   if ( firstpass == 0 )
-   {
-   if ( todebug == 1 ) printf("Enter in closeandcallsubloopandincludeit_0\n");
+   char *ligne;
+
+   if ( todebug == 1 ) printf("> enter in closeandcallsubloop_contains_0\n");
    if ( IsTabvarsUseInArgument_0() == 1 )
    {
-      Remove_Word_Contains_0();
-      sprintf(ligne,"\n      end subroutine Sub_Loop_%s",subroutinename);
-      tofich(fortranout,ligne,1);
-      fclose(fortranout);
-      fortranout = oldfortranout;
-
-      AddUseAgrifUtilBeforeCall_0(fortranout);
-      if ( ImplicitNoneInSubroutine() == 1 ) fprintf(fortranout,
-                                                       "      IMPLICIT NONE\n");
-      WriteLocalParamDeclaration();
+      ligne = (char*) calloc(LONG_M, sizeof(char));
+      RemoveWordCUR_0(fortran_out,9);   // Remove word 'contains'
+      tofich(fortran_out,"\n",1);
+      sprintf(ligne,"end subroutine Sub_Loop_%s\n",subroutinename);
+      tofich(fortran_out,ligne,1);
+      fclose(fortran_out);
+      fortran_out = oldfortran_out;
+
+      AddUseAgrifUtilBeforeCall_0(fortran_out);
+
+      if ( ImplicitNoneInSubroutine() == 1 ) fprintf(fortran_out, "      implicit none\n");
+      WriteLocalParamDeclaration(fortran_out);
       WriteArgumentDeclaration_beforecall();
-      if ( functiondeclarationisdone == 0 ) WriteFunctionDeclaration(0);
-      WriteSubroutineDeclaration(0);
+      if ( functiondeclarationisdone == 0 ) WriteFunctionDeclaration(fortran_out, 0);
+/*      WriteSubroutineDeclaration(0);*/
       if ( !strcasecmp(subofagrifinitgrids,subroutinename) )
-                     fprintf(oldfortranout,"      Call Agrif_Init_Grids () \n");
+          fprintf(fortran_out,"      call Agrif_Init_Grids()\n");
       /* Now we add the call af the new subroutine                            */
-      if ( retour77 == 0 ) sprintf(ligne,"\n      Call Sub_Loop_%s( &"
-                                                               ,subroutinename);
-      else sprintf(ligne,"\n      Call Sub_Loop_%s( ",subroutinename);
-      fprintf(fortranout,ligne);
+      tofich(fortran_out,"\n",1);
+      sprintf(ligne,"  call Sub_Loop_%s(",subroutinename);
       /* Write the list of the local variables used in this new subroutine    */
-      WriteVariablelist_subloop(fortranout,ligne);
+      WriteVariablelist_subloop(ligne);
       /* Write the list of the global tables used in this new subroutine      */
       /*    in doloop                                                         */
-      WriteVariablelist_subloop_Call(fortranout,ligne);
+      WriteVariablelist_subloop_Call(&ligne, LONG_M);
       /* Close the parenthesis of the new subroutine called                   */
-      sprintf(ligne,")");
-      tofich(fortranout,ligne,1);
+      strcat(ligne,")\n");
+      tofich(fortran_out,ligne,1);
       /* We should close the original subroutine                              */
-      sprintf(ligne,"\n      contains");
-      tofich(fortranout,ligne,1);
+      fprintf(fortran_out, "      contains\n");
       /* we should include the above file in the original code                */
-      sprintf(ligne,"\n#include \"Sub_Loop_%s.h\" \n",subroutinename);
-      tofich(fortranout,ligne,1);
+      fprintf(fortran_out,"#include \"Sub_Loop_%s.h\"\n",subroutinename);
       }
-   oldfortranout = (FILE *)NULL;
-   if ( todebug == 1 ) printf("Out of closeandcallsubloopandincludeit_0\n");
-   }
-}
+   oldfortran_out = (FILE *)NULL;
+   if ( todebug == 1 ) printf("<   out of closeandcallsubloop_contains_0\n");
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilAgrif.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilAgrif.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilAgrif.c	(revision 9987)
@@ -45,5 +45,5 @@
 /*                                                                            */
 /******************************************************************************/
-int Vartonumber(char *tokname)
+int Vartonumber(const char *tokname)
 {
    int agrifintheword;
@@ -68,6 +68,11 @@
    else if ( !strcasecmp(tokname,"Agrif_Set_restore")    ) agrifintheword = 1;
    else if ( !strcasecmp(tokname,"Agrif_Save_Forrestore")) agrifintheword = 1;
-   else if ( !strcasecmp(tokname,"agrif_init_grids")     ) agrifintheword = 1;
-   else if ( !strcasecmp(tokname,"agrif_step")           ) agrifintheword = 1;
+   else if ( !strcasecmp(tokname,"Agrif_init_grids")     ) agrifintheword = 1;
+   else if ( !strcasecmp(tokname,"Agrif_step")           ) agrifintheword = 1;
+/**************************************************/
+/* adding specific adjoint agrif subroutine names */
+/**************************************************/
+   else if ( !strcasecmp(tokname,"Agrif_bc_variable_adj")    ) agrifintheword = 1;
+   else if ( !strcasecmp(tokname,"Agrif_update_variable_adj")) agrifintheword = 1;
 
    return agrifintheword;
@@ -85,12 +90,7 @@
 /*                                                                            */
 /******************************************************************************/
-int Agrif_in_Tok_NAME(char *tokname)
-{
-   int agrifintheword;
-
-   if ( strncasecmp(tokname,"Agrif_",6) == 0 )  agrifintheword = 1;
-   else agrifintheword = 0;
-
-   return agrifintheword;
+int Agrif_in_Tok_NAME(const char *tokname)
+{
+    return ( strncasecmp(tokname,"Agrif_",6) == 0 );
 }
 
@@ -104,230 +104,93 @@
 /*                                                                            */
 /******************************************************************************/
-void ModifyTheVariableName_0(char *ident, int lengthname)
-{
-   listvar *newvar;
-   int out;
-   
-   printf("ICI ident = %s\n",ident);
-   
-   if ( firstpass == 0 )
-   {
-      newvar = List_Global_Var;
-      out=0;
-      while ( newvar && out == 0 )
-      {
-         if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-         else newvar=newvar->suiv;
-      }
-       printf("out1 = %d\n",out);
-      if ( out == 0 )
-      {
-         newvar = List_ModuleUsed_Var;
-         while ( newvar && out == 0 )
-         {
+void ModifyTheVariableName_0(const char *ident, int lengthname)
+{
+    listvar *newvar;
+    int out;
+
+    if ( firstpass )  return;
+
+    newvar = List_Global_Var;
+    out = 0;
+    while ( newvar && out == 0 )
+    {
+        if ( !strcasecmp(newvar->var->v_nomvar, ident) ) out = 1;
+        else newvar = newvar->suiv;
+    }
+    if ( out == 0 )
+    {
+        newvar = List_ModuleUsed_Var;
+        while ( newvar && out == 0 )
+        {
             if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-      if (out == 1 && !strcasecmp(newvar->var->v_typevar,"type")) return;
-
-      if ( out == 0 )
-      {
-         newvar = List_Common_Var;
-         while ( newvar && out == 0 )
-         {
+            else newvar = newvar->suiv;
+        }
+    }
+    if ( out && !strcasecmp(newvar->var->v_typevar,"type")) return;
+
+    if ( out == 0 )
+    {
+        newvar = List_Common_Var;
+        while ( newvar && out == 0 )
+        {
             if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-
-      if ( out == 0 )
-      {
-         newvar = List_ModuleUsedInModuleUsed_Var;
-         while ( newvar && out == 0 )
-         {
+            else newvar = newvar->suiv;
+        }
+    }
+    if ( out == 0 )
+    {
+        newvar = List_ModuleUsedInModuleUsed_Var;
+        while ( newvar && out == 0 )
+        {
             if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-
-      if ( out == 1 && strcasecmp(newvar->var->v_typevar,"type"))
-      {
-      printf("ICIC3\n");
-         /* remove the variable                                               */
-         RemoveWordCUR_0(fortranout,(long)(-lengthname),
-                               lengthname);
-         fseek(fortranout,(long)(-lengthname),SEEK_CUR);
-         /* then write the new name                                           */
-         if ( inagrifcallargument == 1 && agrif_parentcall == 0 )
-            fprintf(fortranout,"%d",newvar->var->v_indicetabvars);
-         else
-         {
+            else newvar = newvar->suiv;
+        }
+    }
+    if ( out == 1 && strcasecmp(newvar->var->v_typevar,"type"))
+    {
+        // remove the variable
+        RemoveWordCUR_0(fortran_out,lengthname);
+        // then write the new name
+        if ( inagrifcallargument == 1 && agrif_parentcall == 0 )
+            fprintf(fortran_out,"%d",newvar->var->v_indicetabvars);
+        else
+        {
             if ( retour77 == 0 )
-            {
-               fprintf(fortranout," Agrif_tabvars & \n      ");
-            }
+                fprintf(fortran_out,"Agrif_%s & \n      ", tabvarsname(newvar->var));
             else
             {
-               fprintf(fortranout,"Agrif_tabvars");
-               fprintf(fortranout," \n     & ");
+               fprintf(fortran_out,"Agrif_%s", tabvarsname(newvar->var));
+               fprintf(fortran_out," \n     & ");
             }
-            fprintf(fortranout,"%s",
-                             vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-            colnum = strlen(vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-         }
-      }
-      else
-      {
-         /* we should look in the List_ModuleUsed_Var                         */
-         if ( inagrifcallargument != 1 )
-         {
+            fprintf(fortran_out,"%s",vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
+        }
+    }
+    else
+    {
+        // we should look in the List_ModuleUsed_Var
+        if ( inagrifcallargument != 1 )
+        {
             newvar = List_ModuleUsed_Var;
             while ( newvar && out == 0 )
             {
-               if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-               else newvar=newvar->suiv;
+                if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
+                else newvar = newvar->suiv;
             }
-            if ( out == 1 && strcasecmp(newvar->var->v_typevar,"type"))
+            if ( out == 1 && strcasecmp(newvar->var->v_typevar, "type"))
             {
-            printf("ICICIC4 %s\n",newvar->var->v_typevar);
-               /* remove the variable                                         */
-               RemoveWordCUR_0(fortranout,(long)(-lengthname),
-                                     lengthname);
-               fseek(fortranout,(long)(-lengthname),SEEK_CUR);
-               /* then write the new name                                     */
-               if ( retour77 == 0 )
-               {
-                  fprintf(fortranout," Agrif_tabvars & \n      ");
-               }
-               else
-               {
-                  fprintf(fortranout," \n     & Agrif_tabvars");
-               }
-               fprintf(fortranout,"%s",
-                             vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-               colnum = strlen(
-                             vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
+                // remove the variable
+                RemoveWordCUR_0(fortran_out,lengthname);
+                // then write the new name
+                if ( retour77 == 0 )
+                    fprintf(fortran_out,"Agrif_%s & \n      ",tabvarsname(newvar->var));
+                else
+                {
+                    fprintf(fortran_out," \n     &Agrif_%s",tabvarsname(newvar->var));
+                }
+                fprintf(fortran_out,"%s",vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
             }
-         }
-      }
-   }
-}
-
-/******************************************************************************/
-/*                     ModifyTheVariableName_0                                */
-/******************************************************************************/
-/* Firstpass 0                                                                */
-/******************************************************************************/
-/*                                                                            */
-/*               Agrif_<toto>(variable) ====>     Agrif_<toto>(variable)      */
-/*                                                                            */
-/******************************************************************************/
-void ModifyTheVariableNamecoupled_0(char *ident, char* coupledident)
-{
-   listvar *newvar;
-   int out;
-   
-   if ( firstpass == 0 )
-   {
-      newvar = List_Global_Var;
-      out=0;
-      while ( newvar && out == 0 )
-      {
-         if ( !strcasecmp(newvar->var->v_nomvar,coupledident) ) out = 1;
-         else newvar=newvar->suiv;
-      }
-
-      if ( out == 0 )
-      {
-         newvar = List_ModuleUsed_Var;
-         while ( newvar && out == 0 )
-         {
-            if ( !strcasecmp(newvar->var->v_nomvar,coupledident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-      if ( out == 0 )
-      {
-         newvar = List_Common_Var;
-         while ( newvar && out == 0 )
-         {
-            if ( !strcasecmp(newvar->var->v_nomvar,coupledident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-
-      if ( out == 0 )
-      {
-         newvar = List_ModuleUsedInModuleUsed_Var;
-         while ( newvar && out == 0 )
-         {
-            if ( !strcasecmp(newvar->var->v_nomvar,coupledident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-
-      if ( out == 1 )
-      {
-         /* remove the variable                                               */
-         RemoveWordCUR_0(fortranout,(long)(-strlen(ident)),
-                               strlen(ident));
-         fseek(fortranout,(long)(-strlen(ident)),SEEK_CUR);
-         /* then write the new name                                           */
-         if ( inagrifcallargument == 1 && agrif_parentcall == 0 )
-            fprintf(fortranout,"%d",newvar->var->v_indicetabvars);
-         else
-         {
-            if ( retour77 == 0 )
-            {
-               fprintf(fortranout," Agrif_tabvars & \n      ");
-            }
-            else
-            {
-               fprintf(fortranout,"Agrif_tabvars");
-               fprintf(fortranout," \n     & ");
-            }
-            fprintf(fortranout,"%s",
-                             vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-            colnum = strlen(vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-         }
-      }
-      else
-      {
-         /* we should look in the List_ModuleUsed_Var                         */
-         if ( inagrifcallargument != 1 )
-         {
-            newvar = List_ModuleUsed_Var;
-            while ( newvar && out == 0 )
-            {
-               if ( !strcasecmp(newvar->var->v_nomvar,coupledident) ) out = 1;
-               else newvar=newvar->suiv;
-            }
-            if ( out == 1 )
-            {
-               /* remove the variable                                         */
-               RemoveWordCUR_0(fortranout,(long)(-strlen(ident)),
-                                     strlen(ident));
-               fseek(fortranout,(long)(-strlen(ident)),SEEK_CUR);
-               /* then write the new name                                     */
-               if ( retour77 == 0 )
-               {
-                  fprintf(fortranout," Agrif_tabvars & \n      ");
-               }
-               else
-               {
-                  fprintf(fortranout," \n     & Agrif_tabvars");
-               }
-               fprintf(fortranout,"%s",
-                             vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-               colnum = strlen(
-                             vargridcurgridtabvarswithoutAgrif_Gr(newvar->var));
-            }
-         }
-      }
-   }
-}
-
-
+        }
+    }
+}
 
 /******************************************************************************/
@@ -348,40 +211,36 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_SubroutineWhereAgrifUsed_1(char *sub,char *mod)
-{
-  listnom *listnomtmp;
-  listnom *parcours;
-
-  if ( firstpass == 1 )
-  {
-  if ( !List_SubroutineWhereAgrifUsed )
-  {
-     listnomtmp=(listnom *)malloc(sizeof(listnom));
-     strcpy(listnomtmp->o_nom,sub);
-     Save_Length(sub,23);
-     strcpy(listnomtmp->o_module,mod);
-     Save_Length(mod,24);
-     listnomtmp->suiv = NULL;
-     List_SubroutineWhereAgrifUsed  =  listnomtmp;
-  }
-  else
-  {
-    parcours = List_SubroutineWhereAgrifUsed;
-    while ( parcours && strcasecmp(parcours->o_nom,sub) )
-    {
-       parcours = parcours->suiv;
-    }
-    if ( !parcours )
-    {
-       listnomtmp=(listnom *)malloc(sizeof(listnom));
-       strcpy(listnomtmp->o_nom,sub);
-       Save_Length(sub,23);
-       strcpy(listnomtmp->o_module,mod);
-       Save_Length(mod,24);
-       listnomtmp->suiv = List_SubroutineWhereAgrifUsed;
-       List_SubroutineWhereAgrifUsed  =  listnomtmp;
-    }
-  }
-  }
+void Add_SubroutineWhereAgrifUsed_1(const char *sub, const char *mod)
+{
+    listnom *listnomtmp;
+    listnom *parcours;
+
+    if ( firstpass == 1 )
+    {
+        if ( !List_SubroutineWhereAgrifUsed )
+        {
+            listnomtmp = (listnom*) calloc(1, sizeof(listnom));
+            strcpy(listnomtmp->o_nom, sub);
+            strcpy(listnomtmp->o_module, mod);
+            listnomtmp->suiv = NULL;
+            List_SubroutineWhereAgrifUsed = listnomtmp;
+        }
+        else
+        {
+            parcours = List_SubroutineWhereAgrifUsed;
+            while ( parcours && strcasecmp(parcours->o_nom,sub) )
+            {
+                parcours = parcours->suiv;
+            }
+            if ( !parcours )
+            {
+                listnomtmp = (listnom*) calloc(1, sizeof(listnom));
+                strcpy(listnomtmp->o_nom, sub);
+                strcpy(listnomtmp->o_module, mod);
+                listnomtmp->suiv = List_SubroutineWhereAgrifUsed;
+                List_SubroutineWhereAgrifUsed = listnomtmp;
+            }
+        }
+    }
 }
 
@@ -411,7 +270,11 @@
      parcours = List_SubroutineWhereAgrifUsed;
      while ( parcours && strcasecmp(parcours->o_nom,subroutinename) )
-                                                    parcours = parcours -> suiv;
+     {
+        parcours = parcours -> suiv;
+     }
      if ( parcours && parcours->o_val != 0 )
-                                   fprintf(fileout,"\n      USE Agrif_Util \n");
+        fprintf(fileout,"\n      use Agrif_Util\n");
+     else
+        fprintf(fileout,"\n      use Agrif_Types, only : Agrif_tabvars\n");
   }
 }
@@ -419,25 +282,26 @@
 void  AddUseAgrifUtilBeforeCall_0(FILE *fileout)
 {
-  listusemodule *parcours;
-
-  int out;
-
-  if ( firstpass == 0 )
-  {
-     parcours = List_NameOfModuleUsed;
-     out = 0 ;
-     while ( parcours && out == 0 )
-     {
-        if ( !strcasecmp(parcours->u_usemodule,"Agrif_Util")     &&
-             !strcasecmp(parcours->u_modulename,curmodulename)   &&
-             !strcasecmp(parcours->u_cursubroutine,subroutinename)
-            ) out = 1;
-        else parcours = parcours->suiv;
-     }
-     if ( out == 0 )
-     {
-        fprintf(fileout,"\n      USE Agrif_Util \n");
-     }
-  }
+    listusemodule *parcours;
+
+    int out;
+
+    if ( firstpass == 0 )
+    {
+        parcours = List_NameOfModuleUsed;
+        out = 0 ;
+        while ( parcours && out == 0 )
+        {
+            if ( !strcasecmp(parcours->u_usemodule, "Agrif_Util")   &&
+                 !strcasecmp(parcours->u_modulename, curmodulename) &&
+                 !strcasecmp(parcours->u_cursubroutine, subroutinename) )
+                out = 1;
+            else
+                parcours = parcours->suiv;
+        }
+        if ( out == 0 )
+        {
+            fprintf(fileout,"\n      use Agrif_Util\n");
+        }
+    }
 }
 
@@ -451,164 +315,163 @@
 /*                                                                            */
 /******************************************************************************/
-void NotifyAgrifFunction_0(char *ident)
-{
-   if ( firstpass == 0 )
-   {
-      if ( !strcasecmp(ident,"Agrif_parent") )
-      {
-         InAgrifParentDef = 1;
-         pos_curagrifparent = setposcur()-12;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Get_Coarse_grid") )
-      {
-         InAgrifParentDef = 2;
-         pos_curagrifparent = setposcur()-21;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Rhox") )
-      {
-         InAgrifParentDef = 3;
-         pos_curagrifparent = setposcur()-10;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_Rhox") )
-      {
-         InAgrifParentDef = 4;
-         pos_curagrifparent = setposcur()-17;
-      }
-      else if ( !strcasecmp(ident,"Agrif_IRhox") )
-      {
-         InAgrifParentDef = 5;
-         pos_curagrifparent = setposcur()-11;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_IRhox") )
-      {
-         InAgrifParentDef = 6;
-         pos_curagrifparent = setposcur()-18;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Rhoy") )
-      {
-         InAgrifParentDef = 7;
-         pos_curagrifparent = setposcur()-10;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_Rhoy") )
-      {
-         InAgrifParentDef = 8;
-         pos_curagrifparent = setposcur()-17;
-      }
-      else if ( !strcasecmp(ident,"Agrif_IRhoy") )
-      {
-         InAgrifParentDef = 9;
-         pos_curagrifparent = setposcur()-11;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_IRhoy") )
-      {
-         InAgrifParentDef = 10;
-         pos_curagrifparent = setposcur()-18;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Rhoz") )
-      {
-         InAgrifParentDef = 11;
-         pos_curagrifparent = setposcur()-10;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_Rhoz") )
-      {
-         InAgrifParentDef = 12;
-         pos_curagrifparent = setposcur()-17;
-      }
-      else if ( !strcasecmp(ident,"Agrif_IRhoz") )
-      {
-         InAgrifParentDef = 13;
-         pos_curagrifparent = setposcur()-11;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_IRhoz") )
-      {
-         InAgrifParentDef = 14;
-         pos_curagrifparent = setposcur()-18;
-      }
-      else if ( !strcasecmp(ident,"Agrif_NearCommonBorderX") )
-      {
-         InAgrifParentDef = 15;
-         pos_curagrifparent = setposcur()-23;
-      }
-      else if ( !strcasecmp(ident,"Agrif_NearCommonBorderY") )
-      {
-         InAgrifParentDef = 16;
-         pos_curagrifparent = setposcur()-23;
-      }
-      else if ( !strcasecmp(ident,"Agrif_NearCommonBorderZ") )
-      {
-         InAgrifParentDef = 17;
-         pos_curagrifparent = setposcur()-23;
-      }
-      else if ( !strcasecmp(ident,"Agrif_DistantCommonBorderX") )
-      {
-         InAgrifParentDef = 18;
-         pos_curagrifparent = setposcur()-26;
-      }
-      else if ( !strcasecmp(ident,"Agrif_DistantCommonBorderY") )
-      {
-         InAgrifParentDef = 19;
-         pos_curagrifparent = setposcur()-26;
-      }
-      else if ( !strcasecmp(ident,"Agrif_DistantCommonBorderZ") )
-      {
-         InAgrifParentDef = 20;
-         pos_curagrifparent = setposcur()-26;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Get_parent_id") )
-      {
-         InAgrifParentDef = 21;
-         pos_curagrifparent = setposcur()-19;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Get_grid_id") )
-      {
-         InAgrifParentDef = 22;
-         pos_curagrifparent = setposcur()-17;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_Iz") )
-      {
-         InAgrifParentDef = 23;
-         pos_curagrifparent = setposcur()-15;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_Iy") )
-      {
-         InAgrifParentDef = 24;
-         pos_curagrifparent = setposcur()-15;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Parent_Ix") )
-      {
-         InAgrifParentDef = 25;
-         pos_curagrifparent = setposcur()-15;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Iz") )
-      {
-         InAgrifParentDef = 26;
-         pos_curagrifparent = setposcur()-8;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Iy") )
-      {
-         InAgrifParentDef = 27;
-         pos_curagrifparent = setposcur()-8;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Ix") )
-      {
-         InAgrifParentDef = 28;
-         pos_curagrifparent = setposcur()-8;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Nb_Fixed_Grids") )
-      {
-         InAgrifParentDef = 29;
-         pos_curagrifparent = setposcur()-20;
-      }
-      else if ( !strcasecmp(ident,"Agrif_Nb_Fine_Grids") )
-      {
-         InAgrifParentDef = 29;
-         pos_curagrifparent = setposcur()-19;
-      }
-      else if ( !strcasecmp(ident,"AGRIF_Nb_Step") )
-      {
-         InAgrifParentDef = 30;
-         pos_curagrifparent = setposcur()-13;
-      }
-   }
+void NotifyAgrifFunction_0(const char *ident)
+{
+    if ( firstpass == 1 )   return;
+
+    if ( !strcasecmp(ident,"Agrif_parent") )
+    {
+        InAgrifParentDef = 1;
+        pos_curagrifparent = setposcur()-12;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Get_Coarse_grid") )
+    {
+        InAgrifParentDef = 2;
+        pos_curagrifparent = setposcur()-21;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Rhox") )
+    {
+        InAgrifParentDef = 3;
+        pos_curagrifparent = setposcur()-10;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_Rhox") )
+    {
+        InAgrifParentDef = 4;
+        pos_curagrifparent = setposcur()-17;
+    }
+    else if ( !strcasecmp(ident,"Agrif_IRhox") )
+    {
+        InAgrifParentDef = 5;
+        pos_curagrifparent = setposcur()-11;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_IRhox") )
+    {
+        InAgrifParentDef = 6;
+        pos_curagrifparent = setposcur()-18;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Rhoy") )
+    {
+        InAgrifParentDef = 7;
+        pos_curagrifparent = setposcur()-10;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_Rhoy") )
+    {
+        InAgrifParentDef = 8;
+        pos_curagrifparent = setposcur()-17;
+    }
+    else if ( !strcasecmp(ident,"Agrif_IRhoy") )
+    {
+        InAgrifParentDef = 9;
+        pos_curagrifparent = setposcur()-11;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_IRhoy") )
+    {
+        InAgrifParentDef = 10;
+        pos_curagrifparent = setposcur()-18;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Rhoz") )
+    {
+        InAgrifParentDef = 11;
+        pos_curagrifparent = setposcur()-10;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_Rhoz") )
+    {
+        InAgrifParentDef = 12;
+        pos_curagrifparent = setposcur()-17;
+    }
+    else if ( !strcasecmp(ident,"Agrif_IRhoz") )
+    {
+        InAgrifParentDef = 13;
+        pos_curagrifparent = setposcur()-11;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_IRhoz") )
+    {
+        InAgrifParentDef = 14;
+        pos_curagrifparent = setposcur()-18;
+    }
+    else if ( !strcasecmp(ident,"Agrif_NearCommonBorderX") )
+    {
+        InAgrifParentDef = 15;
+        pos_curagrifparent = setposcur()-23;
+    }
+    else if ( !strcasecmp(ident,"Agrif_NearCommonBorderY") )
+    {
+        InAgrifParentDef = 16;
+        pos_curagrifparent = setposcur()-23;
+    }
+    else if ( !strcasecmp(ident,"Agrif_NearCommonBorderZ") )
+    {
+        InAgrifParentDef = 17;
+        pos_curagrifparent = setposcur()-23;
+    }
+    else if ( !strcasecmp(ident,"Agrif_DistantCommonBorderX") )
+    {
+        InAgrifParentDef = 18;
+        pos_curagrifparent = setposcur()-26;
+    }
+    else if ( !strcasecmp(ident,"Agrif_DistantCommonBorderY") )
+    {
+        InAgrifParentDef = 19;
+        pos_curagrifparent = setposcur()-26;
+    }
+    else if ( !strcasecmp(ident,"Agrif_DistantCommonBorderZ") )
+    {
+        InAgrifParentDef = 20;
+        pos_curagrifparent = setposcur()-26;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Get_parent_id") )
+    {
+        InAgrifParentDef = 21;
+        pos_curagrifparent = setposcur()-19;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Get_grid_id") )
+    {
+        InAgrifParentDef = 22;
+        pos_curagrifparent = setposcur()-17;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_Iz") )
+    {
+        InAgrifParentDef = 23;
+        pos_curagrifparent = setposcur()-15;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_Iy") )
+    {
+        InAgrifParentDef = 24;
+        pos_curagrifparent = setposcur()-15;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Parent_Ix") )
+    {
+        InAgrifParentDef = 25;
+        pos_curagrifparent = setposcur()-15;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Iz") )
+    {
+        InAgrifParentDef = 26;
+        pos_curagrifparent = setposcur()-8;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Iy") )
+    {
+        InAgrifParentDef = 27;
+        pos_curagrifparent = setposcur()-8;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Ix") )
+    {
+        InAgrifParentDef = 28;
+        pos_curagrifparent = setposcur()-8;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Nb_Fixed_Grids") )
+    {
+        InAgrifParentDef = 29;
+        pos_curagrifparent = setposcur()-20;
+    }
+    else if ( !strcasecmp(ident,"Agrif_Nb_Fine_Grids") )
+    {
+        InAgrifParentDef = 29;
+        pos_curagrifparent = setposcur()-19;
+    }
+    else if ( !strcasecmp(ident,"AGRIF_Nb_Step") )
+    {
+        InAgrifParentDef = 30;
+        pos_curagrifparent = setposcur()-13;
+    }
 }
 
@@ -622,9 +485,8 @@
 /*                                                                            */
 /******************************************************************************/
-void ModifyTheAgrifFunction_0(char *ident)
+void ModifyTheAgrifFunction_0(const char *ident)
 {
    if ( InAgrifParentDef != 0 )
           AgriffunctionModify_0(ident,InAgrifParentDef);
-   /*                                                                         */
    InAgrifParentDef = 0;
 }
@@ -700,240 +562,228 @@
 /*                                                                            */
 /******************************************************************************/
-void AgriffunctionModify_0(char *ident,int whichone)
-{
-   char toprint[LONG_C];
-   if ( firstpass == 0 )
-   {
-      strcpy(toprint,"");
-      pos_end = setposcur();
-      fseek(fortranout,pos_curagrifparent,SEEK_SET);
-      if ( whichone == 1 || whichone == 2 )
-      {
-         /*                                                                   */
-         FindAndChangeNameToTabvars(ident,toprint,List_Global_Var,1);
-         if ( !strcasecmp(ident,toprint) )
-         {
-            /* la liste des use de cette subroutine                           */
-            strcpy(toprint,"");
-            FindAndChangeNameToTabvars(ident,
-                                          toprint,List_Common_Var,whichone);
-         }
-         if ( !strcasecmp(ident,toprint) )
-         {
-            /* la liste des use de cette subroutine                           */
-            strcpy(toprint,"");
-            FindAndChangeNameToTabvars(ident,
-                                          toprint,List_ModuleUsed_Var,whichone);
-         }
-      }
-      else if ( whichone == 3 ) /* Agrif_Rhox                                 */
-      {
-         sprintf(toprint,"REAL(");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"Agrif_Curgrid % spaceref(1))");
-      }
-      else if ( whichone == 4 ) /* Agrif_Parent_Rhox                          */
-      {
-         sprintf(toprint,"REAL(");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"Agrif_Curgrid % parent % spaceref(1))");
-      }
-      else if ( whichone == 5 ) /* Agrif_Rhox                                 */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% spaceref(1)");
-      }
-      else if ( whichone == 6 ) /* Agrif_Parent_Rhox                          */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % spaceref(1)");
-      }
-      else if ( whichone == 7 ) /* Agrif_Rhoy                                 */
-      {
-         sprintf(toprint,"REAL(Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% spaceref(2))");
-      }
-      else if ( whichone == 8 ) /* Agrif_Parent_Rhoy                          */
-      {
-         sprintf(toprint,"REAL(Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % spaceref(2))");
-      }
-      else if ( whichone == 9 ) /* Agrif_Rhoy                                 */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% spaceref(2)");
-      }
-      else if ( whichone == 10 ) /* Agrif_Parent_Rhoy                         */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % spaceref(2)");
-      }
-      else if ( whichone == 11 ) /* Agrif_Rhoz                                */
-      {
-         sprintf(toprint,"REAL(Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% spaceref(3))");
-      }
-      else if ( whichone == 12 ) /* Agrif_Parent_Rhoz                         */
-      {
-         sprintf(toprint,"REAL(Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % spaceref(3))");
-      }
-      else if ( whichone == 13 ) /* Agrif_Rhoz                                */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% spaceref(3)");
-      }
-      else if ( whichone == 14 ) /* Agrif_Parent_Rhoz                         */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % spaceref(3)");
-      }
-      else if ( whichone == 15 ) /* Agrif_NearCommonBorderX                   */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% NearRootBorder(1)");
-      }
-      else if ( whichone == 16 ) /* Agrif_NearCommonBorderY                   */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% NearRootBorder(2)");
-      }
-      else if ( whichone == 17 ) /* Agrif_NearCommonBorderZ                   */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% NearRootBorder(3)");
-      }
-      else if ( whichone == 18 ) /* Agrif_NearCommonBorderX                   */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
+void AgriffunctionModify_0(const char *ident,int whichone)
+{
+    char toprint[LONG_M];
+    if ( firstpass == 0 )
+    {
+        strcpy(toprint,"");
+        pos_end = setposcur();
+        fseek(fortran_out,pos_curagrifparent,SEEK_SET);
+        if ( whichone == 1 || whichone == 2 )
+        {
+            FindAndChangeNameToTabvars(ident,toprint,List_Global_Var,1);
+            if ( !strcasecmp(ident,toprint) )
+            {
+                /* la liste des use de cette subroutine                           */
+                strcpy(toprint,"");
+                FindAndChangeNameToTabvars(ident,toprint,List_Common_Var,whichone);
+            }
+            if ( !strcasecmp(ident,toprint) )
+            {
+                /* la liste des use de cette subroutine                           */
+                strcpy(toprint,"");
+                FindAndChangeNameToTabvars(ident,toprint,List_ModuleUsed_Var,whichone);
+            }
+        }
+        else if ( whichone == 3 ) /* Agrif_Rhox                                 */
+        {
+            sprintf(toprint,"REAL(");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"Agrif_Curgrid % spaceref(1))");
+        }
+        else if ( whichone == 4 ) /* Agrif_Parent_Rhox                          */
+        {
+            sprintf(toprint,"REAL(");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"Agrif_Curgrid % parent % spaceref(1))");
+        }
+        else if ( whichone == 5 ) /* Agrif_Rhox                                 */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% spaceref(1)");
+        }
+        else if ( whichone == 6 ) /* Agrif_Parent_Rhox                          */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % spaceref(1)");
+        }
+        else if ( whichone == 7 ) /* Agrif_Rhoy                                 */
+        {
+            sprintf(toprint,"REAL(Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% spaceref(2))");
+        }
+        else if ( whichone == 8 ) /* Agrif_Parent_Rhoy                          */
+        {
+            sprintf(toprint,"REAL(Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % spaceref(2))");
+        }
+        else if ( whichone == 9 ) /* Agrif_Rhoy                                 */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% spaceref(2)");
+        }
+        else if ( whichone == 10 ) /* Agrif_Parent_Rhoy                         */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % spaceref(2)");
+        }
+        else if ( whichone == 11 ) /* Agrif_Rhoz                                */
+        {
+            sprintf(toprint,"REAL(Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% spaceref(3))");
+        }
+        else if ( whichone == 12 ) /* Agrif_Parent_Rhoz                         */
+        {
+            sprintf(toprint,"REAL(Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % spaceref(3))");
+        }
+        else if ( whichone == 13 ) /* Agrif_Rhoz                                */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% spaceref(3)");
+        }
+        else if ( whichone == 14 ) /* Agrif_Parent_Rhoz                         */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % spaceref(3)");
+        }
+        else if ( whichone == 15 ) /* Agrif_NearCommonBorderX                   */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% NearRootBorder(1)");
+        }
+        else if ( whichone == 16 ) /* Agrif_NearCommonBorderY                   */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% NearRootBorder(2)");
+        }
+        else if ( whichone == 17 ) /* Agrif_NearCommonBorderZ                   */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% NearRootBorder(3)");
+        }
+        else if ( whichone == 18 ) /* Agrif_NearCommonBorderX                   */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
          strcat(toprint,"% DistantRootBorder(1)");
-      }
-      else if ( whichone == 19 ) /* Agrif_NearCommonBorderY                   */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% DistantRootBorder(2)");
-      }
-      else if ( whichone == 20 ) /* Agrif_NearCommonBorderZ                   */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% DistantRootBorder(3)");
-      }
-      else if ( whichone == 21 ) /* Agrif_Get_parent_id                       */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % grid_id");
-      }
-      else if ( whichone == 22 ) /*  Agrif_Get_grid_id                        */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% grid_id");
-      }
-      else if ( whichone == 23 ) /*  Agrif_Parent_Iz                          */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % ix(3)");
-      }
-      else if ( whichone == 24 ) /*  Agrif_Parent_Iy                          */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % ix(2)");
-      }
-      else if ( whichone == 25 ) /*  Agrif_Parent_Ix                          */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% parent % ix(1)");
-      }
-      else if ( whichone == 26 ) /* Agrif_Iz                                  */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint," % ix(3)");
-      }
-      else if ( whichone == 27 ) /* Agrif_Iy                                  */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% ix(2)");
-      }
-      else if ( whichone == 28 ) /* Agrif_Ix                                  */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% ix(1)");
-      }
-      else if ( whichone == 29 ) /* Agrif_Nb_Fixed_Grids                      */
-      {
-         sprintf(toprint,"Agrif_nbfixedgrids");
-      }
-      else if ( whichone == 30 ) /* AGRIF_Nb_Step                             */
-      {
-         sprintf(toprint,"Agrif_Curgrid");
-         if( retour77 == 0 ) strcat(toprint," & \n");
-         else strcat(toprint,"\n     & ");
-         strcat(toprint,"% ngridstep");
-      }
-      /*                                                                      */
-      if ( whichone == 1 || whichone == 2 )
-      {
-         Save_Length(toprint,43);
-         tofich(fortranout,toprint,2);
-      }
-      else
-      {
-/*         if( retour77 == 0 ) fprintf(fortranout," & \n");
-         else fprintf(fortranout,"\n     & ");*/
-         Save_Length(toprint,43);
-         fprintf(fortranout,"%s",toprint);
-      }
-   }
-}
-
+        }
+        else if ( whichone == 19 ) /* Agrif_NearCommonBorderY                   */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% DistantRootBorder(2)");
+        }
+        else if ( whichone == 20 ) /* Agrif_NearCommonBorderZ                   */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% DistantRootBorder(3)");
+        }
+        else if ( whichone == 21 ) /* Agrif_Get_parent_id                       */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % grid_id");
+        }
+        else if ( whichone == 22 ) /*  Agrif_Get_grid_id                        */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% grid_id");
+        }
+        else if ( whichone == 23 ) /*  Agrif_Parent_Iz                          */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % ix(3)");
+        }
+        else if ( whichone == 24 ) /*  Agrif_Parent_Iy                          */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % ix(2)");
+        }
+        else if ( whichone == 25 ) /*  Agrif_Parent_Ix                          */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% parent % ix(1)");
+        }
+        else if ( whichone == 26 ) /* Agrif_Iz                                  */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint," % ix(3)");
+        }
+        else if ( whichone == 27 ) /* Agrif_Iy                                  */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% ix(2)");
+        }
+        else if ( whichone == 28 ) /* Agrif_Ix                                  */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% ix(1)");
+        }
+        else if ( whichone == 29 ) /* Agrif_Nb_Fixed_Grids                      */
+        {
+            sprintf(toprint,"Agrif_nbfixedgrids");
+        }
+        else if ( whichone == 30 ) /* AGRIF_Nb_Step                             */
+        {
+            sprintf(toprint,"Agrif_Curgrid");
+            if( retour77 == 0 ) strcat(toprint," & \n");
+            else                strcat(toprint,"\n     & ");
+            strcat(toprint,"% ngridstep");
+        }
+
+        Save_Length(toprint,43);
+
+        if ( whichone == 1 || whichone == 2 )   tofich(fortran_out,toprint,0);
+        else                                    fprintf(fortran_out,"%s",toprint);
+    }
+}
 
 /******************************************************************************/
@@ -946,51 +796,43 @@
 /*                                                                            */
 /******************************************************************************/
-void Instanciation_0(char *ident)
-{
-   listvar *newvar;
-   int out;
-
-   if ( firstpass == 0 && sameagrifargument == 1 )
-   {
-      newvar = List_Global_Var;
-
-      out=0;
-      while ( newvar && out == 0 )
-      {
-         if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-         else newvar=newvar->suiv;
-      }
-
-      if ( out == 0 )
-      {
-         newvar = List_Common_Var;
-
-         out=0;
-         while ( newvar && out == 0 )
-         {
+void Instanciation_0(const char *ident)
+{
+    listvar *newvar;
+    int out;
+
+    if ( firstpass == 0 && sameagrifargument == 1 )
+    {
+        newvar = List_Global_Var;
+        out = 0;
+        while ( newvar && out == 0 )
+        {
             if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-      if ( out == 0 )
-      {
-         newvar = List_ModuleUsed_Var;
-
-         out=0;
-         while ( newvar && out == 0 )
-         {
-            if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
-            else newvar=newvar->suiv;
-         }
-      }
-
-      if ( out == 1 )
-      {
-         /* then write the instanciation                                      */
-         fprintf(fortranout,"\n      %s = %s",ident,
-                                          vargridcurgridtabvars(newvar->var,3));
-         colnum = 0;
-      }
-   }
-   sameagrifargument = 0;
-}
+            else newvar = newvar->suiv;
+        }
+        if ( out == 0 )
+        {
+            newvar = List_Common_Var;
+            while ( newvar && out == 0 )
+            {
+                if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
+                else newvar = newvar->suiv;
+            }
+        }
+        if ( out == 0 )
+        {
+            newvar = List_ModuleUsed_Var;
+            while ( newvar && out == 0 )
+            {
+                if ( !strcasecmp(newvar->var->v_nomvar,ident) ) out = 1;
+                else newvar = newvar->suiv;
+            }
+        }
+//         if ( out == 1 )
+//         {
+//             /* then write the instanciation                                      */
+//             fprintf(fortran_out,"\n      %s = %s",ident,vargridcurgridtabvars(newvar->var,3));
+//             printf("#\n# Instanciation_0: |%s = %s|\n#\n", ident,vargridcurgridtabvars(newvar->var,3));
+//         }
+    }
+    sameagrifargument = 0;
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilCharacter.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilCharacter.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilCharacter.c	(revision 9987)
@@ -46,10 +46,10 @@
 /*                                                                            */
 /******************************************************************************/
-/* if  whichone = 0 ----> Agrif_tabvars(i) % var % array2                     */
-/*                                                                            */
-/* if  whichone = 1 ----> Agrif_tabvars(i) % parentvar % var % array2         */
-/*                                                                            */
-/******************************************************************************/
-void FindAndChangeNameToTabvars(char name[LONG_C],char toprint[LONG_4C],
+/* if  whichone = 0 ----> Agrif_tabvars(i) % array2                           */
+/*                                                                            */
+/* if  whichone = 1 ----> Agrif_tabvars(i) % parentvar % array2               */
+/*                                                                            */
+/******************************************************************************/
+void FindAndChangeNameToTabvars(const char name[LONG_M],char toprint[LONG_M],
                                               listvar * listtosee, int whichone)
 {
@@ -71,5 +71,5 @@
             {
                out = 1;
-               strcat(toprint,vargridcurgridtabvars(newvar->var,whichone));
+               strcat(toprint,vargridcurgridtabvars(newvar->var, whichone));
             }
             else newvar=newvar->suiv;
@@ -92,82 +92,37 @@
 /*                                                                            */
 /******************************************************************************/
-char *ChangeTheInitalvaluebyTabvarsName(char *nom,listvar *listtoread,
-                                                                   int whichone)
-{
-   char toprinttmp[LONG_4C];
-   int i;
-   char chartmp[2];
-
-   i=0;
-   strcpy(toprintglob,"");
-   strcpy(toprinttmp,"");
-
-   /*                                                                         */
-   while ( i < strlen(nom) )
-   {
-      if ( nom[i] == '+' )
-      {
-        FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,"+");
-      }
-      else if ( nom[i] == '-' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,"-");
-      }
-      else if ( nom[i] == '*' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,"*");
-      }
-      else if ( nom[i] == '/' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,"/");
-      }
-      else if ( nom[i] == '(' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,"(");
-      }
-      else if ( nom[i] == ')' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,")");
-      }
-      else if ( nom[i] == ':' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,":");
-      }
-      else if ( nom[i] == ',' )
-      {
-         FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-         strcpy(toprinttmp,"");
-         strcat(toprintglob,",");
-      }
-      else
-      {
-         sprintf(chartmp,"%c",nom[i]);
-         strcat(toprinttmp,chartmp);
-      }
-      /*                                                                      */
-      i=i+1;
-   }
-   FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,whichone);
-   strcpy(toprinttmp,"");
-
-   Save_Length(toprinttmp,44);
-   Save_Length(toprintglob,39);
-
-   /*                                                                         */
-   return toprintglob;
+const char *ChangeTheInitalvaluebyTabvarsName(const char *nom, listvar *listtoread)
+{
+    char toprinttmp[LONG_M];
+    char chartmp[2];
+    size_t i = 0;
+
+    strcpy(toprintglob, "");
+    strcpy(toprinttmp,  "");
+
+    while ( i < strlen(nom) )
+    {
+        if ( (nom[i] == '+') || (nom[i] == '-') || (nom[i] == '*') || (nom[i] == '/') ||
+             (nom[i] == '(') || (nom[i] == ')') || (nom[i] == ':') || (nom[i] == ',') )
+        {
+            FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,0);
+            strcpy(toprinttmp, "");
+            sprintf(chartmp, "%c", nom[i]);
+            strcat(toprintglob, chartmp);
+        }
+        else
+        {
+            sprintf(chartmp, "%c", nom[i]);
+            strcat(toprinttmp, chartmp);
+        }
+        i += 1;
+    }
+    FindAndChangeNameToTabvars(toprinttmp,toprintglob,listtoread,0);
+    strcpy(toprinttmp,"");
+
+    Save_Length(toprinttmp,44);
+    Save_Length(toprintglob,39);
+
+    return toprintglob;
 }
 
@@ -181,19 +136,10 @@
 /*                                                                            */
 /******************************************************************************/
-int IsVariableReal(char *nom)
-{
-   int Real;
-
-   Real = 0;
-   if ( ( nom[0] >= 'a' && nom[0] <= 'h' ) ||
+int IsVariableReal(const char *nom)
+{
+    return ( ( nom[0] >= 'a' && nom[0] <= 'h' ) ||
         ( nom[0] >= 'A' && nom[0] <= 'H' ) ||
         ( nom[0] >= 'o' && nom[0] <= 'z' ) ||
-        ( nom[0] >= 'O' && nom[0] <= 'Z' )
-       )
-       {
-          Real = 1;
-       }
-   /*                                                                         */
-   return Real;
+        ( nom[0] >= 'O' && nom[0] <= 'Z' ) );
 }
 /******************************************************************************/
@@ -206,5 +152,5 @@
 /*                                                                            */
 /******************************************************************************/
-void IsVarInUseFile(char *nom)
+void IsVarInUseFile(const char *nom)
 {
    listvar *parcours;
@@ -217,5 +163,5 @@
    while( parcours && out == 0 )
    {
-      if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out =1 ;
+      if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out = 1 ;
      else parcours=parcours->suiv;
    }
@@ -225,4 +171,13 @@
       while( parcours && out == 0 )
       {
+         if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out = 1 ;
+        else parcours=parcours->suiv;
+      }
+   }
+   if ( out == 0 )
+   {
+      parcours = List_GlobalParameter_Var;
+      while( parcours && out == 0 )
+      {
          if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out =1 ;
         else parcours=parcours->suiv;
@@ -231,17 +186,8 @@
    if ( out == 0 )
    {
-      parcours = List_GlobalParameter_Var;
-      while( parcours && out == 0 )
-      {
-         if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out =1 ;
-        else parcours=parcours->suiv;
-      }
-   }
-   if ( out == 0 )
-   {
       parcours = List_Parameter_Var;
       while( parcours && out == 0 )
       {
-         if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out =1 ;
+         if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out = 1 ;
         else parcours=parcours->suiv;
       }
@@ -252,5 +198,5 @@
       while( parcoursparam && out == 0 )
       {
-         if ( !strcasecmp(nom,parcoursparam->p_name) ) out =2 ;
+         if ( !strcasecmp(nom,parcoursparam->p_name) ) out = 2 ;
          else parcoursparam=parcoursparam->suiv;
       }
@@ -261,5 +207,5 @@
       while( parcours && out == 0 )
       {
-         if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out =2 ;
+         if ( !strcasecmp(nom,parcours->var->v_nomvar) ) out = 2 ;
         else parcours=parcours->suiv;
       }
@@ -270,5 +216,5 @@
       while( parcoursparam && out != 1 )
       {
-         if ( !strcasecmp(nom,parcoursparam->p_name) ) out =1 ;
+         if ( !strcasecmp(nom,parcoursparam->p_name) ) out = 1 ;
          else parcoursparam=parcoursparam->suiv;
       }
@@ -299,13 +245,12 @@
 /*                                                                            */
 /******************************************************************************/
-listnom *DecomposeTheNameinlistnom(char *nom, listnom * listout)
-{
-   char toprinttmp[LONG_4C];
-   int i;
+listnom *DecomposeTheNameinlistnom(const char *nom, listnom * listout)
+{
+   char toprinttmp[LONG_M];
    char chartmp[2];
-
-   i=0;
+   size_t i = 0;
+
    strcpy(toprinttmp,"");
-   /*                                                                         */
+
    while ( i < strlen(nom) )
    {
@@ -320,5 +265,4 @@
          )
       {
-
          if (strcasecmp(toprinttmp,"") && ( toprinttmp[0] >= 'A' ) )
          {
@@ -331,7 +275,5 @@
          sprintf(chartmp,"%c",nom[i]);
          strcat(toprinttmp,chartmp);
-
-      }
-      /*                                                                      */
+      }
       i=i+1;
    }
@@ -340,6 +282,6 @@
       listout = Addtolistnom(toprinttmp,listout,0);
    }
+   Save_Length(toprinttmp,44);
    strcpy(toprinttmp,"");
-   Save_Length(toprinttmp,44);
 
    return listout;
@@ -356,13 +298,12 @@
 /*                                                                            */
 /******************************************************************************/
-void DecomposeTheName(char *nom)
-{
-   char toprinttmp[LONG_4C];
-   int i;
+void DecomposeTheName(const char *nom)
+{
+   char toprinttmp[LONG_M];
    char chartmp[2];
-
-   i=0;
+   size_t i = 0;
+   
    strcpy(toprinttmp,"");
-   /*                                                                         */
+
    while ( i < strlen(nom) )
    {
@@ -390,8 +331,6 @@
          strcat(toprinttmp,chartmp);
       }
-      /*                                                                      */
       i=i+1;
    }
-   Save_Length(toprinttmp,44);
    if (strcasecmp(toprinttmp,"") && ( toprinttmp[0] >= 'A' ) )
    {
@@ -400,26 +339,27 @@
       IsVarInUseFile(toprinttmp);
    }
+   Save_Length(toprinttmp,44);
    strcpy(toprinttmp,"");
 
 }
 
-void convert2lower(char *name)
-{
-   int l;
-   int i;
-   int caractere;
-
-   l=strlen(name)-1;
-   for (i=0;i<=l;i++)
-   {
-      caractere=name[i];
-      if ((caractere>=65 && caractere<=90)||(caractere>=192 && caractere<=221))
-      {
-         name[i]+=32;
-      }
-   }
-}
-
-int convert2int(char *name)
+void convert2lower(char *lowername, const char* inputname)
+{
+    int i, l, caractere;
+
+    strcpy(lowername, inputname);
+    l = strlen(lowername)-1;
+
+    for ( i=0 ; i<=l ; i++)
+    {
+        caractere = lowername[i];
+        if ( (caractere>=65 && caractere<=90) || (caractere>=192 && caractere<=221) )
+        {
+            lowername[i] += 32;
+        }
+    }
+}
+
+int convert2int(const char *name)
 {
    int i;
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilFile.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilFile.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilFile.c	(revision 9987)
@@ -40,31 +40,29 @@
 
 /******************************************************************************/
-/*                            associate                                       */
+/*                         open_for_write                                     */
 /******************************************************************************/
 /* This subroutine is used to open a file                                     */
 /******************************************************************************/
-FILE * associate (char *filename)
+FILE* open_for_write (const char *filename)
 {
-  char filefich[LONG_C];
-  sprintf(filefich,"%s/%s",nomdir,filename);
-  return fopen (filefich, "w");
+    char filefich[LONG_FNAME];
+    sprintf(filefich,"%s/%s",include_dir,filename);
+    return fopen(filefich, "w");
 }
 
-
 /******************************************************************************/
-/*                          associateaplus                                    */
+/*                          open_for_append                                   */
 /******************************************************************************/
 /* This subroutine is used to open a file with option a+                      */
 /******************************************************************************/
-FILE * associateaplus (char *filename)
+FILE* open_for_append (const char *filename)
 {
-  char filefich[LONG_C];
-  sprintf(filefich,"%s/%s",nomdir,filename);
-  return fopen (filefich, "a+");
+    char filefich[LONG_M];
+    sprintf(filefich,"%s/%s",include_dir,filename);
+    return fopen(filefich, "a+");
 }
 
-
 /******************************************************************************/
-/*                           setposcurname                                       */
+/*                           setposcurname                                    */
 /******************************************************************************/
 /* This subroutine is used to know the current position in the file in argument    */
@@ -76,6 +74,6 @@
 long int setposcurname(FILE *fileout)
 {
-   fflush(fileout);
-   return ftell(fileout);
+    fflush(fileout);
+    return ftell(fileout);
 }
 
@@ -91,21 +89,5 @@
 long int setposcur()
 {
-   fflush(fortranout);
-   return ftell(fortranout);
-}
-
-/******************************************************************************/
-/*                      setposcurinoldfortranout                              */
-/******************************************************************************/
-/* This subroutine is used to know the position in the oldfortranout         */
-/******************************************************************************/
-/*                                                                            */
-/*             setposcurinoldfortranout ---------> position in file           */
-/*                                                                            */
-/******************************************************************************/
-long int setposcurinoldfortranout()
-{
-   fflush(oldfortranout);
-   return ftell(oldfortranout);
+    return setposcurname(fortran_out);
 }
 
@@ -114,16 +96,16 @@
 /******************************************************************************/
 /* Firstpass 0                                                                */
-/* We should write in the fortranout the USE tok_name                         */
+/* We should write in the fortran_out the USE tok_name                         */
 /* read in the original file                                                  */
 /******************************************************************************/
 /*                                                                            */
 /******************************************************************************/
-void copyuse_0(char *namemodule)
+void copyuse_0(const char *namemodule)
 {
-   if (firstpass == 0 && IsTabvarsUseInArgument_0() == 1 )
-   {
-      /* We should write this declaration into the original subroutine too    */
-      fprintf(oldfortranout,"      USE %s \n",namemodule);
-   }
+    if ( IsTabvarsUseInArgument_0() == 1 )
+    {
+        /* We should write this declaration into the original subroutine too    */
+        fprintf(oldfortran_out,"      use %s\n", namemodule);
+    }
 }
 
@@ -132,15 +114,15 @@
 /******************************************************************************/
 /* Firstpass 0                                                                */
-/* We should write in the fortranout the USE tok_name, only                   */
+/* We should write in the fortran_out the USE tok_name, only                   */
 /* read in the original file                                                  */
 /******************************************************************************/
 /*                                                                            */
 /******************************************************************************/
-void copyuseonly_0(char *namemodule)
+void copyuseonly_0(const char *namemodule)
 {
    if (firstpass == 0 && IsTabvarsUseInArgument_0() == 1 )
    {
       /* We should write this declaration into the original subroutine too    */
-      fprintf(oldfortranout,"      USE %s , ONLY : \n",namemodule);
+      fprintf(oldfortran_out,"      use %s , only : \n", namemodule);
    }
 }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilFortran.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilFortran.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilFortran.c	(revision 9987)
@@ -43,19 +43,15 @@
 /* This subroutine is used to initialized grid dimension variable             */
 /******************************************************************************/
-/*                                                                            */
-/*                                                                            */
-/*                                                                            */
-/******************************************************************************/
-void initdimprob(int dimprobmod, char * nx, char * ny,char* nz)
-{
-  dimprob = dimprobmod;
-
-  strcpy(nbmaillesX,nx);
-  strcpy(nbmaillesY,ny);
-  strcpy(nbmaillesZ,nz);
-}
-
-/******************************************************************************/
-/*                      Variableshouldberemove                                */
+void initdimprob(int dimprobmod, const char * nx, const char * ny, const char* nz)
+{
+    dimprob = dimprobmod;
+
+    strcpy(nbmaillesX, nx);
+    strcpy(nbmaillesY, ny);
+    strcpy(nbmaillesZ, nz);
+}
+
+/******************************************************************************/
+/*                      Variableshouldberemoved                               */
 /******************************************************************************/
 /* Firstpass 0                                                                */
@@ -65,14 +61,7 @@
 /*                                                                            */
 /******************************************************************************/
-int Variableshouldberemove(char *nom)
-{
-
-   int remove;
-
-   remove = 0 ;
-
-   if ( remove == 0 && Agrif_in_Tok_NAME(nom) == 1 ) remove = 1 ;
-
-   return remove;
+int Variableshouldberemoved(const char *nom)
+{
+    return Agrif_in_Tok_NAME(nom);
 }
 
@@ -97,18 +86,17 @@
         /* Now we should give the definition of the variable in the           */
         /* table List_UsedInSubroutine_Var                                    */
-        printf("QDKFLSDFKSLDF\n");
-        strcpy(curvar->var->v_typevar,newvar->var->v_typevar);
-        strcpy(curvar->var->v_dimchar,newvar->var->v_dimchar);
-        curvar->var->v_nbdim = newvar->var->v_nbdim;
+        strcpy(curvar->var->v_typevar, newvar->var->v_typevar);
+        strcpy(curvar->var->v_dimchar, newvar->var->v_dimchar);
+        curvar->var->v_nbdim          = newvar->var->v_nbdim;
         curvar->var->v_dimensiongiven = newvar->var->v_dimensiongiven;
-        curvar->var->v_allocatable = newvar->var->v_allocatable;
-        curvar->var->v_target = newvar->var->v_target;
+        curvar->var->v_allocatable    = newvar->var->v_allocatable;
+        curvar->var->v_target         = newvar->var->v_target;
+        curvar->var->v_catvar         = newvar->var->v_catvar;
         curvar->var->v_pointerdeclare = newvar->var->v_pointerdeclare;
-        curvar->var->v_indicetabvars = newvar->var->v_indicetabvars;
-        strcpy(curvar->var->v_nameinttypename,newvar->var->v_nameinttypename);
-        strcpy(curvar->var->v_precision,newvar->var->v_precision);
-        strcpy(curvar->var->v_readedlistdimension,
-                                            newvar->var->v_readedlistdimension);
-        strcpy(curvar->var->v_commoninfile,newvar->var->v_commoninfile);
+        curvar->var->v_indicetabvars  = newvar->var->v_indicetabvars;
+        strcpy(curvar->var->v_nameinttypename, newvar->var->v_nameinttypename);
+        strcpy(curvar->var->v_precision, newvar->var->v_precision);
+        strcpy(curvar->var->v_readedlistdimension, newvar->var->v_readedlistdimension);
+        strcpy(curvar->var->v_commoninfile, newvar->var->v_commoninfile);
      }
      else
@@ -128,13 +116,12 @@
   present = 0;
   newvar = listin;
+
   while ( newvar && present == 0 )
   {
      if ( !strcasecmp(newvar->var->v_nomvar,curvar->var->v_nomvar) &&
-          !strcasecmp(newvar->var->v_subroutinename,
-                                    curvar->var->v_subroutinename)
-        )
+          !strcasecmp(newvar->var->v_subroutinename, curvar->var->v_subroutinename) )
      {
         strcpy(curvar->var->v_commoninfile,newvar->var->v_commoninfile);
-        CopyRecord(curvar->var,newvar->var);
+        Merge_Variables(curvar->var,newvar->var);
         present = 1;
      }
@@ -156,5 +143,5 @@
      if ( !strcasecmp(newvar->var->v_nomvar,curvar->var->v_nomvar) )
      {
-        CopyRecord(curvar->var,newvar->var);
+        Merge_Variables(curvar->var,newvar->var);
         present = 1;
      }
@@ -170,5 +157,5 @@
 /* This subroutine is to know if a variable is global                         */
 /******************************************************************************/
-void variableisglobalinmodule(listcouple *listin, char *module, FILE *fileout, long int oldposcuruse)
+void variableisglobalinmodule(listcouple *listin, const char *module, FILE *fileout, long int oldposcuruse)
 {
   int Globalite;
@@ -178,5 +165,5 @@
   listvar *newvar2;
   int out;
-  char truename[LONG_C];  
+  char truename[LONG_VNAME];
 
   Globalite = 1;
@@ -195,5 +182,5 @@
        strcpy(truename,newvar->c_namepointedvar);
      }
-     
+
      out = 0;
      newvar2 = tempo;
@@ -227,11 +214,10 @@
   {
      pos_end = setposcurname(fileout);
-     RemoveWordSET_0(fileout,oldposcuruse,
-                                pos_end-oldposcuruse);
-                                  
+     RemoveWordSET_0(fileout,oldposcuruse,pos_end-oldposcuruse);
+
      newvar = listin;
      while ( newvar )
      {
-        fprintf(fileout,"      USE %s, ONLY : %s \n",module,newvar->c_namevar);
+        fprintf(fileout,"      use %s, only : %s \n",module,newvar->c_namevar);
         newvar = newvar->suiv;
      }
@@ -239,40 +225,13 @@
 }
 
-
-void Remove_Word_Contains_0()
-{
-   if ( firstpass == 0 )
-   {
-      RemoveWordCUR_0(fortranout,(long)(-9),9);
-   }
-}
-
-void Remove_Word_end_module_0(int modulenamelength)
-{
-   if ( firstpass == 0 )
-   {
-      RemoveWordCUR_0(fortranout,(long)(-modulenamelength-12),
-                                         modulenamelength+11);
-   }
-}
-
-void Write_Word_Contains_0()
-{
-   if ( firstpass == 0 )
-   {
-      fprintf(fortranout,"\n      contains\n");
-   }
-}
-
-
 void Write_Word_end_module_0()
 {
-   if ( firstpass == 0 )
-   {
-      fprintf(fortranout,"\n      end module %s",curmodulename);
-   }
-}
-
-void Add_Subroutine_For_Alloc(char *nom)
+    if ( firstpass == 0 )
+    {
+        fprintf(fortran_out,"\n      end module %s",curmodulename);
+    }
+}
+
+void Add_Subroutine_For_Alloc(const char *nom)
 {
    listnom *parcours;
@@ -280,7 +239,6 @@
    int out;
 
-   newvar = (listnom *)malloc(sizeof(listnom));
+   newvar = (listnom*) calloc(1, sizeof(listnom));
    strcpy(newvar->o_nom,nom);
-   Save_Length(nom,23);
    newvar->suiv = NULL;
 
@@ -306,270 +264,137 @@
 }
 
-
-void Write_Alloc_Subroutine_0()
-{
-   listnom *parcours_nom;
-   listnom *parcours_nomprec;
-   int out;
-   char ligne[LONG_C];
-
-   if ( firstpass == 0 )
-   {
-      parcours_nomprec = (listnom *)NULL;
-      parcours_nom = List_NameOfModule;
-      out = 0 ;
-      while ( parcours_nom && out == 0 )
-      {
-         /*                                                                   */
-         if ( !strcasecmp(curmodulename,parcours_nom->o_nom) ) out = 1;
-         else parcours_nom = parcours_nom -> suiv;
-      }
-      if ( out == 1 )
-      {
-         if ( parcours_nom->o_val == 1 )
-         {
-            strcpy (ligne, "\n      PUBLIC Alloc_agrif_");
-            strcat (ligne, curmodulename);
-            strcat (ligne, "\n");
-            convert2lower(ligne);
-            fprintf(fortranout,ligne);
-         }
-      }
-      Write_Word_Contains_0();
-      if ( out == 1 )
-      {
-         if ( parcours_nom->o_val == 1 )
-         {
-            sprintf (ligne, "Subroutine Alloc_agrif_%s(Agrif_Gr)",
-                                                                 curmodulename);
-            tofich(fortranout,ligne,1);
-            strcpy(ligne,"Use Agrif_Util");
-            tofich(fortranout,ligne,1);
-            strcpy (ligne, "Type(Agrif_grid), Pointer :: Agrif_Gr");
-            tofich(fortranout,ligne,1);
-            strcpy(ligne, "INTEGER :: i");
-            tofich (fortranout, ligne,1);
-            strcpy (ligne, "\n#include \"alloc_agrif_");
-            strcat (ligne, curmodulename);
-            strcat (ligne, ".h\"\n");
-            convert2lower(ligne);
-            fprintf(fortranout,ligne);
-            strcpy (ligne, "Return");
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "End Subroutine Alloc_agrif_%s",curmodulename);
-            tofich(fortranout,ligne,1);
-            /* List all Call Alloc_agrif_                                     */
+void Write_Closing_Module(int forend)
+{
+    listvar *parcours;
+    listnom *parcours_nom;
+    listnom *parcours_nomprec;
+    variable *v;
+    int out = 0;
+    int headtypewritten = 0;
+    char ligne[LONG_M];
+    int changeval;
+
+    // Write Global Parameter Declaration
+    parcours = List_GlobalParameter_Var;
+    while( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_modulename, curmodulename) )
+        {
+            WriteVarDeclaration(parcours->var, module_declar, 0, 1);
+        }
+        parcours = parcours -> suiv;
+    }
+
+    // Write Global Type declaration
+    parcours = List_Global_Var;
+    while( parcours )
+    {
+        v = parcours->var;
+        if ( !strcasecmp(v->v_modulename, curmodulename) &&
+             !strcasecmp(v->v_typevar, "type") )
+        {
+            if ( headtypewritten == 0 )
+            {
+                fprintf(fortran_out, "\n      type Agrif_%s\n", curmodulename);
+                headtypewritten = 1;
+            }
+            changeval = 0;
+            if ( v->v_allocatable )
+            {
+                changeval = 1;
+                v->v_allocatable = 0;
+                v->v_pointerdeclare = 1;
+            }
+            WriteVarDeclaration(v, fortran_out, 0, 0);
+            if ( changeval )
+            {
+                v->v_allocatable = 1;
+                v->v_pointerdeclare = 0;
+            }
+            out = 1;
+        }
+        parcours = parcours -> suiv;
+    }
+    if (out == 1)
+    {
+        fprintf(fortran_out, "      end type Agrif_%s\n", curmodulename);
+        sprintf(ligne, "type(Agrif_%s), dimension(:), allocatable :: Agrif_%s_var",curmodulename, curmodulename);
+        tofich(fortran_out,ligne,1);
+        fprintf(fortran_out, "      public :: Agrif_%s\n", curmodulename);
+        fprintf(fortran_out, "      public :: Agrif_%s_var\n", curmodulename);
+    }
+
+    // Write NotGridDepend declaration
+    parcours = List_NotGridDepend_Var;
+    while( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_modulename,curmodulename) )
+        {
+            WriteVarDeclaration(parcours->var, fortran_out, 0, 1);
+        }
+        parcours = parcours -> suiv;
+    }
+
+    // Write Alloc_agrif_'modulename' subroutine
+    parcours_nomprec = (listnom*) NULL;
+    parcours_nom = List_NameOfModule;
+    out = 0 ;
+    while ( parcours_nom && out == 0 )
+    {
+        if ( !strcasecmp(curmodulename,parcours_nom->o_nom) ) out = 1;
+        else parcours_nom = parcours_nom -> suiv;
+    }
+    if ( ! out )
+    {
+        printf("#\n# Write_Closing_Module : OUT == 0   *** /!\\ ***\n");
+        printf("# FIXME: POSSIBLE BUG in CONV !!!\n#\n");
+    }
+    if ( out )
+    {
+        if ( parcours_nom->o_val == 1 )
+        {
+            fprintf(fortran_out,"\n      public :: Alloc_agrif_%s\n",curmodulename);
+        }
+        if ( (forend == 0) || (parcours_nom->o_val == 1) )
+        {
+           fprintf(fortran_out,"\n      contains\n");
+        }
+        if ( parcours_nom->o_val == 1 )
+        {
+            fprintf(fortran_out, "      subroutine Alloc_agrif_%s(Agrif_Gr)\n", curmodulename);
+            fprintf(fortran_out, "          use Agrif_Util\n");
+            fprintf(fortran_out, "          type(Agrif_grid), pointer :: Agrif_Gr\n");
+            fprintf(fortran_out, "          integer :: i\n");
+            fprintf(fortran_out, "\n#include \"alloc_agrif_%s.h\"\n", curmodulename);
+            fprintf(fortran_out, "      end subroutine Alloc_agrif_%s\n", curmodulename);
             Add_Subroutine_For_Alloc(curmodulename);
-         }
-         else
-         {
+        }
+        else
+        {
             parcours_nom = List_Subroutine_For_Alloc;
             out = 0;
             while ( parcours_nom && out == 0 )
             {
-               if ( !strcasecmp(parcours_nom->o_nom,curmodulename) ) out = 1;
-               else
-               {
-                  parcours_nomprec = parcours_nom;
-                  parcours_nom = parcours_nom->suiv;
-               }
-            }
-            if ( out == 1 )
-            {
-               if ( parcours_nom == List_Subroutine_For_Alloc)
-               {
-                  List_Subroutine_For_Alloc = List_Subroutine_For_Alloc->suiv;
-               }
-               else
-               {
-                  parcours_nomprec->suiv = parcours_nom->suiv;
-                  parcours_nom = parcours_nomprec->suiv ;
-               }
-            }
-         }
-      }
-   }
-}
-
-
-void Write_Alloc_Subroutine_For_End_0()
-{
-   listnom *parcours_nom;
-   listnom *parcours_nomprec;
-   int out;
-   char ligne[LONG_C];
-
-   if ( firstpass == 0 )
-   {
-      parcours_nomprec = (listnom *)NULL;
-      parcours_nom = List_NameOfModule;
-      out = 0 ;
-      while ( parcours_nom && out == 0 )
-      {
-         /*                                                                   */
-         if ( !strcasecmp(curmodulename,parcours_nom->o_nom) ) out = 1;
-         else parcours_nom = parcours_nom -> suiv;
-      }
-      if ( out == 1 )
-      {
-         if ( parcours_nom->o_val == 1 )
-         {
-            strcpy (ligne, "\n      PUBLIC Alloc_agrif_");
-            strcat (ligne, curmodulename);
-            strcat (ligne, "\n");
-            convert2lower(ligne);
-            fprintf(fortranout,ligne);
-            strcpy (ligne, "\n      contains\n");
-            fprintf(fortranout,ligne);
-            sprintf (ligne, "Subroutine Alloc_agrif_%s(Agrif_Gr)",
-                                                                 curmodulename);
-            tofich(fortranout,ligne,1);
-            strcpy(ligne,"Use Agrif_Util");
-            tofich(fortranout,ligne,1);
-            strcpy (ligne, "Type(Agrif_grid), Pointer :: Agrif_Gr");
-            tofich(fortranout,ligne,1);
-            strcpy(ligne, "INTEGER :: i");
-            tofich (fortranout, ligne,1);
-            strcpy (ligne, "\n#include \"alloc_agrif_");
-            strcat (ligne, curmodulename);
-            strcat (ligne, ".h\"\n");
-            convert2lower(ligne);
-            fprintf(fortranout,ligne);
-            strcpy (ligne, "Return");
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "End Subroutine Alloc_agrif_%s",curmodulename);
-            tofich(fortranout,ligne,1);
-            /* List all Call Alloc_agrif                                      */
-            Add_Subroutine_For_Alloc(parcours_nom->o_nom);
-         }
-         else
-         {
-            parcours_nom = List_Subroutine_For_Alloc;
-            out = 0;
-            while ( parcours_nom && out == 0 )
-            {
-               if ( !strcasecmp(parcours_nom->o_nom,curmodulename) ) out = 1;
-               else
-               {
-                  parcours_nomprec = parcours_nom;
-                  parcours_nom = parcours_nom->suiv;
-               }
-            }
-            if ( out == 1 )
-            {
-               if ( parcours_nom == List_Subroutine_For_Alloc)
-               {
-                  List_Subroutine_For_Alloc = List_Subroutine_For_Alloc->suiv;
-               }
-               else
-               {
-                  parcours_nomprec->suiv = parcours_nom->suiv;
-                  parcours_nom = parcours_nomprec->suiv ;
-               }
-            }
-         }
-      }
-   }
-}
-
-void Write_GlobalParameter_Declaration_0()
-{
-   listvar *parcours;
-
-   if ( firstpass == 0 )
-   {
-      parcours = List_GlobalParameter_Var;
-      while( parcours )
-      {
-         if ( !strcasecmp(parcours->var->v_modulename,curmodulename) )
-         {
-            writevardeclaration(parcours,module_declar,0,1);
-         }
-         parcours = parcours -> suiv;
-      }
-   }
-}
-
-void Write_GlobalType_Declaration_0()
-{
-   listvar *parcours;
-   int out = 0;
-   int headtypewritten = 0;
-   char ligne[LONGNOM];
-   int changeval;
-
-   if ( firstpass == 0 )
-   {
-      parcours = List_Global_Var;
-      while( parcours )
-      {
-         if ( !strcasecmp(parcours->var->v_modulename,curmodulename) )
-         {
-           if (!strcasecmp(parcours->var->v_typevar,"type"))
-           {
-            out = 1;
-            if (headtypewritten == 0)
-              {
-/*RB*/
-                sprintf (ligne, "Module_DeclarType_%s.h",curmodulename);
-                module_declar_type = associate(ligne);
-                sprintf (ligne, " ");
-                tofich (module_declar_type, ligne,1);
-                sprintf(ligne,"TYPE :: Agrif_%s",curmodulename);
-                tofich(module_declar_type,ligne,1);
-                headtypewritten = 1;
-/*RBend*/
-              }
-            changeval = 0;
-            if (parcours->var->v_allocatable == 1)
-             {
-               changeval = 1;
-               parcours->var->v_allocatable = 0;
-               parcours->var->v_pointerdeclare = 1;
-             }
-/*RB*/
-            writevardeclaration(parcours,module_declar_type,0,0);
-/*RBend*/
-            if (changeval == 1)
-              {
-               parcours->var->v_allocatable = 1;
-               parcours->var->v_pointerdeclare = 0;
-              }
-            }
-         }
-         parcours = parcours -> suiv;
-      }
-      if (out == 1)
-        {
-/*RB*/
-                sprintf(ligne,"END TYPE Agrif_%s",curmodulename);
-                tofich(module_declar_type,ligne,1);
-                sprintf(ligne,"TYPE(Agrif_%s), DIMENSION(:), ALLOCATABLE :: Agrif_%s_var",curmodulename,curmodulename); 
-                tofich(module_declar_type,ligne,1);
-                sprintf(ligne,"PUBLIC :: Agrif_%s",curmodulename); 
-                tofich(module_declar_type,ligne,1);
-                sprintf(ligne,"PUBLIC :: Agrif_%s_var",curmodulename); 
-                tofich(module_declar_type,ligne,1);
-/*RBend*/
-        }
-   }
-}
-
-void Write_NotGridDepend_Declaration_0()
-{
-   listvar *parcours;
-
-   if ( firstpass == 0 )
-   {
-      parcours = List_NotGridDepend_Var;
-      while( parcours )
-      {
-         if ( !strcasecmp(parcours->var->v_modulename,curmodulename) )
-         {
-            writevardeclaration(parcours,fortranout,0,1);
-         }
-         parcours = parcours -> suiv;
-      }
-   }
+                if ( !strcasecmp(parcours_nom->o_nom, curmodulename) ) out = 1;
+                else
+                {
+                    parcours_nomprec = parcours_nom;
+                    parcours_nom = parcours_nom->suiv;
+                }
+            }
+            if ( out )
+            {
+                if ( parcours_nom == List_Subroutine_For_Alloc)
+                {
+                    List_Subroutine_For_Alloc = List_Subroutine_For_Alloc->suiv;
+                }
+                else
+                {
+                    parcours_nomprec->suiv = parcours_nom->suiv;
+                    parcours_nom = parcours_nomprec->suiv ;
+                }
+            }
+        }
+    }
 }
 
@@ -669,7 +494,6 @@
       if ( !List_Pointer_Var )
       {
-         newvar = (listname *)malloc(sizeof(listname));
-         strcpy(newvar->n_name,nom);
-         Save_Length(nom,20);
+         newvar = (listname*) calloc(1, sizeof(listname));
+         strcpy(newvar->n_name, nom);
          newvar->suiv = NULL;
          List_Pointer_Var = newvar;
@@ -691,7 +515,6 @@
             {
                /* add the record                                              */
-              newvar = (listname *)malloc(sizeof(listname));
+              newvar = (listname*) calloc(1, sizeof(listname));
               strcpy(newvar->n_name,nom);
-              Save_Length(nom,20);
               newvar->suiv = NULL;
               parcours->suiv = newvar;
@@ -745,5 +568,5 @@
       while( parcours && out == 0 )
       {
-         if ( !strcasecmp(ident,parcours->var->v_nomvar) ) 
+         if ( !strcasecmp(ident,parcours->var->v_nomvar) )
              {
              if (!strcasecmp(parcours->var->v_typevar,"type")) out = 1;
@@ -757,45 +580,56 @@
 
 /******************************************************************************/
-/*                          VariableIsNotFunction                             */
-/******************************************************************************/
-/*                                                                            */
-/******************************************************************************/
-int VariableIsNotFunction(char *ident)
-{
-   int out;
-   listvar *newvar;
-
-   out =0;
-
-   if ( !strcasecmp(ident,"size") ||
-        !strcasecmp(ident,"if")   ||
-        !strcasecmp(ident,"max")  ||
-        !strcasecmp(ident,"min")
-      )
-   {
-      newvar = List_SubroutineDeclaration_Var;
-      while ( newvar && out == 0 )
-      {
-         if ( !strcasecmp(subroutinename, newvar->var->v_subroutinename) &&
-              !strcasecmp(ident, newvar->var->v_nomvar) ) out = 1;
-         newvar = newvar -> suiv ;
-      }
-      if ( out == 1 ) out = 0;
-      else out = 1;
-      /* if it has not been found                                             */
-      if ( out == 1 )
-      {
-         out = 0;
-         newvar = List_Global_Var;
-         while ( newvar && out == 0 )
-         {
-            if ( !strcasecmp(ident, newvar->var->v_nomvar) ) out = 1;
+/*                          VariableIsFunction                                */
+/******************************************************************************/
+/*                                                                            */
+/******************************************************************************/
+int VariableIsFunction(const char *ident)
+{
+    int out;
+    listvar *newvar;
+
+    out = 0;
+
+    if ( !strcasecmp(ident,"size") ||
+         !strcasecmp(ident,"if")   ||
+         !strcasecmp(ident,"max")  ||
+         !strcasecmp(ident,"min")  )
+    {
+        newvar = List_SubroutineDeclaration_Var;
+        while ( newvar && out == 0 )
+        {
+            if ( !strcasecmp(subroutinename, newvar->var->v_subroutinename) &&
+                 !strcasecmp(ident, newvar->var->v_nomvar) )
+            {
+                out = 1;
+            }
             newvar = newvar -> suiv ;
-         }
-         if ( out == 1 ) out = 0;
-         else out = 1;
-      }
-   }
-   /*                                                                         */
-   return out;
-}
+        }
+        if ( out == 0 ) /* if it has not been found */
+        {
+            newvar = List_Global_Var;
+            while ( newvar && out == 0 )
+            {
+                if ( !strcasecmp(ident, newvar->var->v_nomvar) ) out = 1;
+                newvar = newvar -> suiv ;
+            }
+        }
+    }
+    return (out == 0);
+}
+
+void dump_var(const variable* var)
+{
+    fprintf(stderr, "   var->v_nomvar : %s\n",var->v_nomvar);
+    fprintf(stderr, "   var->v_indice : %d\n",var->v_indicetabvars);
+    fprintf(stderr, "   var->v_typevar: %s\n",var->v_typevar);
+    fprintf(stderr, "   var->v_catvar : %d\n",var->v_catvar);
+    fprintf(stderr, "   var->v_modulename: %s\n",var->v_modulename);
+    fprintf(stderr, "   var->v_subroutinename: %s\n",var->v_subroutinename);
+    fprintf(stderr, "   var->v_commonname: %s\n",var->v_commonname);
+    fprintf(stderr, "   var->v_commoninfile: %s\n",var->v_commoninfile);
+    fprintf(stderr, "   var->v_nbdim: %d\n",var->v_nbdim);
+    fprintf(stderr, "   var->v_common: %d\n",var->v_common);
+    fprintf(stderr, "   var->v_module: %d\n",var->v_module);
+    fprintf(stderr, "   var->v_initialvalue: %s\n",var->v_initialvalue);
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilListe.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilListe.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilListe.c	(revision 9987)
@@ -41,18 +41,18 @@
 void Init_Variable(variable *var)
 {
-   strcpy(var->v_typevar            ,"");
-   strcpy(var->v_nomvar             ,"");
-   strcpy(var->v_oldname            ,"");
-   strcpy(var->v_dimchar            ,"");
-   strcpy(var->v_modulename         ,"");
-   strcpy(var->v_commonname         ,"");
-   strcpy(var->v_vallengspec        ,"");
-   strcpy(var->v_nameinttypename    ,"");
-   strcpy(var->v_commoninfile       ,"");
-   strcpy(var->v_subroutinename     ,"");
-   strcpy(var->v_precision          ,"");
-   strcpy(var->v_initialvalue       ,"");
-   strcpy(var->v_IntentSpec         ,"");
-   strcpy(var->v_readedlistdimension,"");
+   strcpy(var->v_typevar            , "");
+   strcpy(var->v_nomvar             , "");
+   strcpy(var->v_oldname            , "");
+   strcpy(var->v_dimchar            , "");
+   strcpy(var->v_modulename         , "");
+   strcpy(var->v_commonname         , "");
+   strcpy(var->v_vallengspec        , "");
+   strcpy(var->v_nameinttypename    , "");
+   strcpy(var->v_commoninfile       , "");
+   strcpy(var->v_subroutinename     , "");
+   strcpy(var->v_precision          , "");
+   strcpy(var->v_initialvalue       , "");
+   strcpy(var->v_IntentSpec         , "");
+   strcpy(var->v_readedlistdimension, "");
    var->v_nbdim               = 0 ;
    var->v_common              = 0 ;
@@ -60,4 +60,5 @@
    var->v_module              = 0 ;
    var->v_save                = 0 ;
+   var->v_catvar              = 0 ;
    var->v_VariableIsParameter = 0 ;
    var->v_PublicDeclare       = 0 ;
@@ -74,5 +75,5 @@
    var->v_target              = 0 ;
    var->v_dimsempty           = 0 ;
-   var->v_dimension = (listdim *)NULL;
+   var->v_dimension = (listdim *) NULL;
 }
 /******************************************************************************/
@@ -89,18 +90,19 @@
 /*                                                                            */
 /******************************************************************************/
-listvar * AddListvarToListvar(listvar *l,listvar *glob,int ValueFirstpass)
-{
-   listvar *newvar;
-   if ( firstpass == ValueFirstpass )
-   {
-      if ( !glob) glob = l ;
-      else
-      {
-         newvar=glob;
-         while (newvar->suiv) newvar = newvar->suiv;
-         newvar->suiv = l;
-      }
-   }
-   return glob;
+listvar * AddListvarToListvar ( listvar *l, listvar *glob, int ValueFirstpass )
+{
+    listvar *newvar;
+    if ( firstpass == ValueFirstpass )
+    {
+        if ( !glob ) glob = l;
+        else
+        {
+            newvar = glob;
+            while (newvar->suiv)
+                newvar = newvar->suiv;
+            newvar->suiv = l;
+        }
+    }
+    return glob;
 }
 
@@ -113,65 +115,81 @@
 /*                                                                            */
 /******************************************************************************/
-void CreateAndFillin_Curvar(char *type,variable *curvar)
-{
-   if (!strcasecmp(type,"character") && strcasecmp(CharacterSize,"") )
-   {
-      strcpy(curvar->v_dimchar,CharacterSize);
-      Save_Length(CharacterSize,5);
-   }
-
-  /* On donne la precision de la variable si elle a ete donnee                */
-  curvar->v_c_star = 0;
-  if ( c_star == 1 ) curvar->v_c_star = 1;
-  /*                                                                          */
-  strcpy(curvar->v_vallengspec,"");
-  if ( strcasecmp(vallengspec,"") )
-  {
-     strcpy(curvar->v_vallengspec,vallengspec);
-     Save_Length(vallengspec,8);
-  }
-
-  strcpy(curvar->v_precision,"");
-  if ( strcasecmp(NamePrecision,"") )
-  {
-     strcpy(curvar->v_precision,NamePrecision);
-     Save_Length(NamePrecision,12);
-  }
-  /* Si cette variable a ete declaree dans un module on met curvar->module=1  */
-  if ( inmoduledeclare == 1 || SaveDeclare == 1)
-  {
-      curvar->v_module = 1;
-   }
-   /* Puis on donne le nom du module dans curvar->v_modulename                */
-   strcpy(curvar->v_modulename,curmodulename);
-   Save_Length(curmodulename,6);
-   /* Si cette variable a ete initialisee                                     */
-/*RB*/
-   if ( ! strcmp(InitialValueGiven,"=")  ) 
-/*RBend*/
-   {
-      strcpy(curvar->v_initialvalue,InitValue);
-      Save_Length(InitValue,14);
-   }
-   /* Si cette variable est declaree en save                                  */
-/*RB*/
-   if (SaveDeclare == 1 &&  !strcasecmp(curvar->v_typevar,"type")) {
-/*RBend*/
-   curvar->v_save = 1;
-   }
-
-   /* Si cette variable est v_allocatable                                     */
-   if (Allocatabledeclare == 1 ) curvar->v_allocatable=1;
-   
-   /* Si cette variable est v_targer                                     */
-   if (Targetdeclare == 1 ) curvar->v_target=1;
-   /* if INTENT spec has been given                                           */
-   if ( strcasecmp(IntentSpec,"") )
-   {
-      strcpy(curvar->v_IntentSpec,IntentSpec);
-      Save_Length(IntentSpec,13);
-   }
-}
-
+void CreateAndFillin_Curvar(const char *type, variable *curvar)
+{
+    if ( !strcasecmp(type, "character") && strcasecmp(CharacterSize, "") )
+    {
+        strcpy(curvar->v_dimchar, CharacterSize);
+    }
+
+    /* On donne la precision de la variable si elle a ete donnee                */
+    curvar->v_c_star = 0;
+    if ( c_star == 1 )  curvar->v_c_star = 1;
+
+    strcpy(curvar->v_vallengspec,"");
+    if ( strcasecmp(vallengspec,"") )
+    {
+        strcpy(curvar->v_vallengspec,vallengspec);
+        Save_Length(vallengspec,8);
+    }
+
+    strcpy(curvar->v_precision,"");
+    if ( strcasecmp(NamePrecision,"") )
+    {
+        strcpy(curvar->v_precision,NamePrecision);
+        addprecision_derivedfromkind(curvar);
+        Save_Length(NamePrecision,12);
+    }
+    /* Si cette variable a ete declaree dans un module on met curvar->module=1  */
+    if ( inmoduledeclare == 1 || SaveDeclare == 1 )
+    {
+        curvar->v_module = 1;
+    }
+    /* Puis on donne le nom du module dans curvar->v_modulename                */
+    strcpy(curvar->v_modulename,curmodulename);
+    /* Si cette variable a ete initialisee                                     */
+    if (InitialValueGiven == 1 )
+    {
+        strcpy(curvar->v_initialvalue,InitValue);
+        Save_Length(InitValue,14);
+    }
+    /* Si cette variable est declaree en save                                  */
+    if (SaveDeclare == 1 && !strcasecmp(curvar->v_typevar,"type")) curvar->v_save = 1;
+
+    /* Si cette variable est v_allocatable                                     */
+    if (Allocatabledeclare == 1 ) curvar->v_allocatable=1;
+
+    /* Si cette variable est v_target                                     */
+    if (Targetdeclare == 1 ) curvar->v_target=1;
+
+    /* if INTENT spec has been given                                           */
+    if ( strcasecmp(IntentSpec,"") )
+    {
+        strcpy(curvar->v_IntentSpec,IntentSpec);
+        Save_Length(IntentSpec,13);
+    }
+}
+
+
+void addprecision_derivedfromkind(variable *curvar)
+{
+    listnom *parcours;
+    char kind[LONG_VNAME];
+    char kind_val[LONG_C];
+
+    sscanf(curvar->v_precision, "%100s =", kind_val);
+
+    if ( !strcasecmp(kind_val, "kind") )
+        sscanf(curvar->v_precision, "%50s = %50s", kind, kind_val);
+
+    parcours = listofkind;
+    while (parcours)
+    {
+        if ( !strcasecmp(parcours->o_nom, kind_val) )
+        {
+            sprintf(curvar->v_nameinttypename, "%d", parcours->o_val);
+        }
+        parcours=parcours->suiv;
+    }
+}
 
 /******************************************************************************/
@@ -180,79 +198,74 @@
 /*                                                                            */
 /******************************************************************************/
-void duplicatelistvar(listvar *orig)
-{
-   listvar *parcours;
-   listvar *tmplistvar;
-   listvar *tmplistvarprec;
-   listdim *tmplistdim;
-   variable *tmpvar;
-
-   tmplistvarprec = (listvar *)NULL;
-   parcours = orig;
-   while ( parcours )
-   {
-      tmplistvar = (listvar *)malloc(sizeof(listvar));
-      tmpvar = (variable *)malloc(sizeof(variable));
-      /*                                                                      */
-      Init_Variable(tmpvar);
-      /*                                                                      */
-      strcpy(tmpvar->v_typevar,parcours->var->v_typevar);
-      strcpy(tmpvar->v_nomvar,parcours->var->v_nomvar);
-      strcpy(tmpvar->v_oldname,parcours->var->v_oldname);
-      strcpy(tmpvar->v_dimchar,parcours->var->v_dimchar);
-      if ( parcours->var->v_dimension )
-      {
-         tmplistdim = (listdim *)malloc(sizeof(listdim));
-         tmplistdim = parcours->var->v_dimension;
-         tmpvar->v_dimension = tmplistdim;
-      }
-      tmpvar->v_nbdim=parcours->var->v_nbdim;
-      tmpvar->v_common=parcours->var->v_common;
-      tmpvar->v_positioninblock=parcours->var->v_positioninblock;
-      tmpvar->v_module=parcours->var->v_module;
-      tmpvar->v_save=parcours->var->v_save;
-      tmpvar->v_VariableIsParameter=parcours->var->v_VariableIsParameter;
-      printf("QLKDF\n");
-      tmpvar->v_indicetabvars=parcours->var->v_indicetabvars;
-      strcpy(tmpvar->v_modulename,parcours->var->v_modulename);
-      strcpy(tmpvar->v_commonname,parcours->var->v_commonname);
-      strcpy(tmpvar->v_vallengspec,parcours->var->v_vallengspec);
-
-      strcpy(tmpvar->v_nameinttypename,parcours->var->v_nameinttypename);
-            
-      tmpvar->v_pointedvar=parcours->var->v_pointedvar;
-      strcpy(tmpvar->v_commoninfile,mainfile);
-      Save_Length(mainfile,10);
-      strcpy(tmpvar->v_subroutinename,parcours->var->v_subroutinename);
-      tmpvar->v_dimensiongiven=parcours->var->v_dimensiongiven;
-      tmpvar->v_c_star=parcours->var->v_c_star;
-      strcpy(tmpvar->v_precision,parcours->var->v_precision);
-      strcpy(tmpvar->v_initialvalue,parcours->var->v_initialvalue);
-      tmpvar->v_pointerdeclare=parcours->var->v_pointerdeclare;
-      tmpvar->v_optionaldeclare=parcours->var->v_optionaldeclare;
-      tmpvar->v_allocatable=parcours->var->v_allocatable;
-      tmpvar->v_target=parcours->var->v_target;
-      strcpy(tmpvar->v_IntentSpec,parcours->var->v_IntentSpec);
-      tmpvar->v_dimsempty=parcours->var->v_dimsempty;
-      strcpy(tmpvar->v_readedlistdimension,
-                                          parcours->var->v_readedlistdimension);
-      /*                                                                      */
-      tmplistvar->var = tmpvar;
-      tmplistvar->suiv = NULL;
-      /*                                                                      */
-      if ( !listduplicated )
-      {
-         listduplicated = tmplistvar;
-         tmplistvarprec = listduplicated;
-      }
-      else
-      {
-         tmplistvarprec->suiv = tmplistvar;
-         tmplistvarprec = tmplistvar;
-      }
-      /*                                                                      */
-      parcours = parcours->suiv;
-   }
-}
+// void duplicatelistvar(listvar *orig)
+// {
+//    listvar *parcours;
+//    listvar *tmplistvar;
+//    listvar *tmplistvarprec;
+//    listdim *tmplistdim;
+//    variable *tmpvar;
+//
+//    tmplistvarprec = (listvar *)NULL;
+//    parcours = orig;
+//    while ( parcours )
+//    {
+//       tmplistvar = (listvar *)calloc(1,sizeof(listvar));
+//       tmpvar = (variable *)calloc(1,sizeof(variable));
+//       /*                                                                      */
+//       Init_Variable(tmpvar);
+//       /*                                                                      */
+//       strcpy(tmpvar->v_typevar, parcours->var->v_typevar);
+//       strcpy(tmpvar->v_nomvar,  parcours->var->v_nomvar);
+//       strcpy(tmpvar->v_oldname, parcours->var->v_oldname);
+//       strcpy(tmpvar->v_dimchar, parcours->var->v_dimchar);
+//       if ( parcours->var->v_dimension )
+//       {
+//          tmplistdim = (listdim*) calloc(1,sizeof(listdim));
+//          tmplistdim = parcours->var->v_dimension;
+//          tmpvar->v_dimension = tmplistdim;
+//       }
+//       tmpvar->v_nbdim  = parcours->var->v_nbdim;
+//       tmpvar->v_common = parcours->var->v_common;
+//       tmpvar->v_module = parcours->var->v_module;
+//       tmpvar->v_save   = parcours->var->v_save;
+//       tmpvar->v_positioninblock = parcours->var->v_positioninblock;
+//       tmpvar->v_VariableIsParameter = parcours->var->v_VariableIsParameter;
+//       tmpvar->v_indicetabvars = parcours->var->v_indicetabvars;
+//       tmpvar->v_pointedvar    = parcours->var->v_pointedvar;
+//       tmpvar->v_dimensiongiven = parcours->var->v_dimensiongiven;
+//       tmpvar->v_c_star = parcours->var->v_c_star;
+//       tmpvar->v_catvar = parcours->var->v_catvar;
+//       tmpvar->v_pointerdeclare = parcours->var->v_pointerdeclare;
+//       tmpvar->v_optionaldeclare = parcours->var->v_optionaldeclare;
+//       tmpvar->v_allocatable = parcours->var->v_allocatable;
+//       tmpvar->v_target      = parcours->var->v_target;
+//       tmpvar->v_dimsempty   = parcours->var->v_dimsempty;
+//       strcpy(tmpvar->v_modulename,  parcours->var->v_modulename);
+//       strcpy(tmpvar->v_commonname,  parcours->var->v_commonname);
+//       strcpy(tmpvar->v_vallengspec, parcours->var->v_vallengspec);
+//       strcpy(tmpvar->v_nameinttypename, parcours->var->v_nameinttypename);
+//       strcpy(tmpvar->v_commoninfile, cur_filename);
+//       strcpy(tmpvar->v_subroutinename, parcours->var->v_subroutinename);
+//       strcpy(tmpvar->v_precision, parcours->var->v_precision);
+//       strcpy(tmpvar->v_initialvalue, parcours->var->v_initialvalue);
+//       strcpy(tmpvar->v_IntentSpec, parcours->var->v_IntentSpec);
+//       strcpy(tmpvar->v_readedlistdimension, parcours->var->v_readedlistdimension);
+//
+//       tmplistvar->var = tmpvar;
+//       tmplistvar->suiv = NULL;
+//
+//       if ( !listduplicated )
+//       {
+//          listduplicated = tmplistvar;
+//          tmplistvarprec = listduplicated;
+//       }
+//       else
+//       {
+//          tmplistvarprec->suiv = tmplistvar;
+//          tmplistvarprec = tmplistvar;
+//       }
+//       parcours = parcours->suiv;
+//    }
+// }
 
 /******************************************************************************/
@@ -273,5 +286,5 @@
    listdim *parcours ;
 
-   newdim=(listdim *) malloc (sizeof (listdim));
+   newdim=(listdim *) calloc(1,sizeof(listdim));
    newdim->dim=nom;
    newdim->suiv=NULL;
@@ -310,7 +323,6 @@
    while(parcours_var)
    {
-      v=parcours_var->var;
+      v = parcours_var->var;
       strcpy(v->v_dimchar,(lin->dim).last);
-      Save_Length((lin->dim).last,5);
       parcours_var=parcours_var->suiv;
    }
@@ -319,24 +331,24 @@
 
 /******************************************************************************/
-/*                                num_dims                                    */
+/*                              get_num_dims                                  */
 /******************************************************************************/
 /* This subroutine is used to know the dimension of a table                   */
 /******************************************************************************/
 /*                                                                            */
-/*             Dimension(jpi,jpj,jpk) ----------> num_dims = 3                */
-/*                                                                            */
-/******************************************************************************/
-int num_dims(listdim *d)
-{
-   listdim *parcours;
-   int compteur = 0;
-
-   parcours = d;
-   while(parcours)
-   {
-     compteur++;
-     parcours=parcours->suiv;
-   }
-   return compteur;
+/*             Dimension(jpi,jpj,jpk) ----------> get_num_dims = 3            */
+/*                                                                            */
+/******************************************************************************/
+int get_num_dims ( const listdim *d )
+{
+    listdim *parcours;
+    int compteur = 0;
+
+    parcours = (listdim *) d;
+    while(parcours)
+    {
+        compteur++;
+        parcours = parcours->suiv;
+    }
+    return compteur;
 }
 
@@ -348,69 +360,62 @@
 /*      struct : variable                                                     */
 /******************************************************************************/
-variable * createvar(char *nom,listdim *d)
-{
-  variable *var;
-  listdim *dims;
-  char ligne[LONG_C];
-  char listdimension[LONG_C];
-
-   var=(variable *) malloc(sizeof(variable));
-   /*                                                                         */
-   Init_Variable(var);
-   /*                                                                         */
-   strcpy(var->v_nomvar,nom);
-   Save_Length(nom,4);
-   /*                                                                         */
-   strcpy(listdimension,"");
-   strcpy(var->v_modulename,curmodulename);
-   Save_Length(curmodulename,6);
-   strcpy(var->v_commoninfile,mainfile);
-   Save_Length(mainfile,10);
-   strcpy(var->v_subroutinename,subroutinename);
-   Save_Length(subroutinename,11);
-   /*                                                                         */
-   if ( strcasecmp(nameinttypename,"") )
-   {
-      strcpy(var->v_nameinttypename,nameinttypename);
-      Save_Length(nameinttypename,9);
-   }
-         
-   if ( optionaldeclare     == 1 ) var->v_optionaldeclare = 1;
-   if ( pointerdeclare      == 1 ) var->v_pointerdeclare = 1;
-   if ( VariableIsParameter == 1 ) var->v_VariableIsParameter = 1 ;
-   if ( PublicDeclare       == 1 ) var->v_PublicDeclare = 1 ;
-   if ( PrivateDeclare      == 1 ) var->v_PrivateDeclare = 1;
-   if ( ExternalDeclare     == 1 ) var->v_ExternalDeclare = 1;
-   /*                                                                         */
-   var->v_dimension=d;
+variable * createvar(const char *nom, listdim *d)
+{
+    variable *var;
+    listdim *dims;
+    char ligne[LONG_M];
+    char listdimension[LONG_M];
+
+    var = (variable *) calloc(1,sizeof(variable));
+
+    Init_Variable(var);
+
+    strcpy(listdimension,"");
+    strcpy(var->v_nomvar,nom);
+    strcpy(var->v_modulename,curmodulename);
+    strcpy(var->v_commoninfile,cur_filename);
+    strcpy(var->v_subroutinename,subroutinename);
+
+    if ( strcasecmp(nameinttypename,"") )
+    {
+        strcpy(var->v_nameinttypename,nameinttypename);
+    }
+
+    if ( optionaldeclare     == 1 ) var->v_optionaldeclare = 1;
+    if ( pointerdeclare      == 1 ) var->v_pointerdeclare = 1;
+    if ( VariableIsParameter == 1 ) var->v_VariableIsParameter = 1 ;
+    if ( PublicDeclare       == 1 ) var->v_PublicDeclare = 1 ;
+    if ( PrivateDeclare      == 1 ) var->v_PrivateDeclare = 1;
+    if ( ExternalDeclare     == 1 ) var->v_ExternalDeclare = 1;
+
+   var->v_dimension = d;
 
    /* Creation of the string for the dimension of this variable               */
-   dimsempty = 1;
-   if ( d )
-   {
-      var->v_dimensiongiven=1;
-      dims = d;
-      while (dims)
-      {
-         if ( strcasecmp(dims->dim.first,"") || strcasecmp(dims->dim.last,""))
-                                                                  dimsempty = 0;
-         sprintf(ligne,"%s:%s",dims->dim.first,dims->dim.last);
-         strcat(listdimension,ligne);
-         if ( dims->suiv )
-         {
-            strcat(listdimension,",");
-         }
-         dims = dims->suiv;
-      }
-/*RB*/
-      if ( dimsempty == 1 || GlobalDeclarationType == 1 ) var->v_dimsempty=1;
-/*RBend*/
-   }
-   strcpy(var->v_readedlistdimension,listdimension);
-   Save_Length(listdimension,15);
-   /*                                                                         */
-   var->v_nbdim=num_dims(d);
-   /*                                                                         */
-   return var;
+    dimsempty = 1;
+    if ( d )
+    {
+        var->v_dimensiongiven = 1;
+        dims = d;
+        while (dims)
+        {
+            if ( strcasecmp(dims->dim.first,"") || strcasecmp(dims->dim.last,""))
+            {
+                dimsempty = 0;
+            }
+            sprintf(ligne,"%s:%s",dims->dim.first,dims->dim.last);
+            strcat(listdimension,ligne);
+            if ( dims->suiv )
+            {
+                strcat(listdimension,",");
+            }
+            dims = dims->suiv;
+        }
+        if ( dimsempty == 1 || GlobalDeclarationType == 1 ) var->v_dimsempty = 1;
+    }
+    strcpy(var->v_readedlistdimension,listdimension);
+    Save_Length(listdimension,15);
+    var->v_nbdim = get_num_dims(d);
+
+    return var;
 }
 
@@ -433,5 +438,5 @@
    listvar *tmpvar ;
 
-   newvar=(listvar *) malloc (sizeof (listvar));
+   newvar=(listvar *) calloc(1,sizeof(listvar));
    newvar->var=v;
    newvar->suiv = NULL;
@@ -466,18 +471,18 @@
 /*                                                                            */
 /******************************************************************************/
-listvar *settype(char *nom,listvar *lin)
+listvar *settype(const char *nom, listvar *lin)
 {
    listvar *newvar;
    variable *v;
 
-   newvar=lin;
+   newvar = lin;
    while (newvar)
    {
-      v=newvar->var;
+      v = newvar->var;
       strcpy(v->v_typevar,nom);
-      Save_Length(nom,3);
-      newvar=newvar->suiv;
-   }
-   newvar=lin;
+      v->v_catvar = get_cat_var(v);
+      newvar = newvar->suiv;
+   }
+   newvar = lin;
    return newvar ;
 }
@@ -511,5 +516,5 @@
    variable *v;
    int out ;
-   
+
    newvar=lin;
    out = 0;
@@ -531,5 +536,5 @@
    listname *tmpvar;
 
-   newvar=(listname *) malloc (sizeof (listname));
+   newvar=(listname *) calloc(1,sizeof(listname));
    strcpy(newvar->n_name,nom);
    newvar->suiv = NULL;
@@ -549,5 +554,5 @@
       }
       tmpvar -> suiv = newvar;
-   }
+      }
       else
       {
@@ -568,22 +573,23 @@
     tmpvar = tmpvar->suiv;
    }
-   
+
    tmpvar->suiv = l2;
-   
+
    return l1;
 }
 
-void *createstringfromlistname(char *ligne, listname *lin)
-{
-listname *tmpvar;
-
-strcpy(ligne,"");
-tmpvar = lin;
-while(tmpvar)
-{
-  strcat(ligne,tmpvar->n_name);
-  if (tmpvar->suiv) strcat(ligne,",");
-  tmpvar=tmpvar->suiv;
-}
+void createstringfromlistname(char *ligne, listname *lin)
+{
+    listname *tmpvar;
+
+    strcpy(ligne,"");
+    tmpvar = lin;
+
+    while(tmpvar)
+    {
+        strcat(ligne,tmpvar->n_name);
+        if (tmpvar->suiv) strcat(ligne,",");
+        tmpvar=tmpvar->suiv;
+    }
 }
 
@@ -607,13 +613,12 @@
 void removeglobfromlist(listname **lin)
 {
-  listname *listemp;
   listname *parcours1;
   listvar *parcours2;
   listname * parcourspres;
   int out;
-  
+
   parcours1 = *lin;
   parcourspres = (listname *)NULL;
-  
+
   while (parcours1)
   {
@@ -644,5 +649,5 @@
    {
    parcourspres = parcours1;
-    parcours1 = parcours1->suiv;  
+    parcours1 = parcours1->suiv;
     }
   }
@@ -651,41 +656,51 @@
 void writelistpublic(listname *lin)
 {
-  listname *parcours1;
-  char ligne[LONG_40M];
-  char tempname[LONG_4M];
-  
-  if (lin)
-  {
-  sprintf(ligne,"public :: ");
-  parcours1 = lin;
-  
-  while (parcours1)
-  {
-    strcat(ligne,parcours1->n_name);
-    if (parcours1->suiv) strcat(ligne,", ");
-    parcours1 = parcours1->suiv;  
-  }
-  tofich(fortranout,ligne,1);
-  }
-
+    listname *parcours1;
+    char ligne[LONG_M];
+
+    if (lin)
+    {
+        sprintf(ligne,"public :: ");
+        parcours1 = lin;
+
+        while ( parcours1 )
+        {
+            strcat(ligne, parcours1->n_name);
+            if ( parcours1->suiv ) strcat(ligne,", ");
+            parcours1 = parcours1->suiv;
+        }
+        tofich(fortran_out,ligne,1);
+    }
 }
 
 void Init_List_Data_Var()
 {
-listvar *parcours;
-
-parcours = List_Data_Var_Cur;
-
-if (List_Data_Var_Cur)
-{
-while (parcours)
-{
- List_Data_Var_Cur = List_Data_Var_Cur->suiv;
- free(parcours);
- parcours = List_Data_Var_Cur;
-}
-}
-
-List_Data_Var_Cur = NULL;
-
-}
+    listvar *parcours;
+
+    parcours = List_Data_Var_Cur;
+
+    if (List_Data_Var_Cur)
+    {
+        while (parcours)
+        {
+            List_Data_Var_Cur = List_Data_Var_Cur->suiv;
+            free(parcours);
+            parcours = List_Data_Var_Cur;
+        }
+    }
+    List_Data_Var_Cur = NULL;
+}
+
+int get_cat_var(variable *var)
+{
+    if (!strcasecmp(var->v_typevar, "CHARACTER"))
+        return 1;
+    else if ((var->v_nbdim == 0 ) && (!strcasecmp(var->v_typevar, "REAL")))
+        return 2;
+    else if (!strcasecmp(var->v_typevar, "LOGICAL"))
+        return 3;
+    else if (!strcasecmp(var->v_typevar, "INTEGER"))
+        return 4;
+    else
+        return 0;
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilNotGridDep.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilNotGridDep.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/UtilNotGridDep.c	(revision 9987)
@@ -71,12 +71,9 @@
    }
    /* if variable does not exist, we add it                                   */
-   newvar=(listvar *)malloc(sizeof(listvar));
-   newvar->var=(variable *)malloc(sizeof(variable));
+   newvar=(listvar *)calloc(1,sizeof(listvar));
+   newvar->var=(variable *)calloc(1,sizeof(variable));
    strcpy(newvar->var->v_nomvar,name);
-   Save_Length(name,4);
-   strcpy(newvar->var->v_commoninfile,mainfile);
-   Save_Length(mainfile,10);
+   strcpy(newvar->var->v_commoninfile,cur_filename);
    strcpy(newvar->var->v_subroutinename,subroutinename);
-   Save_Length(subroutinename,11);
    newvar->var->v_notgrid = 1 ;
    newvar->suiv = List_NotGridDepend_Var;
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithAllocatelist.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithAllocatelist.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithAllocatelist.c	(revision 9987)
@@ -45,5 +45,5 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_Allocate_Var_1(char *nom,char *nommodule)
+void Add_Allocate_Var_1(const char *nom, const char *nommodule)
 {
    listallocate *newvar;
@@ -55,11 +55,9 @@
       if ( !List_Allocate_Var )
       {
-         newvar = (listallocate *)malloc(sizeof(listallocate));
+         newvar = (listallocate *)calloc(1,sizeof(listallocate));
          strcpy(newvar->a_nomvar,nom);
+         strcpy(newvar->a_subroutine,subroutinename);
+         strcpy(newvar->a_module,nommodule);
          Save_Length(nom,25);
-         strcpy(newvar->a_subroutine,subroutinename);
-         Save_Length(subroutinename,26);
-         strcpy(newvar->a_module,nommodule);
-         Save_Length(nommodule,27);
          newvar->suiv = NULL;
          List_Allocate_Var = newvar;
@@ -71,7 +69,7 @@
          while ( parcours->suiv && out == 0 )
          {
-            if (  !strcasecmp(parcours->a_nomvar,nom) &&
-                  !strcasecmp(parcours->a_subroutine,subroutinename) &&
-                  !strcasecmp(parcours->a_module,nommodule) ) out = 1;
+            if (  !strcasecmp(parcours->a_nomvar, nom) &&
+                  !strcasecmp(parcours->a_subroutine, subroutinename) &&
+                  !strcasecmp(parcours->a_module, nommodule) ) out = 1;
             else
                parcours=parcours->suiv;
@@ -85,11 +83,9 @@
             {
                /* add the record                                              */
-              newvar = (listallocate *)malloc(sizeof(listallocate));
-              strcpy(newvar->a_nomvar,nom);
+              newvar = (listallocate *)calloc(1,sizeof(listallocate));
+              strcpy(newvar->a_nomvar, nom);
+              strcpy(newvar->a_subroutine, subroutinename);
+              strcpy(newvar->a_module, nommodule);
               Save_Length(nom,25);
-              strcpy(newvar->a_subroutine,subroutinename);
-              Save_Length(subroutinename,26);
-              strcpy(newvar->a_module,nommodule);
-              Save_Length(nommodule,27);
               newvar->suiv = NULL;
               parcours->suiv = newvar;
@@ -108,45 +104,19 @@
 /*                                                                            */
 /******************************************************************************/
-int IsVarAllocatable_0(char *ident)
-{
-   listallocate *parcours;
-   int out;
-
-   out = 0 ;
-   if ( firstpass == 0 )
-   {
-      parcours = List_Allocate_Var;
-      while ( parcours && out == 0 )
-      {
-         if ( !strcasecmp(parcours->a_nomvar,ident)  ) out = 1 ;
-         else parcours=parcours->suiv;
-      }
-   }
-   return out;
-}
-
-
-/******************************************************************************/
-/*                          varisallocatable_0                                */
-/******************************************************************************/
-/* Firstpass 0                                                                */
-/******************************************************************************/
-/*                                                                            */
-/******************************************************************************/
-int varisallocatable_0(char *ident)
-{
-   listallocate *newvaralloc;
-   int out;
-
-   out =0;
-   if (firstpass == 0 )
-   {
-         newvaralloc = List_Allocate_Var;
-         while ( newvaralloc && out == 0 )
-         {
-            if ( !strcasecmp(ident,newvaralloc->a_nomvar) )  out = 1;
-            else newvaralloc = newvaralloc->suiv;
-         }
-   }
-   return out;
-}
+// int IsVarAllocatable_0(const char *ident)
+// {
+//    listallocate *parcours;
+//    int out;
+// 
+//    out = 0 ;
+//    if ( firstpass == 0 )
+//    {
+//       parcours = List_Allocate_Var;
+//       while ( parcours && out == 0 )
+//       {
+//          if ( !strcasecmp(parcours->a_nomvar,ident)  ) out = 1 ;
+//          else parcours=parcours->suiv;
+//       }
+//    }
+//    return out;
+// }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithParameterlist.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithParameterlist.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithParameterlist.c	(revision 9987)
@@ -47,10 +47,6 @@
 void Add_GlobalParameter_Var_1(listvar *listin)
 {
-   if ( firstpass == 1 )
-   {
-      if ( VariableIsParameter == 1 ) {
-      List_GlobalParameter_Var =  AddListvarToListvar(listin,List_GlobalParameter_Var,1);
-   }
-   }
+    if ( VariableIsParameter )
+        List_GlobalParameter_Var =  AddListvarToListvar(listin, List_GlobalParameter_Var, 1);
 }
 
@@ -64,19 +60,19 @@
 void Add_Parameter_Var_1(listvar *listin)
 {
-   listvar *parcours;
+    listvar *parcours;
 
-   if ( firstpass == 1 && VariableIsParameter == 1 )
-   {
-      if ( !List_Parameter_Var )
-      {
-         List_Parameter_Var = listin;
-      }
-      else
-      {
-         parcours = List_Parameter_Var;
-         while (parcours->suiv) parcours=parcours->suiv;
-         parcours->suiv = listin;
-      }
-   }
+    if ( !VariableIsParameter )    return;
+
+    if ( List_Parameter_Var == NULL )
+    {
+        List_Parameter_Var = listin;
+    }
+    else
+    {
+        parcours = List_Parameter_Var;
+        while ( parcours->suiv )
+            parcours = parcours->suiv;
+        parcours->suiv = listin;
+    }
 }
 
@@ -92,16 +88,14 @@
    listvar *parcours;
 
-   if ( firstpass == 1 )
-   {
-      if ( !List_Dimension_Var )
-      {
-         List_Dimension_Var = listin;
-      }
-      else
-      {
-         parcours = List_Dimension_Var;
-         while (parcours->suiv) parcours=parcours->suiv;
-         parcours->suiv = listin;
-      }
-   }
+    if ( List_Dimension_Var == NULL )
+    {
+        List_Dimension_Var = listin;
+    }
+    else
+    {
+        parcours = List_Dimension_Var;
+        while (parcours->suiv)
+            parcours = parcours->suiv;
+        parcours->suiv = listin;
+    }
 }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithglobliste.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithglobliste.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithglobliste.c	(revision 9987)
@@ -46,12 +46,8 @@
 void Add_Globliste_1(listvar *listtoadd)
 {
-   if ( firstpass == 1 )
-   {
-      if ( aftercontainsdeclare == 0 &&
-           VariableIsParameter  == 0 )
-      {
-         List_Global_Var = AddListvarToListvar(listtoadd,List_Global_Var,1);
-      }
-   }
+    if ( aftercontainsdeclare == 0 && VariableIsParameter == 0 )
+    {
+        List_Global_Var = AddListvarToListvar(listtoadd, List_Global_Var, 1);
+    }
 }
 
@@ -100,5 +96,5 @@
    {
     strcpy(oldvar->v_dimension->dim.last,newvar->v_dimension->dim.last);
-    strcpy(oldvar->v_dimension->dim.first,newvar->v_dimension->dim.first);    
+    strcpy(oldvar->v_dimension->dim.first,newvar->v_dimension->dim.first);
    }
    out = 1;
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistdatavariable.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistdatavariable.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistdatavariable.c	(revision 9987)
@@ -51,10 +51,10 @@
 {
   listvar *newvar;
-  char ligne[LONG_C];
+  char ligne[LONG_M];
 
 //  if ( firstpass == 1 )
 //  {
-     newvar=(listvar *)malloc(sizeof(listvar));
-     newvar->var=(variable *)malloc(sizeof(variable));
+     newvar=(listvar *)calloc(1,sizeof(listvar));
+     newvar->var=(variable *)calloc(1,sizeof(variable));
      /*                                                                       */
      Init_Variable(newvar->var);
@@ -62,17 +62,11 @@
      if ( inmoduledeclare == 1 ) newvar->var->v_module=1;
      strcpy(newvar->var->v_nomvar,name);
-     Save_Length(name,4);
      strcpy(newvar->var->v_subroutinename,subroutinename);
-     Save_Length(subroutinename,11);
      strcpy(newvar->var->v_modulename,curmodulename);
-     Save_Length(curmodulename,6);
-     strcpy(newvar->var->v_commoninfile,mainfile);
-     Save_Length(mainfile,10);
+     strcpy(newvar->var->v_commoninfile,cur_filename);
      if (strchr(values,',') && strncasecmp(values,"'",1))
-            {
-            sprintf(ligne,"(/%s/)",values);
-            }
+        sprintf(ligne,"(/%s/)",values);
      else
-       strcpy(ligne,values);
+        strcpy(ligne,values);
        
      strcpy(newvar->var->v_initialvalue,ligne);
@@ -93,51 +87,59 @@
 void Add_Data_Var_Names_01 (listvar **curlist,listname *l1,listname *l2)
 {
-  listvar *newvar;
-  listvar *tmpvar;
-  listname *tmpvar1;
-  listname *tmpvar2;  
-  char ligne[LONG_C];
+    listvar *newvar;
+    listvar *tmpvar;
+    listname *tmpvar1;
+    listname *tmpvar2;  
+    variable *found_var = NULL;
+    
+    tmpvar1 = l1;
+    tmpvar2 = l2;
   
-  tmpvar1 = l1;
-  tmpvar2 = l2;
-  
-  while (tmpvar1)
-     {
-     newvar=(listvar *)malloc(sizeof(listvar));
-     newvar->var=(variable *)malloc(sizeof(variable));
-     /*                                                                       */
-     Init_Variable(newvar->var);
-     /*                                                                       */
-     if ( inmoduledeclare == 1 ) newvar->var->v_module=1;
-     strcpy(newvar->var->v_nomvar,tmpvar1->n_name);
-     Save_Length(tmpvar1->n_name,4);
-     strcpy(newvar->var->v_subroutinename,subroutinename);
-     Save_Length(subroutinename,11);
-     strcpy(newvar->var->v_modulename,curmodulename);
-     Save_Length(curmodulename,6);
-     strcpy(newvar->var->v_commoninfile,mainfile);
-     Save_Length(mainfile,10);
-       
-     strcpy(newvar->var->v_initialvalue,tmpvar2->n_name);
-     Save_Length(tmpvar2->n_name,14);
-     newvar->suiv = NULL;
+    while (tmpvar1)
+    {
+        newvar = (listvar *) calloc(1,sizeof(listvar));
+        newvar->var = (variable *) calloc(1,sizeof(variable));
+
+        Init_Variable(newvar->var);
+
+        if ( inmoduledeclare == 1 ) newvar->var->v_module=1;
      
-     if ( ! (*curlist) )
-     {
-        *curlist  = newvar ;
-     }
-     else
-     {
-        tmpvar = *curlist;
-        while (tmpvar->suiv)
-          tmpvar=tmpvar->suiv;
-        tmpvar->suiv = newvar;
-     }
+        found_var = get_variable_in_list_from_name(List_Common_Var, tmpvar1->n_name);
+        if ( ! found_var )  found_var = get_variable_in_list_from_name(List_Global_Var,tmpvar1->n_name);
+        if ( ! found_var )  found_var = get_variable_in_list_from_name(List_SubroutineDeclaration_Var,tmpvar1->n_name);
+        
+        if ( found_var && found_var->v_nbdim > 0 )
+        {
+            printf("##############################################################################################################\n");
+            printf("## CONV Error : arrays in data_stmt_object lists not yet supported. Please complain to the proper authorities.\n");
+            printf("##   variable name : %s (in %s:%s:%s)\n", found_var->v_nomvar, found_var->v_modulename,
+                                                              found_var->v_subroutinename, found_var->v_commonname);
+            exit(1);
+        }
+        
+        strcpy(newvar->var->v_nomvar,tmpvar1->n_name);
+        strcpy(newvar->var->v_subroutinename,subroutinename);
+        strcpy(newvar->var->v_modulename,curmodulename);
+        strcpy(newvar->var->v_commoninfile,cur_filename);
+        strcpy(newvar->var->v_initialvalue,tmpvar2->n_name);
+
+        Save_Length(tmpvar2->n_name,14);
+
+        newvar->suiv = NULL;
      
-  tmpvar1 = tmpvar1->suiv;
-  tmpvar2 = tmpvar2->suiv;  
-  }
-  return;
-
-
+        if ( *curlist != NULL )
+        {
+            tmpvar = *curlist;
+            while (tmpvar->suiv)
+                tmpvar = tmpvar->suiv;
+            tmpvar->suiv = newvar;
+        }
+        else
+        {
+            *curlist  = newvar ;
+        }
+     
+        tmpvar1 = tmpvar1->suiv;
+        tmpvar2 = tmpvar2->suiv;  
+    }
 }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistmoduleinfile.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistmoduleinfile.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistmoduleinfile.c	(revision 9987)
@@ -38,481 +38,115 @@
 #include "decl.h"
 
-void Save_Length(char *nom, int whichone)
+void Save_Length(const char *nom, int whichone)
 {
-   if ( whichone == 1  && strlen(nom) > length_last )
+    size_t len_nom = strlen(nom);
+    
+   if ( whichone == 1  && len_nom > length_last )
    {
-      length_last               = strlen(nom);
-      if ( length_last > LONG_C )
-      {
-         printf("WARNING 1 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_last+100);
-      }
+      length_last = len_nom;
+      if ( length_last > LONG_M )
+            printf("WARNING 1 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_last+100);
    }
-   if ( whichone == 2  && strlen(nom) > length_first )
+   if ( whichone == 2  && len_nom > length_first )
    {
-      length_first              = strlen(nom);
-      if ( length_first > LONG_C )
-      {
-         printf("WARNING 2 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_first+100);
-      }
+      length_first = len_nom;
+      if ( length_first > LONG_M )
+           printf("WARNING 2 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_first+100);
    }
-   if ( whichone == 3  && strlen(nom) > length_v_typevar )
+   if ( whichone == 8  && len_nom > length_v_vallengspec )
    {
-      length_v_typevar          = strlen(nom);
-      if ( length_v_typevar > LONG_C )
-      {
-         printf("WARNING 3 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_v_typevar+100);
-      }
+      length_v_vallengspec = len_nom;
+      if ( length_v_vallengspec > LONG_M )
+           printf("WARNING 8 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_v_vallengspec+100);
    }
-   if ( whichone == 4  && strlen(nom) > length_v_nomvar )
+   if ( whichone == 12 && len_nom > length_v_precision )
    {
-      length_v_nomvar           = strlen(nom);
-      if ( length_v_nomvar > LONG_C )
-      {
-         printf("WARNING 4 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_v_nomvar+100);
-      }
+      length_v_precision = len_nom;
+      if ( length_v_precision > LONG_M )
+           printf("WARNING 12 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_v_precision+100);
    }
-   if ( whichone == 5  && strlen(nom) > length_v_dimchar )
+   if ( whichone == 13 && len_nom > length_v_IntentSpec )
    {
-      length_v_dimchar          = strlen(nom);
-      if ( length_v_dimchar > LONG_C )
-      {
-         printf("WARNING 5 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                          length_v_dimchar+100);
-      }
+      length_v_IntentSpec = len_nom;
+      if ( length_v_IntentSpec > LONG_M )
+           printf("WARNING 13 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_v_IntentSpec+100);
    }
-   if ( whichone == 6  && strlen(nom) > length_v_modulename )
+   if ( whichone == 14 && len_nom > length_v_initialvalue )
    {
-      length_v_modulename       = strlen(nom);
-      if ( length_v_modulename > LONG_C )
-      {
-         printf("WARNING 6 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_v_modulename+100);
-      }
+      length_v_initialvalue = len_nom;
+      if ( length_v_initialvalue > LONG_M )
+           printf("WARNING 14 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_v_initialvalue+100);
    }
-   if ( whichone == 7  && strlen(nom) > length_v_commonname )
+   if ( whichone == 15 && len_nom > length_v_readedlistdimension )
    {
-      length_v_commonname       = strlen(nom);
-      if ( length_v_commonname > LONG_C )
-      {
-         printf("WARNING 7 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_v_commonname+100);
-      }
+      length_v_readedlistdimension = len_nom;
+      if ( length_v_readedlistdimension > LONG_M )
+           printf("WARNING 15 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_v_readedlistdimension+100);
    }
-   if ( whichone == 8  && strlen(nom) > length_v_vallengspec )
+   if ( whichone == 25 && len_nom > length_a_nomvar )
    {
-      length_v_vallengspec      = strlen(nom);
-      if ( length_v_vallengspec > LONG_C )
-      {
-         printf("WARNING 8 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                      length_v_vallengspec+100);
-      }
+      length_a_nomvar = len_nom;
+      if ( length_a_nomvar > LONG_C )
+           printf("WARNING 25 : The value of LONG_C (defined in decl.h) should be upgrated to %lu\n", length_a_nomvar+100);
    }
-   if ( whichone == 9  && strlen(nom) > length_v_nameinttypename )
+   if ( whichone == 39 && len_nom > length_toprintglob )
    {
-      length_v_nameinttypename  = strlen(nom);
-      if ( length_v_nameinttypename > LONG_C )
-      {
-         printf("WARNING 9 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                  length_v_nameinttypename+100);
-      }
+      length_toprintglob = len_nom;
+      if ( length_toprintglob > LONG_M )
+           printf("WARNING 39 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_toprintglob+100);
    }
-   if ( whichone == 10 && strlen(nom) > length_v_commoninfile )
+   if ( whichone == 40 && len_nom > length_tmpvargridname )
    {
-      length_v_commoninfile     = strlen(nom);
-      if ( length_v_commoninfile > LONG_C )
-      {
-         printf("WARNING 10 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                     length_v_commoninfile+100);
-      }
+      length_tmpvargridname = len_nom;
+      if ( length_tmpvargridname > LONG_M )
+           printf("WARNING 40 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_tmpvargridname+100);
    }
-   if ( whichone == 11 && strlen(nom) > length_v_subroutinename )
+   if ( whichone == 41 && len_nom > length_ligne_Subloop )
    {
-      length_v_subroutinename   = strlen(nom);
-      if ( length_v_subroutinename > LONG_C )
-      {
-         printf("WARNING 11 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                   length_v_subroutinename+100);
-      }
+       length_ligne_Subloop = len_nom;
+      if ( length_ligne_Subloop > LONG_M )
+           printf("WARNING 41 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n",length_ligne_Subloop+100);
    }
-   if ( whichone == 12 && strlen(nom) > length_v_precision )
+   if ( whichone == 43 && len_nom > length_toprint_utilagrif )
    {
-      length_v_precision        = strlen(nom);
-      if ( length_v_precision > LONG_C )
-      {
-         printf("WARNING 12 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_v_precision+100);
-      }
+      length_toprint_utilagrif = len_nom;
+      if ( length_toprint_utilagrif > LONG_M )
+           printf("WARNING 43 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_toprint_utilagrif+100);
    }
-   if ( whichone == 13 && strlen(nom) > length_v_IntentSpec )
+   if ( whichone == 44 && len_nom > length_toprinttmp_utilchar )
    {
-      length_v_IntentSpec       = strlen(nom);
-      if ( length_v_IntentSpec > LONG_C )
-      {
-         printf("WARNING 13 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_v_IntentSpec+100);
-      }
+      length_toprinttmp_utilchar = len_nom;
+      if ( length_toprinttmp_utilchar > LONG_M)
+           printf("WARNING 44 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_toprinttmp_utilchar+100);
    }
-   if ( whichone == 14 && strlen(nom) > length_v_initialvalue )
+   if ( whichone == 45 && len_nom > length_ligne_writedecl )
    {
-      length_v_initialvalue     = strlen(nom);
-      if ( length_v_initialvalue > LONG_4C )
-      {
-         printf("WARNING 14 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                     length_v_initialvalue+100);
-      }
+      length_ligne_writedecl = len_nom;
+      if ( length_ligne_writedecl > LONG_M )
+           printf("WARNING 45 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_ligne_writedecl+100);
    }
-   if ( whichone == 15 && strlen(nom) > length_v_readedlistdimension )
+   if ( whichone == 46 && len_nom > length_newname_toamr )
    {
-      length_v_readedlistdimension = strlen(nom);
-      if ( length_v_readedlistdimension > LONG_C )
-      {
-         printf("WARNING 15 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                              length_v_readedlistdimension+100);
-      }
+      length_newname_toamr = len_nom;
+      if ( length_newname_toamr > LONG_C )
+           printf("WARNING 46 : The value of LONG_C (defined in decl.h) should be upgrated to %lu\n", length_newname_toamr+100);
    }
-   if ( whichone == 16 && strlen(nom) > length_u_usemodule )
+   if ( whichone == 47 && len_nom > length_newname_writedecl )
    {
-      length_u_usemodule        = strlen(nom);
-      if ( length_u_usemodule > LONG_C )
-      {
-         printf("WARNING 16 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_u_usemodule+100);
-      }
+      length_newname_writedecl = len_nom;
+      if ( length_newname_writedecl > LONG_M )
+           printf("WARNING 47 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_newname_writedecl +100);
    }
-   if ( whichone == 17 && strlen(nom) > length_u_charusemodule )
+   if ( whichone == 48 && len_nom > length_ligne_toamr )
    {
-      length_u_charusemodule    = strlen(nom);
-      if ( length_u_charusemodule > LONG_C )
-      {
-         printf("WARNING 17 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                    length_u_charusemodule+100);
-      }
+      length_ligne_toamr = len_nom;
+      if ( length_ligne_toamr > LONG_M )
+           printf("WARNING 48 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_ligne_toamr +100);
    }
-   if ( whichone == 18 && strlen(nom) > length_u_cursubroutine )
+   if ( whichone == 49 && len_nom > length_tmpligne_writedecl )
    {
-      length_u_cursubroutine    = strlen(nom);
-      if ( length_u_cursubroutine > LONG_C )
-      {
-         printf("WARNING 18 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                    length_u_cursubroutine+100);
-      }
-   }
-   if ( whichone == 19 && strlen(nom) > length_u_modulename )
-   {
-      length_u_modulename       = strlen(nom);
-      if ( length_u_modulename > LONG_C )
-      {
-         printf("WARNING 19 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_u_modulename+100);
-      }
-   }
-   if ( whichone == 20 && strlen(nom) > length_n_name )
-   {
-      length_n_name             = strlen(nom);
-      if ( length_n_name > LONG_C )
-      {
-         printf("WARNING 20 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_n_name+100);
-      }
-   }
-   if ( whichone == 21 && strlen(nom) > length_c_namevar )
-   {
-      length_c_namevar          = strlen(nom);
-      if ( length_c_namevar > LONG_C )
-      {
-         printf("WARNING 21 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_c_namevar+100);
-      }
-   }
-   if ( whichone == 22 && strlen(nom) > length_c_namepointedvar )
-   {
-      length_c_namepointedvar   = strlen(nom);
-      if ( length_c_namepointedvar > LONG_C )
-      {
-         printf("WARNING 22 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                   length_c_namepointedvar+100);
-      }
-   }
-   if ( whichone == 23 && strlen(nom) > length_o_nom )
-   {
-      length_o_nom              = strlen(nom);
-      if ( length_o_nom > LONG_C )
-      {
-         printf("WARNING 23 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_o_nom+100);
-      }
-   }
-   if ( whichone == 24 && strlen(nom) > length_o_module )
-   {
-      length_o_module           = strlen(nom);
-      if ( length_o_module > LONG_C )
-      {
-         printf("WARNING 24 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_o_module+100);
-      }
-   }
-   if ( whichone == 25 && strlen(nom) > length_a_nomvar )
-   {
-      length_a_nomvar           = strlen(nom);
-      if ( length_a_nomvar > LONG_C )
-      {
-         printf("WARNING 25 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_a_nomvar+100);
-      }
-   }
-   if ( whichone == 26 && strlen(nom) > length_a_subroutine )
-   {
-      length_a_subroutine       = strlen(nom);
-      if ( length_a_subroutine > LONG_C )
-      {
-         printf("WARNING 26 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_a_subroutine+100);
-      }
-   }
-   if ( whichone == 27 && strlen(nom) > length_a_module )
-   {
-      length_a_module           = strlen(nom);
-      if ( length_a_module > LONG_C )
-      {
-         printf("WARNING 27 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_a_module+100);
-      }
-   }
-   if ( whichone == 28 && strlen(nom) > length_t_usemodule )
-   {
-      length_t_usemodule        = strlen(nom);
-      if ( length_t_usemodule > LONG_C )
-      {
-         printf("WARNING 28 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_t_usemodule+100);
-      }
-   }
-   if ( whichone == 29 && strlen(nom) > length_t_cursubroutine )
-   {
-      length_t_cursubroutine    = strlen(nom);
-      if ( length_t_cursubroutine > LONG_C )
-      {
-         printf("WARNING 29 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                    length_t_cursubroutine+100);
-      }
-   }
-   if ( whichone == 30 && strlen(nom) > length_curfilename )
-   {
-      length_curfilename        = strlen(nom);
-      if (length_curfilename  > LONG_C )
-      {
-         printf("WARNING 30 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_curfilename+100);
-      }
-   }
-   if ( whichone == 31 && strlen(nom) > length_nomfileoutput )
-   {
-      length_nomfileoutput      = strlen(nom);
-      if ( length_nomfileoutput > LONG_C )
-      {
-         printf("WARNING 31 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                      length_nomfileoutput+100);
-      }
-   }
-   if ( whichone == 32 && strlen(nom) > length_motparse )
-   {
-      length_motparse           = strlen(nom);
-      if ( length_motparse > LONG_4C )
-      {
-         printf("WARNING 32 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_motparse+100);
-      }
-   }
-   if ( whichone == 33 && strlen(nom) > length_mainfile )
-   {
-      length_mainfile           = strlen(nom);
-      if ( length_mainfile > LONG_C )
-      {
-         printf("WARNING 33 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_mainfile+100);
-      }
-   }
-   if ( whichone == 34 && strlen(nom) > length_nomdir )
-   {
-      length_nomdir             = strlen(nom);
-      if ( length_nomdir > LONG_C )
-      {
-         printf("WARNING 34 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_nomdir+100);
-      }
-   }
-   if ( whichone == 35 && strlen(nom) > length_commondirout )
-   {
-      length_commondirout       = strlen(nom);
-      if ( length_commondirout > LONG_C )
-      {
-         printf("WARNING 35 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_commondirout+100);
-      }
-   }
-   if ( whichone == 36 && strlen(nom) > length_commondirin )
-   {
-      length_commondirin        = strlen(nom);
-      if ( length_commondirin > LONG_C )
-      {
-         printf("WARNING 36 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_commondirin+100);
-      }
-   }
-   if ( whichone == 37 && strlen(nom) > length_filetoparse )
-   {
-      length_filetoparse        = strlen(nom);
-      if ( length_filetoparse > LONG_C )
-      {
-         printf("WARNING 37 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_filetoparse+100);
-      }
-   }
-   if ( whichone == 38 && strlen(nom) > length_curbuf )
-   {
-      length_curbuf             = strlen(nom);
-      if ( length_curbuf > LONG_40M )
-      {
-         printf("WARNING 38 : The value of LONG_40M - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",length_curbuf+100);
-      }
-   }
-   if ( whichone == 39 && strlen(nom) > length_toprintglob )
-   {
-      length_toprintglob        = strlen(nom);
-      if ( length_toprintglob > LONG_4C )
-      {
-         printf("WARNING 39 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                        length_toprintglob+100);
-      }
-   }
-   if ( whichone == 40 && strlen(nom) > length_tmpvargridname )
-   {
-      length_tmpvargridname     = strlen(nom);
-      if ( length_tmpvargridname > LONG_4C )
-      {
-         printf("WARNING 40 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                     length_tmpvargridname+100);
-      }
-   }
-   if ( whichone == 41 && strlen(nom) > length_ligne_Subloop )
-   {
-       length_ligne_Subloop    = strlen(nom);
-      if ( length_ligne_Subloop > LONG_40M )
-      {
-         printf("WARNING 41 : The value of LONG_40M - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                      length_ligne_Subloop+100);
-      }
-   }
-   if ( whichone == 42 && strlen(nom) > length_lvargridname_toamr )
-   {
-      length_lvargridname_toamr     = strlen(nom);
-      if ( length_lvargridname_toamr > LONG_4C )
-      {
-         printf("WARNING 42 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                 length_lvargridname_toamr+100);
-      }
-   }
-   if ( whichone == 43 && strlen(nom) > length_toprint_utilagrif )
-   {
-      length_toprint_utilagrif     = strlen(nom);
-      if ( length_toprint_utilagrif > LONG_C )
-      {
-         printf("WARNING 43 : The value of LONG_C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                  length_toprint_utilagrif+100);
-      }
-   }
-   if ( whichone == 44 && strlen(nom) > length_toprinttmp_utilchar )
-   {
-      length_toprinttmp_utilchar     = strlen(nom);
-      if ( length_toprinttmp_utilchar > LONG_4C)
-      {
-         printf("WARNING 44 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                length_toprinttmp_utilchar+100);
-      }
-   }
-   if ( whichone == 45 && strlen(nom) > length_ligne_writedecl )
-   {
-      length_ligne_writedecl     = strlen(nom);
-      if ( length_ligne_writedecl > LONG_4C )
-      {
-         printf("WARNING 45 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                    length_ligne_writedecl+100);
-      }
-   }
-   if ( whichone == 46 && strlen(nom) > length_newname_toamr )
-   {
-      length_newname_toamr    = strlen(nom);
-      if ( length_newname_toamr > LONG_4C )
-      {
-         printf("WARNING 46 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                      length_newname_toamr+100);
-      }
-   }
-   if ( whichone == 47 && strlen(nom) > length_newname_writedecl )
-   {
-      length_newname_writedecl    = strlen(nom);
-      if ( length_newname_writedecl > LONG_4C )
-      {
-         printf("WARNING 47 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                 length_newname_writedecl +100);
-      }
-   }
-   if ( whichone == 48 && strlen(nom) > length_ligne_toamr )
-   {
-      length_ligne_toamr    = strlen(nom);
-      if ( length_ligne_toamr > LONGNOM )
-      {
-         printf("WARNING 48 : The value of LONGNOM - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                       length_ligne_toamr +100);
-      }
-   }
-   if ( whichone == 49 && strlen(nom) > length_tmpligne_writedecl )
-   {
-      length_tmpligne_writedecl     = strlen(nom);
-      if ( length_tmpligne_writedecl > LONG_4C )
-      {
-         printf("WARNING 49 : The value of LONG_4C - define in decl.h -\n");
-         printf("             should be upgrated to %d\n",
-                                                 length_tmpligne_writedecl+100);
-      }
+      length_tmpligne_writedecl = len_nom;
+      if ( length_tmpligne_writedecl > LONG_M )
+           printf("WARNING 49 : The value of LONG_M (defined in decl.h) should be upgrated to %lu\n", length_tmpligne_writedecl+100);
    }
 }
@@ -520,11 +154,7 @@
 void Save_Length_int(int val, int whichone)
 {
-   if ( whichone == 1 && val > value_char_size )
-                               value_char_size                            = val;
-   if ( whichone == 2 && val > value_char_size1 )
-                               value_char_size1                           = val;
-   if ( whichone == 3 && val > value_char_size2 )
-                               value_char_size2                           = val;
-   if ( whichone == 4 && val > value_char_size3 )
-                               value_char_size3                           = val;
+   if ( whichone == 1 && val > value_char_size )    value_char_size  = val;
+   if ( whichone == 2 && val > value_char_size1 )   value_char_size1 = val;
+   if ( whichone == 3 && val > value_char_size2 )   value_char_size2 = val;
+   if ( whichone == 4 && val > value_char_size3 )   value_char_size3 = val;
 }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistofcoupled.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistofcoupled.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistofcoupled.c	(revision 9987)
@@ -40,5 +40,5 @@
 
 /******************************************************************************/
-/*                          varisallocatable_0                                */
+/*                          variscoupled_0                                    */
 /******************************************************************************/
 /* Firstpass 0                                                                */
@@ -46,66 +46,60 @@
 /*                                                                            */
 /******************************************************************************/
-int variscoupled_0(char *ident)
+int variscoupled_0(const char *ident)
 {
-   listallocate *newvaralloc;
-  listvarpointtovar *pointtmplist; 
-  listcouple *coupletmp;   
-  int out;
-
-   out =0;
-   if (firstpass == 0 )
-   {
-  pointtmplist = List_CouplePointed_Var;
-  while ( pointtmplist && out == 0)
-  {
-      coupletmp = pointtmplist->t_couple;
-      while ( coupletmp && out == 0)
-      {
-           /* we should find the same variable name in the same subroutine    */
-           if ( !strcasecmp(ident,coupletmp->c_namevar) &&
-                !strcasecmp(subroutinename,
-                                       pointtmplist->t_cursubroutine) &&
-                 strcasecmp(coupletmp->c_namepointedvar,"")
-              )
-           {
-              out = 1;
-           }
-         coupletmp = coupletmp->suiv;
-     }
-     pointtmplist = pointtmplist->suiv;
-   }
-   }
-   return out;
+    listvarpointtovar *pointtmplist; 
+    listcouple *coupletmp;   
+    int out = 0;
+    
+    if (firstpass == 0 )
+    {
+        pointtmplist = List_CouplePointed_Var;
+        while ( pointtmplist && out == 0)
+        {
+            coupletmp = pointtmplist->t_couple;
+            while ( coupletmp && out == 0)
+            {
+                /* we should find the same variable name in the same subroutine    */
+                if ( !strcasecmp(ident, coupletmp->c_namevar) &&
+                     !strcasecmp(subroutinename, pointtmplist->t_cursubroutine) &&
+                      strcasecmp(coupletmp->c_namepointedvar, "") )
+                {
+                    out = 1;
+                }
+                coupletmp = coupletmp->suiv;
+            }
+            pointtmplist = pointtmplist->suiv;
+        }
+    }
+    return out;
 }
 
-char * getcoupledname_0(char *ident)
+const char * getcoupledname_0(const char *ident)
 {
-   listallocate *newvaralloc;
-  listvarpointtovar *pointtmplist; 
-  listcouple *coupletmp;   
-  int out;
-
-   out =0;
-   if (firstpass == 0 )
-   {
-  pointtmplist = List_CouplePointed_Var;
-  while ( pointtmplist && out == 0)
-  {
-      coupletmp = pointtmplist->t_couple;
-      while ( coupletmp && out == 0)
-      {
-           /* we should find the same variable name in the same subroutine    */
-           if ( !strcasecmp(ident,coupletmp->c_namevar) &&
-                !strcasecmp(subroutinename,
-                                       pointtmplist->t_cursubroutine) &&
-                 strcasecmp(coupletmp->c_namepointedvar,"")
-              )
-           {
-              return(coupletmp->c_namepointedvar);
-           }
-         coupletmp = coupletmp->suiv;
-     }
-     pointtmplist = pointtmplist->suiv;
-   }
-   }
+    listvarpointtovar *pointtmplist; 
+    listcouple *coupletmp;   
+    int out = 0;
+    
+    if (firstpass == 0 )
+    {
+        pointtmplist = List_CouplePointed_Var;
+        while ( pointtmplist && out == 0)
+        {
+            coupletmp = pointtmplist->t_couple;
+            while ( coupletmp && out == 0)
+            {
+                /* we should find the same variable name in the same subroutine    */
+                if ( !strcasecmp(coupletmp->c_namevar,ident) &&
+                     !strcasecmp(pointtmplist->t_cursubroutine,subroutinename) &&
+                      strcasecmp(coupletmp->c_namepointedvar,"") )
+                {
+                    return coupletmp->c_namepointedvar;
+                }
+                coupletmp = coupletmp->suiv;
+            }
+            pointtmplist = pointtmplist->suiv;
+        }
+    }
+    printf("end of getcoupledname_0 -- you should not be there !!! \n");
+    return NULL;
 }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistofmodulebysubroutine.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistofmodulebysubroutine.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistofmodulebysubroutine.c	(revision 9987)
@@ -61,5 +61,4 @@
            List_ModuleUsed_Var = Readthedependfile
                                (tmplistmodule->u_usemodule,List_ModuleUsed_Var);
-         printf("PPPPPPPPPPPPPP\n");
            List_GlobParamModuleUsed_Var = ReaddependParameterList
                       (tmplistmodule->u_usemodule,List_GlobParamModuleUsed_Var);
@@ -76,55 +75,50 @@
 /******************************************************************************/
 /******************************************************************************/
-void  RecordUseModulesUseModulesVariables()
-{
-  listusemodule *tmplistmodule;
-  listusemodule *tmplistmodule1;
-
-  /* we should record all variables defined in modules used in this file      */
-  if ( List_NameOfModuleUsed )
-  {
-     /* and we should read the .depend of the module used by the module used  */
-     tmplistmodule = List_NameOfModuleUsed;
-     while ( tmplistmodule )
-     {
+void RecordUseModulesUseModulesVariables()
+{
+    listusemodule *tmplistmodule;
+    listusemodule *save_list;
+
+    if ( ! List_NameOfModuleUsed )  return;
+
+    /* we should record all variables defined in modules used in this file      */
+    /* and we should read the .depend of the module used by the module used  */
+    tmplistmodule = List_NameOfModuleUsed;
+    while ( tmplistmodule )
+    {
         Readthedependlistofmoduleused(tmplistmodule->u_usemodule);
         while( tmpuselocallist )
         {
-           Addmoduletothelisttmp(tmpuselocallist->u_usemodule);
-           tmplistmodule1 = tmpuselocallist->suiv;
-           free(tmpuselocallist);
-           tmpuselocallist = tmplistmodule1;
+            Addmoduletothelisttmp(tmpuselocallist->u_usemodule);
+            save_list = tmpuselocallist->suiv;
+            free(tmpuselocallist);
+            tmpuselocallist = save_list;
         }
         tmplistmodule = tmplistmodule->suiv;
-     }
-
-     tmplistmodule = listofmoduletmp;
-     while ( tmplistmodule )
-     {
+    }
+    tmplistmodule = listofmoduletmp;
+    while ( tmplistmodule )
+    {
         Readthedependlistofmoduleused(tmplistmodule->u_usemodule);
         while( tmpuselocallist )
         {
-           Addmoduletothelisttmp(tmpuselocallist->u_usemodule);
-           tmplistmodule1 = tmpuselocallist->suiv;
-           free(tmpuselocallist);
-           tmpuselocallist = tmplistmodule1;
+            Addmoduletothelisttmp(tmpuselocallist->u_usemodule);
+            save_list = tmpuselocallist->suiv;
+            free(tmpuselocallist);
+            tmpuselocallist = save_list;
         }
         tmplistmodule = tmplistmodule->suiv;
-     }
-
-
-
-     tmplistmodule = listofmoduletmp;
-     while ( tmplistmodule )
-     {
-        /* check if the file .depend<u_usemodule> exist                       */
-        List_ModuleUsedInModuleUsed_Var = Readthedependfile
-                   (tmplistmodule->u_usemodule,List_ModuleUsedInModuleUsed_Var);
-
-        List_GlobParamModuleUsedInModuleUsed_Var = ReaddependParameterList
-          (tmplistmodule->u_usemodule,List_GlobParamModuleUsedInModuleUsed_Var);
+    }
+    tmplistmodule = listofmoduletmp;
+    while ( tmplistmodule )
+    {
+        // check if the file .depend<u_usemodule> exists
+        List_ModuleUsedInModuleUsed_Var =
+            Readthedependfile(tmplistmodule->u_usemodule,List_ModuleUsedInModuleUsed_Var);
+
+        List_GlobParamModuleUsedInModuleUsed_Var =
+            ReaddependParameterList(tmplistmodule->u_usemodule,List_GlobParamModuleUsedInModuleUsed_Var);
         tmplistmodule = tmplistmodule->suiv;
-     }
-  }
+    }
 }
 
@@ -147,60 +141,52 @@
 void Add_NameOfModuleUsed_1(char *name)
 {
-  listusemodule *newmodule;
-  listusemodule *parcours;
-  int out;
-
-  if ( firstpass == 1 )
-  {
-     newmodule =(listusemodule *)malloc(sizeof(listusemodule));
-     strcpy(newmodule->u_usemodule,name);
-     Save_Length(name,16);
-     strcpy(newmodule->u_charusemodule,charusemodule);
-     Save_Length(charusemodule,17);
-     strcpy(newmodule->u_modulename,curmodulename);
-     Save_Length(curmodulename,19);
-     strcpy(newmodule->u_cursubroutine,subroutinename);
-     Save_Length(subroutinename,18);
-     newmodule->u_firstuse = 1 ;
-     newmodule->suiv = NULL;
-
-     if ( !List_NameOfModuleUsed)
-     {
-         List_NameOfModuleUsed = newmodule ;
-     }
-     else
-     {
-    parcours = List_NameOfModuleUsed;
-    while ( parcours && newmodule->u_firstuse == 1 )
-    {
-       if ( !strcasecmp(name,parcours->u_usemodule) )
-       {
-          newmodule->u_firstuse = 0 ;
-       }
-       parcours=parcours->suiv;
-    }
-    /* we can not add the same module twice for the same subroutine           */
-    parcours = List_NameOfModuleUsed;
-    out = 0 ;
-    while ( parcours && out == 0 )
-    {
-       if ( !strcasecmp(name,parcours->u_usemodule) &&
-            !strcasecmp(subroutinename,parcours->u_cursubroutine)
-           )
-       {
-          out = 1 ;
-          free(newmodule);
-       }
-       else parcours=parcours->suiv;
-    }
-    if ( out == 0 )
-    {
-       newmodule->suiv = List_NameOfModuleUsed;
-       List_NameOfModuleUsed = newmodule;
-    }
-  }
-  }
-}
-
+    listusemodule *newmodule;
+    listusemodule *parcours;
+    int out;
+
+    newmodule = (listusemodule*) calloc(1, sizeof(listusemodule));
+    strcpy(newmodule->u_usemodule, name);
+    strcpy(newmodule->u_charusemodule, charusemodule);
+    strcpy(newmodule->u_modulename, curmodulename);
+    strcpy(newmodule->u_cursubroutine, subroutinename);
+    newmodule->u_firstuse = 1 ;
+    newmodule->suiv = NULL;
+
+    if ( List_NameOfModuleUsed == NULL )
+    {
+        List_NameOfModuleUsed = newmodule ;
+    }
+    else
+    {
+        parcours = List_NameOfModuleUsed;
+        while ( parcours && newmodule->u_firstuse )
+        {
+            if ( !strcasecmp(name,parcours->u_usemodule) )
+            {
+                newmodule->u_firstuse = 0 ;
+            }
+            parcours = parcours->suiv;
+        }
+        /* we can not add the same module twice for the same subroutine           */
+        parcours = List_NameOfModuleUsed;
+        out = 0 ;
+        while ( parcours && out == 0 )
+        {
+            if ( !strcasecmp(name,parcours->u_usemodule) &&
+                 !strcasecmp(subroutinename,parcours->u_cursubroutine) )
+            {
+                out = 1 ;
+                free(newmodule);
+            }
+            else
+                parcours = parcours->suiv;
+        }
+        if ( out == 0 )
+        {
+            newmodule->suiv = List_NameOfModuleUsed;
+            List_NameOfModuleUsed = newmodule;
+        }
+    }
+}
 
 /******************************************************************************/
@@ -220,55 +206,52 @@
 /*                                                                            */
 /******************************************************************************/
-void Addmoduletothelist(char *name)
-{
-  listusemodule *newmodule;
-  listusemodule *parcours;
-  int out;
-
-     newmodule =(listusemodule *)malloc(sizeof(listusemodule));
-     strcpy(newmodule->u_usemodule,name);
-     Save_Length(name,16);
-     strcpy(newmodule->u_charusemodule,charusemodule);
-     Save_Length(charusemodule,17);
-     strcpy(newmodule->u_cursubroutine,subroutinename);
-     Save_Length(subroutinename,18);
-     newmodule->u_firstuse = 1 ;
-     newmodule->suiv = NULL;
-
-     if ( !List_NameOfModuleUsed)
-     {
-         List_NameOfModuleUsed = newmodule ;
-     }
-     else
-     {
-    parcours = List_NameOfModuleUsed;
-    while ( parcours && newmodule->u_firstuse == 1 )
-    {
-       if ( !strcasecmp(name,parcours->u_usemodule) )
-       {
-          newmodule->u_firstuse = 0 ;
-       }
-       parcours=parcours->suiv;
-    }
-    /* we can not add the same module twice for the same subroutine           */
-    parcours = List_NameOfModuleUsed;
-    out = 0 ;
-    while ( parcours && out == 0 )
-    {
-       if ( !strcasecmp(name,parcours->u_usemodule) &&
-            !strcasecmp(subroutinename,parcours->u_cursubroutine)
-           )
-       {
-          out = 1 ;
-          free(newmodule);
-       }
-       else parcours=parcours->suiv;
-    }
-    if ( out == 0 )
-    {
-       newmodule->suiv = List_NameOfModuleUsed;
-       List_NameOfModuleUsed = newmodule;
-    }
-  }
+void Addmoduletothelist(const char *name)
+{
+    listusemodule *newmodule;
+    listusemodule *parcours;
+    int out;
+
+    newmodule = (listusemodule*) calloc(1,sizeof(listusemodule));
+    strcpy(newmodule->u_usemodule, name);
+    strcpy(newmodule->u_charusemodule, charusemodule);
+    strcpy(newmodule->u_cursubroutine, subroutinename);
+    newmodule->u_firstuse = 1 ;
+    newmodule->suiv = NULL;
+
+    if ( !List_NameOfModuleUsed )
+    {
+        List_NameOfModuleUsed = newmodule ;
+    }
+    else
+    {
+        parcours = List_NameOfModuleUsed;
+        while ( parcours && newmodule->u_firstuse == 1 )
+        {
+            if ( !strcasecmp(name,parcours->u_usemodule) )
+            {
+                newmodule->u_firstuse = 0 ;
+            }
+            parcours=parcours->suiv;
+        }
+        /* we can not add the same module twice for the same subroutine           */
+        parcours = List_NameOfModuleUsed;
+        out = 0 ;
+        while ( parcours && out == 0 )
+        {
+            if ( !strcasecmp(name,parcours->u_usemodule) &&
+                 !strcasecmp(subroutinename,parcours->u_cursubroutine) )
+            {
+                out = 1 ;
+                free(newmodule);
+            }
+            else
+                parcours=parcours->suiv;
+        }
+        if ( out == 0 )
+        {
+            newmodule->suiv = List_NameOfModuleUsed;
+            List_NameOfModuleUsed = newmodule;
+        }
+    }
 }
 
@@ -281,23 +264,40 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteUsemoduleDeclaration(char *cursubroutinename)
-{
-  listusemodule *newmodule;
-  
-
-  newmodule = List_NameOfModuleUsed;
-  fprintf(fortranout,"\n");
-
-  while ( newmodule )
-  {
-     if ( !strcasecmp(newmodule->u_cursubroutine,cursubroutinename) )
-     {
-     if (strcmp(newmodule->u_charusemodule,""))
-     {
-             fprintf(fortranout,"      USE %s \n"
-                                                   ,newmodule->u_charusemodule);
-     }
-     }
+void WriteUsemoduleDeclaration(const char *cursubroutinename)
+{
+    listusemodule     *newmodule;
+    listvarpointtovar *pointtmp;
+    long int          fictifpos;
+    int               findcoupled;
+
+    fprintf(fortran_out,"\n");
+    newmodule = List_NameOfModuleUsed;
+
+    while ( newmodule )
+    {
+        if ( !strcasecmp(newmodule->u_cursubroutine, cursubroutinename) )
+        {
+            if (strcmp(newmodule->u_charusemodule,""))
+            {
+/*
+                findcoupled = 0;
+                pointtmp = List_CouplePointed_Var;
+                while(pointtmp)
+                {
+                    if ((!strcasecmp(pointtmp->t_usemodule, newmodule->u_charusemodule)) && \
+                        (!strcasecmp(pointtmp->t_cursubroutine, cursubroutinename)))
+                    {
+                        fictifpos = setposcur();
+                        variableisglobalinmodule(pointtmp->t_couple,newmodule->u_charusemodule,fortran_out,fictifpos);
+                        findcoupled = 1;
+                    }
+                    pointtmp=pointtmp->suiv;
+                }
+                if (findcoupled == 0)   fprintf(fortran_out,"      use %s\n",newmodule->u_charusemodule);
+*/
+                fprintf(fortran_out,"      use %s\n", newmodule->u_charusemodule);
+            }
+        }
         newmodule = newmodule ->suiv;
-  }
-}
+    }
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistvarindoloop.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistvarindoloop.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithlistvarindoloop.c	(revision 9987)
@@ -34,6 +34,6 @@
 /******************************************************************************/
 #include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+//#include <stdlib.h>
+//#include <string.h>
 
 #include "decl.h"
@@ -47,5 +47,5 @@
 /*                                                                            */
 /******************************************************************************/
-void Add_UsedInSubroutine_Var_1 (char *ident)
+void Add_UsedInSubroutine_Var_1 (const char *ident)
 {
   listvar *newvar;
@@ -59,6 +59,6 @@
   if ( !List_UsedInSubroutine_Var )
   {
-      newvar=(listvar *)malloc(sizeof(listvar));
-      newvar->var=(variable *)malloc(sizeof(variable));
+      newvar=(listvar *)calloc(1,sizeof(listvar));
+      newvar->var=(variable *)calloc(1,sizeof(variable));
       /*                                                                      */
       Init_Variable(newvar->var);
@@ -66,17 +66,9 @@
       newvar->suiv = NULL;
       strcpy(newvar->var->v_nomvar,ident);
-
-      Save_Length(ident,4);
       strcpy(newvar->var->v_modulename,curmodulename);
-      Save_Length(curmodulename,6);
-     printf("ICI %d\n",newvar->var->v_module);
-
-      strcpy(newvar->var->v_commoninfile,mainfile);
-      Save_Length(mainfile,10);
+      strcpy(newvar->var->v_commoninfile,cur_filename);
       strcpy(newvar->var->v_subroutinename,subroutinename);
-      Save_Length(subroutinename,11);
       newvar->var->v_pointedvar=pointedvar;
       List_UsedInSubroutine_Var = newvar ;
-       printf("jaoute %s\n",newvar->var->v_nomvar);
   }
   else
@@ -94,23 +86,16 @@
       if ( out == 0 )
       {
-         newvar=(listvar *)malloc(sizeof(listvar));
-         newvar->var=(variable *)malloc(sizeof(variable));
+         newvar=(listvar *)calloc(1,sizeof(listvar));
+         newvar->var=(variable *)calloc(1,sizeof(variable));
          /*                                                                   */
          Init_Variable(newvar->var);
          /*                                                                   */
          strcpy(newvar->var->v_nomvar,ident);
-
-         Save_Length(ident,4);
-         strcpy(newvar->var->v_commoninfile,mainfile);
-         Save_Length(mainfile,10);
+         strcpy(newvar->var->v_commoninfile,cur_filename);
          strcpy(newvar->var->v_modulename,curmodulename);
-         Save_Length(curmodulename,6);
-       printf("ICI %d\n",newvar->var->v_module);
          strcpy(newvar->var->v_subroutinename,subroutinename);
-         Save_Length(subroutinename,11);
          newvar->var->v_pointedvar=pointedvar;
          newvar->suiv = List_UsedInSubroutine_Var;
-         printf("jaoute %s\n",newvar->var->v_nomvar);
-         List_UsedInSubroutine_Var = newvar;        
+         List_UsedInSubroutine_Var = newvar;
       }
   }
@@ -134,6 +119,6 @@
   if ( !List_UsedInSubroutine_Var )
   {
-      newvar=(listvar *)malloc(sizeof(listvar));
-      newvar->var=(variable *)malloc(sizeof(variable));
+      newvar=(listvar *)calloc(1,sizeof(listvar));
+      newvar->var=(variable *)calloc(1,sizeof(variable));
       /*                                                                      */
       Init_Variable(newvar->var);
@@ -141,12 +126,7 @@
       newvar->suiv = NULL;
       strcpy(newvar->var->v_nomvar,name);
-
-      Save_Length(name,4);
       strcpy(newvar->var->v_modulename,curmodulename);
-      Save_Length(curmodulename,6);
-      strcpy(newvar->var->v_commoninfile,mainfile);
-      Save_Length(mainfile,10);
+      strcpy(newvar->var->v_commoninfile,cur_filename);
       strcpy(newvar->var->v_subroutinename,subroutinename);
-      Save_Length(subroutinename,11);
       newvar->var->v_pointedvar=pointedvar;
       List_UsedInSubroutine_Var = newvar ;
@@ -183,18 +163,13 @@
       if ( out == 2 || out == 0 )
       {
-         newvar=(listvar *)malloc(sizeof(listvar));
-         newvar->var=(variable *)malloc(sizeof(variable));
+         newvar=(listvar *)calloc(1,sizeof(listvar));
+         newvar->var=(variable *)calloc(1,sizeof(variable));
          /*                                                                   */
          Init_Variable(newvar->var);
          /*                                                                   */
          strcpy(newvar->var->v_nomvar,name);
-
-         Save_Length(name,4);
          strcpy(newvar->var->v_modulename,curmodulename);
-         Save_Length(curmodulename,6);
-         strcpy(newvar->var->v_commoninfile,mainfile);
-         Save_Length(mainfile,10);
+         strcpy(newvar->var->v_commoninfile,cur_filename);
          strcpy(newvar->var->v_subroutinename,subroutinename);
-         Save_Length(subroutinename,11);
          newvar->var->v_pointedvar=pointedvar;
 
@@ -254,163 +229,172 @@
 void  CompleteThelistvarindoloop()
 {
-  listvar *newvar;
-  listvarpointtovar *pointtmplist;
-  listcouple *coupletmp;
-  int outvar;
-
-  pointtmplist = List_CouplePointed_Var;
-  while ( pointtmplist )
-  {
-      coupletmp = pointtmplist->t_couple;
-      while ( coupletmp )
-      {
-         newvar = List_UsedInSubroutine_Var;
-         outvar = 0 ;
-         while ( newvar && outvar == 0)
-         {
-           /* we should find the same variable name in the same subroutine    */
-           if ( !strcasecmp(newvar->var->v_nomvar,coupletmp->c_namevar) &&
-                !strcasecmp(newvar->var->v_subroutinename,
-                                       pointtmplist->t_cursubroutine) &&
-                 strcasecmp(coupletmp->c_namepointedvar,"")
-              )
-           {
-              outvar = 1;
-              strcpy(newvar->var->v_oldname,newvar->var->v_nomvar);
-              strcpy(newvar->var->v_nomvar,coupletmp->c_namepointedvar);
-           }
-           else
-           {
-              newvar = newvar->suiv;
-           }
-         }
-         coupletmp = coupletmp->suiv;
-     }
-     pointtmplist = pointtmplist->suiv;
-  }
-}
-
-/******************************************************************************/
-/*                             CopyRecord                                     */
+    listvar *newvar;
+    listvarpointtovar *pointtmplist;
+    listcouple *coupletmp;
+    int outvar;
+
+    pointtmplist = List_CouplePointed_Var;
+    while ( pointtmplist )
+    {
+        coupletmp = pointtmplist->t_couple;
+        while ( coupletmp )
+        {
+            newvar = List_UsedInSubroutine_Var;
+            outvar = 0 ;
+            while ( newvar && outvar == 0)
+            {
+                /* we should find the same variable name in the same subroutine    */
+                if ( !strcasecmp(newvar->var->v_nomvar, coupletmp->c_namevar) &&
+                     !strcasecmp(newvar->var->v_subroutinename, pointtmplist->t_cursubroutine) &&
+                      strcasecmp(coupletmp->c_namepointedvar, "") )
+                {
+                    outvar = 1;
+                    strcpy(newvar->var->v_oldname, newvar->var->v_nomvar);
+                    strcpy(newvar->var->v_nomvar, coupletmp->c_namepointedvar);
+                }
+                else
+                {
+                    newvar = newvar->suiv;
+                }
+            }
+            coupletmp = coupletmp->suiv;
+        }
+        pointtmplist = pointtmplist->suiv;
+    }
+}
+
+/******************************************************************************/
+/*                             Merge_Variables                                */
 /******************************************************************************/
 /*                                                                            */
 /******************************************************************************/
-void CopyRecord(variable *var1,variable *var2)
-{
-   if ( !strcasecmp(var1->v_typevar,"") )
-                                        strcpy(var1->v_typevar,var2->v_typevar);
-   else strcpy(var2->v_typevar,var1->v_typevar);
-
-   if ( !strcasecmp(var1->v_oldname,"") )
-                                        strcpy(var1->v_oldname,var2->v_oldname);
-   else strcpy(var2->v_oldname,var1->v_oldname);
-
-   if ( !strcasecmp(var1->v_dimchar,"") )
-                                        strcpy(var1->v_dimchar,var2->v_dimchar);
-   else strcpy(var2->v_dimchar,var1->v_dimchar);
-
-   if ( !strcasecmp(var1->v_commonname,"") )
-                                  strcpy(var1->v_commonname,var2->v_commonname);
-   else strcpy(var2->v_commonname,var1->v_commonname);
-   
-   printf("modulenameII = %s %s %d %s\n",var1->v_modulename,var2->v_modulename,var1->v_module,var1->v_nomvar);
-
-   if ( !strcasecmp(var1->v_modulename,"") || (var1->v_module ==0))
-                                  strcpy(var1->v_modulename,var2->v_modulename);
-   else strcpy(var2->v_modulename,var1->v_modulename);
-
-   if ( !strcasecmp(var1->v_vallengspec,"") )
-                                strcpy(var1->v_vallengspec,var2->v_vallengspec);
-   else strcpy(var2->v_vallengspec,var1->v_vallengspec);
-
-   if ( !strcasecmp(var1->v_nameinttypename,"") )
-                        strcpy(var1->v_nameinttypename,var2->v_nameinttypename);
-   else strcpy(var2->v_nameinttypename,var1->v_nameinttypename);
-          
-   if ( !strcasecmp(var1->v_commoninfile,"") )
-                              strcpy(var1->v_commoninfile,var2->v_commoninfile);
-   else strcpy(var2->v_commoninfile,var1->v_commoninfile);
-
-   if ( !strcasecmp(var1->v_precision,"") )
-                                    strcpy(var1->v_precision,var2->v_precision);
-   else strcpy(var2->v_precision,var1->v_precision);
-
-   if ( !strcasecmp(var1->v_initialvalue,"") )
-                              strcpy(var1->v_initialvalue,var2->v_initialvalue);
-   else strcpy(var2->v_initialvalue,var1->v_initialvalue);
-
-   if ( !strcasecmp(var1->v_IntentSpec,"") )
-                                  strcpy(var1->v_IntentSpec,var2->v_IntentSpec);
-   else strcpy(var2->v_IntentSpec,var1->v_IntentSpec);
-
-   if ( !strcasecmp(var1->v_readedlistdimension,"") )
-                strcpy(var1->v_readedlistdimension,var2->v_readedlistdimension);
-   else strcpy(var2->v_readedlistdimension,var1->v_readedlistdimension);
-
-   if ( var1->v_dimension ) var2->v_dimension = var1->v_dimension ;
-   else var1->v_dimension = var2->v_dimension ;
-
-   if ( var1->v_nbdim == 0 ) var1->v_nbdim = var2->v_nbdim ;
-   else var2->v_nbdim = var1->v_nbdim ;
-
-   if ( var1->v_common == 0 ) var1->v_common = var2->v_common ;
-   else var2->v_common = var1->v_common ;
-
-   if ( var1->v_positioninblock == 0 ) var1->v_positioninblock =
-                                                       var2->v_positioninblock ;
-   else var2->v_positioninblock = var1->v_positioninblock ;
-
-   if ( var1->v_module == 0 ) var1->v_module = var2->v_module ;
-   else var2->v_module = var1->v_module ;
-
-   if ( var1->v_save == 0 ) var1->v_save = var2->v_save ;
-   else var2->v_save = var1->v_save ;
-   
-   if ( var1->v_VariableIsParameter == 0 )
-                     var1->v_VariableIsParameter = var2->v_VariableIsParameter ;
-                    
-   else var2->v_VariableIsParameter = var1->v_VariableIsParameter ;
-   if ( var1->v_indicetabvars == 0 )
-   {
-   
-                                 var1->v_indicetabvars = var2->v_indicetabvars ;
-       printf("HERHEHR %s mm %s mm %d\n",var1->v_nomvar,var2->v_modulename,var2->v_indicetabvars);
-                                 }
-   else var2->v_indicetabvars = var1->v_indicetabvars ;
-
-   if ( var1->v_ExternalDeclare == 0 )
-                             var1->v_ExternalDeclare = var2->v_ExternalDeclare ;
-   else var2->v_ExternalDeclare = var1->v_ExternalDeclare ;
-
-   if ( var1->v_pointedvar == 0 ) var1->v_pointedvar = var2->v_pointedvar ;
-   else var2->v_pointedvar = var1->v_pointedvar ;
-
-   if ( var1->v_dimensiongiven == 0 )
-                                var1->v_dimensiongiven = var2->v_dimensiongiven;
-   else var2->v_dimensiongiven = var1->v_dimensiongiven ;
-
-   if ( var1->v_c_star == 0 ) var1->v_c_star = var2->v_c_star;
-   else var2->v_c_star = var1->v_c_star ;
-
-   if ( var1->v_pointerdeclare == 0 )
-                               var1->v_pointerdeclare = var2->v_pointerdeclare ;
-   else var2->v_pointerdeclare = var1->v_pointerdeclare ;
-
-
-   if ( var1->v_notgrid == 0 ) var1->v_notgrid = var2->v_notgrid ;
-   else var2->v_notgrid = var1->v_notgrid;
-
-   if ( var1->v_optionaldeclare == 0 )
-                              var1->v_optionaldeclare = var2->v_optionaldeclare;
-   else var2->v_optionaldeclare = var1->v_optionaldeclare ;
-
-   if ( var1->v_allocatable == 0 ) var1->v_allocatable = var2->v_allocatable ;
-   else var2->v_allocatable = var1->v_allocatable ;
-   
-   if ( var1->v_target == 0 ) var1->v_target = var2->v_target ;
-   else var2->v_target = var1->v_target ;
-
-   if ( var1->v_dimsempty == 0 ) var1->v_dimsempty = var2->v_dimsempty ;
-   else var2->v_dimsempty = var1->v_dimsempty ;
+void Merge_Variables(variable *var1, variable *var2)
+{
+    if ( !strcasecmp(var1->v_typevar,"") )
+            strcpy(var1->v_typevar,var2->v_typevar);
+    else
+      {
+      strcpy(var2->v_typevar,var1->v_typevar);
+      }
+
+    if ( !strcasecmp(var1->v_oldname,"") )
+            strcpy(var1->v_oldname,var2->v_oldname);
+    else    strcpy(var2->v_oldname,var1->v_oldname);
+
+    if ( !strcasecmp(var1->v_dimchar,"") )
+            strcpy(var1->v_dimchar,var2->v_dimchar);
+    else    strcpy(var2->v_dimchar,var1->v_dimchar);
+
+    if ( !strcasecmp(var1->v_commonname,"") )
+            strcpy(var1->v_commonname,var2->v_commonname);
+    else    strcpy(var2->v_commonname,var1->v_commonname);
+
+    if ( !strcasecmp(var1->v_modulename,"") || (var1->v_module ==0))
+            strcpy(var1->v_modulename,var2->v_modulename);
+    else    strcpy(var2->v_modulename,var1->v_modulename);
+
+    if ( !strcasecmp(var1->v_vallengspec,"") )
+            strcpy(var1->v_vallengspec,var2->v_vallengspec);
+    else    strcpy(var2->v_vallengspec,var1->v_vallengspec);
+
+    if ( !strcasecmp(var1->v_nameinttypename,"") )
+            strcpy(var1->v_nameinttypename,var2->v_nameinttypename);
+    else    strcpy(var2->v_nameinttypename,var1->v_nameinttypename);
+
+    if ( !strcasecmp(var1->v_commoninfile,"") )
+            strcpy(var1->v_commoninfile,var2->v_commoninfile);
+    else    strcpy(var2->v_commoninfile,var1->v_commoninfile);
+
+    if ( !strcasecmp(var1->v_precision,"") )
+            strcpy(var1->v_precision,var2->v_precision);
+    else    strcpy(var2->v_precision,var1->v_precision);
+
+    if ( !strcasecmp(var1->v_initialvalue,"") )
+            strcpy(var1->v_initialvalue,var2->v_initialvalue);
+    else    strcpy(var2->v_initialvalue,var1->v_initialvalue);
+
+    if ( !strcasecmp(var1->v_IntentSpec,"") )
+            strcpy(var1->v_IntentSpec,var2->v_IntentSpec);
+    else    strcpy(var2->v_IntentSpec,var1->v_IntentSpec);
+
+    if ( !strcasecmp(var1->v_readedlistdimension,"") )
+            strcpy(var1->v_readedlistdimension,var2->v_readedlistdimension);
+    else    strcpy(var2->v_readedlistdimension,var1->v_readedlistdimension);
+
+    if ( var1->v_dimension )
+            var2->v_dimension = var1->v_dimension ;
+    else    var1->v_dimension = var2->v_dimension ;
+
+    if ( var1->v_nbdim == 0 )
+            var1->v_nbdim = var2->v_nbdim ;
+    else    var2->v_nbdim = var1->v_nbdim ;
+
+    if ( var1->v_common == 0 )
+            var1->v_common = var2->v_common ;
+    else    var2->v_common = var1->v_common ;
+
+    if ( var1->v_positioninblock == 0 )
+            var1->v_positioninblock = var2->v_positioninblock ;
+    else    var2->v_positioninblock = var1->v_positioninblock ;
+
+    if ( var1->v_module == 0 )
+            var1->v_module = var2->v_module ;
+    else    var2->v_module = var1->v_module ;
+
+    if ( var1->v_save == 0 )
+            var1->v_save = var2->v_save ;
+    else    var2->v_save = var1->v_save ;
+
+    if ( var1->v_VariableIsParameter == 0 )
+            var1->v_VariableIsParameter = var2->v_VariableIsParameter ;
+    else    var2->v_VariableIsParameter = var1->v_VariableIsParameter ;
+
+    if ( var1->v_indicetabvars == 0 )
+            var1->v_indicetabvars = var2->v_indicetabvars ;
+    else    var2->v_indicetabvars = var1->v_indicetabvars ;
+
+    if ( var1->v_ExternalDeclare == 0 )
+            var1->v_ExternalDeclare = var2->v_ExternalDeclare ;
+    else    var2->v_ExternalDeclare = var1->v_ExternalDeclare ;
+
+    if ( var1->v_pointedvar == 0 )
+            var1->v_pointedvar = var2->v_pointedvar ;
+    else    var2->v_pointedvar = var1->v_pointedvar ;
+
+    if ( var1->v_dimensiongiven == 0 )
+            var1->v_dimensiongiven = var2->v_dimensiongiven;
+    else    var2->v_dimensiongiven = var1->v_dimensiongiven ;
+
+    if ( var1->v_c_star == 0 )
+            var1->v_c_star = var2->v_c_star;
+    else    var2->v_c_star = var1->v_c_star ;
+
+    if ( var1->v_catvar == 0 )
+            var1->v_catvar = var2->v_catvar;
+    else    var2->v_catvar = var1->v_catvar ;
+
+    if ( var1->v_pointerdeclare == 0 )
+            var1->v_pointerdeclare = var2->v_pointerdeclare ;
+    else    var2->v_pointerdeclare = var1->v_pointerdeclare ;
+
+    if ( var1->v_notgrid == 0 )
+            var1->v_notgrid = var2->v_notgrid ;
+    else    var2->v_notgrid = var1->v_notgrid;
+
+    if ( var1->v_optionaldeclare == 0 )
+            var1->v_optionaldeclare = var2->v_optionaldeclare;
+    else    var2->v_optionaldeclare = var1->v_optionaldeclare ;
+
+    if ( var1->v_allocatable == 0 )
+            var1->v_allocatable = var2->v_allocatable ;
+    else    var2->v_allocatable = var1->v_allocatable ;
+
+    if ( var1->v_target == 0 )
+            var1->v_target = var2->v_target ;
+    else    var2->v_target = var1->v_target ;
+
+    if ( var1->v_dimsempty == 0 )
+            var1->v_dimsempty = var2->v_dimsempty ;
+    else    var2->v_dimsempty = var1->v_dimsempty ;
 }
 
@@ -437,10 +421,7 @@
       while ( parcours1 && out == 0 )
       {
-         if ( !strcasecmp(parcours->var->v_nomvar,
-                          parcours1->var->v_nomvar)         &&
-              !strcasecmp(parcours->var->v_subroutinename,
-                          parcours1->var->v_subroutinename) &&
-              !strcasecmp(parcours->var->v_modulename,
-                          parcours1->var->v_modulename)
+         if ( !strcasecmp(parcours->var->v_nomvar,         parcours1->var->v_nomvar)         &&
+              !strcasecmp(parcours->var->v_subroutinename, parcours1->var->v_subroutinename) &&
+              !strcasecmp(parcours->var->v_modulename,     parcours1->var->v_modulename)
             ) out = 1;
          else parcours1 = parcours1->suiv;
@@ -448,6 +429,6 @@
       /* if variable has been found                                           */
 
-      if ( out == 1 ) CopyRecord(parcours->var,parcours1->var);
-      
+      if ( out == 1 ) Merge_Variables(parcours->var,parcours1->var);
+
       /* looking in List_Dimension_Var                                        */
       if (out == 0 )
@@ -471,8 +452,8 @@
         }
         /* if variable has been found                                         */
-        
+
         if ( out == 1 )
         {
-           CopyRecord(parcours->var,parcours1->var);
+           Merge_Variables(parcours->var,parcours1->var);
            /* we should remove this record from the List_Dimension_Var        */
            if ( parcours1 == List_Dimension_Var )
@@ -495,5 +476,5 @@
    listvar *parcours;
    listvar *newvar;
-   char ligne[LONG_C];
+   char tmpname[LONG_VNAME];
 
    parcours = List_Save_Var;
@@ -503,18 +484,17 @@
       /* Save in subroutine which is not defined in a module                  */
       {
-         newvar = (listvar *)malloc(sizeof(listvar));
-         newvar->var = (variable *)malloc(sizeof(variable));
+         newvar = (listvar *)calloc(1,sizeof(listvar));
+         newvar->var = (variable *)calloc(1,sizeof(variable));
          /*                                                                   */
          Init_Variable(newvar->var);
          /*                                                                   */
          newvar->suiv = NULL;
-         CopyRecord(parcours->var,newvar->var);
+         Merge_Variables(parcours->var,newvar->var);
          strcpy(newvar->var->v_subroutinename,parcours->var->v_subroutinename);
          strcpy(newvar->var->v_nomvar,parcours->var->v_nomvar);
-
-         sprintf(ligne,"save_%s",parcours->var->v_subroutinename);
-         Add_NameOfCommon_1(ligne,parcours->var->v_subroutinename);
-         strcpy(newvar->var->v_commonname,ligne);
-         Save_Length(ligne,7);
+         newvar->var->v_catvar=parcours->var->v_catvar;
+         sprintf(tmpname,"save_%s",parcours->var->v_subroutinename);
+         Add_NameOfCommon_1(tmpname,parcours->var->v_subroutinename);
+         strcpy(newvar->var->v_commonname,tmpname);
          List_Common_Var = AddListvarToListvar(newvar,List_Common_Var,1);
       }
@@ -522,6 +502,6 @@
       /* Save in subroutine which is defined in a module                      */
       {
-         newvar = (listvar *)malloc(sizeof(listvar));
-         newvar->var = (variable *)malloc(sizeof(variable));
+         newvar = (listvar *)calloc(1,sizeof(listvar));
+         newvar->var = (variable *)calloc(1,sizeof(variable));
          /*                                                                   */
          Init_Variable(newvar->var);
@@ -529,9 +509,10 @@
          newvar->suiv = NULL;
 
-         CopyRecord(parcours->var,newvar->var);
+         Merge_Variables(parcours->var,newvar->var);
          strcpy(newvar->var->v_subroutinename,parcours->var->v_subroutinename);
 
          strcpy(newvar->var->v_nomvar,parcours->var->v_nomvar);
 
+         newvar->var->v_catvar=parcours->var->v_catvar;
          strcpy(newvar->var->v_modulename,parcours->var->v_modulename);
          List_Global_Var = AddListvarToListvar(newvar,List_Global_Var,1);
@@ -560,11 +541,9 @@
       {
 
-         if ( !strcasecmp(parcours->var->v_nomvar,
-                          parcours1->var->v_nomvar)         &&
-              !strcasecmp(parcours->var->v_subroutinename,
-                          parcours1->var->v_subroutinename)
-            ) {
-            out = 1;     
-            }
+         if ( !strcasecmp(parcours->var->v_nomvar,         parcours1->var->v_nomvar) &&
+              !strcasecmp(parcours->var->v_subroutinename, parcours1->var->v_subroutinename) )
+         {
+            out = 1;
+         }
          else parcours1 = parcours1->suiv;
       }
@@ -573,6 +552,6 @@
       {
          strcpy(parcours->var->v_commoninfile,parcours1->var->v_commoninfile);
-             
-         CopyRecord(parcours->var,parcours1->var);
+
+         Merge_Variables(parcours->var,parcours1->var);
       }
       parcours = parcours->suiv;
@@ -587,103 +566,77 @@
 void Update_List_Var(listvar *list_to_modify)
 {
-   listvar *parcours;
-   listvar *parcours1;
-   int out;
-   int out2;
-   
-   parcours = list_to_modify;
-
-   while( parcours )
-   {
-     printf("LE NOM EST %s\n",parcours->var->v_nomvar);
-      /* looking in List_Global_Var                                           */
-      
-      out = 0;
-      
-//       if (list_to_modify != List_SubroutineDeclaration_Var && list_to_modify != List_UsedInSubroutine_Var) {
-//       parcours1 = List_Global_Var;
-//       while ( parcours1 && out == 0 )
-//       {
-//          if ( !strcasecmp(parcours->var->v_nomvar,
-//                           parcours1->var->v_nomvar)         &&
-//               !strcasecmp(parcours->var->v_modulename,
-//                           parcours1->var->v_modulename)
-//             ) out = 1;
-//          else parcours1 = parcours1->suiv;
-//       }
-//       }
-      
-  //    if (list_to_modify == List_UsedInSubroutine_Var) {
-      parcours1 = List_Global_Var;
-      while ( parcours1 && out == 0 )
-      {
-      printf("lenombis est %s\n",parcours1->var->v_nomvar);
-         if ( !strcasecmp(parcours->var->v_nomvar,
-                          parcours1->var->v_nomvar)         &&
-                 !strcasecmp(parcours->var->v_subroutinename,
-                             parcours1->var->v_subroutinename) &&
-              !strcasecmp(parcours->var->v_modulename,
-                          parcours1->var->v_modulename)
-            ) {
-            out = 1;
+    listvar *parcours;
+    listvar *parcours1;
+    int out;
+
+    parcours = list_to_modify;
+
+    while( parcours )
+    {
+        /*printf("LE NOM EST %s\n",parcours->var->v_nomvar);*/
+        /* looking in List_Global_Var                                           */
+        out = 0;
+        parcours1 = List_Global_Var;
+
+        while ( parcours1 && out == 0 )
+        {
+            if ( !strcasecmp(parcours->var->v_nomvar, parcours1->var->v_nomvar)         &&
+                 !strcasecmp(parcours->var->v_subroutinename, parcours1->var->v_subroutinename) &&
+                 !strcasecmp(parcours->var->v_modulename, parcours1->var->v_modulename) )
+            {
+                out = 1;
             }
-         else parcours1 = parcours1->suiv;
-      }
-//      }      
-
-      /* if variable has been found                                           */
-      if ( out == 1 ) {
-      CopyRecord(parcours->var,parcours1->var);
-      }
-      /* looking in List_SubroutineDeclaration_Var                            */
-      else
-      {
-         parcours1 = List_SubroutineDeclaration_Var ;
-         out = 0;
-         while ( parcours1)
-         {
-            if ( !strcasecmp(parcours->var->v_nomvar,
-                             parcours1->var->v_nomvar)         &&
-                 !strcasecmp(parcours->var->v_subroutinename,
-                             parcours1->var->v_subroutinename) &&
-                 !strcasecmp(parcours->var->v_modulename,
-                             parcours1->var->v_modulename)
-               ) {
-
-               out = 1;
-               break;
-               }
             else parcours1 = parcours1->suiv;
-         }
-             
-         /* if variable has been found                                        */
-         if ( out == 1 ) {
-         CopyRecord(parcours->var,parcours1->var);
-        
-         }
-         else
-         {
-            parcours1 = List_Common_Var ;
+        }
+
+        /* if variable has been found                                           */
+        if ( out == 1 )
+        {
+            Merge_Variables(parcours->var,parcours1->var);
+        }
+        /* looking in List_SubroutineDeclaration_Var                            */
+        else
+        {
+            parcours1 = List_SubroutineDeclaration_Var ;
             out = 0;
-            while ( parcours1 && out == 0 )
+            while ( parcours1 )
             {
-               if ( !strcasecmp(parcours->var->v_nomvar,
-                                parcours1->var->v_nomvar)         &&
-                    !strcasecmp(parcours->var->v_subroutinename,
-                                parcours1->var->v_subroutinename) &&
-                    !strcasecmp(parcours->var->v_modulename,
-                                parcours1->var->v_modulename)
-                  ) out = 1;
-               else parcours1 = parcours1->suiv;
+                if ( !strcasecmp(parcours->var->v_nomvar, parcours1->var->v_nomvar)                 &&
+                     !strcasecmp(parcours->var->v_subroutinename, parcours1->var->v_subroutinename) &&
+                     !strcasecmp(parcours->var->v_modulename, parcours1->var->v_modulename) )
+                {
+                    out = 1;
+                    break;
+                }
+                else parcours1 = parcours1->suiv;
             }
-            /* if variable has been found                                     */
-            if ( out == 1 ) {
-            CopyRecord(parcours->var,parcours1->var);       
-         }
-      }
-      }
-      parcours = parcours->suiv;
-   }
-   
+            /* if variable has been found                                        */
+            if ( out == 1 )
+            {
+                Merge_Variables(parcours->var,parcours1->var);
+            }
+            else
+            {
+                parcours1 = List_Common_Var ;
+                out = 0;
+                while ( parcours1 && out == 0 )
+                {
+                    if ( !strcasecmp(parcours->var->v_nomvar, parcours1->var->v_nomvar)                 &&
+                         !strcasecmp(parcours->var->v_subroutinename, parcours1->var->v_subroutinename) &&
+                         !strcasecmp(parcours->var->v_modulename, parcours1->var->v_modulename) )
+                    {
+                        out = 1;
+                    }
+                    else parcours1 = parcours1->suiv;
+                }
+                /* if variable has been found                                     */
+                if ( out == 1 )
+                {
+                    Merge_Variables(parcours->var,parcours1->var);
+                }
+            }
+        }
+        parcours = parcours->suiv;
+    }
 }
 
@@ -696,20 +649,16 @@
    int out;
 
-   
+
    parcours = List_UsedInSubroutine_Var;
    while( parcours )
    {
       out = 0 ;
-      printf("OIEROZEIR %s %s\n",parcours->var->v_nomvar,parcours->var->v_modulename);
       if ( parcours->var->v_indicetabvars == 0 )
       {
-       printf("OIEROZEIR %s\n",parcours->var->v_nomvar);
          parcours2 = List_NameOfModuleUsed;
          while( parcours2 )
          {
-            if ( !strcasecmp(parcours2->u_cursubroutine,"") &&
-                 !strcasecmp(parcours2->u_modulename,
-                             parcours->var->v_modulename)
-               )
+            if ( !strcasecmp(parcours2->u_cursubroutine, "") &&
+                 !strcasecmp(parcours2->u_modulename, parcours->var->v_modulename) )
             {
                parcours3 = List_Global_Var;
@@ -722,11 +671,8 @@
                   else parcours3 = parcours3->suiv;
                }
-               if ( out == 1 ) CopyRecord(parcours->var,parcours3->var);
+               if ( out == 1 ) Merge_Variables(parcours->var,parcours3->var);
             }
-            else if ( !strcasecmp(parcours2->u_cursubroutine,
-                             parcours->var->v_subroutinename) &&
-                 !strcasecmp(parcours2->u_modulename,
-                             parcours->var->v_modulename)
-               )
+            else if ( !strcasecmp(parcours2->u_cursubroutine, parcours->var->v_subroutinename) &&
+                      !strcasecmp(parcours2->u_modulename,    parcours->var->v_modulename) )
             {
                parcours3 = List_Global_Var;
@@ -739,5 +685,5 @@
                   else parcours3 = parcours3->suiv;
                }
-               if ( out == 1 ) CopyRecord(parcours->var,parcours3->var);
+               if ( out == 1 ) Merge_Variables(parcours->var,parcours3->var);
             }
             parcours2 = parcours2->suiv;
@@ -755,5 +701,5 @@
                else parcours3 = parcours3->suiv;
             }
-            if ( out == 1 ) CopyRecord(parcours->var,parcours3->var);
+            if ( out == 1 ) Merge_Variables(parcours->var,parcours3->var);
          }
          /*                                                                   */
@@ -792,5 +738,5 @@
       if ( out == 1 )
       {
-         CopyRecord(parcours->var,parcours1->var);
+         Merge_Variables(parcours->var,parcours1->var);
          strcpy(parcours->var->v_subroutinename,
                 parcours1->var->v_subroutinename);
@@ -841,5 +787,5 @@
 }
 
-int LookingForVariableInListName(listvar *listin,char *name)
+int LookingForVariableInListName(listvar *listin,const char *name)
 {
    listvar *parcours1;
@@ -860,4 +806,22 @@
 }
 
+variable *get_variable_in_list_from_name( listvar *listin, const char *name )
+{
+    listvar *parcours = listin;
+    variable *var = NULL;
+
+    while ( parcours && (!var) )
+    {
+        if ( !strcasecmp(name,parcours->var->v_nomvar) &&
+           ( !strcasecmp(subroutinename,parcours->var->v_subroutinename) ||
+             !strcasecmp(subroutinename,"") ) )
+        {
+            var = parcours->var;
+        }
+        else parcours = parcours -> suiv;
+   }
+   return var;
+}
+
 int LookingForVariableInListGlob(listvar *listin,variable *var)
 {
@@ -897,6 +861,5 @@
 void UpdateListDeclarationWithDimensionList()
 {
-   List_SubroutineDeclaration_Var = AddListvarToListvar(List_Dimension_Var,
-                                              List_SubroutineDeclaration_Var,1);
+   List_SubroutineDeclaration_Var = AddListvarToListvar(List_Dimension_Var, List_SubroutineDeclaration_Var,1);
 }
 
@@ -915,32 +878,20 @@
    listvar *parcoursprec;
    int remove;
-    
-        
+
    parcoursprec = (listvar *)NULL;
    parcours = List_UsedInSubroutine_Var;
    while ( parcours )
    {
-      /*                                                                      */
-      remove = LookingForVariableInListGlobal(List_SubroutineArgument_Var,
-                                                                 parcours->var);
+      remove = LookingForVariableInListGlobal(List_SubroutineArgument_Var,   parcours->var);
       if ( remove == 0 )
-           remove = LookingForVariableInList(List_SubroutineDeclaration_Var,
-                                                                 parcours->var);
-
+           remove = LookingForVariableInList(List_SubroutineDeclaration_Var, parcours->var);
       if ( remove == 0 )
-           remove = LookingForVariableInList(List_Parameter_Var,
-                                                                 parcours->var);
+           remove = LookingForVariableInList(List_Parameter_Var, parcours->var);
       if ( remove == 0 )
-           remove = LookingForVariableInList(List_FunctionType_Var,
-                                                                 parcours->var);
+           remove = LookingForVariableInList(List_FunctionType_Var, parcours->var);
       if ( remove == 0 )
-           remove = LookingForVariableInListGlob(List_GlobalParameter_Var,
-                                                                 parcours->var);
-      
+           remove = LookingForVariableInListGlob(List_GlobalParameter_Var, parcours->var);
       if ( remove == 0 )
-           remove = LookingForVariableInListParamGlob(
-                                    List_GlobParamModuleUsed_Var,parcours->var);
-
-  
+           remove = LookingForVariableInListParamGlob(List_GlobParamModuleUsed_Var, parcours->var);
       if ( remove == 0 )
       {
@@ -976,6 +927,4 @@
       }
    }
-   
-
 }
 
@@ -1023,5 +972,4 @@
       }
    }
-
 }
 
@@ -1032,5 +980,5 @@
    listvar *parcoursprec;
    int out ;
-           
+
    parcoursprec = (listvar *)NULL;
    parcours = List_SubroutineDeclaration_Var;
@@ -1041,8 +989,6 @@
       while ( parcours1 && out == 0 )
       {
-         if ( !strcasecmp(parcours->var->v_subroutinename,
-                          parcours1->var->v_subroutinename) &&
-              !strcasecmp(parcours->var->v_nomvar,
-                          parcours1->var->v_nomvar)
+         if ( !strcasecmp(parcours->var->v_subroutinename,parcours1->var->v_subroutinename) &&
+              !strcasecmp(parcours->var->v_nomvar,parcours1->var->v_nomvar)
             ) out = 1;
          else parcours1 = parcours1->suiv;
@@ -1054,8 +1000,6 @@
          while ( parcours1 && out == 0 )
          {
-            if ( !strcasecmp(parcours->var->v_subroutinename,
-                             parcours1->var->v_subroutinename) &&
-                 !strcasecmp(parcours->var->v_nomvar,
-                             parcours1->var->v_nomvar)
+            if ( !strcasecmp(parcours->var->v_subroutinename,parcours1->var->v_subroutinename) &&
+                 !strcasecmp(parcours->var->v_nomvar,parcours1->var->v_nomvar)
                ) out = 1;
             else parcours1 = parcours1->suiv;
@@ -1083,5 +1027,4 @@
       }
    }
-       
 }
 
@@ -1133,5 +1076,5 @@
                          parcours2->var->v_modulename) )
          {
-            CopyRecord(parcours->var,parcours2->var);
+            Merge_Variables(parcours->var,parcours2->var);
             /* remove var from the parcours2                                  */
             parcours2prec ->suiv = parcours2->suiv;
@@ -1160,5 +1103,5 @@
    Clean_List_UsedInSubroutine_Var();
    Clean_List_SubroutineDeclaration_Var();
-   
+
    newvar = (listvar *)NULL;
 /*   newvar = List_Common_Var;*/
@@ -1184,39 +1127,35 @@
 void ListUpdate()
 {
-   listvar *newvar;
-        
-   Update_List_Subroutine_Var(List_SubroutineArgument_Var);
-
-
-       
-   Update_List_Subroutine_Var(List_FunctionType_Var);
-   Update_List_Var(List_Parameter_Var);
-   Update_List_Var(List_Dimension_Var);
-   Update_List_Var(List_Data_Var);
-   Update_List_Var(List_Save_Var);
-   Update_List_Var(List_GlobalParameter_Var);
-   Update_List_Var(List_Common_Var);
-   Update_List_Var(List_SubroutineDeclaration_Var);
-   Update_List_Var(List_UsedInSubroutine_Var);
-   Update_List_From_Common_Var(List_UsedInSubroutine_Var);
-   Update_List_From_Common_Var(List_SubroutineDeclaration_Var);
-   Update_NotGridDepend_Var(List_NotGridDepend_Var);
-    
-   newvar =(listvar * )NULL;
-/*   newvar = List_Common_Var;*/
-/*   newvar = List_UsedInSubroutine_Var;*/
-/*   newvar = List_Data_Var;*/
-   while ( newvar )
-   {
-      printf("++++ %s - %d - %s - %s - %s - %s\n",
-      newvar->var->v_nomvar,
-      newvar->var->v_VariableIsParameter,
-      newvar->var->v_subroutinename,
-      newvar->var->v_modulename,
-      newvar->var->v_typevar,
-      newvar->var->v_initialvalue      
-            );
-      newvar = newvar->suiv;
-   }
+    listvar *newvar;
+
+    Update_List_Subroutine_Var(List_SubroutineArgument_Var);
+    Update_List_Subroutine_Var(List_FunctionType_Var);
+    Update_List_Var(List_Parameter_Var);
+    Update_List_Var(List_Dimension_Var);
+    Update_List_Var(List_Data_Var);
+    Update_List_Var(List_Save_Var);
+    Update_List_Var(List_GlobalParameter_Var);
+    Update_List_Var(List_Common_Var);
+    Update_List_Var(List_SubroutineDeclaration_Var);
+    Update_List_Var(List_UsedInSubroutine_Var);
+    Update_List_From_Common_Var(List_UsedInSubroutine_Var);
+    Update_List_From_Common_Var(List_SubroutineDeclaration_Var);
+    Update_NotGridDepend_Var(List_NotGridDepend_Var);
+
+    newvar = (listvar * ) NULL;
+//   newvar = List_Common_Var;
+//   newvar = List_UsedInSubroutine_Var;
+//   newvar = List_Data_Var;
+    while ( newvar )
+    {
+        printf("++++ %s - %s - %s - %d - %s - %s\n",
+                newvar->var->v_modulename,
+                newvar->var->v_subroutinename,
+                newvar->var->v_nomvar,
+                newvar->var->v_VariableIsParameter,
+                newvar->var->v_typevar,
+                newvar->var->v_initialvalue );
+        newvar = newvar->suiv;
+    }
 }
 
@@ -1273,5 +1212,5 @@
       parcours = parcours -> suiv ;
    }
-       
+
 }
 
@@ -1284,5 +1223,5 @@
    int position;
    int out;
-   char name_sub[LONG_C];
+   char name_sub[LONG_M];
 
    parcours = List_SubroutineArgument_Var;
@@ -1343,5 +1282,5 @@
       parcours = parcours->suiv;
    }
-       
+
 }
 
@@ -1364,5 +1303,5 @@
    parcoursprec = (listvar *)NULL;
 
-   if ( mark == 1 ) printf("MODULE Treated %s \n",nom);
+   if ( todebug == 1 ) printf("MODULE Treated %s \n",nom);
 
    List_ModuleUsed_Var = (listvar *)NULL;
@@ -1389,5 +1328,5 @@
          if ( out == 1 )
          {
-            CopyRecord(parcours->var,parcours1->var);
+            Merge_Variables(parcours->var,parcours1->var);
             /* Remove this variable from the List_ModuleUsed_Var              */
             if ( parcours1 == List_ModuleUsed_Var )
@@ -1405,18 +1344,20 @@
          /* if we do not found the var Module name in the old list            */
          {
-            if ( Listofavailableindices )
-            {
-               parcours->var->v_indicetabvars = Listofavailableindices ->
-                                                                       i_indice;
-               if ( Listofavailableindices->suiv )
-                          Listofavailableindices = Listofavailableindices->suiv;
-               else
-                          Listofavailableindices = (listindice *)NULL;
-            }
-            else
-            {
-               indicemaxtabvars = indicemaxtabvars + 1 ;
-               parcours->var->v_indicetabvars = indicemaxtabvars;
-            }
+  //       update_indicemaxtabvars(parcours->var,Listofavailableindices);
+         update_indicemaxtabvars(parcours->var,Listofavailableindices_glob);
+  //          if ( Listofavailableindices )
+  //          {
+  //             parcours->var->v_indicetabvars = Listofavailableindices ->
+  //                                                                     i_indice;
+  //             if ( Listofavailableindices->suiv )
+  //                        Listofavailableindices = Listofavailableindices->suiv;
+  //             else
+  //                        Listofavailableindices = (listindice *)NULL;
+  //          }
+  //          else
+  //          {
+  //             indicemaxtabvars = indicemaxtabvars + 1 ;
+  //             parcours->var->v_indicetabvars = indicemaxtabvars;
+  //          }
          }
       }
@@ -1428,8 +1369,8 @@
   while ( parcours1 )
   {
-     newindice=(listindice *) malloc (sizeof (listindice));
+     newindice=(listindice *) calloc(1,sizeof(listindice));
      newindice -> i_indice = parcours1 -> var -> v_indicetabvars;
-     newindice -> suiv = Listofavailableindices;
-     Listofavailableindices = newindice;
+     newindice -> suiv = Listofavailableindices_glob[parcours1 -> var -> v_catvar];
+     Listofavailableindices_glob[parcours1 -> var -> v_catvar] = newindice;
      parcours1 = parcours1->suiv;
   }
@@ -1444,5 +1385,5 @@
    listvar *parcours;
 
-   if ( mark == 1 ) printf("MODULE No Treated %s \n",nom);
+   if ( todebug == 1 ) printf("MODULE No Treated %s \n",nom);
 
    parcours = List_Global_Var;
@@ -1454,6 +1395,6 @@
           )
       {
-         indicemaxtabvars = indicemaxtabvars + 1 ;
-         parcours->var->v_indicetabvars = indicemaxtabvars;
+         indicemaxtabvars[parcours->var->v_catvar] = indicemaxtabvars[parcours->var->v_catvar] + 1 ;
+         parcours->var->v_indicetabvars = indicemaxtabvars[parcours->var->v_catvar];
       }
       parcours = parcours->suiv;
@@ -1474,5 +1415,5 @@
       {
          strcpy(parcours->var->v_commoninfile,record->var->v_commoninfile);
-         CopyRecord(parcours->var,record->var);
+         Merge_Variables(parcours->var,record->var);
       }
       parcours = parcours -> suiv;
@@ -1490,5 +1431,4 @@
 {
    listvar *parcours;
-   listvar *parcoursprec;
    listvar *parcours1;
    listvar *List_CommonUsed_Var;
@@ -1496,7 +1436,5 @@
    int out;
 
-   parcoursprec = (listvar *)NULL;
-
-   if ( mark == 1 ) printf("COMMON Treated %s \n",nom);
+   if ( todebug == 1 ) printf("COMMON Treated %s \n",nom);
 
    List_CommonUsed_Var = (listvar *)NULL;
@@ -1518,5 +1456,4 @@
             else
             {
-               parcoursprec = parcours1 ;
                parcours1 = parcours1->suiv;
             }
@@ -1527,23 +1464,25 @@
             strcpy(parcours->var->v_commoninfile,
                    parcours1->var->v_commoninfile);
-            CopyRecord(parcours->var,parcours1->var);
+            Merge_Variables(parcours->var,parcours1->var);
          }
          else
          /* if we do not found the var common name in the old list            */
          {
-            if ( Listofavailableindices )
-            {
-               parcours->var->v_indicetabvars = Listofavailableindices ->
-                                                                       i_indice;
-               if ( Listofavailableindices->suiv )
-                          Listofavailableindices = Listofavailableindices->suiv;
-               else
-                          Listofavailableindices = (listindice *)NULL;
-            }
-            else
-            {
-               indicemaxtabvars = indicemaxtabvars + 1 ;
-               parcours->var->v_indicetabvars = indicemaxtabvars;
-            }
+    //     update_indicemaxtabvars(parcours->var,Listofavailableindices);
+         update_indicemaxtabvars(parcours->var,Listofavailableindices_glob);
+    //        if ( Listofavailableindices )
+    //        {
+    //           parcours->var->v_indicetabvars = Listofavailableindices ->
+    //                                                                   i_indice;
+    //           if ( Listofavailableindices->suiv )
+    //                      Listofavailableindices = Listofavailableindices->suiv;
+    //           else
+    //                      Listofavailableindices = (listindice *)NULL;
+    //        }
+    //        else
+    //        {
+    //           indicemaxtabvars = indicemaxtabvars + 1 ;
+    //           parcours->var->v_indicetabvars = indicemaxtabvars;
+    //        }
          }
          /* Look in the remaining list in the variable is define              */
@@ -1559,12 +1498,33 @@
      if ( parcours1 -> var -> v_indicetabvars == 0 )
      {
-        newindice=(listindice *) malloc (sizeof (listindice));
+        newindice=(listindice *) calloc(1,sizeof(listindice));
         newindice -> i_indice = parcours1 -> var -> v_indicetabvars;
-        newindice -> suiv = Listofavailableindices;
-        Listofavailableindices = newindice;
+        newindice -> suiv = Listofavailableindices_glob[parcours1 -> var -> v_catvar];
+        Listofavailableindices_glob[parcours1 -> var -> v_catvar] = newindice;
      }
      parcours1 = parcours1->suiv;
   }
 }
+
+void update_indicemaxtabvars(variable *var,listindice **Listofindices)
+{
+
+
+            if ( Listofindices[var->v_catvar] )
+            {
+               var->v_indicetabvars = Listofindices[var->v_catvar] -> i_indice;
+               if ( Listofindices[var->v_catvar]->suiv )
+                          Listofindices[var->v_catvar] = Listofindices[var->v_catvar]->suiv;
+               else
+                          Listofindices[var->v_catvar] = (listindice *)NULL;
+            }
+            else
+            {
+               indicemaxtabvars[var->v_catvar] = indicemaxtabvars[var->v_catvar] + 1 ;
+               var->v_indicetabvars = indicemaxtabvars[var->v_catvar];
+            }
+
+}
+
 /******************************************************************************/
 /*                     IndiceTabvars_Common_Var_No_Treated                    */
@@ -1577,5 +1537,5 @@
    listvar *parcours2;
 
-   if ( mark == 1 ) printf("COMMON No Treated %s \n",nom);
+   if ( todebug == 1 ) printf("COMMON No Treated %s \n",nom);
 
    parcours = List_Common_Var;
@@ -1587,6 +1547,6 @@
           )
       {
-         indicemaxtabvars = indicemaxtabvars + 1 ;
-         parcours->var->v_indicetabvars = indicemaxtabvars;
+         indicemaxtabvars[parcours->var->v_catvar] = indicemaxtabvars[parcours->var->v_catvar] + 1 ;
+         parcours->var->v_indicetabvars = indicemaxtabvars[parcours->var->v_catvar];
          parcours2 = parcours;
          while ( parcours2 )
@@ -1619,5 +1579,5 @@
    while ( parcours_nom )
    {
-      if ( Did_module_common_treaded(parcours_nom->o_nom) == 1 )
+      if ( is_dependfile_created(parcours_nom->o_nom) == 1 )
       {
          IndiceTabvars_Global_Var_Treated(parcours_nom->o_nom);
@@ -1633,5 +1593,5 @@
    while ( parcours_nom )
    {
-      if ( Did_module_common_treaded(parcours_nom->o_nom) == 1 )
+      if ( is_dependfile_created(parcours_nom->o_nom) == 1 )
       {
          IndiceTabvars_Common_Var_Treated(parcours_nom->o_nom);
@@ -1663,16 +1623,18 @@
               !strcasecmp(parcours->var->v_subroutinename,"")            &&
               parcours->var->v_VariableIsParameter == 0                  &&
-              (parcours->var->v_allocatable == 0  || !strcasecmp(parcours->var->v_typevar,"type"))      &&
+              ( parcours->var->v_allocatable == 0 || !strcasecmp(parcours->var->v_typevar,"type"))      &&
               parcours->var->v_notgrid == 0                              &&
-              ( parcours->var->v_nbdim != 0 ||
-                strcasecmp(parcours->var->v_initialvalue,"")
-              ) ) out = 1;
+              ( ( parcours->var->v_nbdim != 0 || !strcasecmp(parcours->var->v_typevar,"type") )
+              || strcasecmp(parcours->var->v_initialvalue,"") )
+            )
+         {
+            out = 1;
+         }
          else parcours = parcours -> suiv;
       }
-      if ( out == 1 )
+      if ( out )
       {
          parcours_nom->o_val = 1 ;
       }
-      /*                                                                      */
       parcours_nom = parcours_nom -> suiv;
    }
@@ -1688,5 +1650,4 @@
    while ( parcours_nom )
    {
-      /*                                                                      */
       parcours = List_Common_Var;
       out = 0 ;
@@ -1695,8 +1656,11 @@
          if ( !strcasecmp(parcours->var->v_commonname,parcours_nom->o_nom)  &&
               strcasecmp(parcours->var->v_subroutinename,"")                &&
-              !strcasecmp(parcours->var->v_commoninfile,mainfile)           &&
-              ( parcours->var->v_nbdim != 0 ||
-                strcasecmp(parcours->var->v_initialvalue,"")
-              ) ) out = 1;
+              !strcasecmp(parcours->var->v_commoninfile,cur_filename)       &&
+              ( ( parcours->var->v_nbdim != 0 || !strcasecmp(parcours->var->v_typevar,"type") )
+              || strcasecmp(parcours->var->v_initialvalue,"") )
+            )
+         {
+            out = 1;
+         }
          else parcours = parcours -> suiv;
       }
@@ -1705,5 +1669,4 @@
          parcours_nom->o_val = 1 ;
       }
-      /*                                                                      */
       parcours_nom = parcours_nom -> suiv;
    }
@@ -1713,48 +1676,26 @@
 {
    listnom *parcours_nom;
-   char ligne[LONG_C];
-   if ( firstpass == 0 )
-   {
-      parcours_nom = List_NameOfCommon;
-      while ( parcours_nom )
-      {
-         if ( parcours_nom->o_val == 1 )
-         {
-            strcpy(ligne,"");
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "module %s",parcours_nom->o_nom);
-            tofich(fortranout,ligne,1);
-            WriteUsemoduleDeclaration(parcours_nom->o_subroutinename);
-            strcpy(ligne,"implicit none");
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "public Alloc_agrif_%s",parcours_nom->o_nom);
-            tofich(fortranout,ligne,1);
-            strcpy (ligne, "contains");
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "subroutine Alloc_agrif_%s(Agrif_Gr)",
-                                                           parcours_nom->o_nom);
-            tofich(fortranout,ligne,1);
-            strcpy(ligne,"Use Agrif_Util");
-            tofich(fortranout,ligne,1);
-            strcpy (ligne, "Type(Agrif_grid), Pointer :: Agrif_Gr");
-            tofich(fortranout,ligne,1);
-            strcpy(ligne, "INTEGER :: i");
-            tofich (fortranout, ligne,1);
-            strcpy (ligne, "\n#include \"alloc_agrif_");
-            strcat (ligne, parcours_nom->o_nom);
-            strcat (ligne, ".h\"\n");
-            fprintf(fortranout,ligne);
-            strcpy (ligne, "Return");
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "end subroutine Alloc_agrif_%s",
-                                                           parcours_nom->o_nom);
-            tofich(fortranout,ligne,1);
-            sprintf (ligne, "end module %s",parcours_nom->o_nom);
-            tofich(fortranout,ligne,1);
-            /* List all Call Alloc_agrif                                      */
-            Add_Subroutine_For_Alloc(parcours_nom->o_nom);
-         }
-         parcours_nom = parcours_nom->suiv;
-      }
+
+   parcours_nom = List_NameOfCommon;
+   while ( parcours_nom )
+   {
+      if ( parcours_nom->o_val == 1 )
+      {
+         fprintf(fortran_out, "      module %s\n\n", parcours_nom->o_nom);
+         WriteUsemoduleDeclaration(parcours_nom->o_subroutinename);
+         fprintf(fortran_out, "        implicit none\n");
+         fprintf(fortran_out, "        public :: Alloc_agrif_%s\n", parcours_nom->o_nom);
+         fprintf(fortran_out, "      contains\n");
+         fprintf(fortran_out, "      subroutine Alloc_agrif_%s(Agrif_Gr)\n", parcours_nom->o_nom);
+         fprintf(fortran_out, "        use Agrif_Util\n");
+         fprintf(fortran_out, "        type(Agrif_grid), pointer :: Agrif_Gr\n");
+         fprintf(fortran_out, "        integer :: i\n");
+         fprintf(fortran_out, "#include \"alloc_agrif_%s.h\"\n", parcours_nom->o_nom);
+         fprintf(fortran_out, "      end subroutine Alloc_agrif_%s\n", parcours_nom->o_nom);
+         fprintf(fortran_out, "      end module %s\n", parcours_nom->o_nom);
+         /* List all Call Alloc_agrif                                      */
+         Add_Subroutine_For_Alloc(parcours_nom->o_nom);
+      }
+      parcours_nom = parcours_nom->suiv;
    }
 }
@@ -1768,54 +1709,50 @@
    listvar *parcours4;
    int out;
-   char name_module[LONG_C];
+   char name_module[LONG_M];
 
    /* We should integrate allocate and pointer variables                      */
-   parcours2 = List_Allocate_Var;
-   while ( parcours2 )
-   {
-      parcours4 = List_UsedInSubroutine_Var;
-      out = 0 ;
-      while ( parcours4 && out == 0 )
-      {
-         if ( !strcasecmp(parcours2->a_nomvar,parcours4->var->v_nomvar) )
-         {
-            Add_SubroutineWhereAgrifUsed_1(parcours4->var->v_subroutinename,
-                                           parcours4->var->v_modulename);
-            out = 1;
-         }
-         else parcours4 = parcours4 -> suiv ;
-      }
-      parcours2 = parcours2->suiv;
-   }
-   /*                                                                         */
-   parcours3 = List_Pointer_Var;
-   while ( parcours3 )
-   {
-      parcours4 = List_UsedInSubroutine_Var;
-      out = 0 ;
-      while ( parcours4 && out == 0 )
-      {
-         if ( !strcasecmp(parcours3->n_name,parcours4->var->v_nomvar) )
-         {
-            Add_SubroutineWhereAgrifUsed_1(parcours4->var->v_subroutinename,
-                                           parcours4->var->v_modulename);
-            out = 1;
-         }
-         else parcours4 = parcours4 -> suiv ;
-      }
-      parcours3 = parcours3 -> suiv;
-   }
-   /*                                                                         */
-   parcours4 = List_UsedInSubroutine_Var;
-   while ( parcours4 )
-   {
-      if ( parcours4->var->v_allocatable == 1 && strcasecmp(parcours4->var->v_typevar,"type"))
-      {
-         Add_SubroutineWhereAgrifUsed_1(parcours4->var->v_subroutinename,
-                                        parcours4->var->v_modulename);
-      }
-      parcours4 = parcours4 -> suiv ;
-   }
-   /*                                                                         */
+//    parcours2 = List_Allocate_Var;
+//    while ( parcours2 )
+//    {
+//       parcours4 = List_UsedInSubroutine_Var;
+//       out = 0 ;
+//       while ( parcours4 && out == 0 )
+//       {
+//          if ( !strcasecmp(parcours2->a_nomvar,parcours4->var->v_nomvar) )
+//          {
+//             Add_SubroutineWhereAgrifUsed_1(parcours4->var->v_subroutinename, parcours4->var->v_modulename);
+//             out = 1;
+//          }
+//          else parcours4 = parcours4 -> suiv ;
+//       }
+//       parcours2 = parcours2->suiv;
+//    }
+//
+//    parcours3 = List_Pointer_Var;
+//    while ( parcours3 )
+//    {
+//       parcours4 = List_UsedInSubroutine_Var;
+//       out = 0 ;
+//       while ( parcours4 && out == 0 )
+//       {
+//          if ( !strcasecmp(parcours3->n_name, parcours4->var->v_nomvar) )
+//          {
+//             Add_SubroutineWhereAgrifUsed_1(parcours4->var->v_subroutinename, parcours4->var->v_modulename);
+//             out = 1;
+//          }
+//          else parcours4 = parcours4 -> suiv ;
+//       }
+//       parcours3 = parcours3 -> suiv;
+//    }
+//    parcours4 = List_UsedInSubroutine_Var;
+//    while ( parcours4 )
+//    {
+//       if ( parcours4->var->v_allocatable == 1 && strcasecmp(parcours4->var->v_typevar,"type"))
+//       {
+//          Add_SubroutineWhereAgrifUsed_1(parcours4->var->v_subroutinename, parcours4->var->v_modulename);
+//       }
+//       parcours4 = parcours4 -> suiv ;
+//    }
+
    parcours = List_SubroutineWhereAgrifUsed;
    while ( parcours )
@@ -1833,11 +1770,10 @@
             if ( !strcasecmp(parcours->o_nom,parcours1->u_cursubroutine) )
             {
-               strcpy(name_module,parcours->o_module);
+               strcpy(name_module, parcours->o_module);
             }
             parcours1 = parcours1->suiv;
          }
       }
-      /* if out == 0 we should look in the module declaration                 */
-      if ( out == 0 )
+      if ( out == 0 )   /* we should look in the module declaration */
       {
          parcours1 = List_NameOfModuleUsed;
@@ -1853,5 +1789,5 @@
       }
       if ( out == 0 ) parcours->o_val = 1;
-      /*                                                                      */
+
       parcours = parcours->suiv;
    }
@@ -1876,15 +1812,10 @@
 }
 
-void Affiche()
-{
-   listvar *parcours;
-
-   parcours = (listvar *)NULL;
+void Affiche(listvar *in_parcours)
+{
 /*   parcours = List_Global_Var;                  */
 /*   parcours = List_SubroutineDeclaration_Var;   */
-
 /*   parcours = List_SubroutineArgument_Var;      */
 /*   parcours = List_FunctionType_Var;            */
-
 /*   parcours = List_Data_Var;                    */
 /*   parcours = List_Save_Var;                    */
@@ -1893,34 +1824,33 @@
 /*   parcours = List_GlobalParameter_Var;         */
 /*   parcours = List_NotGridDepend_Var;           */
-
 /*   parcours = List_Common_Var;                  */
+   listvar *parcours = in_parcours;
 
    while( parcours )
    {
-      printf("module- %s \n",parcours->var->v_modulename);
-      printf("subroutine- %s  \n",parcours->var->v_subroutinename);
-      printf("nom- %s  \n",parcours->var->v_nomvar);
-      printf("common- %s  \n",parcours->var->v_commonname);
-      printf("type- %s  \n",parcours->var->v_typevar);
-      printf("indice- %d  \n",parcours->var->v_indicetabvars);
-      printf("variableisparameter- %d \n",parcours->var->v_VariableIsParameter);
-      printf("module1- %d  \n",parcours->var->v_module);
-      printf("save- %d  \n",parcours->var->v_save);
-      printf("notgrid- %d  \n",parcours->var->v_notgrid);
-      printf("nbdim- %d  \n",parcours->var->v_nbdim);
-      printf("common1- %d  \n",parcours->var->v_common);
-      printf("v_dimensiongiven- %d  \n",parcours->var->v_dimensiongiven);
-      printf("v_dimsempty- %d  \n",parcours->var->v_dimsempty);
-      printf("initialvalue- %s\n \n",parcours->var->v_initialvalue);
-      printf("dim- %s\n \n",parcours->var->v_readedlistdimension);
+      printf("modulename     - %s \n", parcours->var->v_modulename);
+      printf("subroutinename - %s \n", parcours->var->v_subroutinename);
+      printf("nomvar         - %s \n", parcours->var->v_nomvar);
+      printf("commonname     - %s \n", parcours->var->v_commonname);
+      printf("commoninfile   - %s \n", parcours->var->v_commoninfile);
+      printf("typevar        - %s \n", parcours->var->v_typevar);
+      printf("catvar         - %d \n", parcours->var->v_catvar);
+      printf("indicetabvars  - %d \n", parcours->var->v_indicetabvars);
+      printf("isparameter    - %d \n", parcours->var->v_VariableIsParameter);
+      printf("module         - %d \n", parcours->var->v_module);
+      printf("save           - %d \n", parcours->var->v_save);
+      printf("notgrid        - %d \n", parcours->var->v_notgrid);
+      printf("nbdim          - %d \n", parcours->var->v_nbdim);
+      printf("common         - %d \n", parcours->var->v_common);
+      printf("dimensiongiven - %d \n", parcours->var->v_dimensiongiven);
+      printf("dimsempty      - %d \n", parcours->var->v_dimsempty);
+      printf("initialvalue   - %s \n", parcours->var->v_initialvalue);
+      printf("readedlistdim  - %s \n", parcours->var->v_readedlistdimension);
+      printf("-------------------------------------\n");
 
       parcours = parcours -> suiv ;
    }
-   if ( mark == 1 ) printf("Indicemaxtabvars = %d \n",indicemaxtabvars);
-   
-}
-
-
-
+   if ( todebug == 1 ) printf("Indicemaxtabvars = %d \n",indicemaxtabvars[0]);
+}
 
 int SubInList_ContainsSubroutine()
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithvarofsubroutineliste.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithvarofsubroutineliste.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WorkWithvarofsubroutineliste.c	(revision 9987)
@@ -41,18 +41,7 @@
 /*                      Add_SubroutineArgument_Var_1                          */
 /******************************************************************************/
-/* Firstpass 1                                                                */
-/* We should complete the                                                     */
-/******************************************************************************/
-/*                                                                            */
-/*                                                                            */
-/******************************************************************************/
 void Add_SubroutineArgument_Var_1(listvar *listtoadd)
 {
-
-   if ( firstpass == 1 )
-   {
-       List_SubroutineArgument_Var = AddListvarToListvar
-                              (listtoadd,List_SubroutineArgument_Var,1);
-   }
+    List_SubroutineArgument_Var = AddListvarToListvar(listtoadd, List_SubroutineArgument_Var, 1);
 }
 
@@ -60,46 +49,30 @@
 /*                             Add_FunctionType_Var_1                         */
 /******************************************************************************/
-/* Firstpass 1                                                                */
-/* We should complete the                                                     */
-/******************************************************************************/
-/*                                                                            */
-/*                                                                            */
-/******************************************************************************/
-void Add_FunctionType_Var_1(char *nom)
+void Add_FunctionType_Var_1(const char *nom)
 {
-   listvar *newvar;
+    listvar *newvar;
 
-   if ( firstpass == 1 )
-   {
-      curvar=createvar(nom,NULL);
-      strcpy(curvar->v_typevar,DeclType);
-      newvar = insertvar(NULL,curvar);
-      List_FunctionType_Var = AddListvarToListvar
-                              (newvar,List_FunctionType_Var,1);
-   }
+    curvar = createvar(nom, NULL);
+    strcpy(curvar->v_typevar, DeclType);
+    newvar = insertvar(NULL, curvar);
+    List_FunctionType_Var = AddListvarToListvar(newvar,List_FunctionType_Var,1);
 }
-
 
 /******************************************************************************/
 /*                      Add_SubroutineDeclaration_Var_1                       */
 /******************************************************************************/
-/* Firstpass 1                                                                */
 /* We should complete the listvarofsubroutine                                 */
 /******************************************************************************/
-/*                                                                            */
-/*                                                                            */
-/******************************************************************************/
-void Add_SubroutineDeclaration_Var_1 (listvar *listtoadd)
-{
-   if ( firstpass == 1 )
-   {
-      if ( VariableIsParameter == 0 &&
-           SaveDeclare         == 0 )
-      {
-         listduplicated = (listvar *)NULL;
-         duplicatelistvar(listtoadd);
-         List_SubroutineDeclaration_Var = AddListvarToListvar
-                              (listduplicated,List_SubroutineDeclaration_Var,1);
-      }
-   }
-}
+// void Add_SubroutineDeclaration_Var_1 (listvar *listtoadd)
+// {
+//    if ( firstpass == 1 )
+//    {
+//       if ( VariableIsParameter == 0 &&
+//            SaveDeclare         == 0 )
+//       {
+//          listduplicated = (listvar *)NULL;
+//          duplicatelistvar(listtoadd);
+//          List_SubroutineDeclaration_Var = AddListvarToListvar(listduplicated,List_SubroutineDeclaration_Var,1);
+//       }
+//    }
+// }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WriteInFile.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WriteInFile.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/WriteInFile.c	(revision 9987)
@@ -43,60 +43,30 @@
 /* This subroutine is used to write the string s into the fileout             */
 /******************************************************************************/
-void tofich_reste (FILE * filout, char *s,int returnlineornot)
+void tofich_reste (FILE * filout, const char *s, int do_returnline)
 {
-  char temp[61];
-  char *tmp;
-  int size;
-  int val_min;
+    const size_t line_length = 66;
+    char temp[line_length+1];
+    size_t s_length;
 
-  if (strlen (s) <= 60)
+    s_length = strlen(s);
+
+    if ( !strcmp(&s[strlen(s)-1], "\n") )
+        s_length = strlen(s)-1;
+
+    if ( s_length <= line_length )
     {
-      if ( returnlineornot == 0 ) fprintf (filout, "     &%s", s);
-      else if ( returnlineornot == 2 ) fprintf (filout, "&%s", s);
-      else if ( returnlineornot == 3 ) fprintf (filout, "&%s\n", s);
-      else                             fprintf (filout, "     &%s\n", s);
-      if ( returnlineornot == 0 ||
-           returnlineornot == 2 ) colnum=colnum+strlen(s)+6;
-      else colnum=0;
+        if ( do_returnline ) fprintf(filout, "     &%s\n", s);
+        else                 fprintf(filout, "&%s", s);
     }
-  else
+    else
     {
-      val_min = 60;
-      strncpy (temp, s, 60);
-      strcpy (&temp[60], "\0");
+        strncpy(temp, s, line_length);
+        temp[line_length] = '\0';
+        if ( retour77 == 0 && (s_length-strlen(temp) > 0) )
+                fprintf(filout, "     &%s&\n", temp);
+        else    fprintf(filout, "     &%s\n", temp);
 
-      tmp = strrchr(temp, '+');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '-');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '/');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '*');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '%');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, ',');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, ')');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '(');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-
-      size = val_min;
-
-      strcpy (&temp[60-size], "\0");
-
-      if ( retour77 == 0 ) fprintf (filout, "     &%s&\n", temp);
-      else fprintf (filout, "     &%s\n", temp);
-      colnum=0;
-      tofich_reste (filout, (char *) &s[60-size],returnlineornot);
+        if ( s_length-strlen(temp) > 0 )
+            tofich_reste(filout, (char *) &s[line_length], do_returnline);
     }
 }
@@ -107,60 +77,29 @@
 /* This subroutine is used to write the string s into the fileout             */
 /******************************************************************************/
-void tofich (FILE * filout, char *s, int returnlineornot)
+void tofich (FILE * filout, const char *s, int do_returnline)
 {
-  char temp[61];
-  char *tmp;
-  int size;
-  int val_min;
+    const size_t line_length = 66;
+    char temp[line_length+1];
+    size_t s_length;
 
-  if (strlen (s) <= 60)
+    s_length = strlen(s);
+
+    if ( !strcmp(&s[strlen(s)-1], "\n") )
+        s_length = strlen(s)-1;
+
+    if ( s_length <= line_length )
     {
-      if ( returnlineornot == 0 ) fprintf (filout, "      %s", s);
-      else if ( returnlineornot == 2 ) fprintf (filout, "%s", s);
-      else if ( returnlineornot == 3 ) fprintf (filout, "%s\n", s);
-      else                             fprintf (filout, "      %s\n", s);
-      if ( returnlineornot == 0 || returnlineornot == 2 )
-                                                      colnum=colnum+strlen(s)+6;
-      else colnum=0;
+        if ( do_returnline ) fprintf(filout, "      %s\n", s);
+        else                 fprintf(filout, "%s", s);
     }
-  else
+    else
     {
-      val_min = 60;
-      strncpy (temp, s, 60);
-      strcpy (&temp[60], "\0");
+        strncpy(temp, s, line_length);
+        temp[line_length] = '\0';
 
-      tmp = strrchr(temp, '+');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '-');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '/');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '*');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '%');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, ',');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, ')');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
-      tmp = strrchr(temp, '(');
-      if ( tmp )
-      if ( strlen(tmp) < val_min ) val_min = strlen(tmp);
+        if ( retour77 == 0 )    fprintf(filout, "      %s&\n", temp);
+        else                    fprintf(filout, "      %s\n", temp);
 
-      size = val_min;
-
-      strcpy (&temp[60-size], "\0");
-
-      if ( retour77 == 0 ) fprintf (filout, "      %s&\n", temp);
-      else fprintf (filout, "      %s\n", temp);
-      colnum=0;
-      tofich_reste (filout, (char *) &s[60-size], returnlineornot);
+        tofich_reste(filout, (char *) &s[line_length], do_returnline);
     }
 }
@@ -173,49 +112,21 @@
 void tofich_blanc (FILE * filout, int size)
 {
-  int i;
+    const char* empty_char = " ";
+    int i = 0;
 
-  if (size <= 65) fprintf (filout, "%*s\n",size,EmptyChar);
-  else
-  {
-      i=0;
-      do
-      {
-         fprintf (filout, "%*s\n",65,EmptyChar);
-         i = i+1;
-      } while ( i <= size / 65 );
-         fprintf (filout, "%*s\n",size%65,EmptyChar);
-  }
+    if (size <= 65)
+        fprintf(filout, "%*s\n", size, empty_char);
+    else
+    {
+        do
+        {
+            fprintf(filout, "%*s\n", 65, empty_char);
+            i++;
+        }
+        while ( i <= size / 65 );
 
+        fprintf(filout, "%*s\n", size%65, empty_char);
+    }
 }
-/******************************************************************************/
-/*                       tofich_line                                          */
-/******************************************************************************/
-/* This subroutine is used to write size blank into the fileout               */
-/******************************************************************************/
-void tofich_line (FILE * filout, int size, int long position)
-{
-  int i;
-  int retour;
-
-  if (size <= 65) fprintf (filout, "%*s",size,EmptyChar);
-  else
-  {
-      i=0;
-      do
-      {
-         fprintf (filout, "%*s",65,EmptyChar);
-         i = i+1;
-      } while ( i <= size / 65 );
-         fprintf (filout, "%*s",size%65,EmptyChar);
-  }
-
-   if ( !strstr(motparse1,"\n") ) retour=0;
-   else retour=1;
-
-   fseek(filout,position,SEEK_SET);
-   if (retour == 1 ) fprintf (filout, "\n");
-
-}
-
 
 /******************************************************************************/
@@ -224,14 +135,12 @@
 /* This subroutine is used to remove a sentence in the file filout            */
 /******************************************************************************/
-void RemoveWordSET_0(FILE * filout, long int position, long int sizetoremove)
+void RemoveWordSET_0(FILE * filout, long int position, int sizetoremove)
 {
-   if ( firstpass == 0 && couldaddvariable == 1 )
-   {
-      fseek(filout,position,SEEK_SET);
-      tofich_line(filout,sizetoremove,position);
+    if ( inside_type_declare || firstpass ) return;
 
-   }
+    fseek(filout, position, SEEK_SET);
+    tofich_blanc(filout, sizetoremove);
+    fseek(filout, position, SEEK_SET);
 }
-
 
 /******************************************************************************/
@@ -240,11 +149,11 @@
 /* This subroutine is used to remove a sentence in the file filout            */
 /******************************************************************************/
-void RemoveWordCUR_0(FILE * filout, long int position, long int sizetoremove)
+void RemoveWordCUR_0(FILE * filout, int sizetoremove)
 {
-   if ( firstpass == 0  && couldaddvariable == 1 )
-   {
-      fseek(filout,position,SEEK_CUR);
-      tofich_blanc(filout,sizetoremove);
+    if ( inside_type_declare || firstpass ) return;
 
-   }
+    fseek(filout, (long int)(-sizetoremove), SEEK_CUR);
+    tofich_blanc(filout, sizetoremove);
+    fseek(filout, (long int)(-sizetoremove), SEEK_CUR);
+    if ( strstr(fortran_text, "\n") )   fprintf(filout, "\n");
 }
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/Writedeclarations.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/Writedeclarations.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/Writedeclarations.c	(revision 9987)
@@ -50,60 +50,59 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteBeginDeclaration(variable *v,char ligne[LONG_4C], int visibility)
-{
-  char tmpligne[LONG_4C];
+void WriteBeginDeclaration(variable *v, char line[LONG_M], int visibility)
+{
+  char tmpligne[LONG_M];
+  int precision_given ;
 
   if ( !strcasecmp(v->v_typevar,"") )
   {
-     printf("WARNING : The type of the variable %s \n",v->v_nomvar);
-     printf("          is unknown. CONV should define a type\n");
-  }
-  
-  sprintf (ligne, "%s", v->v_typevar);
-  if ( v->v_c_star == 1 ) strcat(ligne,"*");
-  
+     printf("# WARNING : The type of the variable %s is unknown.\n", v->v_nomvar);
+     printf("#           CONV should define a type\n");
+  }
+
+  sprintf(line, "%s", v->v_typevar);
+  if ( v->v_c_star == 1 ) strcat(line, "*");
+
   /* We should give the precision of the variable if it has been given        */
+  precision_given = 0;
   if ( strcasecmp(v->v_precision,"") )
   {
-     sprintf(tmpligne,"(%s)",v->v_precision);
-     Save_Length(tmpligne,49);
-     strcat(ligne,tmpligne);
-  }
-  
+     sprintf(tmpligne, "(%s)", v->v_precision);
+     Save_Length(tmpligne, 49);
+     strcat(line, tmpligne);
+     precision_given = 1;
+  }
+
   if (strcasecmp(v->v_dimchar,""))
   {
      sprintf(tmpligne,"(%s)",v->v_dimchar);
-     Save_Length(tmpligne,49);
-     strcat(ligne,tmpligne);
-  }
-  
-  if ( strcasecmp(v->v_nameinttypename,"") )
+     Save_Length(tmpligne, 49);
+     strcat(line,tmpligne);
+  }
+
+  if ((precision_given == 0) && ( strcasecmp(v->v_nameinttypename,"") ))
   {
      sprintf(tmpligne,"*%s",v->v_nameinttypename);
-     Save_Length(tmpligne,49);
-     strcat(ligne,tmpligne);
+     Save_Length(tmpligne, 49);
+     strcat(line,tmpligne);
   }
   if (strcasecmp (v->v_IntentSpec, ""))
   {
-     sprintf(tmpligne,",INTENT(%s) ",v->v_IntentSpec);
-     Save_Length(tmpligne,49);
-     strcat(ligne,tmpligne);
-  }
-  if ( v->v_VariableIsParameter == 1 ) strcat(ligne, ", PARAMETER");
-  if (visibility == 1)
-  {
-  if ( v->v_PublicDeclare       == 1 ) strcat(ligne, ", PUBLIC");
-  if ( v->v_PrivateDeclare      == 1 ) strcat(ligne, ", PRIVATE");
-  }
-  if ( v->v_ExternalDeclare     == 1 ) strcat(ligne, ", EXTERNAL");
-  if ( v->v_allocatable         == 1)
-       {strcat(ligne,", ALLOCATABLE");
-       }
-  if ( v->v_target         == 1)
-       {strcat(ligne,", TARGET");
-       }
-  if ( v->v_optionaldeclare     == 1 ) strcat(ligne,", OPTIONAL");
-  if ( v->v_pointerdeclare      == 1 ) strcat(ligne,", POINTER");
-  Save_Length(ligne,45);
+     sprintf(tmpligne,", intent(%s)", v->v_IntentSpec);
+     Save_Length(tmpligne, 49);
+     strcat(line,tmpligne);
+  }
+  if ( v->v_VariableIsParameter ) strcat(line, ", parameter");
+  if ( visibility )
+  {
+      if ( v->v_PublicDeclare  )  strcat(line, ", public");
+      if ( v->v_PrivateDeclare )  strcat(line, ", private");
+  }
+  if ( v->v_ExternalDeclare ) strcat(line, ", external");
+  if ( v->v_allocatable     ) strcat(line, ", allocatable");
+  if ( v->v_target          ) strcat(line, ", target");
+  if ( v->v_optionaldeclare ) strcat(line, ", optional");
+  if ( v->v_pointerdeclare  ) strcat(line, ", pointer");
+  Save_Length(line, 45);
 }
 
@@ -120,18 +119,17 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteScalarDeclaration(variable *v,char ligne[LONG_4C])
-{
-
-  strcat (ligne, " :: ");
-  strcat (ligne, v->v_nomvar);
-  if ( strcasecmp(v->v_vallengspec,"") ) strcat(ligne,v->v_vallengspec);
-  if ( v->v_VariableIsParameter == 1 )
-  {
-     strcat(ligne," = ");
-     strcat(ligne,v->v_initialvalue);
-  }
-  Save_Length(ligne,45);
-}
-
+void WriteScalarDeclaration( variable *v, char line[LONG_M])
+{
+    strcat(line, " :: ");
+    strcat(line, v->v_nomvar);
+
+    if ( strcasecmp(v->v_vallengspec, "") ) strcat(line,v->v_vallengspec);
+    if ( v->v_VariableIsParameter )
+    {
+        strcat(line," = ");
+        strcat(line, v->v_initialvalue);
+    }
+    Save_Length(line, 45);
+}
 
 /******************************************************************************/
@@ -147,48 +145,39 @@
 /*                                                                            */
 /******************************************************************************/
-void WriteTableDeclaration(variable * v,char ligne[LONG_4C],int tmpok)
-{
-  char newname[LONG_4C];
-
-  strcat (ligne, ", Dimension(");
-
-  if ( v->v_dimensiongiven == 1 && tmpok == 1 )
-  {
-                                         strcat(ligne,v->v_readedlistdimension);
-                                         }
-  if ( v->v_dimensiongiven == 1 && tmpok == 0 )
-  {
-     strcpy(newname,ChangeTheInitalvaluebyTabvarsName
-                                  (v->v_readedlistdimension,List_Global_Var,0));
-
-     if ( !strcasecmp(newname,"") ) strcat(newname,v->v_readedlistdimension);
-
-        strcpy(newname,ChangeTheInitalvaluebyTabvarsName
-                                 (newname,List_Common_Var,0));
-
-     if ( !strcasecmp(newname,"") ) strcat(newname,v->v_readedlistdimension); 
-     
-        strcpy(newname,ChangeTheInitalvaluebyTabvarsName
-                              (newname,List_ModuleUsed_Var,0));
+void WriteTableDeclaration(variable * v,char ligne[LONG_M],int tmpok)
+{
+    char newname[LONG_M];
+
+    strcat (ligne, ", dimension(");
+
+    if ( v->v_dimensiongiven == 1 && tmpok == 1 )   strcat(ligne,v->v_readedlistdimension);
+    if ( v->v_dimensiongiven == 1 && tmpok == 0 )
+    {
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(v->v_readedlistdimension,List_Global_Var));
         if ( !strcasecmp(newname,"") ) strcat(newname,v->v_readedlistdimension);
 
-     Save_Length(newname,47);
-     strcat(ligne,newname);
-  }
-  strcat (ligne, ")");
-  strcat (ligne, " :: ");
-  strcat (ligne, v->v_nomvar);
-  if ( strcasecmp(vallengspec,"") ) strcat(ligne,v->v_vallengspec);
-
-  if ( v->v_VariableIsParameter == 1 )
-  {
-     strcat(ligne," = ");
-     strcat(ligne,v->v_initialvalue);
-  }
-  Save_Length(ligne,45);
-}
-
-/******************************************************************************/
-/*                        writevardeclaration                                 */
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname,List_Common_Var));
+        if ( !strcasecmp(newname,"") ) strcat(newname,v->v_readedlistdimension);
+
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname,List_ModuleUsed_Var));
+        if ( !strcasecmp(newname,"") ) strcat(newname,v->v_readedlistdimension);
+
+        Save_Length(newname,47);
+        strcat(ligne,newname);
+    }
+    strcat(ligne, ") :: ");
+    strcat(ligne, v->v_nomvar);
+    if ( strcasecmp(vallengspec,"") ) strcat(ligne,v->v_vallengspec);
+
+    if ( v->v_VariableIsParameter == 1 )
+    {
+        strcat(ligne," = ");
+        strcat(ligne,v->v_initialvalue);
+    }
+    Save_Length(ligne,45);
+}
+
+/******************************************************************************/
+/*                        WriteVarDeclaration                                 */
 /******************************************************************************/
 /* This subroutine is used to write the initial declaration in the file       */
@@ -201,216 +190,228 @@
 /*                                                                            */
 /******************************************************************************/
-void writevardeclaration (listvar * var_record, FILE *fileout, int value, int visibility)
+void WriteVarDeclaration( variable *v, FILE *fileout, int value, int visibility )
 {
   FILE *filecommon;
+  char ligne[LONG_M];
+
+  filecommon = fileout;
+
+  if ( v->v_save == 0 || inmodulemeet == 0 )
+  {
+     WriteBeginDeclaration(v, ligne, visibility);
+
+     if ( v->v_nbdim == 0 )
+        WriteScalarDeclaration(v, ligne);
+     else
+        WriteTableDeclaration(v, ligne, value);
+
+     if ( v->v_VariableIsParameter != 1 && strcasecmp(v->v_initialvalue,"") )
+     {
+        strcat(ligne," = ");
+        strcat(ligne,v->v_initialvalue);
+     }
+     tofich(filecommon, ligne, 1);
+  }
+  else
+    printf("-- in writevardeclaration : |%s| -- MHCHECK\n", v->v_nomvar);
+  Save_Length(ligne,45);
+}
+
+
+void WriteLocalParamDeclaration(FILE* tofile)
+{
+    listvar *parcours;
+
+    parcours = List_Parameter_Var;
+    while ( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) )
+        {
+            WriteVarDeclaration(parcours->var, tofile, 0, 1);
+        }
+        parcours = parcours -> suiv;
+    }
+}
+
+void WriteFunctionDeclaration(FILE* tofile, int value)
+{
+    listvar *parcours;
+
+    parcours = List_FunctionType_Var;
+    while ( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_subroutinename, subroutinename) &&
+              strcasecmp(parcours->var->v_typevar, "") )
+        {
+            WriteVarDeclaration(parcours->var, tofile, value, 1);
+        }
+        parcours = parcours -> suiv;
+    }
+}
+
+void WriteSubroutineDeclaration(int value)
+{
+    listvar *parcours;
+    variable *v;
+
+    parcours = List_SubroutineDeclaration_Var;
+    while ( parcours )
+    {
+        v = parcours->var;
+        if ( !strcasecmp(v->v_subroutinename, subroutinename)   &&
+             (v->v_save == 0)                                   &&
+             (v->v_pointerdeclare == 0)                         &&
+             (v->v_VariableIsParameter == 0)                    &&
+             (v->v_common == 0) )
+        {
+            WriteVarDeclaration(v, fortran_out, value, 1);
+        }
+        else if ( !strcasecmp(v->v_subroutinename, subroutinename)  &&
+                  (v->v_save == 0)                                  &&
+                  (v->v_VariableIsParameter == 0)                   &&
+                  (v->v_common == 0) )
+        {
+            WriteVarDeclaration(v, fortran_out, value, 1);
+        }
+        parcours = parcours -> suiv;
+    }
+}
+
+void WriteArgumentDeclaration_beforecall()
+{
+    int position;
+    listnom *neededparameter;
+    FILE *paramtoamr;
+    listvar *parcours;
+    variable *v;
+    char ligne[LONG_M];
+
+    fprintf(fortran_out,"#include \"Param_BeforeCall_%s.h\"\n",subroutinename);
+
+    sprintf(ligne,"Param_BeforeCall_%s.h",subroutinename);
+    paramtoamr = open_for_write(ligne);
+
+    neededparameter = (listnom * )NULL;
+    position = 1;
+    parcours = List_SubroutineArgument_Var;
+
+    while ( parcours )
+    {
+        v = parcours->var;
+        if ( !strcasecmp(v->v_subroutinename, subroutinename) && (v->v_positioninblock == position) )
+        {
+            position++;
+            WriteVarDeclaration(v, fortran_out, 0, 1);
+            neededparameter = writedeclarationintoamr(List_Parameter_Var, paramtoamr,
+                                    v, v->v_subroutinename, neededparameter, subroutinename);
+            parcours = List_SubroutineArgument_Var;
+        }
+        else parcours = parcours -> suiv;
+    }
+    Save_Length(ligne,45);
+
+    // Write interface for 'Sub_Loop_machin' in 'Param_BeforeCall_machin.h' when outside a module
+    if ( IsTabvarsUseInArgument_0() && (inmodulemeet == 0) && (inprogramdeclare == 0) )
+    {
+        fprintf(paramtoamr, "      interface\n");
+        if (isrecursive) sprintf(ligne,"  recursive subroutine Sub_Loop_%s(", subroutinename);
+        else             sprintf(ligne,"  subroutine Sub_Loop_%s(", subroutinename);
+        WriteVariablelist_subloop(ligne);
+        WriteVariablelist_subloop_Def(ligne);
+        strcat(ligne,")");
+        Save_Length(ligne,45);
+        tofich(paramtoamr,ligne,1);
+
+        listusemodule *parcours_mod;
+        parcours_mod = List_NameOfModuleUsed;
+        while ( parcours_mod )
+        {
+            if ( !strcasecmp(parcours_mod->u_cursubroutine, subroutinename) )
+            {
+                fprintf(paramtoamr, "          use %s\n", parcours_mod->u_usemodule);
+            }
+            parcours_mod = parcours_mod->suiv;
+        }
+        fprintf(paramtoamr, "          implicit none\n");
+        WriteLocalParamDeclaration(paramtoamr);
+        writesub_loopdeclaration_scalar(List_UsedInSubroutine_Var, paramtoamr);
+        writesub_loopdeclaration_tab(List_UsedInSubroutine_Var, paramtoamr);
+        WriteArgumentDeclaration_Sort(paramtoamr);
+        WriteFunctionDeclaration(paramtoamr, 1);
+
+        sprintf(ligne,"  end subroutine Sub_Loop_%s\n", subroutinename);
+        tofich(paramtoamr, ligne, 1);
+        fprintf(paramtoamr, "      end interface\n");
+    }
+    fclose(paramtoamr);
+}
+
+void WriteArgumentDeclaration_Sort(FILE* tofile)
+{
+    int position = 1;
+    listvar *parcours;
+
+    parcours = List_SubroutineArgument_Var;
+    while ( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_subroutinename, subroutinename) &&
+                         parcours->var->v_positioninblock == position )
+        {
+            position = position + 1;
+            WriteVarDeclaration(parcours->var, tofile, 1, 1);
+            parcours = List_SubroutineArgument_Var;
+        }
+        else parcours = parcours -> suiv;
+    }
+
+    parcours = List_SubroutineArgument_Var;
+    while ( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) &&
+                         parcours->var->v_positioninblock == 0           &&
+                        parcours->var->v_nbdim == 0 )
+        {
+            WriteVarDeclaration(parcours->var,tofile,1,1);
+        }
+        parcours = parcours -> suiv;
+    }
+
+    parcours = List_SubroutineArgument_Var;
+    while ( parcours )
+    {
+        if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) &&
+                         parcours->var->v_positioninblock == 0           &&
+                         parcours->var->v_nbdim != 0 )
+        {
+            WriteVarDeclaration(parcours->var, tofile, 1, 1);
+        }
+        parcours = parcours -> suiv;
+    }
+}
+
+/******************************************************************************/
+/*                      writedeclarationintoamr                               */
+/******************************************************************************/
+/* This subroutine is used to write the declaration of parameters needed in   */
+/*    allocation subroutines creates in toamr.c                               */
+/******************************************************************************/
+/*                                                                            */
+/*                                                                            */
+/******************************************************************************/
+listnom *writedeclarationintoamr (listvar * deb_common, FILE *fileout,
+                              variable *var , const char *commonname,
+                           listnom *neededparameter, const char *name_common)
+{
   listvar *newvar;
   variable *v;
-  char ligne[LONG_4C];
-
-  filecommon=fileout;
-  newvar = var_record;
-  
-  if ( newvar->var->v_save == 0 || inmodulemeet == 0 )
-  {
-     v = newvar->var;
-     if (mark == 1) fprintf(fileout,"222222233333333\n");
-     WriteBeginDeclaration(v,ligne,visibility);
-
-     if ( v->v_nbdim == 0 ) WriteScalarDeclaration(v,ligne);
-     else WriteTableDeclaration(v,ligne,value);
-
-     if ( v->v_VariableIsParameter != 1 && strcasecmp(v->v_initialvalue,"") )
-     {
-        strcat(ligne," = ");
-        strcat(ligne,v->v_initialvalue);
-     }
-     
-     tofich (filecommon, ligne,1);
-     if (mark == 1) fprintf(fileout,"44444433333333\n");     
-  }
-  Save_Length(ligne,45);
-  
-}
-
-
-void WriteLocalParamDeclaration()
-{
-   listvar *parcours;
-
-   parcours = List_Parameter_Var;
-   while ( parcours )
-   {
-      if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) )
-      {
-         writevardeclaration(parcours,fortranout,0,1);
-      }
-      parcours = parcours -> suiv;
-   }
-}
-
-void WriteFunctionDeclaration(int value)
-{
-   listvar *parcours;
-
-   parcours = List_FunctionType_Var;
-   while ( parcours )
-   {
-      if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) &&
-            strcasecmp(parcours->var->v_typevar,"")
-         )
-      {
-         writevardeclaration(parcours,fortranout,value,1);
-      }
-      parcours = parcours -> suiv;
-   }
-}
-
-void WriteSubroutineDeclaration(int value)
-{
-   listvar *parcours;
-
-   parcours = List_SubroutineDeclaration_Var;
-   while ( parcours )
-   {
-      if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) &&
-           parcours->var->v_save == 0                                  &&
-           parcours->var->v_pointerdeclare == 0                        &&
-           parcours->var->v_VariableIsParameter == 0                   &&
-           parcours->var->v_common == 0
-         )
-      {
-         writevardeclaration(parcours,fortranout,value,1);
-
-      }
-      else if ( !strcasecmp(parcours->var->v_subroutinename,subroutinename) &&
-           parcours->var->v_save == 0                                  &&
-           parcours->var->v_VariableIsParameter == 0                   &&
-           parcours->var->v_common == 0
-              )
-      {
-         writevardeclaration(parcours,fortranout,value,1);
-
-      }
-      parcours = parcours -> suiv;
-   }
-}
-
-void WriteArgumentDeclaration_beforecall()
-{
-   int position;
-   listnom *neededparameter;
-   FILE *paramtoamr;
-   listvar *newvar;
-   char ligne[LONG_4C];
-
-   fprintf(fortranout,"#include \"Param_BeforeCall_%s.h\" \n",subroutinename);
-   /*                                                                         */
-   sprintf(ligne,"Param_BeforeCall_%s.h",subroutinename);
-   paramtoamr = associate (ligne);
-   /*                                                                         */
-   neededparameter = (listnom * )NULL;
-   /*                                                                         */
-   position = 1;
-   newvar = List_SubroutineArgument_Var;
-   while ( newvar )
-   {
-      if ( !strcasecmp(newvar->var->v_subroutinename,subroutinename) &&
-                       newvar->var->v_positioninblock == position
-         )
-      {
-         position = position + 1;
-
-         writevardeclaration(newvar,fortranout,0,1);
-         neededparameter = writedeclarationintoamr(List_Parameter_Var,
-                   paramtoamr,newvar->var,newvar->var->v_subroutinename,
-                   neededparameter,subroutinename);
-
-         newvar = List_SubroutineArgument_Var;
-      }
-      else newvar = newvar -> suiv;
-   }
-   Save_Length(ligne,45);
-   fclose(paramtoamr);
-}
-
-void WriteArgumentDeclaration_Sort()
-{
-   int position;
-   listvar *newvar;
-
-   /*                                                                         */
-   position = 1;
-   newvar = List_SubroutineArgument_Var;
-   while ( newvar )
-   {
-      if ( !strcasecmp(newvar->var->v_subroutinename,subroutinename) &&
-                       newvar->var->v_positioninblock == position
-         )
-      {
-         position = position + 1;
-
-         writevardeclaration(newvar,fortranout,1,1);
-         /*                                                                   */
-         newvar = List_SubroutineArgument_Var;
-      }
-      else newvar = newvar -> suiv;
-   }
-   /*                                                                         */
-   newvar = List_SubroutineArgument_Var;
-   while ( newvar )
-   {
-      if ( !strcasecmp(newvar->var->v_subroutinename,subroutinename) &&
-                       newvar->var->v_positioninblock == 0           &&
-                       newvar->var->v_nbdim == 0
-         )
-      {
-
-         writevardeclaration(newvar,fortranout,1,1);
-      }
-      newvar = newvar -> suiv;
-   }
-   /*                                                                         */
-   newvar = List_SubroutineArgument_Var;
-   while ( newvar )
-   {
-      if ( !strcasecmp(newvar->var->v_subroutinename,subroutinename) &&
-                       newvar->var->v_positioninblock == 0           &&
-                       newvar->var->v_nbdim != 0
-         )
-      {
-         writevardeclaration(newvar,fortranout,1,1);
-      }
-      newvar = newvar -> suiv;
-   }
-}
-
-/******************************************************************************/
-/*                      writedeclarationintoamr                               */
-/******************************************************************************/
-/* This subroutine is used to write the declaration of parameters needed in   */
-/*    allocation subroutines creates in toamr.c                               */
-/******************************************************************************/
-/*                                                                            */
-/*                                                                            */
-/******************************************************************************/
-listnom *writedeclarationintoamr (listvar * deb_common, FILE *fileout,
-                              variable *var , char commonname[LONG_C],
-                           listnom *neededparameter, char name_common[LONG_C])
-{
-  listvar *newvar;
-  variable *v;
-  char ligne[LONG_4C];
+  char ligne[LONG_M];
   int changeval;
   int out;
   int writeit;
   listnom *parcours;
-  listnom *parcoursprec;
-
-  parcoursprec = (listnom * )NULL;
 
   /* we should list the needed parameter                                      */
   if ( !strcasecmp(name_common,commonname) )
-     neededparameter = DecomposeTheNameinlistnom(var->v_readedlistdimension,
-                                                               neededparameter);
+     neededparameter = DecomposeTheNameinlistnom(var->v_readedlistdimension,neededparameter);
   /*                                                                          */
   parcours = neededparameter;
@@ -422,5 +423,5 @@
      while ( newvar && out == 0 )
      {
-     
+
         if ( !strcasecmp(parcours->o_nom,newvar->var->v_nomvar) && !strcasecmp(var->v_subroutinename,newvar->var->v_subroutinename))
         {
@@ -443,5 +444,5 @@
      while ( newvar && out == 0 )
      {
-        if ( !strcasecmp(parcours->o_nom,newvar->var->v_nomvar) && !strcasecmp(var->v_subroutinename,newvar->var->v_subroutinename))        
+        if ( !strcasecmp(parcours->o_nom,newvar->var->v_nomvar) && !strcasecmp(var->v_subroutinename,newvar->var->v_subroutinename))
         {
            out=1;
@@ -455,6 +456,4 @@
      parcours=parcours->suiv;
    }
-  /*                                                                          */
-  tofich (fileout, "",1);
   parcours = neededparameter;
   while (parcours)
@@ -482,9 +481,9 @@
 //           v->v_allocatable = 0;
 //        }
-        WriteBeginDeclaration(v,ligne,1);
+        WriteBeginDeclaration(v, ligne, 1);
         if ( v->v_nbdim == 0 ) WriteScalarDeclaration(v,ligne);
-        else WriteTableDeclaration(v,ligne,1);
-
-        tofich (fileout, ligne,1);
+        else WriteTableDeclaration(v, ligne, 1);
+
+        tofich(fileout, ligne, 1);
         if ( changeval == 1 )
         {
@@ -498,5 +497,5 @@
         {
            shouldincludempif = 0;
-           fprintf(fileout,"      include \'mpif.h\' \n");
+           fprintf(fileout,"      include \'mpif.h\'\n");
         }
      }
@@ -524,7 +523,7 @@
   listvar *newvar;
   variable *v;
-  char ligne[LONG_4C];
-
-  tofich (fileout, "",1);
+  char ligne[LONG_M];
+
+//   tofich (fileout, "",1);
   newvar = deb_common;
 
@@ -533,8 +532,5 @@
      if ( newvar->var->v_nbdim == 0 &&
           !strcasecmp(newvar->var->v_subroutinename,subroutinename)  &&
-/*RB*/
-           (newvar->var->v_pointerdeclare == 0  || !strcasecmp(newvar->var->v_typevar,"type"))  
-/*RBend*/
-         )
+           (newvar->var->v_pointerdeclare == 0 || !strcasecmp(newvar->var->v_typevar,"type")) )
      {
         v = newvar->var;
@@ -565,19 +561,16 @@
   listvar *newvar;
   variable *v;
-  char ligne[LONG_4C];
+  char ligne[LONG_M];
   int changeval;
 
-  tofich (fileout, "",1);
   newvar = deb_common;
   while (newvar)
   {
-  printf("newvar = %s %d %s\n",newvar->var->v_nomvar,newvar->var->v_pointerdeclare,newvar->var->v_typevar);
-     if ( newvar->var->v_nbdim != 0                                 &&
-          !strcasecmp(newvar->var->v_subroutinename,subroutinename) &&
-          (newvar->var->v_pointerdeclare == 0 || !strcasecmp(newvar->var->v_typevar,"type"))
-        )
+      v = newvar->var;
+//  printf("newvar = %s %d %s\n",newvar->var->v_nomvar,newvar->var->v_pointerdeclare,newvar->var->v_typevar);
+     if ( (v->v_nbdim != 0)  && !strcasecmp(v->v_subroutinename, subroutinename) &&
+          (v->v_pointerdeclare == 0 || !strcasecmp(v->v_typevar,"type")) )
      {
         changeval = 0;
-        v = newvar->var;
         if ( v->v_allocatable == 1)
         {
@@ -595,6 +588,6 @@
         }
 
-        WriteBeginDeclaration(v,ligne,1);
-        WriteTableDeclaration(v,ligne,1);
+        WriteBeginDeclaration(v, ligne, 1);
+        WriteTableDeclaration(v, ligne, 1);
         tofich (fileout, ligne,1);
         if ( changeval >= 1 ) v->v_allocatable = 1;
@@ -606,99 +599,70 @@
 }
 
-
 void ReWriteDeclarationAndAddTosubroutine_01(listvar *listdecl)
 {
-listvar *parcours;
-listvar *parcours2;
-listvar *parcours3;
-int out;
-
-if (insubroutinedeclare == 1)
-{
-parcours = listdecl;
-while (parcours)
-{
-/*
-parcours2 = List_SubroutineArgument_Var;
-out = 0;
-while (parcours2 && out == 0)
-{
-if (!strcasecmp(parcours2->var->v_subroutinename,subroutinename) && !strcasecmp(parcours2->var->v_nomvar,parcours->var->v_nomvar))
- {
- out = 1;
- }
-parcours2 = parcours2->suiv;
-}
-*/
-out = LookingForVariableInList(List_SubroutineArgument_Var,parcours->var);
-if (out == 0) out = VariableIsInListCommon(parcours,List_Common_Var);
-
-
-
-if (out == 0) out = LookingForVariableInList(List_Parameter_Var,parcours->var);
-if (out == 0) out = LookingForVariableInList(List_FunctionType_Var,parcours->var);
-if (out == 0) out = LookingForVariableInListGlobal(List_Global_Var,parcours->var);
-
-/*
-parcours2 = List_Common_Var;
-while (parcours2 && out == 0)
-{
-if (!strcasecmp(parcours2->var->v_commoninfile,mainfile) && !strcasecmp(parcours2->var->v_nomvar,parcours->var->v_nomvar))
- {
- out = 1;
- }
-parcours2 = parcours2->suiv;
-}
-*/
-//printf("nom = %s %d %d %d\n",parcours->var->v_nomvar,out,VariableIsParameter,SaveDeclare);
-if (firstpass == 0 && out == 0 && VariableIsParameter == 0 && SaveDeclare == 0) 
-
-{
-writevardeclaration(parcours,fortranout,1,1);
-}
-//if (firstpass == 1 && out == 1)
-if (firstpass == 1)
-  {
-  if (VariableIsParameter == 0 && SaveDeclare == 0)
-    {
-    List_SubroutineDeclaration_Var = insertvar(List_SubroutineDeclaration_Var,parcours->var);
-    }
-  }
-parcours = parcours->suiv;
-}
-}
+    listvar *parcours;
+    variable *v;
+    int out;
+
+    if ( insubroutinedeclare )
+    {
+        parcours = listdecl;
+        while ( parcours )
+        {
+            v = parcours->var;
+                          out = LookingForVariableInList(List_SubroutineArgument_Var, v);
+            if (out == 0) out = VariableIsInListCommon(parcours, List_Common_Var);
+            if (out == 0) out = LookingForVariableInList(List_Parameter_Var, v);
+            if (out == 0) out = LookingForVariableInList(List_FunctionType_Var, v);
+            if (out == 0) out = LookingForVariableInListGlobal(List_Global_Var, v);
+
+            if (firstpass == 0 && out == 0 && VariableIsParameter == 0 && SaveDeclare == 0)
+            {
+                WriteVarDeclaration(v, fortran_out, 1, 1);
+            }
+            if (firstpass == 1)
+            {
+                if (VariableIsParameter == 0 && SaveDeclare == 0)
+                {
+                    List_SubroutineDeclaration_Var = insertvar(List_SubroutineDeclaration_Var, v);
+                }
+            }
+            parcours = parcours->suiv;
+        }
+    }
 }
 
 void ReWriteDataStatement_0(FILE * filout)
 {
-listvar *parcours;
-int out;
-char ligne[LONG_C];
-char initialvalue[LONG_C];
-
-if (insubroutinedeclare == 1)
-{
-parcours = List_Data_Var_Cur ;
-while (parcours)
-{
-out = VariableIsInListCommon(parcours,List_Common_Var);
-if (out == 0) out = LookingForVariableInListGlobal(List_Global_Var,parcours->var);
-
-if (out == 0)
-{
-if (strncasecmp(parcours->var->v_initialvalue,"(/",2))
-{
-strcpy(initialvalue,parcours->var->v_initialvalue);
-}
-else
-{
-strncpy(initialvalue,&parcours->var->v_initialvalue[2],strlen(parcours->var->v_initialvalue)-4);
-strcpy(&initialvalue[strlen(parcours->var->v_initialvalue)-4],"\0");
-}
-sprintf(ligne,"data %s/%s/",parcours->var->v_nomvar,initialvalue);
-tofich(filout,ligne,1);
-}
-parcours = parcours->suiv;
-}
-}
-}
+    listvar *parcours;
+    int out;
+    char ligne[LONG_M];
+    char initialvalue[LONG_M];
+
+    if (insubroutinedeclare == 1)
+    {
+        parcours = List_Data_Var_Cur ;
+        while (parcours)
+        {
+            out = VariableIsInListCommon(parcours,List_Common_Var);
+            if (out)   break;
+
+            out = LookingForVariableInListGlobal(List_Global_Var,parcours->var);
+            if (out)   break;
+
+            if (strncasecmp(parcours->var->v_initialvalue,"(/",2))
+            {
+                strcpy(initialvalue,parcours->var->v_initialvalue);
+            }
+            else
+            {
+                strncpy(initialvalue,&parcours->var->v_initialvalue[2],strlen(parcours->var->v_initialvalue)-4);
+                strcpy(&initialvalue[strlen(parcours->var->v_initialvalue)-4],"\0");
+            }
+            sprintf(ligne,"data %s/%s/",parcours->var->v_nomvar,initialvalue);
+            tofich(filout,ligne,1);
+
+            parcours = parcours->suiv;
+        }
+    }
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/decl.h
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/decl.h	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/decl.h	(revision 9987)
@@ -33,10 +33,10 @@
 /* version 1.7                                                                */
 /******************************************************************************/
-#define LONGNOM 8000
-
-#define LONG_C 3000
-#define LONG_4C 4000
-#define LONG_4M 4000
-#define LONG_40M 4000000
+#define LONG_VNAME 80		// Max length for a variable name
+#define LONG_FNAME 1000		// Max length for a file name
+#define LONG_C     200
+#define LONG_M     1500
+
+#define NB_CAT_VARIABLES 5
 
 /******************************************************************************/
@@ -46,6 +46,6 @@
 typedef struct
 {
-   char first[LONG_C];
-   char last[LONG_C];
+   char first[LONG_M];
+   char last[LONG_M];
 } typedim ;                /* fortran dimension as 'ndeb:nfin'                */
 
@@ -58,18 +58,18 @@
 typedef struct variable
 {
-   char v_typevar[LONG_C];
-   char v_nomvar[LONG_C] ;
-   char v_oldname[LONG_C] ;
-   char v_dimchar[LONG_C];
-   char v_modulename[LONG_C];
-   char v_commonname[LONG_C];
-   char v_vallengspec[LONG_C];
-   char v_nameinttypename[LONG_C];
-   char v_commoninfile[LONG_C];
-   char v_subroutinename[LONG_C];
+   char v_typevar[LONG_VNAME];
+   char v_nomvar[LONG_VNAME] ;
+   char v_oldname[LONG_VNAME] ;
+   char v_dimchar[LONG_VNAME];
+   char v_modulename[LONG_VNAME];
+   char v_commonname[LONG_VNAME];
+   char v_vallengspec[LONG_VNAME];
+   char v_nameinttypename[LONG_VNAME];
+   char v_commoninfile[LONG_FNAME];
+   char v_subroutinename[LONG_VNAME];
    char v_precision[LONG_C];
-   char v_initialvalue[LONG_4C];
-   char v_IntentSpec[LONG_C];
-   char v_readedlistdimension[LONG_C];
+   char v_initialvalue[LONG_M];
+   char v_IntentSpec[LONG_M];
+   char v_readedlistdimension[LONG_M];
    int  v_nbdim;
    int  v_common;
@@ -77,4 +77,5 @@
    int  v_module;
    int  v_save;
+   int  v_catvar;
    int  v_VariableIsParameter;
    int  v_PublicDeclare;
@@ -110,8 +111,8 @@
 typedef struct listusemodule
 {
-   char u_usemodule[LONG_C];
-   char u_charusemodule[LONG_C];
-   char u_cursubroutine[LONG_C];
-   char u_modulename[LONG_C];
+   char u_usemodule[LONG_VNAME];
+   char u_charusemodule[LONG_VNAME];
+   char u_cursubroutine[LONG_VNAME];
+   char u_modulename[LONG_VNAME];
    int  u_firstuse;
    struct listusemodule * suiv;
@@ -120,6 +121,6 @@
 typedef struct listparameter
 {
-   char p_name[LONG_C];
-   char p_modulename[LONG_C];
+   char p_name[LONG_M];
+   char p_modulename[LONG_M];
    struct listparameter * suiv;
 } listparameter ;           /* list of names                                  */
@@ -127,5 +128,5 @@
 typedef struct listname
 {
-   char n_name[LONG_C];
+   char n_name[LONG_VNAME];
    struct  listname* suiv;
 } listname ;            /* list of names                                  */
@@ -133,6 +134,6 @@
 typedef struct listcouple
 {
-   char c_namevar[LONG_C];
-   char c_namepointedvar[LONG_C];
+   char c_namevar[LONG_VNAME];
+   char c_namepointedvar[LONG_VNAME];
    struct listcouple * suiv;
 } listcouple;              /* list of names                                   */
@@ -142,6 +143,6 @@
 {
    char o_nom[LONG_C];
-   char o_module[LONG_C];
-   char o_subroutinename[LONG_C];
+   char o_module[LONG_VNAME];
+   char o_subroutinename[LONG_M];
    int  o_val;
    listcouple *couple;
@@ -153,6 +154,6 @@
 {
    char a_nomvar[LONG_C];
-   char a_subroutine[LONG_C];
-   char a_module[LONG_C];
+   char a_subroutine[LONG_VNAME];
+   char a_module[LONG_VNAME];
    struct listallocate * suiv;
 } listallocate ;
@@ -161,6 +162,6 @@
 typedef struct listvarpointtovar
 {
-   char t_usemodule[LONG_C];
-   char t_cursubroutine[LONG_C];
+   char t_usemodule[LONG_VNAME];
+   char t_cursubroutine[LONG_VNAME];
    listcouple *t_couple;
    struct  listvarpointtovar* suiv;
@@ -209,4 +210,5 @@
  listnom *List_Subroutine_For_Alloc;
  listnom *listofmodules;
+ listnom *listofkind;
  listnom *List_NameOfModule;
  listnom *List_NameOfCommon;
@@ -220,4 +222,5 @@
  listindice *Listofavailableindices;
                            /* List of available indices in the tabvars table  */
+ listindice **Listofavailableindices_glob;
 
  listdim *curdim;
@@ -229,6 +232,6 @@
 
  int positioninblock;
- char commonvar[LONG_C];
- char commonblockname[LONG_C];
+ char commonvar[LONG_VNAME];
+ char commonblockname[LONG_VNAME];
 
 /******************************************************************************/
@@ -239,14 +242,14 @@
  int sameagrifargument;
  int InAgrifParentDef;
- char sameagrifname[LONG_C];
+ char sameagrifname[LONG_VNAME];
 /******************************************************************************/
 /****************   *** VAR DEF Variables ***   *******************************/
 /******************************************************************************/
- int indicemaxtabvars;     /* Number of variables in the model i.e. last      */
+ int indicemaxtabvars[NB_CAT_VARIABLES];     /* Number of variables in the model i.e. last      */
                            /*    indice used in  the tabvars table            */
  int PublicDeclare;        /* Variable has been declared as PUBLIC */
  int PrivateDeclare;       /* Variable has been declared as PRIVATE */
  int ExternalDeclare;      /* Variable has been declared as EXTERNAL */
- char InitialValueGiven[LONG_C];  
+ int InitialValueGiven;    /* An initial value has been given */
  int Allocatabledeclare;
  int Targetdeclare;
@@ -255,24 +258,21 @@
  int pointerdeclare;
  int optionaldeclare;
- int VarType;
- int VarTypepar;
+ int inside_type_declare;
  int VariableIsParameter;
  int dimsgiven;
  int shouldincludempif;
  int c_star;
- char DeclType[LONG_C];
- char nameinttypename[LONG_C];
- char nameinttypenameback[LONG_C]; 
+ char DeclType[LONG_VNAME];
+ char nameinttypename[LONG_VNAME];
+ char nameinttypenameback[LONG_VNAME];
  int GlobalDeclaration;
  int GlobalDeclarationType;
- char InitValue[LONG_4C];
- char IntentSpec[LONG_C];
+ char InitValue[LONG_M];
+ char IntentSpec[LONG_M];
  char NamePrecision[LONG_C];
- char CharacterSize[LONG_C];
- char curmodulename[LONG_C];
- char vallengspec[LONG_C];
- char subroutinename[LONG_C];
+ char CharacterSize[LONG_VNAME];
+ char vallengspec[LONG_VNAME];
  int isrecursive;
- char previoussubroutinename[LONG_C];
+ int is_result_present;
 
 /******************************************************************************/
@@ -283,10 +283,8 @@
  int onlyfixedgrids;       /* = 1 if onlyfixedgrids is true                   */
  int todebug;
- int mark;
- int todebugfree;
  int fixedgrids;           /* = 1 if fixedgrids is true                       */
- char nbmaillesX[LONG_C]; /* number of cells in the x direction              */
- char nbmaillesY[LONG_C]; /* number of cells in the y direction              */
- char nbmaillesZ[LONG_C]; /* number of cells in the z direction              */
+ char nbmaillesX[LONG_VNAME];	// number of cells in the x direction
+ char nbmaillesY[LONG_VNAME];	// number of cells in the y direction
+ char nbmaillesZ[LONG_VNAME];	// number of cells in the z direction
  int IndicenbmaillesX;
  int IndicenbmaillesY;
@@ -297,9 +295,7 @@
  int aftercontainsdeclare; /* Signale si l'on vient d'un contains ou non */
  int retour77;
- int colnum;
  int callagrifinitgrids;
  int callmpiinit;
  int firstpass;
- int couldaddvariable;
  int pointedvar;
  int NbMailleXDefined;
@@ -309,7 +305,6 @@
                            /*    only                                         */
                            /*    scalar and not table u(1,1,1) in place of u  */
- int checkexistcommon;
+ int inprogramdeclare;
  int insubroutinedeclare;
- int ininterfacedeclare;
  int inmoduledeclare;
  int dimsempty;
@@ -317,32 +312,26 @@
  int incontainssubroutine;
 
- char meetagrifinitgrids[LONG_C];
- char mpiinitvar[LONG_C];
- char *NameTamponfile;
- char toprintglob[LONG_4C];
- char tmpvargridname[LONG_4C];
- char EmptyChar[2];        /* An empty char */
- char curfilename[LONG_C];
- char nomfileoutput[LONG_C];
- char curbuf[LONG_40M];
- char motparse[LONG_4C];
- char motparse1[LONG_4C];
- char charusemodule[LONG_C];
- char subofagrifinitgrids[LONG_C];
- char curfile[LONG_C];
- char mainfile[LONG_C];
- char nomdir[LONG_C];
- char commondirout[LONG_C];
- char commondirin[LONG_C];
- char filetoparse[LONG_C];
-
- FILE *fortranout;          /* Output File                                    */
- FILE *fortranin;           /* Input File                                     */
- FILE *oldfortranout;
+ char meetagrifinitgrids[LONG_M];
+ char mpiinitvar[LONG_M];
+ char toprintglob[LONG_M];
+ char tmpvargridname[LONG_M];
+ char dependfilename[LONG_FNAME];
+ char charusemodule[LONG_VNAME];
+ char subofagrifinitgrids[LONG_M];
+ char curmodulename[LONG_VNAME];
+ char subroutinename[LONG_VNAME];
+ char cur_filename[LONG_FNAME];		// Name of the current parsed Fortran file
+ char config_file[LONG_FNAME];		// Name of conv configuration file (ex: amr.in)
+ char work_dir[LONG_FNAME];			// Work directory         (default: './')
+ char include_dir[LONG_FNAME];		// Include directory      (default: './AGRIF_INC')
+ char output_dir[LONG_FNAME];		// output directory       (default: './AGRIF_MODELFILES')
+ char input_dir[LONG_FNAME];		// source input directory (default: './')
+
+ FILE *fortran_out;          /* Output File                                    */
+ FILE *fortran_in;           /* Input File                                     */
+ FILE *oldfortran_out;
  FILE *subloop;
  FILE *module_declar;
- FILE *module_declar_type;
  FILE *allocationagrif;
- FILE *paramout;
 
  long int pos_cur;         /* current position in the output file             */
@@ -359,5 +348,4 @@
  long int pos_cursave;     /* current position in the output file             */
  long int pos_curdimension;/* current position in the output file             */
- long int pos_curinit;     /* current position in the output file             */
  long int pos_curinclude;  /* final position of a line in file                */
  long int pos_end;         /* final position of a line in file                */
@@ -365,80 +353,23 @@
                            /* final position of a line in file                */
 
-/* v_oldname = v_nomvar; */
-/* commonvar = v_nomvar; */
-/* commonblockname = v_commonname;*/
-/* sameagrifname = v_nomvar ; */
-/* DeclType = v_typevar; */
-/* nameinttypename = v_nameinttypename; */
-/* IntentSpec = v_IntentSpec; */
-/* NamePrecision = v_precision; */
-/* CharacterSize = v_dimchar; */
-/* curmodulename = v_modulename; */
-/* vallengspec = v_vallengspec; */
-/* subroutinename = v_subroutinename; */
-/* meetagrifinitgrids = v_subroutinename; */
-/* nbmaillesX = v_nomvar; */
-/* nbmaillesY = v_nomvar; */
-/* nbmaillesZ = v_nomvar; */
-/* mpiinitvar = v_nomvar; */
-/* EmptyChar = 2; */
-/* motparse1 = motparse;*/
-/* charusemodule = p_modulename; */
-/* subofagrifinitgrids = v_subroutinename; */
-/* curfile = mainfile; */
-/* InitValue = v_initialvalue; */
-
-/* p_name;???????? */
-/* p_modulename; ?????????????*/
-
- int length_last;
- int length_first;
- int length_v_typevar;
- int length_v_nomvar;
- int length_v_dimchar;
- int length_v_modulename;
- int length_v_commonname;
- int length_v_vallengspec;
- int length_v_nameinttypename;
- int length_v_commoninfile;
- int length_v_subroutinename;
- int length_v_precision;
- int length_v_IntentSpec;
- int length_v_initialvalue;
- int length_v_readedlistdimension;
- int length_u_usemodule;
- int length_u_charusemodule;
- int length_u_cursubroutine;
- int length_u_modulename;
- int length_n_name;
- int length_c_namevar;
- int length_c_namepointedvar;
- int length_o_nom;
- int length_o_module;
- int length_a_nomvar;
- int length_a_subroutine;
- int length_a_module;
- int length_t_usemodule;
- int length_t_cursubroutine;
- int length_curfilename;
- int length_nomfileoutput;
- int length_motparse;
- int length_mainfile;
- int length_nomdir;
- int length_commondirout;
- int length_commondirin;
- int length_filetoparse;
- int length_curbuf;
- int length_toprintglob;
- int length_tmpvargridname;
- int length_ligne_Subloop;
- int length_lvargridname_toamr;
- int length_toprint_utilagrif;
- int length_toprinttmp_utilchar;
- int length_ligne_writedecl;
- int length_newname_toamr;
- int length_newname_writedecl;
- int length_ligne_toamr;
- int length_tmpligne_writedecl;
+size_t length_last;
+size_t length_first;
+size_t length_v_vallengspec;
+size_t length_v_commoninfile;
+size_t length_v_precision;
+size_t length_v_IntentSpec;
+size_t length_v_initialvalue;
+size_t length_v_readedlistdimension;
+size_t length_a_nomvar;
+size_t length_toprintglob;
+size_t length_tmpvargridname;
+size_t length_ligne_Subloop;
+size_t length_toprint_utilagrif;
+size_t length_toprinttmp_utilchar;
+size_t length_ligne_writedecl;
+size_t length_newname_toamr;
+size_t length_newname_writedecl;
+size_t length_ligne_toamr;
+size_t length_tmpligne_writedecl;
  int value_char_size;
  int value_char_size1;
@@ -446,5 +377,5 @@
  int value_char_size3;
 
- 
+
  int inallocate;
  int infixed;
@@ -453,12 +384,15 @@
 /*********** Declaration of externals subroutines *****************************/
 /***************************************************** ************************/
+extern char *fortran_text;
 /******************************************************************************/
 /*********** convert.y ********************************************************/
 /******************************************************************************/
 extern int main(int argc,char *argv[]);
+extern int convert_error(const char *s);
 /******************************************************************************/
 /*********** fortran.y ********************************************************/
 /******************************************************************************/
-extern void processfortran(char *fichier_entree);
+extern void process_fortran(const char *input_file);
+extern int fortran_error(const char *s);
 /******************************************************************************/
 /*********** dependfile.c *****************************************************/
@@ -466,17 +400,15 @@
 extern void Writethedependnbxnbyfile();
 extern void Readthedependnbxnbyfile();
-extern void Writethedependlistofmoduleused(char *NameTampon );
-extern void Readthedependlistofmoduleused(char *NameTampon);
-extern void WritedependParameterList(char *NameTampon );
-extern listparameter *ReaddependParameterList(char *NameTampon,
-                                                        listparameter *listout);
-extern void Writethedependfile(char *NameTampon, listvar *input );
-extern listvar *Readthedependfile( char *NameTampon , listvar *listout);
+extern void Writethedependlistofmoduleused(const char *NameTampon );
+extern void Readthedependlistofmoduleused(const char *NameTampon);
+extern void WritedependParameterList(const char *NameTampon );
+extern listparameter *ReaddependParameterList(const char *NameTampon, listparameter *listout);
+extern void Writethedependfile(const char *NameTampon, listvar *input );
+extern listvar *Readthedependfile(const char *NameTampon , listvar *listout);
 extern void Write_Subroutine_For_Alloc();
 extern void Read_Subroutine_For_Alloc();
 extern void Writethedependavailablefile();
 extern void Readthedependavailablefile();
-extern int Did_filetoparse_readed(char *NameTampon);
-extern int Did_module_common_treaded(char *NameTampon);
+extern int is_dependfile_created(const char *NameTampon);
 extern void Write_val_max();
 extern void Read_val_max();
@@ -485,23 +417,23 @@
 /******************************************************************************/
 extern void Add_Common_var_1();
-extern listnom *Addtolistnom(char *nom, listnom *listin,int value);
-extern listname *Addtolistname(char *nom,listname *input);
-extern int ModuleIsDefineInInputFile(char *name);
-extern void Addmoduletothelisttmp(char *name);
-extern void Add_NameOfModule_1(char *nom);
-extern void Add_NameOfCommon_1(char *nom,char *cursubroutinename);
-extern void Add_CouplePointed_Var_1(char *namemodule,listcouple *couple);
-extern void Add_Include_1(char *name);
+extern listnom  *Addtolistnom(const char *nom, listnom *listin, int value);
+extern listname *Addtolistname(const char *nom, listname *input);
+extern int ModuleIsDefineInInputFile(const char *name);
+extern void Addmoduletothelisttmp(const char *name);
+extern void Add_NameOfModule_1(const char *nom);
+extern void Add_NameOfCommon_1(const char *nom, const char *cursubroutinename);
+extern void Add_CouplePointed_Var_1(const char *namemodule, listcouple *couple);
+extern void Add_Include_1(const char *name);
 extern void Add_ImplicitNoneSubroutine_1();
-extern void WriteIncludeDeclaration();
-extern void Add_Save_Var_1 (char *name,listdim *d);
+extern void WriteIncludeDeclaration(FILE* tofile);
+extern void Add_Save_Var_1 (const char *name,listdim *d);
 extern void Add_Save_Var_dcl_1 (listvar *var);
 /******************************************************************************/
 /*********** SubLoopCreation.c ************************************************/
 /******************************************************************************/
-extern void writeheadnewsub_0();
-extern void WriteVariablelist_subloop(FILE *outputfile,char *ligne);
-extern void WriteVariablelist_subloop_Call(FILE *outputfile,char *ligne);
-extern void WriteVariablelist_subloop_Def(FILE *outputfile,char *ligne);
+extern void WriteBeginof_SubLoop();
+extern void WriteVariablelist_subloop(char *ligne);
+extern void WriteVariablelist_subloop_Call(char **ligne, size_t line_length);
+extern void WriteVariablelist_subloop_Def(char *ligne);
 extern void WriteHeadofSubroutineLoop();
 extern void closeandcallsubloopandincludeit_0(int suborfun);
@@ -510,82 +442,70 @@
 /*********** toamr.c **********************************************************/
 /******************************************************************************/
-extern char *variablenameroottabvars (variable * var);
-extern char *variablenametabvars (variable * var, int iorindice);
-extern char *variablecurgridtabvars (variable * var,int ParentOrCurgrid);
-extern void WARNING_CharSize(variable *var);
-extern char *vargridnametabvars (variable * var,int iorindice);
-extern char *vargridcurgridtabvars (variable * var,int ParentOrCurgrid);
-extern char *vargridcurgridtabvarswithoutAgrif_Gr (variable * var);
-extern char *vargridparam (variable * v, int whichone);
+extern void WARNING_CharSize(const variable *var);
+extern const char * tabvarsname(const variable *var);
+extern const char * variablecurgridtabvars(int which_grid);
+extern const char * vargridnametabvars(const variable *var, int iorindice);
+extern const char * vargridcurgridtabvars(const variable *var, int which_grid);
+extern const char * vargridcurgridtabvarswithoutAgrif_Gr(const variable *var);
+extern const char * vargridparam(const variable *var);
 extern void write_probdimagrif_file();
 extern void write_keysagrif_file();
 extern void write_modtypeagrif_file();
-extern void write_createvarnameagrif_file(variable *v,FILE *createvarname,
-                                                                int *InitEmpty);
+extern void write_createvarnameagrif_file(variable *v,FILE *createvarname,int *InitEmpty);
+extern void write_initialisationsagrif_file(variable *v,FILE *initproc,int *VarnameEmpty);
 extern void write_Setnumberofcells_file();
 extern void write_Getnumberofcells_file();
-extern void write_initialisationsagrif_file(variable *v,FILE *initproc,
-                                                             int *VarnameEmpty);
 extern void Write_Alloc_Agrif_Files();
 extern int IndiceInlist(int indic, listindice *listin);
 extern void write_allocation_Common_0();
 extern void write_allocation_Global_0();
-extern void creefichieramr (char *NameTampon);
+extern void creefichieramr();
 /******************************************************************************/
 /*********** UtilAgrif.c ******************************************************/
 /******************************************************************************/
-extern int Vartonumber(char *tokname);
-extern int Agrif_in_Tok_NAME(char *tokname);
-extern void ModifyTheVariableName_0(char *ident,int lengthname);
-extern void Add_SubroutineWhereAgrifUsed_1(char *sub,char *mod);
+extern int Vartonumber(const char *tokname);
+extern int Agrif_in_Tok_NAME(const char *tokname);
+extern void ModifyTheVariableName_0(const char *ident,int lengthname);
+extern void Add_SubroutineWhereAgrifUsed_1(const char *sub, const char *mod);
 extern void AddUseAgrifUtil_0(FILE *fileout);
 extern void AddUseAgrifUtilBeforeCall_0(FILE *fileout);
-extern void NotifyAgrifFunction_0(char *ident);
-extern void ModifyTheAgrifFunction_0(char *ident);
-extern void AgriffunctionModify_0(char *ident,int whichone);
-extern void Instanciation_0(char *ident);
+extern void NotifyAgrifFunction_0(const char *ident);
+extern void ModifyTheAgrifFunction_0(const char *ident);
+extern void AgriffunctionModify_0(const char *ident,int whichone);
+extern void Instanciation_0(const char *ident);
 /******************************************************************************/
 /*********** UtilCharacter.c **************************************************/
 /******************************************************************************/
-extern void FindAndChangeNameToTabvars(char name[LONG_C],char toprint[LONG_4C],
+extern void FindAndChangeNameToTabvars(const char name[LONG_M],char toprint[LONG_M],
                                              listvar * listtosee, int whichone);
-extern char *ChangeTheInitalvaluebyTabvarsName(char *nom,listvar *listtoread,
-                                                                  int whichone);
-extern int IsVariableReal(char *nom);
-extern void IsVarInUseFile(char *nom);
-extern listnom *DecomposeTheNameinlistnom(char *nom, listnom * listout);
-extern void DecomposeTheName(char *nom);
-extern void convert2lower(char *name);
-extern int convert2int(char *name);
+extern const char *ChangeTheInitalvaluebyTabvarsName(const char *nom,listvar *listtoread);
+extern int IsVariableReal(const char *nom);
+extern void IsVarInUseFile(const char *nom);
+extern listnom *DecomposeTheNameinlistnom(const char *nom, listnom * listout);
+extern void DecomposeTheName(const char *nom);
+extern void convert2lower(char *lowername, const char* inputname);
+extern int convert2int(const char *name);
 /******************************************************************************/
 /*********** UtilFile.c *******************************************************/
 /******************************************************************************/
-extern FILE * associate (char *filename);
-extern FILE * associateaplus (char *filename);
+extern FILE * open_for_write (const char *filename);
+extern FILE * open_for_append (const char *filename);
 extern long int setposcur();
 extern long int setposcurname(FILE *fileout);
-extern long int setposcurinoldfortranout();
-extern void copyuse_0(char *namemodule);
-extern void copyuseonly_0(char *namemodule);
+extern void copyuse_0(const char *namemodule);
+extern void copyuseonly_0(const char *namemodule);
 /******************************************************************************/
 /*********** UtilFortran.c ****************************************************/
 /******************************************************************************/
-extern void initdimprob(int dimprobmod, char * nx, char * ny,char* nz);
-extern int Variableshouldberemove(char *nom);
+extern void initdimprob(int dimprobmod, const char *nx, const char *ny, const char *nz);
+extern int Variableshouldberemoved(const char *nom);
 extern int variableisglobal(listvar *curvar, listvar *listin);
 extern int VariableIsInListCommon(listvar *curvar,listvar *listin);
 extern int VariableIsInList(listvar *curvar,listvar *listin);
-extern void variableisglobalinmodule(listcouple *listin, char *module,
+extern void variableisglobalinmodule(listcouple *listin, const char *module,
                                                                  FILE *fileout,long int oldposcuruse);
-extern void Remove_Word_Contains_0();
-extern void Remove_Word_end_module_0(int modulenamelength);
-extern void Write_Word_Contains_0();
 extern void Write_Word_end_module_0();
-extern void Add_Subroutine_For_Alloc(char *nom);
-extern void Write_Alloc_Subroutine_0();
-extern void Write_Alloc_Subroutine_For_End_0();
-extern void Write_GlobalParameter_Declaration_0();
-extern void Write_GlobalType_Declaration_0();
-extern void Write_NotGridDepend_Declaration_0();
+extern void Add_Subroutine_For_Alloc(const char *nom);
+extern void Write_Closing_Module();
 extern int IsTabvarsUseInArgument_0();
 extern int ImplicitNoneInSubroutine();
@@ -593,29 +513,31 @@
 extern void Add_Pointer_Var_1(char *nom);
 extern int varispointer_0(char *ident);
-extern int VariableIsNotFunction(char *ident);
+extern int VariableIsFunction(const char *ident);
 extern int varistyped_0(char *ident);
+extern void dump_var(const variable* var);
 /******************************************************************************/
 /*********** UtilListe.c ******************************************************/
 /******************************************************************************/
 extern void Init_Variable(variable *var);
-extern listvar * AddListvarToListvar(listvar *l,listvar *glob,
-                                                            int ValueFirstpass);
-extern void CreateAndFillin_Curvar(char *type,variable *curvar);
-extern void duplicatelistvar(listvar *orig);
+extern listvar * AddListvarToListvar(listvar *l,listvar *glob, int ValueFirstpass);
+extern void CreateAndFillin_Curvar(const char *type, variable *curvar);
+// extern void duplicatelistvar(listvar *orig);
 extern listdim * insertdim(listdim *lin,typedim nom);
 extern void change_dim_char(listdim *lin,listvar * l);
-extern int num_dims(listdim *d);
-extern variable * createvar(char *nom,listdim *d);
+extern int get_num_dims(const listdim *d);
+extern variable * createvar(const char *nom, listdim *d);
 extern listvar * insertvar(listvar *lin,variable *v);
-extern listvar *settype(char *nom,listvar *lin);
+extern listvar * settype(const char *nom,listvar *lin);
 extern void printliste(listvar * lin);
 extern int IsinListe(listvar *lin,char *nom);
 extern listname *Insertname(listname *lin,char *nom,int sens);
 extern listname *concat_listname(listname *l1, listname *l2);
-extern void *createstringfromlistname(char *ligne, listname *lin);
+extern void createstringfromlistname(char *ligne, listname *lin);
 extern void printname(listname * lin);
 extern void removeglobfromlist(listname **lin);
 extern void writelistpublic(listname *lin);
 extern void Init_List_Data_Var();
+extern void  addprecision_derivedfromkind(variable *curvar);
+extern int get_cat_var(variable *var);
 /******************************************************************************/
 /*********** UtilNotGridDep.c *************************************************/
@@ -626,7 +548,6 @@
 /*********** WorkWithAllocatelist.c *******************************************/
 /******************************************************************************/
-extern void Add_Allocate_Var_1(char *nom,char *nommodule);
-extern int IsVarAllocatable_0(char *ident);
-extern int varisallocatable_0(char *ident);
+extern void Add_Allocate_Var_1(const char *nom, const char *nommodule);
+extern int IsVarAllocatable_0(const char *ident);
 /******************************************************************************/
 /*********** WorkWithglobliste.c **********************************************/
@@ -643,5 +564,5 @@
 /*********** WorkWithlistmoduleinfile.c ***************************************/
 /******************************************************************************/
-extern void Save_Length(char *nom, int whichone);
+extern void Save_Length(const char *nom, int whichone);
 extern void Save_Length_int(int val, int whichone);
 /******************************************************************************/
@@ -651,14 +572,14 @@
 extern void  RecordUseModulesUseModulesVariables();
 extern void Add_NameOfModuleUsed_1(char *name);
-extern void Addmoduletothelist(char *name);
-extern void WriteUsemoduleDeclaration(char *cursubroutinename);
+extern void Addmoduletothelist(const char *name);
+extern void WriteUsemoduleDeclaration(const char *cursubroutinename);
 /******************************************************************************/
 /*********** WorkWithlistvarindoloop.c ****************************************/
 /******************************************************************************/
-extern void Add_UsedInSubroutine_Var_1 (char *ident);
+extern void Add_UsedInSubroutine_Var_1 (const char *ident);
 extern void ajoutevarindoloop_definedimension (char *name);
 extern void  ModifyThelistvarindoloop();
 extern void  CompleteThelistvarindoloop();
-extern void CopyRecord(variable *var1,variable *var2);
+extern void Merge_Variables(variable *var1,variable *var2);
 extern void Update_List_Subroutine_Var(listvar *list_to_modify);
 extern void Update_List_Global_Var_From_List_Save_Var();
@@ -669,10 +590,11 @@
 extern int LookingForVariableInList(listvar *listin,variable *var);
 extern int LookingForVariableInListGlobal(listvar *listin,variable *var);
-extern int LookingForVariableInListName(listvar *listin,char *var);
+extern int LookingForVariableInListName(listvar *listin,const char *var);
 extern int LookingForVariableInListGlob(listvar *listin,variable *var);
-extern int LookingForVariableInListParamGlob(listparameter *listin,
-                                                                 variable *var);
+extern int LookingForVariableInListParamGlob(listparameter *listin, variable *var);
+extern variable *get_variable_in_list_from_name(listvar *listin, const char *name);
 extern void UpdateListDeclarationWithDimensionList();
 extern void Clean_List_UsedInSubroutine_Var();
+extern void Clean_List_ModuleUsed_Var();
 extern void Clean_List_SubroutineDeclaration_Var();
 extern void Clean_List_Global_Var();
@@ -692,6 +614,7 @@
 extern void UpdateList_SubroutineWhereAgrifUsed();
 extern void UpdateList_UsedInSubroutine_With_dimension();
-extern void Affiche();
+extern void Affiche(listvar *parcours);
 extern int SubInList_ContainsSubroutine();
+extern void update_indicemaxtabvars(variable *var,listindice **Listofindices);
 /******************************************************************************/
 /*********** WorkWithParameterlist.c ******************************************/
@@ -704,25 +627,22 @@
 /******************************************************************************/
 extern void Add_SubroutineArgument_Var_1(listvar *listtoadd);
-extern void Add_FunctionType_Var_1(char *nom);
-extern void Add_SubroutineDeclaration_Var_1 (listvar *listtoadd);
+extern void Add_FunctionType_Var_1(const char *nom);
+// extern void Add_SubroutineDeclaration_Var_1 (listvar *listtoadd);
 /******************************************************************************/
 /*********** Writedeclarations.c **********************************************/
 /******************************************************************************/
-extern void WriteBeginDeclaration(variable *v,char ligne[LONG_4C],int visibility);
-extern void WriteScalarDeclaration(variable *v,char ligne[LONG_4C]);
-extern void WriteTableDeclaration(variable * v,char ligne[LONG_4C],int tmpok);
-extern void writevardeclaration (listvar * var_record, FILE *fileout,
-                                                                     int value,int visibility);
-extern void WriteLocalParamDeclaration();
-extern void WriteFunctionDeclaration(int value);
+extern void WriteBeginDeclaration(variable *v,char ligne[LONG_M],int visibility);
+extern void WriteScalarDeclaration(variable *v,char ligne[LONG_M]);
+extern void WriteTableDeclaration(variable * v,char ligne[LONG_M],int tmpok);
+extern void WriteVarDeclaration( variable *v, FILE *fileout, int value, int visibility );
+extern void WriteLocalParamDeclaration(FILE* tofile);
+extern void WriteFunctionDeclaration(FILE* tofile, int value);
 extern void WriteSubroutineDeclaration(int value);
 extern void WriteArgumentDeclaration_beforecall();
-extern void WriteArgumentDeclaration_Sort();
-extern listnom *writedeclarationintoamr (listvar * deb_common, FILE *fileout,
-                                       variable *var , char commonname[LONG_C],
-                           listnom *neededparameter, char name_common[LONG_C]);
-extern void writesub_loopdeclaration_scalar (listvar * deb_common,
-                                                                 FILE *fileout);
-extern void writesub_loopdeclaration_tab (listvar * deb_common, FILE *fileout);
+extern void WriteArgumentDeclaration_Sort(FILE* tofile);
+extern listnom * writedeclarationintoamr(listvar *deb_common, FILE *fileout, variable *var,
+						const char *commonname, listnom *neededparameter, const char *name_common);
+extern void writesub_loopdeclaration_scalar(listvar *deb_common, FILE *fileout);
+extern void writesub_loopdeclaration_tab(listvar *deb_common, FILE *fileout);
 extern void ReWriteDeclarationAndAddTosubroutine_01(listvar *listdecl);
 extern void ReWriteDataStatement_0(FILE * filout);
@@ -730,17 +650,13 @@
 /*********** WriteInFile.c ****************************************************/
 /******************************************************************************/
-extern void tofich_reste (FILE * filout, char *s,int returnlineornot);
-extern void tofich (FILE * filout, char *s, int returnlineornot);
+extern void tofich_reste (FILE * filout, const char *s, int do_returnline);
+extern void tofich (FILE * filout, const char *s, int do_returnline);
 extern void tofich_blanc (FILE * filout, int size);
-extern void tofich_line (FILE * filout, int size, int long position);
-extern void RemoveWordSET_0(FILE * filout, long int position,
-                                                         long int sizetoremove);
-extern void RemoveWordCUR_0(FILE * filout, long int position,
-                                                         long int sizetoremove);
+extern void RemoveWordSET_0(FILE * filout, long int position, int sizetoremove);
+extern void RemoveWordCUR_0(FILE * filout, int sizetoremove);
 
 /******************************************************************************/
 /*********** WorkWithlistofcoupled.c **********************************************/
-/******************************************************************************/                                                        
-extern int variscoupled_0(char *ident) ;
-extern char * getcoupledname_0(char *ident);
-extern void ModifyTheVariableNamecoupled_0(char *ident, char* coupledident);
+/******************************************************************************/
+extern int variscoupled_0(const char *ident) ;
+extern const char * getcoupledname_0(const char *ident);
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/dependfile.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/dependfile.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/dependfile.c	(revision 9987)
@@ -74,7 +74,6 @@
   int out;
 
-  /* We are looking for all the variable of the current filetoparse file      */
-  /*    in the List_Global_Var                                                */
-  parcours =List_Global_Var;
+  // We look in 'List_Global_Var' for all the variables of the current file to parse
+  parcours = List_Global_Var;
   out = 0;
   while (parcours && out == 0 )
@@ -96,5 +95,7 @@
   {
      NbMailleXDefined = 1;
-     dependfileoutput = fopen(".dependnbxnby","w");
+     sprintf(dependfilename, "%s/.dependnbxnby", work_dir);
+     dependfileoutput = fopen(dependfilename, "w");
+
      fprintf(dependfileoutput,"%d\n",parcours->var->v_indicetabvars);
      IndicenbmaillesX = parcours->var->v_indicetabvars;
@@ -169,13 +170,14 @@
 void Readthedependnbxnbyfile()
 {
-  FILE *dependfileoutput;
-
-  if ((dependfileoutput = fopen(".dependnbxnby","r"))!=NULL)
-  {
-     fscanf(dependfileoutput,"%d\n",&IndicenbmaillesX);
-     if ( dimprob > 1 ) fscanf(dependfileoutput,"%d\n",&IndicenbmaillesY);
-     if ( dimprob > 2 ) fscanf(dependfileoutput,"%d\n",&IndicenbmaillesZ);
-     fclose(dependfileoutput);
-  }
+    FILE *dependfileoutput;
+
+    sprintf(dependfilename, "%s/.dependnbxnby", work_dir);
+    if ((dependfileoutput = fopen(dependfilename, "r"))!=NULL)
+    {
+        fscanf(dependfileoutput,"%d\n",&IndicenbmaillesX);
+        if ( dimprob > 1 ) fscanf(dependfileoutput,"%d\n",&IndicenbmaillesY);
+        if ( dimprob > 2 ) fscanf(dependfileoutput,"%d\n",&IndicenbmaillesZ);
+        fclose(dependfileoutput);
+    }
 }
 
@@ -192,27 +194,102 @@
 /*                                                                            */
 /******************************************************************************/
-void Writethedependlistofmoduleused(char *NameTampon )
+void Writethedependlistofmoduleused(const char *NameTampon )
+{
+    FILE *dependfileoutput;
+    listusemodule *parcours;
+    char lowername[LONG_VNAME];
+
+    if ( ! List_NameOfModuleUsed ) return;
+
+    convert2lower(lowername, NameTampon);
+    sprintf(dependfilename, "%s/.depend_use%s", work_dir, lowername);
+    dependfileoutput = fopen(dependfilename, "w");
+
+    parcours = List_NameOfModuleUsed;
+    while (parcours)
+    {
+    if ( !strcasecmp(lowername,parcours->u_modulename) &&
+         !strcasecmp(parcours->u_cursubroutine,"") )
+    {
+        // We look in 'List_NameOfModuleUsed' for all the variables of the current file to parse
+        fprintf(dependfileoutput,"%s\n",parcours->u_usemodule);
+    }
+    parcours = parcours->suiv;
+    }
+    fclose(dependfileoutput);
+}
+
+/******************************************************************************/
+/*                    Readthedependlistofmoduleused                           */
+/******************************************************************************/
+/* This subroutine is used to create the .dependuse<module>                   */
+/******************************************************************************/
+/*                                                                            */
+/*               .dependuse<name>                                             */
+/*                                                                            */
+/*               mod1                                                         */
+/*               mod2                                                         */
+/*                                                                            */
+/******************************************************************************/
+void Readthedependlistofmoduleused(const char *NameTampon)
 {
   FILE *dependfileoutput;
   listusemodule *parcours;
-  char ligne[LONG_C];
-
-
-  if ( List_NameOfModuleUsed )
-  {
-     convert2lower(NameTampon);
-     sprintf(ligne,".dependuse%s",NameTampon);
-     dependfileoutput = fopen(ligne,"w");
-     /*                                                                       */
-     parcours = List_NameOfModuleUsed;
+  char lowername[LONG_VNAME];
+
+  tmpuselocallist = (listusemodule *)NULL;
+
+  convert2lower(lowername, NameTampon);
+  sprintf(dependfilename, "%s/.depend_use%s", work_dir, lowername);
+
+  if ((dependfileoutput = fopen(dependfilename, "r"))!=NULL)
+  {
+    /* if the file exist we should verify that this file has changed          */
+      while (!feof(dependfileoutput))
+      {
+         parcours=(listusemodule *)calloc(1,sizeof(listusemodule));
+         fscanf(dependfileoutput,"%s\n",parcours->u_usemodule);
+
+         parcours->suiv = tmpuselocallist;
+         tmpuselocallist = parcours;
+
+         parcours = NULL;
+      }
+      fclose(dependfileoutput);
+  }
+}
+
+
+/******************************************************************************/
+/*                        WritedependParameterList                            */
+/******************************************************************************/
+/* This subroutine is used to create the .dependparameter<name>               */
+/******************************************************************************/
+/*                                                                            */
+/*               .dependparameter<name>                                       */
+/*                                                                            */
+/*               mod1                                                         */
+/*               mod2                                                         */
+/*                                                                            */
+/******************************************************************************/
+void WritedependParameterList(const char *NameTampon )
+{
+  FILE *dependfileoutput;
+  listvar *parcours;
+  char lowername[LONG_VNAME];
+
+  if ( List_GlobalParameter_Var )
+  {
+     convert2lower(lowername, NameTampon);
+     sprintf(dependfilename, "%s/.depend_paramater_%s", work_dir, lowername);
+
+     dependfileoutput = fopen(dependfilename, "w");
+     parcours = List_GlobalParameter_Var;
      while (parcours)
      {
-        if ( !strcasecmp(NameTampon,parcours->u_modulename) &&
-             !strcasecmp(parcours->u_cursubroutine,"")
-           )
-        {
-           /* We are looking for all the variable of the current              */
-           /*    filetoparse file in the List_Global_Var                      */
-           fprintf(dependfileoutput,"%s\n",parcours->u_usemodule);
+        if ( !strcasecmp(lowername, parcours->var->v_modulename) )
+        {
+           fprintf(dependfileoutput,"%s\n",parcours->var->v_nomvar);
+           fprintf(dependfileoutput,"%s\n",parcours->var->v_modulename);
         }
         parcours = parcours->suiv;
@@ -222,11 +299,12 @@
 }
 
-/******************************************************************************/
-/*                    Readthedependlistofmoduleused                           */
-/******************************************************************************/
-/* This subroutine is used to create the .dependuse<module>                   */
-/******************************************************************************/
-/*                                                                            */
-/*               .dependuse<name>                                             */
+
+/******************************************************************************/
+/*                         ReaddependParameterList                            */
+/******************************************************************************/
+/* This subroutine is used to create the .dependparameter<name>               */
+/******************************************************************************/
+/*                                                                            */
+/*               .dependparameter<name>                                       */
 /*                                                                            */
 /*               mod1                                                         */
@@ -234,104 +312,19 @@
 /*                                                                            */
 /******************************************************************************/
-void Readthedependlistofmoduleused(char *NameTampon)
+listparameter *ReaddependParameterList(const char *NameTampon,listparameter *listout)
 {
   FILE *dependfileoutput;
-  listusemodule *parcours;
-  char ligne[LONG_C];
-
-  convert2lower(NameTampon);
-  sprintf(ligne,".dependuse%s",NameTampon);
-
-  tmpuselocallist = (listusemodule *)NULL;
-  if ((dependfileoutput = fopen(ligne,"r"))==NULL)
-  {
-  }
-  else
+  listparameter *parcours;
+  char lowername[LONG_VNAME];
+
+  convert2lower(lowername, NameTampon);
+  sprintf(dependfilename, "%s/.depend_paramater_%s", work_dir, lowername);
+
+  if ((dependfileoutput = fopen(dependfilename,"r"))!=NULL)
   {
     /* if the file exist we should verify that this file has changed          */
       while (!feof(dependfileoutput))
       {
-         parcours=(listusemodule *)malloc(sizeof(listusemodule));
-         fscanf(dependfileoutput,"%s\n",parcours->u_usemodule);
-
-         parcours->suiv = tmpuselocallist;
-         tmpuselocallist = parcours;
-
-         parcours = NULL;
-      }
-      fclose(dependfileoutput);
-  }
-}
-
-
-/******************************************************************************/
-/*                        WritedependParameterList                            */
-/******************************************************************************/
-/* This subroutine is used to create the .dependparameter<name>               */
-/******************************************************************************/
-/*                                                                            */
-/*               .dependparameter<name>                                       */
-/*                                                                            */
-/*               mod1                                                         */
-/*               mod2                                                         */
-/*                                                                            */
-/******************************************************************************/
-void WritedependParameterList(char *NameTampon )
-{
-  FILE *dependfileoutput;
-  listvar *parcours;
-  char ligne[LONG_C];
-
-  if ( List_GlobalParameter_Var )
-  {
-     convert2lower(NameTampon);
-     sprintf(ligne,".dependparameter%s",NameTampon);
-     dependfileoutput = fopen(ligne,"w");
-     /*                                                                       */
-     parcours = List_GlobalParameter_Var;
-     while (parcours)
-     {
-        if ( !strcasecmp(NameTampon,parcours->var->v_modulename) )
-        {
-           fprintf(dependfileoutput,"%s\n",parcours->var->v_nomvar);
-           fprintf(dependfileoutput,"%s\n",parcours->var->v_modulename);
-        }
-        parcours = parcours->suiv;
-     }
-     fclose(dependfileoutput);
-  }
-}
-
-
-/******************************************************************************/
-/*                         ReaddependParameterList                            */
-/******************************************************************************/
-/* This subroutine is used to create the .dependparameter<name>               */
-/******************************************************************************/
-/*                                                                            */
-/*               .dependparameter<name>                                       */
-/*                                                                            */
-/*               mod1                                                         */
-/*               mod2                                                         */
-/*                                                                            */
-/******************************************************************************/
-listparameter *ReaddependParameterList(char *NameTampon,listparameter *listout)
-{
-  FILE *dependfileoutput;
-  listparameter *parcours;
-  char ligne[LONG_C];
-
-  convert2lower(NameTampon);
-  sprintf(ligne,".dependparameter%s",NameTampon);
-
-  if ((dependfileoutput = fopen(ligne,"r"))==NULL)
-  {
-  }
-  else
-  {
-    /* if the file exist we should verify that this file has changed          */
-      while (!feof(dependfileoutput))
-      {
-         parcours=(listparameter *)malloc(sizeof(listparameter));
+         parcours=(listparameter *)calloc(1,sizeof(listparameter));
          fscanf(dependfileoutput,"%s\n",parcours->p_name);
          fscanf(dependfileoutput,"%s\n",parcours->p_modulename);
@@ -367,22 +360,22 @@
 /*                                                                            */
 /******************************************************************************/
-void Writethedependfile(char *NameTampon, listvar *input )
+void Writethedependfile(const char *NameTampon, listvar *input )
 {
   FILE *dependfileoutput;
   listvar *parcours;
   listdim *dims;
-  char ligne[LONG_C];
-  char listdimension[LONG_C];
-  char curname[LONG_C];
+  char ligne[LONG_M];
+  char listdimension[LONG_M];
+  char curname[LONG_M];
+  char lowername[LONG_VNAME];
   int out;
 
   if ( input )
   {
-  convert2lower(NameTampon);
-
-  sprintf(ligne,".depend%s",NameTampon);
-  dependfileoutput = fopen(ligne,"w");
-  /* We are looking for all the variable of the current filetoparse file      */
-  /*    in the input                                                          */
+    convert2lower(lowername, NameTampon);
+    sprintf(dependfilename, "%s/.depend_%s", work_dir, lowername);
+
+  dependfileoutput = fopen(dependfilename,"w");
+  // We look in 'input' for all the variables of the current file to parse
   parcours =input;
   out = 0;
@@ -390,6 +383,6 @@
   while (parcours && out == 0 )
   {
-     if ( !strcasecmp(parcours->var->v_modulename,NameTampon) ||
-          !strcasecmp(parcours->var->v_commonname,NameTampon) )
+     if ( !strcasecmp(parcours->var->v_modulename, lowername) ||
+          !strcasecmp(parcours->var->v_commonname, lowername) )
      {
         /*                                                                    */
@@ -402,8 +395,10 @@
            /********** TYPEVAR ************************************************/
            fprintf(dependfileoutput,"%s\n",parcours->var->v_typevar);
+           /********** CATVAR ************************************************/
+           fprintf(dependfileoutput,"%d\n",parcours->var->v_catvar);
            /********** NOMVAR *************************************************/
            fprintf(dependfileoutput,"%s\n",parcours->var->v_nomvar);
            /********** DIMCHAR ************************************************/
-           if ( strcasecmp(parcours->var->v_dimchar,"") )
+           if ( strcasecmp(parcours->var->v_dimchar, "") )
            {
               fprintf(dependfileoutput,"%s\n",parcours->var->v_dimchar);
@@ -479,5 +474,5 @@
            /********** PRIVATE *****************************************/
            fprintf(dependfileoutput,"%d\n",parcours->var->v_PrivateDeclare);
-              
+
            /********** INDICETABVARS ******************************************/
            fprintf(dependfileoutput,"%d\n",parcours->var->v_indicetabvars);
@@ -497,4 +492,5 @@
                  dims = dims->suiv;
               }
+              Save_Length(listdimension,15);
               fprintf(dependfileoutput,"%s\n",listdimension);
            }
@@ -525,19 +521,20 @@
 /*                                                                            */
 /******************************************************************************/
-listvar *Readthedependfile( char *NameTampon , listvar *listout)
-{
-  char ligne[LONG_C];
+listvar *Readthedependfile(const char *NameTampon , listvar *listout)
+{
   FILE *dependfileoutput;
   listvar *parcours0;
   listvar *parcours;
   listvar *parcoursprec;
-  char nothing[LONG_C];
-  int i;
+  char nothing[LONG_M];
+  char lowername[LONG_VNAME];
+  size_t i;
 
   parcoursprec = (listvar *)NULL;
 
-  convert2lower(NameTampon);
-  sprintf(ligne,".depend%s",NameTampon);
-  if ((dependfileoutput = fopen(ligne,"r"))==NULL)
+  convert2lower(lowername, NameTampon);
+  sprintf(dependfilename, "%s/.depend_%s", work_dir, lowername);
+
+  if ((dependfileoutput = fopen(dependfilename, "r"))==NULL)
   {
     /* if the file doesn't exist it means that it is the first time           */
@@ -549,6 +546,6 @@
       while (!feof(dependfileoutput))
       {
-         parcours=(listvar *)malloc(sizeof(listvar));
-         parcours->var=(variable *)malloc(sizeof(variable));
+         parcours=(listvar *)calloc(1,sizeof(listvar));
+         parcours->var=(variable *)calloc(1,sizeof(variable));
          /*                                                                   */
          Init_Variable(parcours->var);
@@ -556,4 +553,6 @@
            /********** TYPEVAR ************************************************/
          fscanf(dependfileoutput,"%s\n",parcours->var->v_typevar);
+           /********** CATVAR ************************************************/
+         fscanf(dependfileoutput,"%d\n",&parcours->var->v_catvar);
            /********** NOMVAR *************************************************/
          fscanf(dependfileoutput,"%s\n",parcours->var->v_nomvar);
@@ -578,12 +577,10 @@
            /********** MODULENAME *********************************************/
          fscanf(dependfileoutput,"%s\n",parcours->var->v_modulename);
-         
-         printf("MODULENAME = %s %s\n",parcours->var->v_nomvar,parcours->var->v_modulename);
-         
+
          if ( !strcasecmp(parcours->var->v_modulename,"T") )
          {
             strcpy(parcours->var->v_modulename,"");
          }
-         
+
 
            /********** NBDIM **************************************************/
@@ -595,10 +592,9 @@
          if ( parcours->var->v_allocatable == 1 )
          {
-            Add_Allocate_Var_1(parcours->var->v_nomvar,
-                               parcours->var->v_commonname);
+            Add_Allocate_Var_1(parcours->var->v_nomvar, parcours->var->v_commonname);
          }
            /********** TARGET ********************************************/
          fscanf(dependfileoutput,"%d\n",&parcours->var->v_target);
-         
+
            /********** POINTERDECLARE *****************************************/
          fscanf(dependfileoutput,"%d\n",&parcours->var->v_pointerdeclare);
@@ -627,5 +623,5 @@
            /********** PRIVATE *****************************************/
          fscanf(dependfileoutput,"%d\n",&parcours->var->v_PrivateDeclare);
-         
+
            /********** INDICETABVARS ******************************************/
          fscanf(dependfileoutput,"%d\n",&parcours->var->v_indicetabvars);
@@ -692,5 +688,7 @@
    if ( List_Subroutine_For_Alloc )
    {
-      if ((dependfileoutput=fopen(".dependAllocAgrif","w"))!=NULL)
+      sprintf(dependfilename, "%s/.dependAllocAgrif", work_dir);
+
+      if ((dependfileoutput=fopen(dependfilename, "w"))!=NULL)
       {
          parcours = List_Subroutine_For_Alloc;
@@ -707,33 +705,34 @@
 void Read_Subroutine_For_Alloc()
 {
-  FILE *dependfileoutput;
-  listnom *parcours;
-  listnom *ref;
-
-  ref = (listnom *)NULL;
-  if ((dependfileoutput=fopen(".dependAllocAgrif","r"))!=NULL)
-  {
-     List_Subroutine_For_Alloc = (listnom *)NULL;
-     while (!feof(dependfileoutput))
-     {
-        parcours=(listnom *)malloc(sizeof(listnom));
-        strcpy(parcours->o_nom,"");
-
-        fscanf(dependfileoutput,"%s\n",&parcours->o_nom);
-        parcours->suiv = NULL;
-
-        if ( !List_Subroutine_For_Alloc )
-        {
-           List_Subroutine_For_Alloc = parcours;
-           ref = parcours;
-        }
-        else
-        {
-            ref->suiv = parcours;
+    FILE *dependfileoutput;
+    listnom *parcours;
+    listnom *ref;
+
+    ref = (listnom*) NULL;
+    sprintf(dependfilename, "%s/.dependAllocAgrif", work_dir);
+
+    if ( (dependfileoutput=fopen(dependfilename, "r")) != NULL )
+    {
+        List_Subroutine_For_Alloc = (listnom*) NULL;
+        while ( !feof(dependfileoutput) )
+        {
+            parcours = (listnom*) calloc(1,sizeof(listnom));
+            strcpy(parcours->o_nom,"");
+
+            fscanf(dependfileoutput,"%s\n",parcours->o_nom);
+            parcours->suiv = NULL;
+
+            if ( !List_Subroutine_For_Alloc )
+            {
+                List_Subroutine_For_Alloc = parcours;
+            }
+            else
+            {
+                ref->suiv = parcours;
+            }
             ref = parcours;
         }
-     }
-     fclose(dependfileoutput);
-  }
+        fclose(dependfileoutput);
+    }
 }
 
@@ -756,21 +755,27 @@
 void Writethedependavailablefile()
 {
-  FILE *dependfileoutput;
-  listindice *parcours;
-
-  if ((dependfileoutput=fopen(".dependavailable","w"))!=NULL)
-  {
-     /* We are looking for all the indices of the Listofavailableindices      */
-     parcours = Listofavailableindices;
-     while (parcours)
-     {
-        if ( parcours->i_indice != 0 )
-        {
-           fprintf(dependfileoutput,"%d\n",parcours->i_indice);
-        }
-        parcours = parcours->suiv;
-     }
-     fclose(dependfileoutput);
-  }
+    FILE *dependfileoutput;
+    listindice *parcours;
+    int i;
+
+    sprintf(dependfilename, "%s/.dependavailable", work_dir);
+
+    if ((dependfileoutput=fopen(dependfilename, "w"))!=NULL)
+    {
+        /* We are looking for all the indices of the Listofavailableindices      */
+        for (i=0;i<NB_CAT_VARIABLES;i++)
+        {
+            parcours = Listofavailableindices_glob[i];
+            while (parcours)
+            {
+                if ( parcours->i_indice != 0 )
+                {
+                    fprintf(dependfileoutput,"%d %d\n",i,parcours->i_indice);
+                }
+                parcours = parcours->suiv;
+            }
+        }
+        fclose(dependfileoutput);
+    }
 }
 
@@ -795,17 +800,20 @@
   FILE *dependfileoutput;
   listindice *parcours;
-
-  if ((dependfileoutput=fopen(".dependavailable","r"))!=NULL)
+  int current_cat;
+
+  sprintf(dependfilename, "%s/.dependavailable", work_dir);
+
+  if ((dependfileoutput=fopen(dependfilename, "r"))!=NULL)
   {
      /* We are looking for all the indices of the Listofavailableindices      */
-     Listofavailableindices = (listindice *)NULL;
+     Listofavailableindices_glob = (listindice **) calloc(NB_CAT_VARIABLES,sizeof(listindice *));
      while (!feof(dependfileoutput))
      {
-        parcours=(listindice *)malloc(sizeof(listindice));
-        fscanf(dependfileoutput,"%d\n",&parcours->i_indice);
+        parcours=(listindice *)calloc(1,sizeof(listindice));
+        fscanf(dependfileoutput,"%d %d\n",&current_cat,&parcours->i_indice);
         if ( parcours->i_indice != 0 && parcours->i_indice < 10000000 )
         {
-           parcours -> suiv = Listofavailableindices;
-           Listofavailableindices = parcours;
+           parcours -> suiv = Listofavailableindices_glob[current_cat];
+           Listofavailableindices_glob[current_cat] = parcours;
         }
         else
@@ -820,5 +828,5 @@
 
 /******************************************************************************/
-/*                      Did_filetoparse_readed                                */
+/*                       is_dependfile_created                                */
 /******************************************************************************/
 /* This subroutine is used to know if the .depend<NameTampon> exist           */
@@ -827,188 +835,80 @@
 /*                                                                            */
 /******************************************************************************/
-int Did_filetoparse_readed(char *NameTampon)
+int is_dependfile_created(const char *NameTampon)
 {
   FILE *dependfileoutput;
-  char ligne[LONG_C];
-  int out;
-
-  convert2lower(NameTampon);
-  sprintf(ligne,".depend%s",NameTampon);
-  if ((dependfileoutput = fopen(ligne,"r"))==NULL)
-  {
-      out = 0;
+  char lowername[LONG_VNAME];
+
+  convert2lower(lowername, NameTampon);
+  sprintf(dependfilename, "%s/.depend_%s", work_dir, lowername);
+
+  dependfileoutput = fopen(dependfilename, "r");
+
+  if ( (dependfileoutput = fopen(dependfilename, "r")) != NULL )
+  {
+    fclose(dependfileoutput);
+    return 1;
   }
   else
-  {
-      out = 1;
-      fclose(dependfileoutput);
-  }
-  return out;
-}
-
-
-/******************************************************************************/
-/*                      Did_module_common_treaded                             */
-/******************************************************************************/
-/* This subroutine is used to know if the .depend<NameTampon> exist           */
-/*    it means if the file has been ever parsed                               */
-/******************************************************************************/
-/*                                                                            */
-/******************************************************************************/
-int Did_module_common_treaded(char *NameTampon)
-{
-  FILE *dependfileoutput;
-  char ligne[LONG_C];
-  int out;
-
-  convert2lower(NameTampon);
-  sprintf(ligne,".depend%s",NameTampon);
-  if ((dependfileoutput = fopen(ligne,"r"))==NULL)
-  {
-      out = 0;
-  }
-  else
-  {
-      out = 1;
-      fclose(dependfileoutput);
-  }
-  return out;
-}
-
-
+    return 0;
+}
 
 void Write_val_max()
 {
-  FILE *dependfileoutput;
-
-  if ((dependfileoutput=fopen(".dependvalmax","w"))!=NULL)
-  {
-     fprintf(dependfileoutput,"length_last\n");
-     fprintf(dependfileoutput,"%d\n",length_last);
-     fprintf(dependfileoutput,"length_first\n");
-     fprintf(dependfileoutput,"%d\n",length_first);
-     fprintf(dependfileoutput,"length_v_typevar\n");
-     fprintf(dependfileoutput,"%d\n",length_v_typevar);
-     fprintf(dependfileoutput,"length_v_nomvar\n");
-     fprintf(dependfileoutput,"%d\n",length_v_nomvar);
-     fprintf(dependfileoutput,"length_v_dimchar\n");
-     fprintf(dependfileoutput,"%d\n",length_v_dimchar);
-     fprintf(dependfileoutput,"length_v_modulename\n");
-     fprintf(dependfileoutput,"%d\n",length_v_modulename);
-     fprintf(dependfileoutput,"length_v_commonname\n");
-     fprintf(dependfileoutput,"%d\n",length_v_commonname);
-     fprintf(dependfileoutput,"length_v_vallengspec\n");
-     fprintf(dependfileoutput,"%d\n",length_v_vallengspec);
-     fprintf(dependfileoutput,"length_v_nameinttypename\n");
-     fprintf(dependfileoutput,"%d\n",length_v_nameinttypename);
-     fprintf(dependfileoutput,"length_v_commoninfile\n");
-     fprintf(dependfileoutput,"%d\n",length_v_commoninfile);
-     fprintf(dependfileoutput,"length_v_subroutinename\n");
-     fprintf(dependfileoutput,"%d\n",length_v_subroutinename);
-     fprintf(dependfileoutput,"length_v_precision\n");
-     fprintf(dependfileoutput,"%d\n",length_v_precision);
-     fprintf(dependfileoutput,"length_v_IntentSpec\n");
-     fprintf(dependfileoutput,"%d\n",length_v_IntentSpec);
-     fprintf(dependfileoutput,"length_v_initialvalue\n");
-     fprintf(dependfileoutput,"%d\n",length_v_initialvalue);
-     fprintf(dependfileoutput,"length_v_readedlistdimension\n");
-     fprintf(dependfileoutput,"%d\n",length_v_readedlistdimension);
-     fprintf(dependfileoutput,"length_u_usemodule\n");
-     fprintf(dependfileoutput,"%d\n",length_u_usemodule);
-     fprintf(dependfileoutput,"length_u_charusemodule\n");
-     fprintf(dependfileoutput,"%d\n",length_u_charusemodule);
-     fprintf(dependfileoutput,"length_u_cursubroutine\n");
-     fprintf(dependfileoutput,"%d\n",length_u_cursubroutine);
-     fprintf(dependfileoutput,"length_u_modulename\n");
-     fprintf(dependfileoutput,"%d\n",length_u_modulename);
-     fprintf(dependfileoutput,"length_n_name\n");
-     fprintf(dependfileoutput,"%d\n",length_n_name);
-     fprintf(dependfileoutput,"length_c_namevar\n");
-     fprintf(dependfileoutput,"%d\n",length_c_namevar);
-     fprintf(dependfileoutput,"length_c_namepointedvar\n");
-     fprintf(dependfileoutput,"%d\n",length_c_namepointedvar);
-     fprintf(dependfileoutput,"length_o_nom\n");
-     fprintf(dependfileoutput,"%d\n",length_o_nom);
-     fprintf(dependfileoutput,"length_o_module\n");
-     fprintf(dependfileoutput,"%d\n",length_o_module);
-     fprintf(dependfileoutput,"length_a_nomvar\n");
-     fprintf(dependfileoutput,"%d\n",length_a_nomvar);
-     fprintf(dependfileoutput,"length_a_subroutine\n");
-     fprintf(dependfileoutput,"%d\n",length_a_subroutine);
-     fprintf(dependfileoutput,"length_a_module\n");
-     fprintf(dependfileoutput,"%d\n",length_a_module);
-     fprintf(dependfileoutput,"length_usemodule\n");
-     fprintf(dependfileoutput,"%d\n",length_t_usemodule);
-     fprintf(dependfileoutput,"length_cursubroutine\n");
-     fprintf(dependfileoutput,"%d\n",length_t_cursubroutine);
-     fprintf(dependfileoutput,"length_curfilename\n");
-     fprintf(dependfileoutput,"%d\n",length_curfilename);
-     fprintf(dependfileoutput,"length_nomfileoutput\n");
-     fprintf(dependfileoutput,"%d\n",length_nomfileoutput);
-     fprintf(dependfileoutput,"length_motparse\n");
-     fprintf(dependfileoutput,"%d\n",length_motparse);
-     fprintf(dependfileoutput,"length_mainfile\n");
-     fprintf(dependfileoutput,"%d\n",length_mainfile);
-     fprintf(dependfileoutput,"length_nomdir\n");
-     fprintf(dependfileoutput,"%d\n",length_nomdir);
-     fprintf(dependfileoutput,"length_commondirout\n");
-     fprintf(dependfileoutput,"%d\n",length_commondirout);
-     fprintf(dependfileoutput,"length_commondirin\n");
-     fprintf(dependfileoutput,"%d\n",length_commondirin);
-     fprintf(dependfileoutput,"length_filetoparse\n");
-     fprintf(dependfileoutput,"%d\n",length_filetoparse);
-     fprintf(dependfileoutput,"length_curbuf\n");
-     fprintf(dependfileoutput,"%d\n",length_curbuf);
-     fprintf(dependfileoutput,"length_toprintglob\n");
-     fprintf(dependfileoutput,"%d\n",length_toprintglob);
-     fprintf(dependfileoutput,"Size_char0d\n");
-     fprintf(dependfileoutput,"%d\n",value_char_size);
-     fprintf(dependfileoutput,"Size_char1d\n");
-     fprintf(dependfileoutput,"%d\n",value_char_size1);
-     fprintf(dependfileoutput,"Size_char2d\n");
-     fprintf(dependfileoutput,"%d\n",value_char_size2);
-     fprintf(dependfileoutput,"Size_char3d\n");
-     fprintf(dependfileoutput,"%d\n",value_char_size3);
-     fprintf(dependfileoutput,"length_tmpvargridname\n");
-     fprintf(dependfileoutput,"%d\n",length_tmpvargridname);
-     fprintf(dependfileoutput,"length_ligne_Subloop\n");
-     fprintf(dependfileoutput,"%d\n",length_ligne_Subloop);
-     fprintf(dependfileoutput,"length_lvargridname_toamr\n");
-     fprintf(dependfileoutput,"%d\n",length_lvargridname_toamr);
-     fprintf(dependfileoutput,"length_toprint_toamr\n");
-     fprintf(dependfileoutput,"%d\n",length_toprint_utilagrif);
-     fprintf(dependfileoutput,"length_toprinttmp_utilchar\n");
-     fprintf(dependfileoutput,"%d\n",length_toprinttmp_utilchar);
-     fprintf(dependfileoutput,"length_ligne_writedecl\n");
-     fprintf(dependfileoutput,"%d\n",length_ligne_writedecl);
-     fprintf(dependfileoutput,"length_newname_toamr\n");
-     fprintf(dependfileoutput,"%d\n",length_newname_toamr);
-     fprintf(dependfileoutput,"length_newname_writedecl\n");
-     fprintf(dependfileoutput,"%d\n",length_newname_writedecl);
-     fprintf(dependfileoutput,"length_ligne_toamr\n");
-     fprintf(dependfileoutput,"%d\n",length_ligne_toamr);
-     fprintf(dependfileoutput,"length_tmpligne_writedecl\n");
-     fprintf(dependfileoutput,"%d\n",length_tmpligne_writedecl);
-/*     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);
-     fprintf(dependfileoutput,"\n");
-     fprintf(dependfileoutput,"%d\n",);*/
-
-     fclose(dependfileoutput);
-  }
+    FILE *dependfileoutput;
+
+    sprintf(dependfilename, "%s/.dependvalmax", work_dir);
+
+    if ((dependfileoutput=fopen(dependfilename, "w"))!=NULL)
+    {
+        fprintf(dependfileoutput,"length_last\n");
+        fprintf(dependfileoutput,"%lu\n", length_last);
+        fprintf(dependfileoutput,"length_first\n");
+        fprintf(dependfileoutput,"%lu\n", length_first);
+        fprintf(dependfileoutput,"length_v_vallengspec\n");
+        fprintf(dependfileoutput,"%lu\n", length_v_vallengspec);
+        fprintf(dependfileoutput,"length_v_commoninfile\n");
+        fprintf(dependfileoutput,"%lu\n", length_v_commoninfile);
+        fprintf(dependfileoutput,"length_v_precision\n");
+        fprintf(dependfileoutput,"%lu\n", length_v_precision);
+        fprintf(dependfileoutput,"length_v_IntentSpec\n");
+        fprintf(dependfileoutput,"%lu\n", length_v_IntentSpec);
+        fprintf(dependfileoutput,"length_v_initialvalue\n");
+        fprintf(dependfileoutput,"%lu\n", length_v_initialvalue);
+        fprintf(dependfileoutput,"length_v_readedlistdimension\n");
+        fprintf(dependfileoutput,"%lu\n", length_v_readedlistdimension);
+        fprintf(dependfileoutput,"length_a_nomvar\n");
+        fprintf(dependfileoutput,"%lu\n", length_a_nomvar);
+        fprintf(dependfileoutput,"length_toprintglob\n");
+        fprintf(dependfileoutput,"%lu\n", length_toprintglob);
+        fprintf(dependfileoutput,"Size_char0d\n");
+        fprintf(dependfileoutput,"%d\n",value_char_size);
+        fprintf(dependfileoutput,"Size_char1d\n");
+        fprintf(dependfileoutput,"%d\n",value_char_size1);
+        fprintf(dependfileoutput,"Size_char2d\n");
+        fprintf(dependfileoutput,"%d\n",value_char_size2);
+        fprintf(dependfileoutput,"Size_char3d\n");
+        fprintf(dependfileoutput,"%d\n",value_char_size3);
+        fprintf(dependfileoutput,"length_tmpvargridname\n");
+        fprintf(dependfileoutput,"%lu\n", length_tmpvargridname);
+        fprintf(dependfileoutput,"length_ligne_Subloop\n");
+        fprintf(dependfileoutput,"%lu\n", length_ligne_Subloop);
+        fprintf(dependfileoutput,"length_toprint_toamr\n");
+        fprintf(dependfileoutput,"%lu\n", length_toprint_utilagrif);
+        fprintf(dependfileoutput,"length_toprinttmp_utilchar\n");
+        fprintf(dependfileoutput,"%lu\n", length_toprinttmp_utilchar);
+        fprintf(dependfileoutput,"length_ligne_writedecl\n");
+        fprintf(dependfileoutput,"%lu\n", length_ligne_writedecl);
+        fprintf(dependfileoutput,"length_newname_toamr\n");
+        fprintf(dependfileoutput,"%lu\n", length_newname_toamr);
+        fprintf(dependfileoutput,"length_newname_writedecl\n");
+        fprintf(dependfileoutput,"%lu\n", length_newname_writedecl);
+        fprintf(dependfileoutput,"length_ligne_toamr\n");
+        fprintf(dependfileoutput,"%lu\n", length_ligne_toamr);
+        fprintf(dependfileoutput,"length_tmpligne_writedecl\n");
+        fprintf(dependfileoutput,"%lu\n", length_tmpligne_writedecl);
+
+        fclose(dependfileoutput);
+    }
 }
 
@@ -1016,135 +916,59 @@
 void Read_val_max()
 {
-  char nothing[LONG_C];
-  FILE *dependfileoutput;
-
-  if ((dependfileoutput=fopen(".dependvalmax","r"))!=NULL)
-  {
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_last);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_first);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_typevar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_nomvar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_dimchar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_modulename);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_commonname);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_vallengspec);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_nameinttypename);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_commoninfile);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_subroutinename);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_precision);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_IntentSpec);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_initialvalue);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_v_readedlistdimension);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_u_usemodule);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_u_charusemodule);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_u_cursubroutine);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_u_modulename);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_n_name);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_c_namevar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_c_namepointedvar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_o_nom);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_o_module);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_a_nomvar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_a_subroutine);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_a_module);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_t_usemodule);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_t_cursubroutine);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_curfilename);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_nomfileoutput);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_motparse);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_mainfile);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_nomdir);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_commondirout);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_commondirin);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_filetoparse);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_curbuf);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_toprintglob);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&value_char_size);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&value_char_size1);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&value_char_size2);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&value_char_size3);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_tmpvargridname);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_ligne_Subloop);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_lvargridname_toamr);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_toprint_utilagrif);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_toprinttmp_utilchar);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_ligne_writedecl);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_newname_toamr);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_newname_writedecl);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_ligne_toamr);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&length_tmpligne_writedecl);
-/*     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);
-     fscanf(dependfileoutput,"%s\n",nothing);
-     fscanf(dependfileoutput,"%d\n",&);*/
-
-     fclose(dependfileoutput);
-  }
-}
+    char nothing[LONG_M];
+    FILE *dependfileoutput;
+
+    sprintf(dependfilename, "%s/.dependvalmax", work_dir);
+
+    if ((dependfileoutput=fopen(".dependvalmax","r"))!=NULL)
+    {
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_last);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_first);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_v_vallengspec);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_v_commoninfile);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_v_precision);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_v_IntentSpec);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_v_initialvalue);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_v_readedlistdimension);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_a_nomvar);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_toprintglob);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%d\n", &value_char_size);
+       fscanf(dependfileoutput,"%s\n", nothing);
+       fscanf(dependfileoutput,"%d\n", &value_char_size1);
+       fscanf(dependfileoutput,"%s\n", nothing);
+       fscanf(dependfileoutput,"%d\n", &value_char_size2);
+       fscanf(dependfileoutput,"%s\n", nothing);
+       fscanf(dependfileoutput,"%d\n", &value_char_size3);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_tmpvargridname);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_ligne_Subloop);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_toprint_utilagrif);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_toprinttmp_utilchar);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_ligne_writedecl);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_newname_toamr);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_newname_writedecl);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_ligne_toamr);
+       fscanf(dependfileoutput,"%s\n",nothing);
+       fscanf(dependfileoutput,"%lu\n", &length_tmpligne_writedecl);
+
+       fclose(dependfileoutput);
+    }
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/fortran.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/fortran.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/fortran.c	(revision 9987)
@@ -1,23 +1,20 @@
-/* A Bison parser, made by GNU Bison 2.3.  */
-
-/* Skeleton implementation for Bison's Yacc-like parsers in C
-
-   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
-   Free Software Foundation, Inc.
-
-   This program is free software; you can redistribute it and/or modify
+/* A Bison parser, made by GNU Bison 2.7.  */
+
+/* Bison implementation for Yacc-like parsers in C
+   
+      Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc.
+   
+   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, or (at your option)
-   any later version.
-
+   the Free Software Foundation, either version 3 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.  */
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
 /* As a special exception, you may create a larger work that contains
@@ -30,5 +27,5 @@
    Bison output files to be licensed under the GNU General Public
    License without this special exception.
-
+   
    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.  */
@@ -48,5 +45,4 @@
 
 /* Bison version.  */
-#define YYBISON_VERSION "2.3"
 
 /* Skeleton name.  */
@@ -56,371 +52,22 @@
 #define YYPURE 0
 
-/* Using locations.  */
-#define YYLSP_NEEDED 0
+/* Push parsers.  */
+#define YYPUSH 0
+
+/* Pull parsers.  */
+#define YYPULL 1
+
 
 /* Substitute the variable and function names.  */
-#define yyparse fortranparse
-#define yylex   fortranlex
-#define yyerror fortranerror
-#define yylval  fortranlval
-#define yychar  fortranchar
-#define yydebug fortrandebug
-#define yynerrs fortrannerrs
-
-
-/* Tokens.  */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
-   /* Put the tokens into the symbol table, so that GDB and other debuggers
-      know about them.  */
-   enum yytokentype {
-     TOK_BINARY_OP = 258,
-     TOK_NEQV = 259,
-     TOK_EQV = 260,
-     TOK_XOR = 261,
-     TOK_OR = 262,
-     TOK_AND = 263,
-     TOK_NOT = 264,
-     TOK_NE = 265,
-     TOK_EQ = 266,
-     TOK_GE = 267,
-     TOK_LE = 268,
-     TOK_GT = 269,
-     TOK_LT = 270,
-     TOK_UNARY_OP = 271,
-     TOK_DSLASH = 272,
-     TOK_SLASH = 273,
-     TOK_DASTER = 274,
-     TOK_SEP = 275,
-     TOK_SEMICOLON = 276,
-     TOK_NEXTLINE = 277,
-     TOK_PARAMETER = 278,
-     TOK_RESULT = 279,
-     TOK_ONLY = 280,
-     TOK_INCLUDE = 281,
-     TOK_SUBROUTINE = 282,
-     TOK_PROGRAM = 283,
-     TOK_FUNCTION = 284,
-     TOK_OMP = 285,
-     TOK_DOLLAR = 286,
-     TOK_FORMAT = 287,
-     TOK_MAX = 288,
-     TOK_TANH = 289,
-     TOK_WHERE = 290,
-     TOK_ELSEWHERE = 291,
-     TOK_ENDWHERE = 292,
-     TOK_MAXVAL = 293,
-     TOK_TRIM = 294,
-     TOK_SUM = 295,
-     TOK_SQRT = 296,
-     TOK_CASE = 297,
-     TOK_SELECTCASE = 298,
-     TOK_FILE = 299,
-     TOK_END = 300,
-     TOK_ERR = 301,
-     TOK_DONOTTREAT = 302,
-     TOK_ENDDONOTTREAT = 303,
-     TOK_EXIST = 304,
-     TOK_MIN = 305,
-     TOK_FLOAT = 306,
-     TOK_EXP = 307,
-     TOK_COS = 308,
-     TOK_COSH = 309,
-     TOK_ACOS = 310,
-     TOK_NINT = 311,
-     TOK_CYCLE = 312,
-     TOK_SIN = 313,
-     TOK_SINH = 314,
-     TOK_ASIN = 315,
-     TOK_EQUIVALENCE = 316,
-     TOK_BACKSPACE = 317,
-     TOK_LOG = 318,
-     TOK_TAN = 319,
-     TOK_ATAN = 320,
-     TOK_RECURSIVE = 321,
-     TOK_ABS = 322,
-     TOK_MOD = 323,
-     TOK_SIGN = 324,
-     TOK_MINLOC = 325,
-     TOK_MAXLOC = 326,
-     TOK_EXIT = 327,
-     TOK_MINVAL = 328,
-     TOK_PUBLIC = 329,
-     TOK_PRIVATE = 330,
-     TOK_ALLOCATABLE = 331,
-     TOK_RETURN = 332,
-     TOK_THEN = 333,
-     TOK_ELSEIF = 334,
-     TOK_ELSE = 335,
-     TOK_ENDIF = 336,
-     TOK_PRINT = 337,
-     TOK_PLAINGOTO = 338,
-     TOK_CONSTRUCTID = 339,
-     TOK_LOGICALIF = 340,
-     TOK_PLAINDO = 341,
-     TOK_CONTAINS = 342,
-     TOK_ENDDO = 343,
-     TOK_MODULE = 344,
-     TOK_ENDMODULE = 345,
-     TOK_DOWHILE = 346,
-     TOK_ALLOCATE = 347,
-     TOK_OPEN = 348,
-     TOK_CLOSE = 349,
-     TOK_INQUIRE = 350,
-     TOK_WRITE = 351,
-     TOK_READ = 352,
-     TOK_REWIND = 353,
-     TOK_DEALLOCATE = 354,
-     TOK_NULLIFY = 355,
-     TOK_FIN = 356,
-     TOK_DEBUT = 357,
-     TOK_DIMENSION = 358,
-     TOK_ENDSELECT = 359,
-     TOK_EXTERNAL = 360,
-     TOK_INTENT = 361,
-     TOK_INTRINSIC = 362,
-     TOK_NAMELIST = 363,
-     TOK_CASEDEFAULT = 364,
-     TOK_OPTIONAL = 365,
-     TOK_POINTER = 366,
-     TOK_CONTINUE = 367,
-     TOK_SAVE = 368,
-     TOK_TARGET = 369,
-     TOK_QUOTE = 370,
-     TOK_IMPLICIT = 371,
-     TOK_NONE = 372,
-     TOK_CALL = 373,
-     TOK_STAT = 374,
-     TOK_POINT_TO = 375,
-     TOK_COMMON = 376,
-     TOK_GLOBAL = 377,
-     TOK_INTERFACE = 378,
-     TOK_ENDINTERFACE = 379,
-     TOK_LEFTAB = 380,
-     TOK_RIGHTAB = 381,
-     TOK_PAUSE = 382,
-     TOK_PROCEDURE = 383,
-     TOK_STOP = 384,
-     TOK_NAMEEQ = 385,
-     TOK_REAL8 = 386,
-     TOK_OUT = 387,
-     TOK_INOUT = 388,
-     TOK_IN = 389,
-     TOK_USE = 390,
-     TOK_TRUE = 391,
-     TOK_FALSE = 392,
-     TOK_LABEL = 393,
-     TOK_TYPE = 394,
-     TOK_TYPEPAR = 395,
-     TOK_ENDTYPE = 396,
-     TOK_REAL = 397,
-     TOK_INTEGER = 398,
-     TOK_LOGICAL = 399,
-     TOK_DOUBLEPRECISION = 400,
-     TOK_DOUBLEREAL = 401,
-     TOK_ENDSUBROUTINE = 402,
-     TOK_ENDFUNCTION = 403,
-     TOK_ENDPROGRAM = 404,
-     TOK_ENDUNIT = 405,
-     TOK_CHARACTER = 406,
-     TOK_CHAR_CONSTANT = 407,
-     TOK_CHAR_CUT = 408,
-     TOK_DATA = 409,
-     TOK_CHAR_INT = 410,
-     TOK_CHAR_MESSAGE = 411,
-     TOK_CSTREAL = 412,
-     TOK_CSTREALDP = 413,
-     TOK_CSTREALQP = 414,
-     TOK_SFREAL = 415,
-     TOK_COMPLEX = 416,
-     TOK_DOUBLECOMPLEX = 417,
-     TOK_NAME = 418,
-     TOK_NAME_CHAR = 419,
-     TOK_PROBTYPE = 420,
-     TOK_INTERPTYPE = 421,
-     TOK_VARTYPE = 422,
-     TOK_BC = 423,
-     TOK_OP = 424,
-     TOK_CSTINT = 425,
-     TOK_COMMENT = 426,
-     TOK_FILENAME = 427
-   };
-#endif
-/* Tokens.  */
-#define TOK_BINARY_OP 258
-#define TOK_NEQV 259
-#define TOK_EQV 260
-#define TOK_XOR 261
-#define TOK_OR 262
-#define TOK_AND 263
-#define TOK_NOT 264
-#define TOK_NE 265
-#define TOK_EQ 266
-#define TOK_GE 267
-#define TOK_LE 268
-#define TOK_GT 269
-#define TOK_LT 270
-#define TOK_UNARY_OP 271
-#define TOK_DSLASH 272
-#define TOK_SLASH 273
-#define TOK_DASTER 274
-#define TOK_SEP 275
-#define TOK_SEMICOLON 276
-#define TOK_NEXTLINE 277
-#define TOK_PARAMETER 278
-#define TOK_RESULT 279
-#define TOK_ONLY 280
-#define TOK_INCLUDE 281
-#define TOK_SUBROUTINE 282
-#define TOK_PROGRAM 283
-#define TOK_FUNCTION 284
-#define TOK_OMP 285
-#define TOK_DOLLAR 286
-#define TOK_FORMAT 287
-#define TOK_MAX 288
-#define TOK_TANH 289
-#define TOK_WHERE 290
-#define TOK_ELSEWHERE 291
-#define TOK_ENDWHERE 292
-#define TOK_MAXVAL 293
-#define TOK_TRIM 294
-#define TOK_SUM 295
-#define TOK_SQRT 296
-#define TOK_CASE 297
-#define TOK_SELECTCASE 298
-#define TOK_FILE 299
-#define TOK_END 300
-#define TOK_ERR 301
-#define TOK_DONOTTREAT 302
-#define TOK_ENDDONOTTREAT 303
-#define TOK_EXIST 304
-#define TOK_MIN 305
-#define TOK_FLOAT 306
-#define TOK_EXP 307
-#define TOK_COS 308
-#define TOK_COSH 309
-#define TOK_ACOS 310
-#define TOK_NINT 311
-#define TOK_CYCLE 312
-#define TOK_SIN 313
-#define TOK_SINH 314
-#define TOK_ASIN 315
-#define TOK_EQUIVALENCE 316
-#define TOK_BACKSPACE 317
-#define TOK_LOG 318
-#define TOK_TAN 319
-#define TOK_ATAN 320
-#define TOK_RECURSIVE 321
-#define TOK_ABS 322
-#define TOK_MOD 323
-#define TOK_SIGN 324
-#define TOK_MINLOC 325
-#define TOK_MAXLOC 326
-#define TOK_EXIT 327
-#define TOK_MINVAL 328
-#define TOK_PUBLIC 329
-#define TOK_PRIVATE 330
-#define TOK_ALLOCATABLE 331
-#define TOK_RETURN 332
-#define TOK_THEN 333
-#define TOK_ELSEIF 334
-#define TOK_ELSE 335
-#define TOK_ENDIF 336
-#define TOK_PRINT 337
-#define TOK_PLAINGOTO 338
-#define TOK_CONSTRUCTID 339
-#define TOK_LOGICALIF 340
-#define TOK_PLAINDO 341
-#define TOK_CONTAINS 342
-#define TOK_ENDDO 343
-#define TOK_MODULE 344
-#define TOK_ENDMODULE 345
-#define TOK_DOWHILE 346
-#define TOK_ALLOCATE 347
-#define TOK_OPEN 348
-#define TOK_CLOSE 349
-#define TOK_INQUIRE 350
-#define TOK_WRITE 351
-#define TOK_READ 352
-#define TOK_REWIND 353
-#define TOK_DEALLOCATE 354
-#define TOK_NULLIFY 355
-#define TOK_FIN 356
-#define TOK_DEBUT 357
-#define TOK_DIMENSION 358
-#define TOK_ENDSELECT 359
-#define TOK_EXTERNAL 360
-#define TOK_INTENT 361
-#define TOK_INTRINSIC 362
-#define TOK_NAMELIST 363
-#define TOK_CASEDEFAULT 364
-#define TOK_OPTIONAL 365
-#define TOK_POINTER 366
-#define TOK_CONTINUE 367
-#define TOK_SAVE 368
-#define TOK_TARGET 369
-#define TOK_QUOTE 370
-#define TOK_IMPLICIT 371
-#define TOK_NONE 372
-#define TOK_CALL 373
-#define TOK_STAT 374
-#define TOK_POINT_TO 375
-#define TOK_COMMON 376
-#define TOK_GLOBAL 377
-#define TOK_INTERFACE 378
-#define TOK_ENDINTERFACE 379
-#define TOK_LEFTAB 380
-#define TOK_RIGHTAB 381
-#define TOK_PAUSE 382
-#define TOK_PROCEDURE 383
-#define TOK_STOP 384
-#define TOK_NAMEEQ 385
-#define TOK_REAL8 386
-#define TOK_OUT 387
-#define TOK_INOUT 388
-#define TOK_IN 389
-#define TOK_USE 390
-#define TOK_TRUE 391
-#define TOK_FALSE 392
-#define TOK_LABEL 393
-#define TOK_TYPE 394
-#define TOK_TYPEPAR 395
-#define TOK_ENDTYPE 396
-#define TOK_REAL 397
-#define TOK_INTEGER 398
-#define TOK_LOGICAL 399
-#define TOK_DOUBLEPRECISION 400
-#define TOK_DOUBLEREAL 401
-#define TOK_ENDSUBROUTINE 402
-#define TOK_ENDFUNCTION 403
-#define TOK_ENDPROGRAM 404
-#define TOK_ENDUNIT 405
-#define TOK_CHARACTER 406
-#define TOK_CHAR_CONSTANT 407
-#define TOK_CHAR_CUT 408
-#define TOK_DATA 409
-#define TOK_CHAR_INT 410
-#define TOK_CHAR_MESSAGE 411
-#define TOK_CSTREAL 412
-#define TOK_CSTREALDP 413
-#define TOK_CSTREALQP 414
-#define TOK_SFREAL 415
-#define TOK_COMPLEX 416
-#define TOK_DOUBLECOMPLEX 417
-#define TOK_NAME 418
-#define TOK_NAME_CHAR 419
-#define TOK_PROBTYPE 420
-#define TOK_INTERPTYPE 421
-#define TOK_VARTYPE 422
-#define TOK_BC 423
-#define TOK_OP 424
-#define TOK_CSTINT 425
-#define TOK_COMMENT 426
-#define TOK_FILENAME 427
-
-
-
+#define yyparse         fortran_parse
+#define yylex           fortran_lex
+#define yyerror         fortran_error
+#define yylval          fortran_lval
+#define yychar          fortran_char
+#define yydebug         fortran_debug
+#define yynerrs         fortran_nerrs
 
 /* Copy the first part of user declarations.  */
+/* Line 371 of yacc.c  */
 #line 36 "fortran.y"
 
@@ -430,25 +77,36 @@
 #include <string.h>
 #include "decl.h"
-extern int line_num_fortran;
-extern int line_num_fortran_common;
-char *tmp;
-char c_selectorname[LONG_C];
-char ligne[LONG_C];
-char truename[LONGNOM];
-char identcopy[LONG_C];
+
+extern int line_num_input;
+extern char *fortran_text;
+
+char c_selectorname[LONG_M];
+char ligne[LONG_M];
+char truename[LONG_VNAME];
+char identcopy[LONG_VNAME];
 int c_selectorgiven=0;
-int incom;
 listvar *curlistvar;
 typedim c_selectordim;
 listcouple *coupletmp;
-listdim *parcoursdim;
 int removeline=0;
 listvar *test;
 
-
-/* Enabling traces.  */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
+int fortran_error(const char *s)
+{
+    printf("%s line %d, file %s motclef = |%s|\n", s, line_num_input, cur_filename, fortran_text);
+    exit(1);
+}
+
+
+/* Line 371 of yacc.c  */
+#line 104 "fortran.tab.c"
+
+# ifndef YY_NULL
+#  if defined __cplusplus && 201103L <= __cplusplus
+#   define YY_NULL nullptr
+#  else
+#   define YY_NULL 0
+#  endif
+# endif
 
 /* Enabling verbose error messages.  */
@@ -460,38 +118,221 @@
 #endif
 
-/* Enabling the token table.  */
-#ifndef YYTOKEN_TABLE
-# define YYTOKEN_TABLE 0
+
+/* Enabling traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 1
 #endif
+#if YYDEBUG
+extern int fortran_debug;
+#endif
+
+/* Tokens.  */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+   /* Put the tokens into the symbol table, so that GDB and other debuggers
+      know about them.  */
+   enum yytokentype {
+     TOK_NEQV = 258,
+     TOK_EQV = 259,
+     TOK_XOR = 260,
+     TOK_OR = 261,
+     TOK_AND = 262,
+     TOK_NOT = 263,
+     TOK_NE = 264,
+     TOK_EQ = 265,
+     TOK_GE = 266,
+     TOK_LE = 267,
+     TOK_GT = 268,
+     TOK_LT = 269,
+     TOK_DSLASH = 270,
+     TOK_SLASH = 271,
+     TOK_DASTER = 272,
+     TOK_SEMICOLON = 273,
+     TOK_PARAMETER = 274,
+     TOK_RESULT = 275,
+     TOK_ONLY = 276,
+     TOK_INCLUDE = 277,
+     TOK_SUBROUTINE = 278,
+     TOK_PROGRAM = 279,
+     TOK_FUNCTION = 280,
+     TOK_FORMAT = 281,
+     TOK_MAX = 282,
+     TOK_TANH = 283,
+     TOK_WHERE = 284,
+     TOK_ELSEWHEREPAR = 285,
+     TOK_ELSEWHERE = 286,
+     TOK_ENDWHERE = 287,
+     TOK_MAXVAL = 288,
+     TOK_TRIM = 289,
+     TOK_NULL_PTR = 290,
+     TOK_SUM = 291,
+     TOK_SQRT = 292,
+     TOK_CASE = 293,
+     TOK_SELECTCASE = 294,
+     TOK_FILE = 295,
+     TOK_UNIT = 296,
+     TOK_FMT = 297,
+     TOK_NML = 298,
+     TOK_END = 299,
+     TOK_EOR = 300,
+     TOK_ERR = 301,
+     TOK_EXIST = 302,
+     TOK_MIN = 303,
+     TOK_FLOAT = 304,
+     TOK_EXP = 305,
+     TOK_COS = 306,
+     TOK_COSH = 307,
+     TOK_ACOS = 308,
+     TOK_NINT = 309,
+     TOK_CYCLE = 310,
+     TOK_SIN = 311,
+     TOK_SINH = 312,
+     TOK_ASIN = 313,
+     TOK_EQUIVALENCE = 314,
+     TOK_BACKSPACE = 315,
+     TOK_LOG = 316,
+     TOK_TAN = 317,
+     TOK_ATAN = 318,
+     TOK_RECURSIVE = 319,
+     TOK_ABS = 320,
+     TOK_MOD = 321,
+     TOK_SIGN = 322,
+     TOK_MINLOC = 323,
+     TOK_MAXLOC = 324,
+     TOK_EXIT = 325,
+     TOK_MINVAL = 326,
+     TOK_PUBLIC = 327,
+     TOK_PRIVATE = 328,
+     TOK_ALLOCATABLE = 329,
+     TOK_RETURN = 330,
+     TOK_THEN = 331,
+     TOK_ELSEIF = 332,
+     TOK_ELSE = 333,
+     TOK_ENDIF = 334,
+     TOK_PRINT = 335,
+     TOK_PLAINGOTO = 336,
+     TOK_LOGICALIF = 337,
+     TOK_PLAINDO = 338,
+     TOK_CONTAINS = 339,
+     TOK_ENDDO = 340,
+     TOK_MODULE = 341,
+     TOK_ENDMODULE = 342,
+     TOK_WHILE = 343,
+     TOK_CONCURRENT = 344,
+     TOK_ALLOCATE = 345,
+     TOK_OPEN = 346,
+     TOK_CLOSE = 347,
+     TOK_INQUIRE = 348,
+     TOK_WRITE = 349,
+     TOK_FLUSH = 350,
+     TOK_READ = 351,
+     TOK_REWIND = 352,
+     TOK_DEALLOCATE = 353,
+     TOK_NULLIFY = 354,
+     TOK_DIMENSION = 355,
+     TOK_ENDSELECT = 356,
+     TOK_EXTERNAL = 357,
+     TOK_INTENT = 358,
+     TOK_INTRINSIC = 359,
+     TOK_NAMELIST = 360,
+     TOK_DEFAULT = 361,
+     TOK_OPTIONAL = 362,
+     TOK_POINTER = 363,
+     TOK_CONTINUE = 364,
+     TOK_SAVE = 365,
+     TOK_TARGET = 366,
+     TOK_IMPLICIT = 367,
+     TOK_NONE = 368,
+     TOK_CALL = 369,
+     TOK_STAT = 370,
+     TOK_POINT_TO = 371,
+     TOK_COMMON = 372,
+     TOK_GLOBAL = 373,
+     TOK_LEFTAB = 374,
+     TOK_RIGHTAB = 375,
+     TOK_PAUSE = 376,
+     TOK_PROCEDURE = 377,
+     TOK_STOP = 378,
+     TOK_REAL8 = 379,
+     TOK_FOURDOTS = 380,
+     TOK_HEXA = 381,
+     TOK_ASSIGNTYPE = 382,
+     TOK_OUT = 383,
+     TOK_INOUT = 384,
+     TOK_IN = 385,
+     TOK_USE = 386,
+     TOK_TRUE = 387,
+     TOK_FALSE = 388,
+     TOK_LABEL = 389,
+     TOK_TYPE = 390,
+     TOK_TYPEPAR = 391,
+     TOK_ENDTYPE = 392,
+     TOK_REAL = 393,
+     TOK_INTEGER = 394,
+     TOK_LOGICAL = 395,
+     TOK_DOUBLEPRECISION = 396,
+     TOK_ENDSUBROUTINE = 397,
+     TOK_ENDFUNCTION = 398,
+     TOK_ENDPROGRAM = 399,
+     TOK_ENDUNIT = 400,
+     TOK_CHARACTER = 401,
+     TOK_CHAR_CONSTANT = 402,
+     TOK_CHAR_CUT = 403,
+     TOK_DATA = 404,
+     TOK_CHAR_MESSAGE = 405,
+     TOK_CSTREAL = 406,
+     TOK_COMPLEX = 407,
+     TOK_DOUBLECOMPLEX = 408,
+     TOK_NAME = 409,
+     TOK_CSTINT = 410
+   };
+#endif
+
 
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-#line 59 "fortran.y"
 {
-       char      nac[LONG_C];
-       char      na[LONGNOM];
-       listdim  *d;
-       listvar  *l;
-       listnom  *ln;
-       listcouple  *lc;
-       listname *lnn;
-       typedim   dim1;
-       variable *v;
-       }
-/* Line 193 of yacc.c.  */
-#line 483 "fortran.tab.c"
-	YYSTYPE;
+/* Line 387 of yacc.c  */
+#line 65 "fortran.y"
+
+    char        na[LONG_M];
+    listdim     *d;
+    listvar     *l;
+    listcouple  *lc;
+    listname    *lnn;
+    typedim     dim1;
+    variable    *v;
+
+
+/* Line 387 of yacc.c  */
+#line 310 "fortran.tab.c"
+} YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1
 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
 # define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
 #endif
 
+extern YYSTYPE fortran_lval;
+
+#ifdef YYPARSE_PARAM
+#if defined __STDC__ || defined __cplusplus
+int fortran_parse (void *YYPARSE_PARAM);
+#else
+int fortran_parse ();
+#endif
+#else /* ! YYPARSE_PARAM */
+#if defined __STDC__ || defined __cplusplus
+int fortran_parse (void);
+#else
+int fortran_parse ();
+#endif
+#endif /* ! YYPARSE_PARAM */
+
 
 
 /* Copy the second part of user declarations.  */
 
-
-/* Line 216 of yacc.c.  */
-#line 496 "fortran.tab.c"
+/* Line 390 of yacc.c  */
+#line 338 "fortran.tab.c"
 
 #ifdef short
@@ -546,9 +387,9 @@
 #  if ENABLE_NLS
 #   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
-#   define YY_(msgid) dgettext ("bison-runtime", msgid)
+#   define YY_(Msgid) dgettext ("bison-runtime", Msgid)
 #  endif
 # endif
 # ifndef YY_
-#  define YY_(msgid) msgid
+#  define YY_(Msgid) Msgid
 # endif
 #endif
@@ -556,24 +397,24 @@
 /* Suppress unused-variable warnings by "using" E.  */
 #if ! defined lint || defined __GNUC__
-# define YYUSE(e) ((void) (e))
+# define YYUSE(E) ((void) (E))
 #else
-# define YYUSE(e) /* empty */
+# define YYUSE(E) /* empty */
 #endif
 
 /* Identity function, used to suppress warnings about constant conditions.  */
 #ifndef lint
-# define YYID(n) (n)
+# define YYID(N) (N)
 #else
 #if (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 static int
-YYID (int i)
+YYID (int yyi)
 #else
 static int
-YYID (i)
-    int i;
+YYID (yyi)
+    int yyi;
 #endif
 {
-  return i;
+  return yyi;
 }
 #endif
@@ -596,9 +437,10 @@
 #   else
 #    define YYSTACK_ALLOC alloca
-#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+#    if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 #     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#     ifndef _STDLIB_H
-#      define _STDLIB_H 1
+      /* Use EXIT_SUCCESS as a witness for stdlib.h.  */
+#     ifndef EXIT_SUCCESS
+#      define EXIT_SUCCESS 0
 #     endif
 #    endif
@@ -623,15 +465,15 @@
 #   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
 #  endif
-#  if (defined __cplusplus && ! defined _STDLIB_H \
+#  if (defined __cplusplus && ! defined EXIT_SUCCESS \
        && ! ((defined YYMALLOC || defined malloc) \
 	     && (defined YYFREE || defined free)))
 #   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#   ifndef _STDLIB_H
-#    define _STDLIB_H 1
+#   ifndef EXIT_SUCCESS
+#    define EXIT_SUCCESS 0
 #   endif
 #  endif
 #  ifndef YYMALLOC
 #   define YYMALLOC malloc
-#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+#   if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
@@ -640,5 +482,5 @@
 #  ifndef YYFREE
 #   define YYFREE free
-#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+#   if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 void free (void *); /* INFRINGES ON USER NAME SPACE */
@@ -656,7 +498,7 @@
 union yyalloc
 {
-  yytype_int16 yyss;
-  YYSTYPE yyvs;
-  };
+  yytype_int16 yyss_alloc;
+  YYSTYPE yyvs_alloc;
+};
 
 /* The size of the maximum gap between one aligned stack and the next.  */
@@ -669,21 +511,5 @@
       + YYSTACK_GAP_MAXIMUM)
 
-/* Copy COUNT objects from FROM to TO.  The source and destination do
-   not overlap.  */
-# ifndef YYCOPY
-#  if defined __GNUC__ && 1 < __GNUC__
-#   define YYCOPY(To, From, Count) \
-      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
-#  else
-#   define YYCOPY(To, From, Count)		\
-      do					\
-	{					\
-	  YYSIZE_T yyi;				\
-	  for (yyi = 0; yyi < (Count); yyi++)	\
-	    (To)[yyi] = (From)[yyi];		\
-	}					\
-      while (YYID (0))
-#  endif
-# endif
+# define YYCOPY_NEEDED 1
 
 /* Relocate STACK from its old location to the new one.  The
@@ -692,10 +518,10 @@
    stack.  Advance YYPTR to a properly aligned location for the next
    stack.  */
-# define YYSTACK_RELOCATE(Stack)					\
+# define YYSTACK_RELOCATE(Stack_alloc, Stack)				\
     do									\
       {									\
 	YYSIZE_T yynewbytes;						\
-	YYCOPY (&yyptr->Stack, Stack, yysize);				\
-	Stack = &yyptr->Stack;						\
+	YYCOPY (&yyptr->Stack_alloc, Stack, yysize);			\
+	Stack = &yyptr->Stack_alloc;					\
 	yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
 	yyptr += yynewbytes / sizeof (*yyptr);				\
@@ -705,21 +531,41 @@
 #endif
 
+#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
+/* Copy COUNT objects from SRC to DST.  The source and destination do
+   not overlap.  */
+# ifndef YYCOPY
+#  if defined __GNUC__ && 1 < __GNUC__
+#   define YYCOPY(Dst, Src, Count) \
+      __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
+#  else
+#   define YYCOPY(Dst, Src, Count)              \
+      do                                        \
+        {                                       \
+          YYSIZE_T yyi;                         \
+          for (yyi = 0; yyi < (Count); yyi++)   \
+            (Dst)[yyi] = (Src)[yyi];            \
+        }                                       \
+      while (YYID (0))
+#  endif
+# endif
+#endif /* !YYCOPY_NEEDED */
+
 /* YYFINAL -- State number of the termination state.  */
 #define YYFINAL  2
 /* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   6070
+#define YYLAST   6268
 
 /* YYNTOKENS -- Number of terminals.  */
-#define YYNTOKENS  190
+#define YYNTOKENS  169
 /* YYNNTS -- Number of nonterminals.  */
-#define YYNNTS  184
+#define YYNNTS  206
 /* YYNRULES -- Number of rules.  */
-#define YYNRULES  555
+#define YYNRULES  597
 /* YYNRULES -- Number of states.  */
-#define YYNSTATES  982
+#define YYNSTATES  1051
 
 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
 #define YYUNDEFTOK  2
-#define YYMAXUTOK   427
+#define YYMAXUTOK   410
 
 #define YYTRANSLATE(YYX)						\
@@ -730,13 +576,13 @@
 {
        0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-     187,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+     166,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,   183,     2,     2,     2,   189,     2,     2,
-     179,   180,    23,    21,     3,    22,     2,   188,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,   168,     2,     2,
+     162,   163,    21,    19,     3,    20,     2,   167,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     4,     2,
-     185,     5,   186,     2,     2,     2,     2,     2,     2,     2,
+     164,     5,   165,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,   181,     2,   182,     2,   184,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
@@ -756,5 +602,5 @@
        2,     2,     2,     2,     2,     2,     1,     2,     6,     7,
        8,     9,    10,    11,    12,    13,    14,    15,    16,    17,
-      18,    19,    20,    24,    25,    26,    27,    28,    29,    30,
+      18,    22,    23,    24,    25,    26,    27,    28,    29,    30,
       31,    32,    33,    34,    35,    36,    37,    38,    39,    40,
       41,    42,    43,    44,    45,    46,    47,    48,    49,    50,
@@ -770,6 +616,5 @@
      141,   142,   143,   144,   145,   146,   147,   148,   149,   150,
      151,   152,   153,   154,   155,   156,   157,   158,   159,   160,
-     161,   162,   163,   164,   165,   166,   167,   168,   169,   170,
-     171,   172,   173,   174,   175,   176,   177,   178
+     161
 };
 
@@ -779,60 +624,64 @@
 static const yytype_uint16 yyprhs[] =
 {
-       0,     0,     3,     4,     7,    10,    13,    15,    19,    23,
-      25,    29,    32,    35,    39,    43,    46,    49,    52,    54,
-      56,    58,    60,    61,    62,    65,    66,    68,    69,    70,
-      72,    73,    78,    81,    88,    93,    96,    98,    99,   101,
-     103,   104,   107,   111,   112,   115,   119,   121,   125,   127,
-     129,   132,   137,   140,   143,   148,   151,   153,   155,   157,
-     159,   161,   163,   165,   167,   169,   171,   176,   180,   184,
-     187,   191,   192,   194,   196,   198,   200,   202,   204,   206,
-     208,   210,   212,   214,   216,   218,   220,   222,   224,   226,
-     228,   230,   232,   234,   236,   238,   240,   242,   244,   248,
-     252,   258,   260,   264,   268,   271,   276,   278,   282,   283,
-     286,   289,   293,   295,   297,   299,   304,   311,   316,   318,
-     322,   325,   329,   335,   339,   341,   342,   345,   347,   352,
-     356,   359,   363,   367,   371,   375,   376,   378,   381,   384,
-     388,   394,   398,   399,   402,   405,   407,   413,   419,   422,
-     426,   429,   433,   435,   439,   442,   446,   452,   454,   457,
-     459,   463,   466,   468,   472,   473,   475,   477,   481,   485,
-     488,   490,   494,   497,   500,   501,   508,   516,   517,   520,
-     523,   527,   531,   533,   534,   537,   542,   546,   550,   555,
-     558,   560,   562,   564,   566,   568,   570,   572,   574,   575,
-     578,   580,   584,   585,   588,   592,   594,   598,   601,   605,
-     607,   609,   611,   613,   614,   618,   619,   622,   627,   629,
-     633,   635,   637,   639,   642,   644,   649,   651,   653,   655,
-     657,   659,   661,   663,   665,   667,   669,   670,   674,   676,
-     680,   682,   684,   687,   690,   694,   696,   698,   700,   704,
-     706,   708,   712,   716,   721,   726,   730,   735,   740,   744,
-     749,   754,   759,   764,   769,   774,   779,   784,   789,   794,
-     799,   804,   809,   813,   818,   823,   828,   833,   835,   839,
-     841,   843,   845,   848,   851,   854,   856,   858,   861,   864,
-     867,   870,   873,   876,   879,   882,   885,   888,   891,   895,
-     898,   902,   905,   908,   911,   914,   917,   920,   923,   924,
-     926,   929,   932,   935,   937,   939,   941,   943,   944,   946,
-     949,   954,   960,   965,   969,   973,   975,   978,   980,   984,
-     986,   988,   992,   998,  1003,  1007,  1010,  1013,  1015,  1017,
-    1019,  1021,  1023,  1025,  1027,  1029,  1032,  1035,  1037,  1040,
-    1042,  1044,  1045,  1047,  1053,  1054,  1056,  1058,  1060,  1061,
-    1065,  1069,  1070,  1076,  1079,  1084,  1091,  1098,  1100,  1102,
-    1104,  1108,  1112,  1114,  1118,  1122,  1124,  1126,  1132,  1138,
-    1143,  1145,  1148,  1151,  1154,  1157,  1159,  1162,  1168,  1170,
-    1172,  1175,  1181,  1183,  1186,  1190,  1195,  1197,  1199,  1201,
-    1203,  1205,  1207,  1209,  1211,  1215,  1219,  1223,  1226,  1229,
-    1230,  1236,  1244,  1245,  1248,  1250,  1252,  1253,  1255,  1257,
-    1259,  1261,  1264,  1266,  1268,  1270,  1276,  1282,  1285,  1288,
-    1291,  1294,  1296,  1297,  1302,  1309,  1311,  1315,  1318,  1321,
-    1324,  1325,  1329,  1330,  1332,  1335,  1337,  1339,  1343,  1345,
-    1348,  1350,  1352,  1355,  1358,  1361,  1365,  1368,  1370,  1371,
-    1373,  1376,  1379,  1380,  1383,  1387,  1391,  1395,  1399,  1401,
-    1405,  1407,  1409,  1413,  1415,  1417,  1419,  1423,  1426,  1431,
-    1436,  1439,  1442,  1444,  1446,  1448,  1450,  1452,  1454,  1456,
-    1458,  1460,  1464,  1466,  1468,  1472,  1476,  1480,  1484,  1487,
-    1491,  1494,  1497,  1500,  1503,  1507,  1509,  1511,  1513,  1515,
-    1519,  1520,  1522,  1525,  1530,  1533,  1536,  1542,  1543,  1545,
-    1548,  1550,  1552,  1554,  1558,  1562,  1566,  1570,  1574,  1578,
-    1580,  1582,  1584,  1588,  1594,  1600,  1606,  1612,  1620,  1622,
-    1631,  1634,  1636,  1638,  1642,  1644,  1646,  1648,  1653,  1655,
-    1659,  1660,  1665,  1667,  1671,  1675
+       0,     0,     3,     4,     7,     9,    11,    14,    16,    19,
+      21,    25,    28,    31,    33,    37,    41,    44,    47,    51,
+      53,    54,    55,    57,    58,    61,    66,    69,    75,    78,
+      80,    83,    85,    87,    88,    91,    95,    96,    99,   103,
+     105,   109,   111,   113,   116,   121,   124,   127,   132,   135,
+     137,   139,   141,   143,   145,   147,   149,   151,   153,   158,
+     162,   166,   169,   172,   173,   175,   177,   179,   181,   183,
+     185,   187,   189,   191,   193,   195,   197,   199,   201,   203,
+     205,   207,   209,   211,   213,   215,   217,   219,   221,   223,
+     225,   229,   233,   239,   241,   245,   249,   252,   257,   259,
+     263,   264,   266,   269,   273,   275,   277,   280,   282,   286,
+     291,   296,   305,   307,   311,   314,   318,   324,   328,   330,
+     331,   334,   336,   341,   345,   348,   352,   356,   360,   364,
+     365,   367,   370,   374,   380,   384,   386,   392,   398,   401,
+     405,   408,   412,   414,   416,   420,   424,   427,   431,   437,
+     439,   442,   444,   448,   451,   453,   457,   458,   460,   462,
+     466,   470,   473,   475,   479,   482,   485,   491,   498,   499,
+     502,   505,   509,   513,   514,   517,   522,   526,   530,   535,
+     538,   540,   542,   544,   546,   548,   550,   552,   553,   556,
+     558,   562,   563,   566,   570,   572,   576,   579,   583,   585,
+     587,   589,   591,   593,   594,   598,   599,   601,   605,   607,
+     611,   613,   615,   617,   620,   622,   627,   629,   631,   633,
+     635,   637,   639,   641,   643,   645,   647,   648,   652,   654,
+     658,   660,   662,   665,   668,   672,   674,   676,   678,   680,
+     682,   686,   690,   694,   699,   704,   708,   713,   718,   722,
+     727,   732,   737,   742,   747,   752,   757,   762,   767,   772,
+     777,   782,   787,   791,   796,   800,   805,   810,   812,   816,
+     818,   820,   822,   825,   828,   831,   833,   835,   838,   841,
+     844,   847,   850,   853,   856,   859,   862,   866,   870,   873,
+     876,   879,   882,   885,   888,   891,   894,   897,   900,   901,
+     903,   906,   909,   912,   914,   916,   918,   920,   921,   923,
+     926,   931,   937,   942,   947,   951,   953,   956,   958,   962,
+     964,   966,   970,   976,   981,   985,   988,   991,   993,   995,
+     997,   999,  1001,  1003,  1005,  1007,  1010,  1013,  1015,  1018,
+    1020,  1022,  1023,  1025,  1031,  1032,  1034,  1036,  1038,  1039,
+    1042,  1045,  1051,  1054,  1059,  1066,  1073,  1075,  1077,  1081,
+    1085,  1087,  1091,  1095,  1097,  1099,  1101,  1103,  1105,  1107,
+    1109,  1111,  1113,  1116,  1118,  1120,  1123,  1126,  1129,  1133,
+    1136,  1142,  1148,  1151,  1154,  1157,  1160,  1162,  1167,  1169,
+    1172,  1175,  1178,  1181,  1183,  1185,  1187,  1189,  1195,  1202,
+    1203,  1207,  1208,  1213,  1214,  1219,  1224,  1226,  1228,  1230,
+    1232,  1234,  1238,  1243,  1245,  1248,  1250,  1253,  1254,  1255,
+    1258,  1262,  1264,  1269,  1271,  1273,  1278,  1281,  1287,  1291,
+    1295,  1297,  1302,  1305,  1312,  1321,  1327,  1331,  1333,  1335,
+    1337,  1339,  1341,  1344,  1351,  1352,  1354,  1357,  1361,  1362,
+    1364,  1367,  1371,  1379,  1385,  1391,  1398,  1400,  1403,  1405,
+    1408,  1414,  1419,  1420,  1422,  1425,  1429,  1436,  1441,  1444,
+    1448,  1450,  1453,  1457,  1459,  1461,  1465,  1467,  1470,  1473,
+    1477,  1479,  1481,  1483,  1485,  1487,  1489,  1491,  1493,  1495,
+    1496,  1501,  1509,  1511,  1515,  1518,  1521,  1524,  1525,  1529,
+    1530,  1532,  1535,  1538,  1540,  1542,  1546,  1548,  1551,  1553,
+    1555,  1556,  1558,  1561,  1564,  1565,  1568,  1572,  1576,  1580,
+    1582,  1586,  1588,  1590,  1594,  1596,  1598,  1600,  1604,  1610,
+    1615,  1618,  1621,  1622,  1624,  1626,  1628,  1630,  1632,  1634,
+    1636,  1638,  1640,  1644,  1646,  1648,  1652,  1656,  1660,  1664,
+    1667,  1671,  1674,  1677,  1680,  1683,  1686,  1689,  1692,  1696,
+    1698,  1700,  1702,  1704,  1708,  1711,  1716,  1719,  1722,  1728,
+    1729,  1731,  1734,  1736,  1738,  1740,  1742,  1746,  1750,  1754,
+    1758,  1762,  1766,  1772,  1778,  1784,  1790,  1798,  1807,  1810,
+    1812,  1816,  1818,  1820,  1824,  1825,  1830,  1832
 };
 
@@ -840,172 +689,188 @@
 static const yytype_int16 yyrhs[] =
 {
-     191,     0,    -1,    -1,   191,   192,    -1,   187,   198,    -1,
-     199,   193,    -1,   177,    -1,   197,   200,   205,    -1,     1,
-     205,   201,    -1,   194,    -1,   193,    27,   194,    -1,   203,
-     196,    -1,   212,   196,    -1,   206,   207,   196,    -1,   315,
-     200,   205,    -1,   195,   196,    -1,   298,     4,    -1,   198,
-     200,    -1,    53,    -1,    54,    -1,    36,    -1,    37,    -1,
-      -1,    -1,   144,   201,    -1,    -1,   177,    -1,    -1,    -1,
-      72,    -1,    -1,   202,    33,   204,   208,    -1,    34,   204,
-      -1,   202,    35,   204,   208,    30,   209,    -1,   202,    35,
-     204,   208,    -1,    95,   169,    -1,   169,    -1,    -1,    32,
-      -1,   158,    -1,    -1,   179,   180,    -1,   179,   210,   180,
-      -1,    -1,   179,   180,    -1,   179,   210,   180,    -1,   211,
-      -1,   210,     3,   211,    -1,   169,    -1,    23,    -1,   257,
-     222,    -1,   145,   213,   221,   324,    -1,   147,   324,    -1,
-     117,   216,    -1,   224,   179,   249,   180,    -1,   224,   249,
-      -1,   243,    -1,   228,    -1,   253,    -1,   239,    -1,   241,
-      -1,   240,    -1,   308,    -1,   251,    -1,   237,    -1,   234,
-      -1,    68,   179,   280,   180,    -1,   111,   221,   242,    -1,
-     113,   221,   215,    -1,    67,   217,    -1,   225,   226,   187,
-      -1,    -1,   275,    -1,    46,    -1,    40,    -1,    44,    -1,
-      56,    -1,    79,    -1,    45,    -1,    47,    -1,    62,    -1,
-      57,    -1,    58,    -1,    59,    -1,    60,    -1,    61,    -1,
-      64,    -1,    65,    -1,    66,    -1,    69,    -1,    70,    -1,
-      71,    -1,    74,    -1,    75,    -1,    76,    -1,    77,    -1,
-     169,    -1,   214,    -1,   215,     3,   214,    -1,   179,   220,
-     180,    -1,   216,     3,   179,   220,   180,    -1,   218,    -1,
-     217,     3,   218,    -1,   179,   219,   180,    -1,   298,   276,
-      -1,   219,     3,   298,   276,    -1,   280,    -1,   220,     3,
-     280,    -1,    -1,     4,     4,    -1,   255,   256,    -1,   223,
-     204,   208,    -1,    35,    -1,    29,    -1,   160,    -1,   169,
-      24,   227,    24,    -1,   226,   248,   169,    24,   227,    24,
-      -1,   231,    24,   227,    24,    -1,   232,    -1,   232,     3,
-     227,    -1,   229,   230,    -1,   229,   247,   230,    -1,   228,
-     248,   247,   248,   230,    -1,   228,     3,   230,    -1,   119,
-      -1,    -1,   169,   276,    -1,   169,    -1,   169,   179,   280,
-     180,    -1,   231,     3,   231,    -1,   233,   299,    -1,   232,
-      21,   232,    -1,   232,    22,   232,    -1,   232,    23,   232,
-      -1,   232,   188,   232,    -1,    -1,   284,    -1,   235,   236,
-      -1,   114,   298,    -1,   114,   247,   298,    -1,   235,   248,
-     247,   248,   298,    -1,   235,     3,   298,    -1,    -1,   129,
-     324,    -1,   130,   324,    -1,   109,    -1,   238,   248,   169,
-     276,   264,    -1,   239,     3,   169,   276,   264,    -1,    81,
-     187,    -1,    81,   221,   242,    -1,    80,   187,    -1,    80,
-     221,   242,    -1,   169,    -1,   242,     3,   169,    -1,   244,
-     245,    -1,   244,   247,   245,    -1,   243,   248,   247,   248,
-     245,    -1,   127,    -1,   128,   127,    -1,   246,    -1,   245,
-       3,   246,    -1,   169,   276,    -1,    20,    -1,    24,   169,
-      24,    -1,    -1,     3,    -1,   250,    -1,   249,     3,   250,
-      -1,   169,     5,   280,    -1,   134,   252,    -1,   169,    -1,
-     252,     3,   169,    -1,   122,   123,    -1,   122,   137,    -1,
-      -1,   271,   254,   169,   276,   264,   305,    -1,   255,     3,
-     254,   169,   276,   264,   305,    -1,    -1,   262,   266,    -1,
-     261,   259,    -1,   263,    23,   176,    -1,   258,   268,   180,
-      -1,   146,    -1,    -1,    23,   176,    -1,    23,   179,   260,
-     180,    -1,   179,   260,   180,    -1,   169,   269,   270,    -1,
-     169,     5,   269,   270,    -1,   269,   270,    -1,   157,    -1,
-     263,    -1,   149,    -1,   148,    -1,   167,    -1,   151,    -1,
-     168,    -1,   150,    -1,    -1,    23,   265,    -1,   280,    -1,
-     179,    23,   180,    -1,    -1,    23,   267,    -1,   179,   268,
-     180,    -1,   280,    -1,   179,    23,   180,    -1,   169,   269,
-      -1,   169,     5,   269,    -1,   169,    -1,   176,    -1,   280,
-      -1,    23,    -1,    -1,     3,   169,   269,    -1,    -1,     4,
-       4,    -1,     3,   272,     4,     4,    -1,   273,    -1,   272,
-       3,   273,    -1,    29,    -1,   275,    -1,    82,    -1,   109,
-     276,    -1,   111,    -1,   112,   179,   274,   180,    -1,   113,
-      -1,   116,    -1,   117,    -1,   119,    -1,   120,    -1,   140,
-      -1,   138,    -1,   139,    -1,    80,    -1,    81,    -1,    -1,
-     179,   277,   180,    -1,   278,    -1,   277,     3,   278,    -1,
-     279,    -1,     4,    -1,   280,     4,    -1,     4,   280,    -1,
-     280,     4,   279,    -1,    23,    -1,   280,    -1,   283,    -1,
-     179,   280,   180,    -1,   307,    -1,   281,    -1,    46,   282,
-     180,    -1,    39,   282,   180,    -1,    40,   179,   282,   180,
-      -1,    44,   179,   282,   180,    -1,    56,   282,   180,    -1,
-      79,   179,   282,   180,    -1,    45,   179,   280,   180,    -1,
-      47,   280,   180,    -1,   148,   179,   282,   180,    -1,    62,
-     179,   280,   180,    -1,    57,   179,   280,   180,    -1,    58,
-     179,   280,   180,    -1,    59,   179,   280,   180,    -1,    60,
-     179,   280,   180,    -1,    61,   179,   280,   180,    -1,    64,
-     179,   280,   180,    -1,    65,   179,   280,   180,    -1,    66,
-     179,   280,   180,    -1,    69,   179,   280,   180,    -1,    70,
-     179,   280,   180,    -1,    71,   179,   280,   180,    -1,    73,
-     280,   180,    -1,    74,   179,   282,   180,    -1,    75,   179,
-     282,   180,    -1,    76,   179,   282,   180,    -1,    77,   179,
-     282,   180,    -1,   280,    -1,   282,     3,   280,    -1,   288,
-      -1,   299,    -1,   293,    -1,   280,   285,    -1,   284,   280,
-      -1,    12,   280,    -1,    21,    -1,    22,    -1,    21,   280,
-      -1,    22,   280,    -1,    23,   280,    -1,    25,   280,    -1,
-      14,   280,    -1,     8,   280,    -1,    17,   280,    -1,   186,
-     280,    -1,    18,   280,    -1,   185,   280,    -1,    15,   280,
-      -1,   186,     5,   280,    -1,    16,   280,    -1,   185,     5,
-     280,    -1,    13,   280,    -1,     7,   280,    -1,     9,   280,
-      -1,    10,   280,    -1,    11,   280,    -1,    24,   286,    -1,
-       5,   287,    -1,    -1,   280,    -1,     5,   280,    -1,    24,
-     280,    -1,     5,   280,    -1,   280,    -1,   298,    -1,   292,
-      -1,   290,    -1,    -1,   291,    -1,   291,   302,    -1,   292,
-     179,   294,   180,    -1,   292,   179,   294,   180,   302,    -1,
-     298,   179,   294,   180,    -1,   288,   189,   288,    -1,   131,
-     360,   132,    -1,   289,    -1,   289,   295,    -1,   296,    -1,
-     295,     3,   296,    -1,   280,    -1,   297,    -1,   280,     4,
-     280,    -1,   280,     4,   280,     4,   280,    -1,     4,   280,
-       4,   280,    -1,     4,     4,   280,    -1,     4,   280,    -1,
-     280,     4,    -1,     4,    -1,   169,    -1,   142,    -1,   143,
-      -1,   176,    -1,   163,    -1,   164,    -1,   165,    -1,   299,
-     169,    -1,   300,   301,    -1,   158,    -1,   300,   158,    -1,
-     162,    -1,   159,    -1,    -1,   302,    -1,   179,   303,     4,
-     303,   180,    -1,    -1,   280,    -1,   187,    -1,   280,    -1,
-      -1,   306,     5,   280,    -1,   306,   126,   280,    -1,    -1,
-     179,   283,     3,   283,   180,    -1,   309,   310,    -1,   309,
-     310,     3,   311,    -1,   309,   310,     3,    31,     4,   187,
-      -1,   309,   310,     3,    31,     4,   313,    -1,   141,    -1,
-     169,    -1,   312,    -1,   311,     3,   312,    -1,   169,   126,
-     169,    -1,   314,    -1,   313,     3,   314,    -1,   169,   126,
-     169,    -1,   169,    -1,   328,    -1,    98,   179,   366,   370,
-     180,    -1,   105,   179,   369,   370,   180,    -1,   106,   179,
-     371,   180,    -1,   317,    -1,   318,   324,    -1,   316,   324,
-      -1,   319,   324,    -1,    96,   324,    -1,   321,    -1,   372,
-     328,    -1,    41,   179,   280,   180,   304,    -1,    42,    -1,
-      43,    -1,   372,    84,    -1,    85,   179,   280,   180,    84,
-      -1,    86,    -1,    87,   324,    -1,    48,   320,   180,    -1,
-      49,   179,   280,   180,    -1,   115,    -1,   110,    -1,    93,
-      -1,   153,    -1,   156,    -1,   155,    -1,   154,    -1,   280,
-      -1,   320,     3,   280,    -1,   320,     4,   280,    -1,   326,
-     323,   322,    -1,   327,   280,    -1,    94,   325,    -1,    -1,
-     373,     5,   280,     3,   280,    -1,   373,     5,   280,     3,
-     280,     3,   280,    -1,    -1,   176,   248,    -1,   187,    -1,
-     169,    -1,    -1,   169,    -1,    92,    -1,    97,    -1,   118,
-      -1,   330,   332,    -1,   365,    -1,   341,    -1,   333,    -1,
-      98,   179,   366,   370,   180,    -1,   105,   179,   369,   370,
-     180,    -1,    78,   303,    -1,    83,   304,    -1,    63,   304,
-      -1,   340,   304,    -1,   331,    -1,    -1,   298,   329,   276,
-     276,    -1,   330,   189,   298,   329,   276,   276,    -1,   176,
-      -1,   331,     3,   176,    -1,     5,   280,    -1,   126,   280,
-      -1,   336,   334,    -1,    -1,   179,   335,   180,    -1,    -1,
-     338,    -1,   337,   169,    -1,   124,    -1,   339,    -1,   338,
-       3,   339,    -1,   280,    -1,    23,   364,    -1,   133,    -1,
-     135,    -1,   349,   345,    -1,   351,   343,    -1,   352,   345,
-      -1,   352,   345,   360,    -1,   104,   346,    -1,    38,    -1,
-      -1,   356,    -1,   345,   342,    -1,   350,   344,    -1,    -1,
-       3,   356,    -1,   179,   347,   180,    -1,   179,   353,   180,
-      -1,   179,   298,   180,    -1,   179,   176,   180,    -1,   176,
-      -1,   179,   283,   180,    -1,   169,    -1,   348,    -1,   347,
-       3,   348,    -1,   353,    -1,    23,    -1,    25,    -1,   298,
-     280,   276,    -1,   298,   280,    -1,   298,   280,   189,   330,
-      -1,   298,   179,   297,   180,    -1,   298,    23,    -1,   298,
-      25,    -1,    99,    -1,   100,    -1,   354,    -1,    23,    -1,
-     103,    -1,   101,    -1,    88,    -1,   102,    -1,   354,    -1,
-     179,   353,   180,    -1,   288,    -1,   299,    -1,   353,   355,
-     353,    -1,   353,    23,   353,    -1,   353,    24,   353,    -1,
-     353,    25,   353,    -1,   355,   353,    -1,   353,    20,   353,
-      -1,    50,   280,    -1,    55,   280,    -1,    52,   280,    -1,
-      51,   280,    -1,   169,     5,   280,    -1,   281,    -1,    21,
-      -1,    22,    -1,   358,    -1,   356,     3,   358,    -1,    -1,
-     288,    -1,   357,   359,    -1,   179,   356,   180,   359,    -1,
-     281,   359,    -1,   299,   359,    -1,   179,   356,     3,   363,
-     180,    -1,    -1,   285,    -1,   359,   285,    -1,   283,    -1,
-     362,    -1,   361,    -1,   283,     3,   280,    -1,   283,     3,
-     362,    -1,   362,     3,   280,    -1,   362,     3,   362,    -1,
-     361,     3,   280,    -1,   361,     3,   362,    -1,   283,    -1,
-     281,    -1,   307,    -1,   179,   280,   180,    -1,   179,   283,
-       3,   363,   180,    -1,   179,   362,     3,   363,   180,    -1,
-     179,   361,     3,   363,   180,    -1,   169,     5,   280,     3,
-     280,    -1,   169,     5,   280,     3,   280,     3,   280,    -1,
-     176,    -1,    89,   179,   280,     3,   280,   180,     3,   280,
-      -1,    89,   364,    -1,   367,    -1,   330,    -1,   366,     3,
-     367,    -1,   298,    -1,   292,    -1,   368,    -1,   298,   179,
-     295,   180,    -1,   367,    -1,   369,     3,   367,    -1,    -1,
-       3,   125,     5,   298,    -1,   298,    -1,   371,     3,   298,
-      -1,    91,   280,   180,    -1,   298,    -1
+     170,     0,    -1,    -1,   170,   171,    -1,   172,    -1,   173,
+      -1,   140,   173,    -1,     1,    -1,   166,   175,    -1,    24,
+      -1,   172,   166,   175,    -1,   172,    24,    -1,   172,   140,
+      -1,   174,    -1,   173,    24,   166,    -1,   173,    24,   174,
+      -1,   178,   175,    -1,   186,   175,    -1,    28,   181,   175,
+      -1,   282,    -1,    -1,    -1,    70,    -1,    -1,    26,   183,
+      -1,   176,    29,   180,   182,    -1,    30,   180,    -1,   176,
+      31,   180,   182,   177,    -1,    92,   160,    -1,   161,    -1,
+     179,   161,    -1,   160,    -1,   153,    -1,    -1,   162,   163,
+      -1,   162,   184,   163,    -1,    -1,   162,   163,    -1,   162,
+     184,   163,    -1,   185,    -1,   184,     3,   185,    -1,   160,
+      -1,    21,    -1,   228,   196,    -1,   141,   187,   195,   336,
+      -1,   143,   336,    -1,   114,   190,    -1,   198,   162,   221,
+     163,    -1,   198,   221,    -1,   215,    -1,   203,    -1,   225,
+      -1,   211,    -1,   213,    -1,   212,    -1,   276,    -1,   223,
+      -1,   209,    -1,    66,   162,   249,   163,    -1,   108,   195,
+     214,    -1,   110,   195,   189,    -1,    65,   191,    -1,   199,
+     166,    -1,    -1,   244,    -1,    42,    -1,    34,    -1,    39,
+      -1,    54,    -1,    77,    -1,    40,    -1,    43,    -1,    60,
+      -1,    55,    -1,    56,    -1,    57,    -1,    58,    -1,    59,
+      -1,    62,    -1,    63,    -1,    64,    -1,    67,    -1,    68,
+      -1,    69,    -1,    72,    -1,    73,    -1,    74,    -1,    75,
+      -1,   160,    -1,   188,    -1,   189,     3,   188,    -1,   162,
+     194,   163,    -1,   190,     3,   162,   194,   163,    -1,   192,
+      -1,   191,     3,   192,    -1,   162,   193,   163,    -1,   267,
+     245,    -1,   193,     3,   267,   245,    -1,   249,    -1,   194,
+       3,   249,    -1,    -1,   131,    -1,   226,   227,    -1,   197,
+     180,   182,    -1,    31,    -1,    25,    -1,   155,   200,    -1,
+     201,    -1,   200,   220,   201,    -1,   160,    22,   202,    22,
+      -1,   206,    22,   202,    22,    -1,   162,   257,     3,   368,
+     163,    22,   202,    22,    -1,   207,    -1,   207,     3,   202,
+      -1,   204,   205,    -1,   204,   219,   205,    -1,   203,   220,
+     219,   220,   205,    -1,   203,     3,   205,    -1,   116,    -1,
+      -1,   160,   245,    -1,   160,    -1,   160,   162,   249,   163,
+      -1,   206,     3,   206,    -1,   208,   268,    -1,   207,    19,
+     207,    -1,   207,    20,   207,    -1,   207,    21,   207,    -1,
+     207,   167,   207,    -1,    -1,   253,    -1,   111,   267,    -1,
+     111,   219,   267,    -1,   209,   220,   219,   220,   267,    -1,
+     209,     3,   267,    -1,   106,    -1,   210,   220,   160,   245,
+     233,    -1,   211,     3,   160,   245,   233,    -1,    79,   166,
+      -1,    79,   195,   214,    -1,    78,   166,    -1,    78,   195,
+     214,    -1,   160,    -1,   133,    -1,   214,     3,   160,    -1,
+     214,     3,   133,    -1,   216,   217,    -1,   216,   219,   217,
+      -1,   215,   220,   219,   220,   217,    -1,   123,    -1,   124,
+     123,    -1,   218,    -1,   217,     3,   218,    -1,   160,   245,
+      -1,    18,    -1,    22,   160,    22,    -1,    -1,     3,    -1,
+     222,    -1,   221,     3,   222,    -1,   160,     5,   249,    -1,
+     128,   224,    -1,   160,    -1,   224,     3,   160,    -1,   118,
+     119,    -1,   118,   130,    -1,   240,   160,   245,   233,   274,
+      -1,   226,     3,   160,   245,   233,   274,    -1,    -1,   232,
+     235,    -1,   231,   229,    -1,   232,    21,   161,    -1,   142,
+     237,   163,    -1,    -1,    21,   161,    -1,    21,   162,   230,
+     163,    -1,   162,   230,   163,    -1,   160,   238,   239,    -1,
+     160,     5,   238,   239,    -1,   238,   239,    -1,   152,    -1,
+     145,    -1,   146,    -1,   144,    -1,   158,    -1,   159,    -1,
+     147,    -1,    -1,    21,   234,    -1,   249,    -1,   162,    21,
+     163,    -1,    -1,    21,   236,    -1,   162,   237,   163,    -1,
+     249,    -1,   162,    21,   163,    -1,   160,   238,    -1,   160,
+       5,   238,    -1,   160,    -1,   161,    -1,   133,    -1,   249,
+      -1,    21,    -1,    -1,     3,   160,   238,    -1,    -1,   131,
+      -1,     3,   241,   131,    -1,   242,    -1,   241,     3,   242,
+      -1,    25,    -1,   244,    -1,    80,    -1,   106,   245,    -1,
+     108,    -1,   109,   162,   243,   163,    -1,   110,    -1,   113,
+      -1,   114,    -1,   116,    -1,   117,    -1,   136,    -1,   134,
+      -1,   135,    -1,    78,    -1,    79,    -1,    -1,   162,   246,
+     163,    -1,   247,    -1,   246,     3,   247,    -1,   248,    -1,
+       4,    -1,   249,     4,    -1,     4,   249,    -1,   249,     4,
+     248,    -1,    21,    -1,   249,    -1,   252,    -1,   275,    -1,
+     250,    -1,   162,   249,   163,    -1,    42,   251,   163,    -1,
+      33,   251,   163,    -1,    34,   162,   251,   163,    -1,    39,
+     162,   251,   163,    -1,    54,   251,   163,    -1,    77,   162,
+     251,   163,    -1,    40,   162,   249,   163,    -1,    43,   249,
+     163,    -1,   144,   162,   251,   163,    -1,    60,   162,   249,
+     163,    -1,    55,   162,   249,   163,    -1,    56,   162,   249,
+     163,    -1,    57,   162,   249,   163,    -1,    58,   162,   249,
+     163,    -1,    59,   162,   249,   163,    -1,    62,   162,   249,
+     163,    -1,    63,   162,   249,   163,    -1,    64,   162,   249,
+     163,    -1,    67,   162,   249,   163,    -1,    68,   162,   249,
+     163,    -1,    69,   162,   249,   163,    -1,    71,   249,   163,
+      -1,    72,   162,   251,   163,    -1,    73,   251,   163,    -1,
+      74,   162,   251,   163,    -1,    75,   162,   251,   163,    -1,
+     249,    -1,   251,     3,   249,    -1,   257,    -1,   268,    -1,
+     262,    -1,   249,   254,    -1,   253,   249,    -1,    11,   249,
+      -1,    19,    -1,    20,    -1,    19,   249,    -1,    20,   249,
+      -1,    21,   249,    -1,    23,   249,    -1,    13,   249,    -1,
+       7,   249,    -1,    16,   249,    -1,   165,   249,    -1,   164,
+     249,    -1,   165,     5,   249,    -1,   164,     5,   249,    -1,
+      17,   249,    -1,    14,   249,    -1,    15,   249,    -1,    12,
+     249,    -1,     6,   249,    -1,     8,   249,    -1,     9,   249,
+      -1,    10,   249,    -1,    22,   255,    -1,     5,   256,    -1,
+      -1,   249,    -1,     5,   249,    -1,    22,   249,    -1,     5,
+     249,    -1,   249,    -1,   267,    -1,   261,    -1,   259,    -1,
+      -1,   260,    -1,   260,   271,    -1,   261,   162,   263,   163,
+      -1,   261,   162,   263,   163,   271,    -1,   267,   162,   263,
+     163,    -1,   257,   168,   356,   257,    -1,   125,   366,   126,
+      -1,   258,    -1,   258,   264,    -1,   265,    -1,   264,     3,
+     265,    -1,   249,    -1,   266,    -1,   249,     4,   249,    -1,
+     249,     4,   249,     4,   249,    -1,     4,   249,     4,   249,
+      -1,     4,     4,   249,    -1,     4,   249,    -1,   249,     4,
+      -1,     4,    -1,   160,    -1,   138,    -1,   139,    -1,    41,
+      -1,   161,    -1,   157,    -1,   132,    -1,   268,   160,    -1,
+     269,   270,    -1,   153,    -1,   269,   153,    -1,   156,    -1,
+     154,    -1,    -1,   271,    -1,   162,   272,     4,   272,   163,
+      -1,    -1,   249,    -1,   166,    -1,   249,    -1,    -1,     5,
+     249,    -1,   122,   249,    -1,   162,   252,     3,   252,   163,
+      -1,   277,   160,    -1,   277,   160,     3,   278,    -1,   277,
+     160,     3,    27,     4,   166,    -1,   277,   160,     3,    27,
+       4,   280,    -1,   137,    -1,   279,    -1,   278,     3,   279,
+      -1,   160,   122,   160,    -1,   281,    -1,   280,     3,   281,
+      -1,   160,   122,   160,    -1,   160,    -1,   283,    -1,   331,
+      -1,   284,    -1,   300,    -1,   320,    -1,   310,    -1,   287,
+      -1,   115,    -1,   338,   340,    -1,   369,    -1,   341,    -1,
+     357,   352,    -1,   359,   350,    -1,   100,   352,    -1,   100,
+     352,   366,    -1,   103,   353,    -1,    96,   162,   370,   373,
+     163,    -1,   104,   162,   372,   373,   163,    -1,    76,   272,
+      -1,    81,   273,    -1,    61,   273,    -1,   348,   273,    -1,
+     339,    -1,   105,   162,   374,   163,    -1,   333,    -1,   334,
+     336,    -1,   332,   336,    -1,   335,   336,    -1,    93,   336,
+      -1,   319,    -1,   286,    -1,    90,    -1,   249,    -1,    35,
+     162,   294,   163,   293,    -1,   291,   172,   288,   289,   290,
+     297,    -1,    -1,   288,   292,   172,    -1,    -1,   289,   295,
+     172,   288,    -1,    -1,   290,   296,   172,   288,    -1,    35,
+     162,   294,   163,    -1,   293,    -1,   286,    -1,   287,    -1,
+     285,    -1,   249,    -1,    36,   294,   163,    -1,    36,   294,
+     163,   160,    -1,    37,    -1,    37,   160,    -1,    38,    -1,
+      38,   160,    -1,    -1,    -1,   299,   282,    -1,   299,   282,
+     172,    -1,   301,    -1,   302,   172,   307,   308,    -1,   303,
+      -1,   304,    -1,   160,     4,    89,   179,    -1,    89,   179,
+      -1,   160,     4,    89,   179,   305,    -1,    89,   179,   305,
+      -1,   160,     4,    89,    -1,    89,    -1,   160,     4,    89,
+     305,    -1,    89,   305,    -1,   220,   306,     5,   249,     3,
+     249,    -1,   220,   306,     5,   249,     3,   249,     3,   249,
+      -1,   220,    94,   162,   249,   163,    -1,   220,    95,   298,
+      -1,   267,    -1,   299,    -1,   309,    -1,   330,    -1,    91,
+      -1,    91,   160,    -1,   315,   172,   299,   311,   313,   318,
+      -1,    -1,   312,    -1,   311,   312,    -1,   316,   172,   299,
+      -1,    -1,   314,    -1,   313,   312,    -1,   317,   172,   299,
+      -1,   160,     4,    88,   162,   249,   163,    82,    -1,    88,
+     162,   249,   163,    82,    -1,    83,   162,   249,   163,    82,
+      -1,    83,   162,   249,   163,    82,   160,    -1,    84,    -1,
+      84,   160,    -1,    85,    -1,    85,   160,    -1,    88,   162,
+     249,   163,   284,    -1,   323,   172,   321,   325,    -1,    -1,
+     322,    -1,   321,   322,    -1,   324,   172,   299,    -1,   160,
+       4,    45,   162,   249,   163,    -1,    45,   162,   249,   163,
+      -1,    44,   326,    -1,    44,   326,   160,    -1,   107,    -1,
+     107,   160,    -1,   162,   327,   163,    -1,   112,    -1,   328,
+      -1,   327,     3,   328,    -1,   329,    -1,   329,     4,    -1,
+       4,   329,    -1,   329,     4,   329,    -1,   249,    -1,   115,
+      -1,    32,    -1,   148,    -1,   151,    -1,   150,    -1,   149,
+      -1,   166,    -1,   160,    -1,    -1,   267,   337,   245,   245,
+      -1,   338,   168,   356,   267,   337,   245,   245,    -1,   161,
+      -1,   339,     3,   161,    -1,     5,   249,    -1,   122,   249,
+      -1,   344,   342,    -1,    -1,   162,   343,   163,    -1,    -1,
+     346,    -1,   345,   101,    -1,   345,   160,    -1,   120,    -1,
+     347,    -1,   346,     3,   347,    -1,   249,    -1,    21,   161,
+      -1,   127,    -1,   129,    -1,    -1,   363,    -1,   352,   349,
+      -1,   358,   351,    -1,    -1,     3,   363,    -1,   162,   354,
+     163,    -1,   162,   267,   163,    -1,   162,   161,   163,    -1,
+     161,    -1,   162,   252,   163,    -1,   160,    -1,   355,    -1,
+     354,     3,   355,    -1,   360,    -1,    21,    -1,    23,    -1,
+     267,   249,   245,    -1,   267,   249,   168,   356,   338,    -1,
+     267,   162,   266,   163,    -1,   267,    21,    -1,   267,    23,
+      -1,    -1,    97,    -1,    98,    -1,   101,    -1,   361,    -1,
+      21,    -1,   102,    -1,    99,    -1,    86,    -1,   361,    -1,
+     162,   360,   163,    -1,   257,    -1,   268,    -1,   360,   362,
+     360,    -1,   360,    21,   360,    -1,   360,    22,   360,    -1,
+     360,    23,   360,    -1,   362,   360,    -1,   360,    18,   360,
+      -1,    46,   249,    -1,    47,   249,    -1,    49,   249,    -1,
+      48,   249,    -1,    53,   249,    -1,    52,   249,    -1,    50,
+     249,    -1,   160,     5,   249,    -1,   250,    -1,    19,    -1,
+      20,    -1,   364,    -1,   363,     3,   364,    -1,   257,   365,
+      -1,   162,   363,   163,   365,    -1,   250,   365,    -1,   268,
+     365,    -1,   162,   363,     3,   368,   163,    -1,    -1,   254,
+      -1,   365,   254,    -1,   275,    -1,   250,    -1,   252,    -1,
+     367,    -1,   252,     3,   249,    -1,   252,     3,   367,    -1,
+     367,     3,   249,    -1,   367,     3,   367,    -1,   366,     3,
+     249,    -1,   366,     3,   367,    -1,   162,   252,     3,   368,
+     163,    -1,   162,   366,     3,   368,   163,    -1,   162,   367,
+       3,   368,   163,    -1,   160,     5,   249,     3,   249,    -1,
+     160,     5,   249,     3,   249,     3,   249,    -1,    87,   162,
+     249,     3,   249,   163,     3,   249,    -1,    87,   161,    -1,
+     371,    -1,   370,     3,   371,    -1,   257,    -1,   371,    -1,
+     372,     3,   371,    -1,    -1,     3,   121,     5,   257,    -1,
+     267,    -1,   374,     3,   267,    -1
 };
 
@@ -1013,144 +878,153 @@
 static const yytype_uint16 yyrline[] =
 {
-       0,   336,   336,   337,   339,   340,   341,   342,   343,   346,
-     347,   349,   350,   351,   360,   361,   363,   365,   367,   374,
-     379,   380,   382,   384,   385,   387,   388,   394,   397,   398,
-     401,   402,   430,   448,   481,   515,   532,   539,   541,   545,
-     550,   553,   556,   561,   562,   563,   571,   582,   594,   595,
-     597,   605,   613,   619,   620,   635,   648,   649,   655,   656,
-     693,   706,   707,   708,   709,   710,   711,   712,   713,   714,
-     715,   734,   735,   741,   742,   743,   744,   745,   746,   747,
-     748,   749,   750,   751,   752,   753,   754,   755,   756,   757,
-     758,   759,   760,   761,   762,   763,   764,   766,   767,   769,
-     770,   772,   773,   775,   777,   778,   780,   781,   783,   784,
-     786,   870,   907,   913,   918,   923,   937,   951,   966,   973,
-     982,   983,   984,   985,   987,   992,   993,   998,  1002,  1007,
-    1012,  1014,  1016,  1018,  1020,  1024,  1025,  1028,  1030,  1031,
-    1032,  1033,  1035,  1037,  1042,  1047,  1053,  1069,  1086,  1087,
-    1089,  1093,  1098,  1102,  1107,  1113,  1124,  1136,  1141,  1147,
-    1152,  1156,  1166,  1175,  1185,  1186,  1188,  1192,  1197,  1220,
-    1222,  1223,  1225,  1235,  1237,  1239,  1272,  1307,  1309,  1311,
-    1315,  1320,  1326,  1334,  1335,  1337,  1338,  1340,  1341,  1342,
-    1344,  1349,  1351,  1356,  1360,  1363,  1369,  1371,  1377,  1378,
-    1380,  1381,  1383,  1384,  1385,  1387,  1388,  1390,  1391,  1400,
-    1404,  1409,  1411,  1414,  1415,  1417,  1418,  1419,  1421,  1422,
-    1424,  1428,  1429,  1431,  1436,  1438,  1440,  1441,  1442,  1443,
-    1449,  1452,  1453,  1454,  1456,  1458,  1461,  1466,  1470,  1472,
-    1476,  1481,  1485,  1490,  1495,  1503,  1504,  1506,  1507,  1509,
-    1511,  1515,  1517,  1519,  1521,  1523,  1525,  1527,  1529,  1531,
-    1533,  1535,  1537,  1539,  1541,  1543,  1545,  1547,  1549,  1551,
-    1553,  1555,  1557,  1559,  1561,  1563,  1565,  1568,  1569,  1573,
-    1574,  1576,  1578,  1580,  1582,  1585,  1586,  1588,  1590,  1592,
-    1594,  1596,  1598,  1600,  1602,  1604,  1606,  1608,  1610,  1612,
-    1614,  1616,  1618,  1620,  1622,  1624,  1626,  1628,  1631,  1632,
-    1634,  1636,  1639,  1641,  1645,  1650,  1655,  1661,  1673,  1678,
-    1680,  1683,  1687,  1697,  1703,  1706,  1707,  1710,  1711,  1714,
-    1715,  1717,  1719,  1722,  1724,  1725,  1726,  1727,  1729,  1787,
-    1789,  1790,  1791,  1792,  1793,  1794,  1796,  1798,  1800,  1801,
-    1803,  1806,  1807,  1809,  1812,  1813,  1815,  1816,  1818,  1819,
-    1827,  1836,  1838,  1841,  1861,  1895,  1915,  1966,  1974,  1977,
-    1981,  1991,  2002,  2006,  2016,  2028,  2037,  2038,  2044,  2050,
-    2051,  2101,  2119,  2139,  2158,  2203,  2204,  2205,  2206,  2207,
-    2208,  2209,  2210,  2211,  2212,  2213,  2214,  2215,  2216,  2260,
-    2270,  2279,  2288,  2297,  2298,  2299,  2301,  2302,  2303,  2305,
-    2306,  2307,  2308,  2309,  2311,  2312,  2314,  2315,  2317,  2319,
-    2326,  2327,  2328,  2329,  2330,  2331,  2337,  2343,  2344,  2345,
-    2346,  2347,  2349,  2350,  2360,  2362,  2363,  2365,  2366,  2368,
-    2396,  2397,  2399,  2400,  2402,  2432,  2434,  2435,  2438,  2452,
-    2455,  2456,  2459,  2460,  2461,  2462,  2463,  2464,  2476,  2477,
-    2479,  2480,  2485,  2486,  2488,  2489,  2491,  2492,  2493,  2494,
-    2495,  2497,  2498,  2500,  2501,  2502,  2503,  2504,  2505,  2506,
-    2507,  2508,  2510,  2511,  2513,  2514,  2517,  2518,  2519,  2522,
-    2525,  2526,  2528,  2529,  2530,  2531,  2532,  2533,  2534,  2535,
-    2536,  2537,  2538,  2539,  2540,  2541,  2543,  2544,  2546,  2547,
-    2549,  2550,  2552,  2553,  2554,  2555,  2556,  2558,  2559,  2560,
-    2562,  2563,  2564,  2566,  2568,  2570,  2572,  2574,  2576,  2578,
-    2579,  2581,  2583,  2585,  2587,  2589,  2593,  2596,  2603,  2605,
-    2606,  2608,  2609,  2610,  2612,  2614,  2615,  2617,  2624,  2625,
-    2627,  2628,  2630,  2631,  2639,  2641
+       0,   313,   313,   314,   316,   317,   318,   319,   322,   323,
+     324,   325,   326,   329,   330,   331,   334,   335,   336,   344,
+     347,   350,   351,   354,   355,   358,   366,   375,   392,   411,
+     412,   415,   417,   419,   420,   421,   423,   424,   425,   427,
+     439,   451,   452,   454,   455,   456,   457,   458,   475,   492,
+     493,   498,   499,   536,   549,   550,   551,   552,   553,   554,
+     555,   556,   557,   570,   571,   578,   579,   580,   581,   582,
+     583,   584,   585,   586,   587,   588,   589,   590,   591,   592,
+     593,   594,   595,   596,   597,   598,   599,   600,   601,   604,
+     605,   608,   609,   612,   613,   615,   618,   619,   622,   623,
+     625,   626,   629,   695,   710,   712,   716,   719,   720,   723,
+     729,   734,   748,   749,   752,   753,   754,   755,   758,   760,
+     761,   764,   765,   766,   769,   770,   771,   772,   773,   775,
+     776,   779,   780,   781,   782,   785,   792,   802,   814,   815,
+     818,   819,   822,   823,   824,   825,   828,   834,   842,   852,
+     853,   856,   857,   860,   868,   874,   881,   882,   885,   886,
+     889,   905,   908,   909,   912,   921,   923,   945,   970,   972,
+     973,   974,   975,   977,   978,   979,   980,   983,   984,   985,
+     987,   990,   991,   992,   993,   994,   995,   997,   998,  1001,
+    1002,  1004,  1005,  1006,  1008,  1009,  1012,  1013,  1023,  1024,
+    1025,  1028,  1029,  1031,  1032,  1034,  1035,  1036,  1038,  1039,
+    1042,  1043,  1044,  1045,  1046,  1047,  1049,  1050,  1051,  1052,
+    1053,  1056,  1057,  1058,  1061,  1062,  1064,  1065,  1073,  1079,
+    1086,  1087,  1088,  1089,  1090,  1093,  1094,  1096,  1097,  1098,
+    1099,  1103,  1104,  1105,  1106,  1107,  1108,  1109,  1110,  1111,
+    1112,  1113,  1114,  1115,  1116,  1117,  1118,  1119,  1120,  1121,
+    1122,  1123,  1124,  1125,  1126,  1127,  1128,  1130,  1131,  1133,
+    1134,  1135,  1136,  1137,  1138,  1140,  1141,  1145,  1146,  1147,
+    1148,  1149,  1150,  1151,  1152,  1153,  1154,  1155,  1156,  1157,
+    1158,  1159,  1160,  1161,  1162,  1163,  1164,  1165,  1167,  1168,
+    1169,  1170,  1173,  1174,  1177,  1178,  1179,  1183,  1194,  1195,
+    1196,  1197,  1200,  1209,  1216,  1219,  1220,  1223,  1224,  1227,
+    1228,  1231,  1232,  1233,  1234,  1235,  1236,  1237,  1239,  1285,
+    1286,  1287,  1288,  1289,  1290,  1291,  1293,  1296,  1297,  1298,
+    1299,  1301,  1302,  1305,  1307,  1308,  1311,  1312,  1314,  1315,
+    1321,  1329,  1332,  1352,  1379,  1399,  1439,  1446,  1450,  1457,
+    1467,  1468,  1476,  1486,  1498,  1499,  1504,  1505,  1506,  1507,
+    1508,  1513,  1514,  1515,  1516,  1517,  1518,  1519,  1520,  1521,
+    1522,  1523,  1524,  1525,  1526,  1527,  1528,  1529,  1530,  1567,
+    1576,  1587,  1595,  1617,  1618,  1619,  1657,  1661,  1665,  1668,
+    1669,  1672,  1673,  1676,  1677,  1682,  1686,  1687,  1688,  1692,
+    1696,  1701,  1702,  1707,  1708,  1713,  1714,  1718,  1722,  1723,
+    1724,  1729,  1734,  1739,  1740,  1745,  1746,  1747,  1748,  1753,
+    1754,  1755,  1756,  1761,  1762,  1763,  1764,  1768,  1772,  1776,
+    1777,  1782,  1783,  1787,  1790,  1791,  1792,  1796,  1799,  1800,
+    1801,  1804,  1809,  1810,  1815,  1816,  1821,  1822,  1827,  1828,
+    1832,  1836,  1839,  1840,  1841,  1844,  1849,  1850,  1855,  1856,
+    1861,  1862,  1867,  1868,  1872,  1873,  1878,  1879,  1880,  1881,
+    1885,  1889,  1893,  1897,  1905,  1912,  1919,  1926,  1927,  1930,
+    1933,  1944,  1950,  1951,  1954,  1955,  1957,  1970,  1971,  1973,
+    1974,  1977,  1978,  2000,  2003,  2004,  2007,  2015,  2018,  2019,
+    2022,  2023,  2026,  2027,  2029,  2030,  2032,  2035,  2036,  2037,
+    2038,  2039,  2042,  2043,  2046,  2047,  2048,  2049,  2050,  2051,
+    2052,  2053,  2056,  2059,  2060,  2061,  2063,  2064,  2067,  2068,
+    2069,  2072,  2073,  2076,  2077,  2078,  2079,  2080,  2081,  2082,
+    2083,  2084,  2085,  2086,  2087,  2088,  2089,  2090,  2091,  2092,
+    2094,  2095,  2097,  2098,  2104,  2105,  2106,  2107,  2108,  2110,
+    2111,  2112,  2115,  2116,  2117,  2118,  2119,  2120,  2121,  2122,
+    2123,  2124,  2127,  2128,  2129,  2131,  2132,  2134,  2135,  2138,
+    2139,  2142,  2145,  2146,  2148,  2149,  2152,  2153
 };
 #endif
 
-#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+#if YYDEBUG || YYERROR_VERBOSE || 0
 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
    First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
 static const char *const yytname[] =
 {
-  "$end", "error", "$undefined", "','", "':'", "'='", "TOK_BINARY_OP",
-  "TOK_NEQV", "TOK_EQV", "TOK_XOR", "TOK_OR", "TOK_AND", "TOK_NOT",
-  "TOK_NE", "TOK_EQ", "TOK_GE", "TOK_LE", "TOK_GT", "TOK_LT",
-  "TOK_UNARY_OP", "TOK_DSLASH", "'+'", "'-'", "'*'", "TOK_SLASH",
-  "TOK_DASTER", "TOK_SEP", "TOK_SEMICOLON", "TOK_NEXTLINE",
-  "TOK_PARAMETER", "TOK_RESULT", "TOK_ONLY", "TOK_INCLUDE",
-  "TOK_SUBROUTINE", "TOK_PROGRAM", "TOK_FUNCTION", "TOK_OMP", "TOK_DOLLAR",
-  "TOK_FORMAT", "TOK_MAX", "TOK_TANH", "TOK_WHERE", "TOK_ELSEWHERE",
-  "TOK_ENDWHERE", "TOK_MAXVAL", "TOK_TRIM", "TOK_SUM", "TOK_SQRT",
-  "TOK_CASE", "TOK_SELECTCASE", "TOK_FILE", "TOK_END", "TOK_ERR",
-  "TOK_DONOTTREAT", "TOK_ENDDONOTTREAT", "TOK_EXIST", "TOK_MIN",
-  "TOK_FLOAT", "TOK_EXP", "TOK_COS", "TOK_COSH", "TOK_ACOS", "TOK_NINT",
-  "TOK_CYCLE", "TOK_SIN", "TOK_SINH", "TOK_ASIN", "TOK_EQUIVALENCE",
-  "TOK_BACKSPACE", "TOK_LOG", "TOK_TAN", "TOK_ATAN", "TOK_RECURSIVE",
-  "TOK_ABS", "TOK_MOD", "TOK_SIGN", "TOK_MINLOC", "TOK_MAXLOC", "TOK_EXIT",
-  "TOK_MINVAL", "TOK_PUBLIC", "TOK_PRIVATE", "TOK_ALLOCATABLE",
-  "TOK_RETURN", "TOK_THEN", "TOK_ELSEIF", "TOK_ELSE", "TOK_ENDIF",
-  "TOK_PRINT", "TOK_PLAINGOTO", "TOK_CONSTRUCTID", "TOK_LOGICALIF",
-  "TOK_PLAINDO", "TOK_CONTAINS", "TOK_ENDDO", "TOK_MODULE",
-  "TOK_ENDMODULE", "TOK_DOWHILE", "TOK_ALLOCATE", "TOK_OPEN", "TOK_CLOSE",
-  "TOK_INQUIRE", "TOK_WRITE", "TOK_READ", "TOK_REWIND", "TOK_DEALLOCATE",
-  "TOK_NULLIFY", "TOK_FIN", "TOK_DEBUT", "TOK_DIMENSION", "TOK_ENDSELECT",
-  "TOK_EXTERNAL", "TOK_INTENT", "TOK_INTRINSIC", "TOK_NAMELIST",
-  "TOK_CASEDEFAULT", "TOK_OPTIONAL", "TOK_POINTER", "TOK_CONTINUE",
-  "TOK_SAVE", "TOK_TARGET", "TOK_QUOTE", "TOK_IMPLICIT", "TOK_NONE",
-  "TOK_CALL", "TOK_STAT", "TOK_POINT_TO", "TOK_COMMON", "TOK_GLOBAL",
-  "TOK_INTERFACE", "TOK_ENDINTERFACE", "TOK_LEFTAB", "TOK_RIGHTAB",
-  "TOK_PAUSE", "TOK_PROCEDURE", "TOK_STOP", "TOK_NAMEEQ", "TOK_REAL8",
+  "$end", "error", "$undefined", "','", "':'", "'='", "TOK_NEQV",
+  "TOK_EQV", "TOK_XOR", "TOK_OR", "TOK_AND", "TOK_NOT", "TOK_NE", "TOK_EQ",
+  "TOK_GE", "TOK_LE", "TOK_GT", "TOK_LT", "TOK_DSLASH", "'+'", "'-'",
+  "'*'", "TOK_SLASH", "TOK_DASTER", "TOK_SEMICOLON", "TOK_PARAMETER",
+  "TOK_RESULT", "TOK_ONLY", "TOK_INCLUDE", "TOK_SUBROUTINE", "TOK_PROGRAM",
+  "TOK_FUNCTION", "TOK_FORMAT", "TOK_MAX", "TOK_TANH", "TOK_WHERE",
+  "TOK_ELSEWHEREPAR", "TOK_ELSEWHERE", "TOK_ENDWHERE", "TOK_MAXVAL",
+  "TOK_TRIM", "TOK_NULL_PTR", "TOK_SUM", "TOK_SQRT", "TOK_CASE",
+  "TOK_SELECTCASE", "TOK_FILE", "TOK_UNIT", "TOK_FMT", "TOK_NML",
+  "TOK_END", "TOK_EOR", "TOK_ERR", "TOK_EXIST", "TOK_MIN", "TOK_FLOAT",
+  "TOK_EXP", "TOK_COS", "TOK_COSH", "TOK_ACOS", "TOK_NINT", "TOK_CYCLE",
+  "TOK_SIN", "TOK_SINH", "TOK_ASIN", "TOK_EQUIVALENCE", "TOK_BACKSPACE",
+  "TOK_LOG", "TOK_TAN", "TOK_ATAN", "TOK_RECURSIVE", "TOK_ABS", "TOK_MOD",
+  "TOK_SIGN", "TOK_MINLOC", "TOK_MAXLOC", "TOK_EXIT", "TOK_MINVAL",
+  "TOK_PUBLIC", "TOK_PRIVATE", "TOK_ALLOCATABLE", "TOK_RETURN", "TOK_THEN",
+  "TOK_ELSEIF", "TOK_ELSE", "TOK_ENDIF", "TOK_PRINT", "TOK_PLAINGOTO",
+  "TOK_LOGICALIF", "TOK_PLAINDO", "TOK_CONTAINS", "TOK_ENDDO",
+  "TOK_MODULE", "TOK_ENDMODULE", "TOK_WHILE", "TOK_CONCURRENT",
+  "TOK_ALLOCATE", "TOK_OPEN", "TOK_CLOSE", "TOK_INQUIRE", "TOK_WRITE",
+  "TOK_FLUSH", "TOK_READ", "TOK_REWIND", "TOK_DEALLOCATE", "TOK_NULLIFY",
+  "TOK_DIMENSION", "TOK_ENDSELECT", "TOK_EXTERNAL", "TOK_INTENT",
+  "TOK_INTRINSIC", "TOK_NAMELIST", "TOK_DEFAULT", "TOK_OPTIONAL",
+  "TOK_POINTER", "TOK_CONTINUE", "TOK_SAVE", "TOK_TARGET", "TOK_IMPLICIT",
+  "TOK_NONE", "TOK_CALL", "TOK_STAT", "TOK_POINT_TO", "TOK_COMMON",
+  "TOK_GLOBAL", "TOK_LEFTAB", "TOK_RIGHTAB", "TOK_PAUSE", "TOK_PROCEDURE",
+  "TOK_STOP", "TOK_REAL8", "TOK_FOURDOTS", "TOK_HEXA", "TOK_ASSIGNTYPE",
   "TOK_OUT", "TOK_INOUT", "TOK_IN", "TOK_USE", "TOK_TRUE", "TOK_FALSE",
   "TOK_LABEL", "TOK_TYPE", "TOK_TYPEPAR", "TOK_ENDTYPE", "TOK_REAL",
-  "TOK_INTEGER", "TOK_LOGICAL", "TOK_DOUBLEPRECISION", "TOK_DOUBLEREAL",
-  "TOK_ENDSUBROUTINE", "TOK_ENDFUNCTION", "TOK_ENDPROGRAM", "TOK_ENDUNIT",
-  "TOK_CHARACTER", "TOK_CHAR_CONSTANT", "TOK_CHAR_CUT", "TOK_DATA",
-  "TOK_CHAR_INT", "TOK_CHAR_MESSAGE", "TOK_CSTREAL", "TOK_CSTREALDP",
-  "TOK_CSTREALQP", "TOK_SFREAL", "TOK_COMPLEX", "TOK_DOUBLECOMPLEX",
-  "TOK_NAME", "TOK_NAME_CHAR", "TOK_PROBTYPE", "TOK_INTERPTYPE",
-  "TOK_VARTYPE", "TOK_BC", "TOK_OP", "TOK_CSTINT", "TOK_COMMENT",
-  "TOK_FILENAME", "'('", "')'", "'['", "']'", "'!'", "'_'", "'<'", "'>'",
-  "'\\n'", "'/'", "'%'", "$accept", "input", "line", "suite_line_list",
-  "suite_line", "instr", "fin_line", "keyword", "position", "thislabel",
-  "cmnt", "nulcurbuf", "opt_recursive", "entry", "name_routine",
-  "writedeclar", "before_include", "filename", "arglist", "arglist1",
+  "TOK_INTEGER", "TOK_LOGICAL", "TOK_DOUBLEPRECISION", "TOK_ENDSUBROUTINE",
+  "TOK_ENDFUNCTION", "TOK_ENDPROGRAM", "TOK_ENDUNIT", "TOK_CHARACTER",
+  "TOK_CHAR_CONSTANT", "TOK_CHAR_CUT", "TOK_DATA", "TOK_CHAR_MESSAGE",
+  "TOK_CSTREAL", "TOK_COMPLEX", "TOK_DOUBLECOMPLEX", "TOK_NAME",
+  "TOK_CSTINT", "'('", "')'", "'<'", "'>'", "'\\n'", "'/'", "'%'",
+  "$accept", "input", "line", "line-break", "suite_line_list",
+  "suite_line", "fin_line", "opt_recursive", "opt_result", "entry",
+  "label", "name_routine", "filename", "arglist", "arglist_after_result",
   "args", "arg", "spec", "opt_spec", "name_intrinsic",
   "use_intrinsic_list", "list_couple", "list_expr_equi", "expr_equi",
   "list_expr_equi1", "list_expr", "opt_sep", "after_type",
-  "before_function", "before_parameter", "before_data", "data",
-  "datavallist", "save", "before_save", "varsave", "datanamelist",
-  "expr_data", "opt_signe", "namelist", "namelist_action",
-  "after_namelist", "interface", "before_dimension", "dimension",
-  "private", "public", "use_name_list", "common", "before_common",
-  "var_common_list", "var_common", "comblock", "opt_comma", "paramlist",
-  "paramitem", "module_proc_stmt", "proc_name_list", "implicit",
-  "opt_retour", "dcl", "nodimsgiven", "type", "before_typepar",
-  "c_selector", "c_attribute", "before_character", "typespec", "typename",
-  "lengspec", "proper_lengspec", "selector", "proper_selector",
-  "attribute", "clause", "opt_clause", "options", "attr_spec_list",
-  "attr_spec", "intent_spec", "access_spec", "dims", "dimlist", "dim",
-  "ubound", "expr", "predefinedfunction", "minmaxlist", "uexpr", "signe",
-  "operation", "after_slash", "after_equal", "lhs", "beforefunctionuse",
+  "before_function", "before_parameter", "data_stmt", "data_stmt_set_list",
+  "data_stmt_set", "data_stmt_value_list", "save", "before_save",
+  "varsave", "datanamelist", "expr_data", "opt_signe", "namelist",
+  "before_dimension", "dimension", "private", "public", "use_name_list",
+  "common", "before_common", "var_common_list", "var_common", "comblock",
+  "opt_comma", "paramlist", "paramitem", "module_proc_stmt",
+  "proc_name_list", "implicit", "dcl", "nodimsgiven", "type", "c_selector",
+  "c_attribute", "before_character", "typespec", "lengspec",
+  "proper_lengspec", "selector", "proper_selector", "attribute", "clause",
+  "opt_clause", "options", "attr_spec_list", "attr_spec", "intent_spec",
+  "access_spec", "dims", "dimlist", "dim", "ubound", "expr",
+  "predefinedfunction", "minmaxlist", "uexpr", "signe", "operation",
+  "after_slash", "after_equal", "lhs", "beforefunctionuse",
   "array_ele_substring_func_ref", "begin_array", "structure_component",
   "vec", "funarglist", "funargs", "funarg", "triplet", "ident",
   "simple_const", "string_constant", "opt_substring", "substring",
-  "optexpr", "opt_expr", "initial_value", "before_initial",
-  "complex_const", "use_stat", "word_use", "module_name", "rename_list",
-  "rename_name", "only_list", "only_name", "exec", "word_endsubroutine",
-  "word_endunit", "word_endprogram", "word_endfunction", "caselist",
-  "boucledo", "do_arg", "opt_int", "opt_name", "optname", "worddo",
-  "wordwhile", "iffable", "before_dims", "ident_dims", "int_list",
-  "after_ident_dims", "call", "opt_call", "opt_callarglist", "keywordcall",
-  "before_call", "callarglist", "callarg", "stop", "io", "option_inlist",
-  "option_read", "opt_inlist", "ioctl", "after_rewind", "ctllist",
-  "ioclause", "iofctl", "infmt", "read", "write", "fexpr", "unpar_fexpr",
-  "addop", "inlist", "opt_lhs", "inelt", "opt_operation", "outlist",
-  "out2", "other", "dospec", "label", "goto", "allocation_list",
-  "allocate_object", "array_element", "allocate_object_list",
-  "opt_stat_spec", "pointer_name_list", "logif", "do_var", 0
+  "optexpr", "opt_expr", "initial_value", "complex_const", "use_stat",
+  "word_use", "rename_list", "rename_name", "only_list", "only_name",
+  "execution-part-construct", "executable-construct", "action-stmt",
+  "assignment-stmt", "where-stmt", "where-construct",
+  "opt-where-body-construct", "opt-masked-elsewhere-construct",
+  "opt-elsewhere-construct", "where-construct-stmt",
+  "where-body-construct", "where-assignment-stmt", "mask-expr",
+  "masked-elsewhere-stmt", "elsewhere-stmt", "end-where-stmt",
+  "forall-header", "block", "do-construct", "block-do-construct",
+  "do-stmt", "label-do-stmt", "nonlabel-do-stmt", "loop-control",
+  "do-variable", "do-block", "end-do", "end-do-stmt", "if-construct",
+  "opt-else-if-stmt-block", "else-if-stmt-block", "opt-else-stmt-block",
+  "else-stmt-block", "if-then-stmt", "else-if-stmt", "else-stmt",
+  "end-if-stmt", "if-stmt", "case-construct", "opt_case-stmt-block",
+  "case-stmt-block", "select-case-stmt", "case-stmt", "end-select-stmt",
+  "case-selector", "case-value-range-list", "case-value-range",
+  "case-value", "continue-stmt", "format-stmt", "word_endsubroutine",
+  "word_endunit", "word_endprogram", "word_endfunction", "opt_name",
+  "before_dims", "ident_dims", "int_list", "after_ident_dims", "call",
+  "opt_call", "opt_callarglist", "keywordcall", "before_call",
+  "callarglist", "callarg", "stop", "option_inlist", "option_read",
+  "opt_inlist", "ioctl", "after_rewind", "ctllist", "ioclause",
+  "declare_after_percent", "iofctl", "infmt", "read", "fexpr",
+  "unpar_fexpr", "addop", "inlist", "inelt", "opt_operation", "outlist",
+  "other", "dospec", "goto", "allocation_list", "allocate_object",
+  "allocate_object_list", "opt_stat_spec", "pointer_name_list", YY_NULL
 };
 #endif
@@ -1162,6 +1036,6 @@
 {
        0,   256,   257,    44,    58,    61,   258,   259,   260,   261,
-     262,   263,   264,   265,   266,   267,   268,   269,   270,   271,
-     272,    43,    45,    42,   273,   274,   275,   276,   277,   278,
+     262,   263,   264,   265,   266,   267,   268,   269,   270,    43,
+      45,    42,   271,   272,   273,   274,   275,   276,   277,   278,
      279,   280,   281,   282,   283,   284,   285,   286,   287,   288,
      289,   290,   291,   292,   293,   294,   295,   296,   297,   298,
@@ -1177,7 +1051,5 @@
      389,   390,   391,   392,   393,   394,   395,   396,   397,   398,
      399,   400,   401,   402,   403,   404,   405,   406,   407,   408,
-     409,   410,   411,   412,   413,   414,   415,   416,   417,   418,
-     419,   420,   421,   422,   423,   424,   425,   426,   427,    40,
-      41,    91,    93,    33,    95,    60,    62,    10,    47,    37
+     409,   410,    40,    41,    60,    62,    10,    47,    37
 };
 # endif
@@ -1186,60 +1058,64 @@
 static const yytype_uint16 yyr1[] =
 {
-       0,   190,   191,   191,   192,   192,   192,   192,   192,   193,
-     193,   194,   194,   194,   194,   194,   195,   196,   197,   197,
-     197,   197,   198,   199,   199,   200,   200,   201,   202,   202,
-     203,   203,   203,   203,   203,   203,   204,   205,   206,   207,
-     208,   208,   208,   209,   209,   209,   210,   210,   211,   211,
-     212,   212,   212,   212,   212,   212,   212,   212,   212,   212,
-     212,   212,   212,   212,   212,   212,   212,   212,   212,   212,
-     212,   213,   213,   214,   214,   214,   214,   214,   214,   214,
-     214,   214,   214,   214,   214,   214,   214,   214,   214,   214,
-     214,   214,   214,   214,   214,   214,   214,   215,   215,   216,
+       0,   169,   170,   170,   171,   171,   171,   171,   172,   172,
+     172,   172,   172,   173,   173,   173,   174,   174,   174,   174,
+     175,   176,   176,   177,   177,   178,   178,   178,   178,   179,
+     179,   180,   181,   182,   182,   182,   183,   183,   183,   184,
+     184,   185,   185,   186,   186,   186,   186,   186,   186,   186,
+     186,   186,   186,   186,   186,   186,   186,   186,   186,   186,
+     186,   186,   186,   187,   187,   188,   188,   188,   188,   188,
+     188,   188,   188,   188,   188,   188,   188,   188,   188,   188,
+     188,   188,   188,   188,   188,   188,   188,   188,   188,   189,
+     189,   190,   190,   191,   191,   192,   193,   193,   194,   194,
+     195,   195,   196,   196,   197,   198,   199,   200,   200,   201,
+     201,   201,   202,   202,   203,   203,   203,   203,   204,   205,
+     205,   206,   206,   206,   207,   207,   207,   207,   207,   208,
+     208,   209,   209,   209,   209,   210,   211,   211,   212,   212,
+     213,   213,   214,   214,   214,   214,   215,   215,   215,   216,
      216,   217,   217,   218,   219,   219,   220,   220,   221,   221,
-     222,   222,   223,   224,   225,   226,   226,   226,   227,   227,
-     228,   228,   228,   228,   229,   230,   230,   231,   231,   231,
-     232,   232,   232,   232,   232,   233,   233,   234,   235,   235,
-     235,   235,   236,   237,   237,   238,   239,   239,   240,   240,
-     241,   241,   242,   242,   243,   243,   243,   244,   244,   245,
-     245,   246,   247,   247,   248,   248,   249,   249,   250,   251,
-     252,   252,   253,   253,   254,   255,   255,   256,   257,   257,
-     257,   257,   258,   259,   259,   259,   259,   260,   260,   260,
-     261,   262,   263,   263,   263,   263,   263,   263,   264,   264,
-     265,   265,   266,   266,   266,   267,   267,   268,   268,   268,
-     268,   269,   269,   270,   270,   271,   271,   271,   272,   272,
-     273,   273,   273,   273,   273,   273,   273,   273,   273,   273,
-     273,   274,   274,   274,   275,   275,   276,   276,   277,   277,
-     278,   278,   278,   278,   278,   279,   279,   280,   280,   280,
-     280,   281,   281,   281,   281,   281,   281,   281,   281,   281,
-     281,   281,   281,   281,   281,   281,   281,   281,   281,   281,
-     281,   281,   281,   281,   281,   281,   281,   282,   282,   283,
-     283,   283,   283,   283,   283,   284,   284,   285,   285,   285,
-     285,   285,   285,   285,   285,   285,   285,   285,   285,   285,
-     285,   285,   285,   285,   285,   285,   285,   285,   286,   286,
-     286,   286,   287,   287,   288,   288,   288,   289,   290,   290,
-     290,   290,   291,   292,   293,   294,   294,   295,   295,   296,
-     296,   297,   297,   297,   297,   297,   297,   297,   298,   299,
-     299,   299,   299,   299,   299,   299,   299,   300,   300,   300,
-     300,   301,   301,   302,   303,   303,   304,   304,   305,   305,
-     305,   306,   307,   308,   308,   308,   308,   309,   310,   311,
-     311,   312,   313,   313,   314,   314,   315,   315,   315,   315,
-     315,   315,   315,   315,   315,   315,   315,   315,   315,   315,
-     315,   315,   315,   315,   315,   315,   315,   315,   315,   316,
-     317,   318,   319,   320,   320,   320,   321,   321,   321,   322,
-     322,   322,   323,   323,   324,   324,   325,   325,   326,   327,
-     328,   328,   328,   328,   328,   328,   328,   328,   328,   328,
-     328,   328,   329,   330,   330,   331,   331,   332,   332,   333,
-     334,   334,   335,   335,   336,   337,   338,   338,   339,   339,
-     340,   340,   341,   341,   341,   341,   341,   341,   342,   342,
-     343,   343,   344,   344,   345,   345,   346,   346,   346,   346,
-     346,   347,   347,   348,   348,   348,   348,   348,   348,   348,
-     348,   348,   349,   349,   350,   350,   351,   351,   351,   352,
-     353,   353,   354,   354,   354,   354,   354,   354,   354,   354,
-     354,   354,   354,   354,   354,   354,   355,   355,   356,   356,
-     357,   357,   358,   358,   358,   358,   358,   359,   359,   359,
-     360,   360,   360,   361,   361,   361,   361,   361,   361,   361,
-     361,   362,   362,   362,   362,   362,   363,   363,   364,   365,
-     365,   366,   366,   366,   367,   367,   367,   368,   369,   369,
-     370,   370,   371,   371,   372,   373
+     222,   223,   224,   224,   225,   225,   226,   226,   227,   228,
+     228,   228,   228,   229,   229,   229,   229,   230,   230,   230,
+     231,   232,   232,   232,   232,   232,   232,   233,   233,   234,
+     234,   235,   235,   235,   236,   236,   237,   237,   237,   237,
+     237,   238,   238,   239,   239,   240,   240,   240,   241,   241,
+     242,   242,   242,   242,   242,   242,   242,   242,   242,   242,
+     242,   243,   243,   243,   244,   244,   245,   245,   246,   246,
+     247,   247,   247,   247,   247,   248,   248,   249,   249,   249,
+     249,   250,   250,   250,   250,   250,   250,   250,   250,   250,
+     250,   250,   250,   250,   250,   250,   250,   250,   250,   250,
+     250,   250,   250,   250,   250,   250,   250,   251,   251,   252,
+     252,   252,   252,   252,   252,   253,   253,   254,   254,   254,
+     254,   254,   254,   254,   254,   254,   254,   254,   254,   254,
+     254,   254,   254,   254,   254,   254,   254,   254,   255,   255,
+     255,   255,   256,   256,   257,   257,   257,   258,   259,   259,
+     259,   259,   260,   261,   262,   263,   263,   264,   264,   265,
+     265,   266,   266,   266,   266,   266,   266,   266,   267,   268,
+     268,   268,   268,   268,   268,   268,   268,   269,   269,   269,
+     269,   270,   270,   271,   272,   272,   273,   273,   274,   274,
+     274,   275,   276,   276,   276,   276,   277,   278,   278,   279,
+     280,   280,   281,   281,   282,   282,   283,   283,   283,   283,
+     283,   284,   284,   284,   284,   284,   284,   284,   284,   284,
+     284,   284,   284,   284,   284,   284,   284,   284,   284,   284,
+     284,   284,   284,   284,   284,   284,   285,   286,   287,   288,
+     288,   289,   289,   290,   290,   291,   292,   292,   292,   293,
+     294,   295,   295,   296,   296,   297,   297,   298,   299,   299,
+     299,   300,   301,   302,   302,   303,   303,   303,   303,   304,
+     304,   304,   304,   305,   305,   305,   305,   306,   307,   308,
+     308,   309,   309,   310,   311,   311,   311,   312,   313,   313,
+     313,   314,   315,   315,   316,   316,   317,   317,   318,   318,
+     319,   320,   321,   321,   321,   322,   323,   323,   324,   324,
+     325,   325,   326,   326,   327,   327,   328,   328,   328,   328,
+     329,   330,   331,   332,   333,   334,   335,   336,   336,   337,
+     338,   338,   339,   339,   340,   340,   341,   342,   342,   343,
+     343,   344,   344,   345,   346,   346,   347,   347,   348,   348,
+     349,   349,   350,   350,   351,   351,   352,   353,   353,   353,
+     353,   353,   354,   354,   355,   355,   355,   355,   355,   355,
+     355,   355,   356,   357,   357,   357,   358,   358,   359,   359,
+     359,   360,   360,   361,   361,   361,   361,   361,   361,   361,
+     361,   361,   361,   361,   361,   361,   361,   361,   361,   361,
+     362,   362,   363,   363,   364,   364,   364,   364,   364,   365,
+     365,   365,   366,   366,   366,   366,   366,   366,   366,   366,
+     366,   366,   367,   367,   367,   368,   368,   369,   369,   370,
+     370,   371,   372,   372,   373,   373,   374,   374
 };
 
@@ -1247,166 +1123,177 @@
 static const yytype_uint8 yyr2[] =
 {
-       0,     2,     0,     2,     2,     2,     1,     3,     3,     1,
-       3,     2,     2,     3,     3,     2,     2,     2,     1,     1,
-       1,     1,     0,     0,     2,     0,     1,     0,     0,     1,
-       0,     4,     2,     6,     4,     2,     1,     0,     1,     1,
-       0,     2,     3,     0,     2,     3,     1,     3,     1,     1,
-       2,     4,     2,     2,     4,     2,     1,     1,     1,     1,
-       1,     1,     1,     1,     1,     1,     4,     3,     3,     2,
-       3,     0,     1,     1,     1,     1,     1,     1,     1,     1,
+       0,     2,     0,     2,     1,     1,     2,     1,     2,     1,
+       3,     2,     2,     1,     3,     3,     2,     2,     3,     1,
+       0,     0,     1,     0,     2,     4,     2,     5,     2,     1,
+       2,     1,     1,     0,     2,     3,     0,     2,     3,     1,
+       3,     1,     1,     2,     4,     2,     2,     4,     2,     1,
+       1,     1,     1,     1,     1,     1,     1,     1,     4,     3,
+       3,     2,     2,     0,     1,     1,     1,     1,     1,     1,
        1,     1,     1,     1,     1,     1,     1,     1,     1,     1,
-       1,     1,     1,     1,     1,     1,     1,     1,     3,     3,
-       5,     1,     3,     3,     2,     4,     1,     3,     0,     2,
-       2,     3,     1,     1,     1,     4,     6,     4,     1,     3,
-       2,     3,     5,     3,     1,     0,     2,     1,     4,     3,
-       2,     3,     3,     3,     3,     0,     1,     2,     2,     3,
-       5,     3,     0,     2,     2,     1,     5,     5,     2,     3,
-       2,     3,     1,     3,     2,     3,     5,     1,     2,     1,
-       3,     2,     1,     3,     0,     1,     1,     3,     3,     2,
-       1,     3,     2,     2,     0,     6,     7,     0,     2,     2,
-       3,     3,     1,     0,     2,     4,     3,     3,     4,     2,
-       1,     1,     1,     1,     1,     1,     1,     1,     0,     2,
-       1,     3,     0,     2,     3,     1,     3,     2,     3,     1,
-       1,     1,     1,     0,     3,     0,     2,     4,     1,     3,
+       1,     1,     1,     1,     1,     1,     1,     1,     1,     1,
+       3,     3,     5,     1,     3,     3,     2,     4,     1,     3,
+       0,     1,     2,     3,     1,     1,     2,     1,     3,     4,
+       4,     8,     1,     3,     2,     3,     5,     3,     1,     0,
+       2,     1,     4,     3,     2,     3,     3,     3,     3,     0,
+       1,     2,     3,     5,     3,     1,     5,     5,     2,     3,
+       2,     3,     1,     1,     3,     3,     2,     3,     5,     1,
+       2,     1,     3,     2,     1,     3,     0,     1,     1,     3,
+       3,     2,     1,     3,     2,     2,     5,     6,     0,     2,
+       2,     3,     3,     0,     2,     4,     3,     3,     4,     2,
+       1,     1,     1,     1,     1,     1,     1,     0,     2,     1,
+       3,     0,     2,     3,     1,     3,     2,     3,     1,     1,
+       1,     1,     1,     0,     3,     0,     1,     3,     1,     3,
        1,     1,     1,     2,     1,     4,     1,     1,     1,     1,
        1,     1,     1,     1,     1,     1,     0,     3,     1,     3,
-       1,     1,     2,     2,     3,     1,     1,     1,     3,     1,
-       1,     3,     3,     4,     4,     3,     4,     4,     3,     4,
+       1,     1,     2,     2,     3,     1,     1,     1,     1,     1,
+       3,     3,     3,     4,     4,     3,     4,     4,     3,     4,
        4,     4,     4,     4,     4,     4,     4,     4,     4,     4,
-       4,     4,     3,     4,     4,     4,     4,     1,     3,     1,
+       4,     4,     3,     4,     3,     4,     4,     1,     3,     1,
        1,     1,     2,     2,     2,     1,     1,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     3,     2,
-       3,     2,     2,     2,     2,     2,     2,     2,     0,     1,
+       2,     2,     2,     2,     2,     2,     3,     3,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     0,     1,
        2,     2,     2,     1,     1,     1,     1,     0,     1,     2,
-       4,     5,     4,     3,     3,     1,     2,     1,     3,     1,
+       4,     5,     4,     4,     3,     1,     2,     1,     3,     1,
        1,     3,     5,     4,     3,     2,     2,     1,     1,     1,
        1,     1,     1,     1,     1,     2,     2,     1,     2,     1,
-       1,     0,     1,     5,     0,     1,     1,     1,     0,     3,
-       3,     0,     5,     2,     4,     6,     6,     1,     1,     1,
-       3,     3,     1,     3,     3,     1,     1,     5,     5,     4,
-       1,     2,     2,     2,     2,     1,     2,     5,     1,     1,
-       2,     5,     1,     2,     3,     4,     1,     1,     1,     1,
-       1,     1,     1,     1,     3,     3,     3,     2,     2,     0,
-       5,     7,     0,     2,     1,     1,     0,     1,     1,     1,
-       1,     2,     1,     1,     1,     5,     5,     2,     2,     2,
-       2,     1,     0,     4,     6,     1,     3,     2,     2,     2,
-       0,     3,     0,     1,     2,     1,     1,     3,     1,     2,
-       1,     1,     2,     2,     2,     3,     2,     1,     0,     1,
-       2,     2,     0,     2,     3,     3,     3,     3,     1,     3,
-       1,     1,     3,     1,     1,     1,     3,     2,     4,     4,
-       2,     2,     1,     1,     1,     1,     1,     1,     1,     1,
-       1,     3,     1,     1,     3,     3,     3,     3,     2,     3,
-       2,     2,     2,     2,     3,     1,     1,     1,     1,     3,
-       0,     1,     2,     4,     2,     2,     5,     0,     1,     2,
-       1,     1,     1,     3,     3,     3,     3,     3,     3,     1,
-       1,     1,     3,     5,     5,     5,     5,     7,     1,     8,
-       2,     1,     1,     3,     1,     1,     1,     4,     1,     3,
-       0,     4,     1,     3,     3,     1
+       1,     0,     1,     5,     0,     1,     1,     1,     0,     2,
+       2,     5,     2,     4,     6,     6,     1,     1,     3,     3,
+       1,     3,     3,     1,     1,     1,     1,     1,     1,     1,
+       1,     1,     2,     1,     1,     2,     2,     2,     3,     2,
+       5,     5,     2,     2,     2,     2,     1,     4,     1,     2,
+       2,     2,     2,     1,     1,     1,     1,     5,     6,     0,
+       3,     0,     4,     0,     4,     4,     1,     1,     1,     1,
+       1,     3,     4,     1,     2,     1,     2,     0,     0,     2,
+       3,     1,     4,     1,     1,     4,     2,     5,     3,     3,
+       1,     4,     2,     6,     8,     5,     3,     1,     1,     1,
+       1,     1,     2,     6,     0,     1,     2,     3,     0,     1,
+       2,     3,     7,     5,     5,     6,     1,     2,     1,     2,
+       5,     4,     0,     1,     2,     3,     6,     4,     2,     3,
+       1,     2,     3,     1,     1,     3,     1,     2,     2,     3,
+       1,     1,     1,     1,     1,     1,     1,     1,     1,     0,
+       4,     7,     1,     3,     2,     2,     2,     0,     3,     0,
+       1,     2,     2,     1,     1,     3,     1,     2,     1,     1,
+       0,     1,     2,     2,     0,     2,     3,     3,     3,     1,
+       3,     1,     1,     3,     1,     1,     1,     3,     5,     4,
+       2,     2,     0,     1,     1,     1,     1,     1,     1,     1,
+       1,     1,     3,     1,     1,     3,     3,     3,     3,     2,
+       3,     2,     2,     2,     2,     2,     2,     2,     3,     1,
+       1,     1,     1,     3,     2,     4,     2,     2,     5,     0,
+       1,     2,     1,     1,     1,     1,     3,     3,     3,     3,
+       3,     3,     5,     5,     5,     5,     7,     8,     2,     1,
+       3,     1,     1,     3,     0,     4,     1,     3
 };
 
-/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
-   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
+/* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM.
+   Performed when YYTABLE doesn't specify something else to do.  Zero
    means the default is an error.  */
 static const yytype_uint16 yydefact[] =
 {
-       2,     0,     1,    37,    20,    21,    18,    19,    27,     6,
-      22,     3,    25,    30,    27,    24,     4,    26,    37,   113,
-      38,     0,   457,     0,   388,   389,     0,     0,     0,     0,
-       0,    29,   354,   108,   108,     0,     0,   392,     0,   488,
-       0,     0,   418,   398,   416,     0,     0,   419,     0,   482,
-     483,   487,   489,   486,     0,     0,     0,   145,   397,   108,
-     108,     0,   396,     0,   420,   124,     0,   445,   157,     0,
-       0,     0,   450,     0,   451,   367,    71,   182,     0,   193,
-     192,   197,   195,   399,   402,   401,   400,   190,   114,   194,
-     196,   338,   435,     5,     9,    22,     0,    22,     0,    22,
-       0,     0,    57,   125,    65,   142,    64,   164,    59,    61,
-      60,    56,     0,    63,    58,   215,     0,   183,   202,   191,
-     432,    62,     0,    25,     0,   380,     0,     0,   385,   412,
-       0,   376,     0,   431,   424,   440,     0,     0,   423,     0,
-       0,     0,   422,     0,     8,     7,    36,    32,     0,     0,
-     285,   286,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   339,   340,
-       0,   347,   350,   349,   342,   343,   344,   341,     0,   403,
-     250,   247,     0,   279,   316,   318,   315,   281,   314,   280,
-     351,   249,     0,     0,   356,   357,   429,     0,    69,   101,
-       0,   355,   427,     0,   150,     0,   148,     0,   428,     0,
-     415,   414,   393,   538,     0,   540,     0,   417,   408,    35,
-     384,     0,   470,   468,     0,   456,     0,     0,     0,     0,
-     162,     0,     0,   138,     0,    53,   172,   173,   158,   143,
-     144,   170,   169,   234,   235,   108,    72,    52,    30,    15,
-      25,     0,     0,    11,    39,    22,    12,     0,     0,    55,
-     166,   127,   164,     0,   125,     0,   236,   120,   125,   165,
-     137,     0,   165,     0,     0,     0,   236,   154,   159,     0,
-       0,     0,   112,    50,     0,   177,   174,   209,   210,     0,
-       0,     0,   179,     0,     0,   178,     0,    16,   236,   368,
-     363,    37,   382,   381,   383,   164,   409,   407,     0,     0,
-       0,   421,     0,   442,   439,   444,   430,     0,   452,   506,
-     507,   485,     0,     0,     0,     0,   338,     0,   505,   492,
-     493,   453,   458,   462,     0,   484,     0,   454,   390,     0,
-       0,   432,   386,     0,   284,   277,     0,     0,     0,     0,
+       2,     0,     1,     7,     9,   105,     0,     0,   482,     0,
+       0,     0,     0,     0,    22,   344,   100,   100,     0,   540,
+       0,     0,   156,   395,     0,     0,     0,   533,   534,   539,
+       0,   535,   538,     0,     0,     0,   135,   100,   100,     0,
+       0,   371,   118,     0,   503,   149,     0,   508,     0,   509,
+     356,    21,    63,     0,     0,   183,   181,   182,   186,   483,
+     486,   485,   484,   180,     0,   184,   185,   328,   492,    20,
+       3,     4,     5,    13,     0,    20,    20,     0,     0,    50,
+     119,    57,   156,    52,    54,    53,    49,     0,    56,    51,
+     205,   173,   191,   489,    55,     0,    19,   364,   366,   394,
+     370,     0,   367,   421,     0,   423,   424,   369,     0,   393,
+     368,     0,   365,     0,   388,     0,     0,     0,   386,   374,
+     497,     0,     0,     0,     0,   373,    32,    20,    31,    26,
+       0,     0,     0,   275,   276,     0,     0,     0,     0,   331,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,   530,   520,   249,     0,   522,   521,     0,
-       0,   247,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   308,     0,     0,
-       0,   282,   283,     0,   354,   319,   317,   317,   345,   348,
-     346,   352,     0,     0,   394,     0,     0,   236,     0,     0,
-     109,   152,   151,   149,     0,     0,   554,     0,   545,   432,
-     542,   550,   541,   546,   341,   247,   314,   544,   548,   550,
-     552,     0,    67,    74,    75,    78,    73,    79,    76,    81,
-      82,    83,    84,    85,    80,    86,    87,    88,    89,    90,
-      91,    92,    93,    94,    95,    77,    96,    97,    68,     0,
-     139,     0,   106,     0,     0,     0,    10,    17,    40,    40,
-      13,     0,     0,     0,   135,     0,    70,     0,     0,   135,
-     123,   164,     0,   126,   121,   141,   164,   236,   236,   164,
-     161,     0,   155,   220,   222,   236,   224,     0,   226,   227,
-     228,   229,   230,     0,   218,   221,   216,    40,   174,   110,
-       0,     0,   212,   207,   211,   181,   184,     0,   338,     0,
-     213,     0,   203,   205,     0,   180,   236,     0,    14,   413,
-     555,   406,     0,   437,   438,   432,   436,     0,   448,     0,
-     443,   446,   474,   475,     0,   314,     0,   471,   473,   490,
-     500,   503,   502,   501,     0,   473,   510,   517,   511,   517,
-     460,   459,   517,   508,   510,   461,     0,     0,     0,     0,
-       0,   498,   455,     0,     0,     0,     0,   252,     0,     0,
-       0,   251,   258,   255,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   272,     0,     0,     0,
-       0,     0,     0,   247,     0,     0,     0,   324,     0,     0,
-       0,   248,     0,     0,   313,   307,   302,   292,   303,   304,
-     305,   301,   291,   297,   299,   293,   295,   287,   288,   289,
-       0,     0,   309,   306,   290,     0,   296,     0,   294,   323,
-       0,   325,     0,     0,   404,   405,   395,     0,   103,   104,
-     102,    66,     0,     0,     0,   317,     0,     0,   467,   469,
-     466,     0,     0,     0,   379,     0,   163,     0,    99,     0,
-     171,    51,     0,    31,    34,   168,    54,   167,     0,   118,
-       0,   136,     0,     0,   127,   129,     0,   125,   241,   245,
-       0,   238,   240,   246,     0,   198,   198,     0,   160,   223,
-       0,     0,     0,   111,     0,   236,   208,     0,     0,   213,
-     186,     0,   189,     0,   204,   433,     0,     0,   364,   369,
-       0,   236,   449,   441,     0,     0,   480,   481,   317,   236,
-       0,   464,   465,   504,   465,     0,   518,   514,   515,   510,
-     512,   463,   499,   495,   496,   497,   494,   550,   550,   387,
-     278,   253,   254,   257,   261,   262,   263,   264,   265,   260,
-     266,   267,   268,   269,   270,   271,   273,   274,   275,   276,
-     256,   248,     0,     0,     0,   523,   524,   527,   528,   525,
-     526,   259,   247,   312,   310,   311,   300,   298,   354,   337,
-     329,   326,   327,   330,   320,   322,   236,   153,   391,     0,
-       0,     0,   543,   377,   549,   378,   553,    98,   107,     0,
-      49,    48,    41,     0,    46,    43,   115,   135,   135,   135,
-     135,   135,   130,   128,   135,   117,   122,   243,     0,   237,
-     242,   140,     0,   146,   147,   156,   232,   233,   231,     0,
-     219,   217,   236,   198,   185,   213,   187,     0,   206,     0,
-       0,     0,     0,   236,   447,   491,     0,     0,     0,   476,
-     472,   473,   510,   517,   519,   509,     0,     0,   338,     0,
-       0,     0,   362,     0,     0,   335,   336,     0,   321,   105,
-       0,   547,     0,   100,     0,    42,     0,    33,   119,   131,
-     132,   133,   134,     0,   239,   244,   246,     0,   199,   200,
-     225,   198,   358,   188,   214,   375,   365,   366,   372,   371,
-     370,     0,   434,   479,   478,     0,   513,   425,   426,     0,
-     533,   535,   534,   353,   334,     0,   331,   328,     0,   551,
-      47,    44,     0,   116,     0,   358,   175,     0,     0,     0,
-     410,   516,     0,   333,     0,   539,    45,   201,   176,     0,
-       0,   374,   373,     0,     0,   332,   359,   360,   411,   536,
-       0,   537
+       0,     0,   334,   329,   330,     0,   337,   340,   339,   333,
+     328,   332,     0,   346,   347,   239,   237,     0,   269,   306,
+     308,   305,   271,   304,   270,   341,   384,   238,     0,    61,
+      93,     0,   345,   382,   101,   140,     0,   138,     0,   383,
+     588,     0,     0,   157,    29,   156,     0,   432,    28,   488,
+     487,   392,     0,     0,   377,   521,   519,     0,   379,     0,
+       0,     0,     0,   154,     0,     0,   131,     0,    46,   164,
+     165,   150,   162,   161,     6,   224,   225,   100,    64,   200,
+     198,   199,     0,    45,   121,     0,   156,   107,     0,     0,
+       8,    11,    12,    20,    21,     0,     0,    16,    17,     0,
+       0,    48,   158,    62,   119,     0,   226,   114,   119,   157,
+       0,     0,     0,     0,   226,   146,   151,     0,     0,   104,
+     206,    43,     0,   168,     0,     0,     0,   170,     0,     0,
+     169,   226,   352,   399,   418,   418,   462,   390,   389,   391,
+       0,     0,   532,   372,     0,   499,   496,   501,   502,   385,
+     375,   560,   561,   537,     0,     0,     0,     0,     0,     0,
+       0,   328,     0,   559,   543,   544,   376,   510,   514,     0,
+     536,     0,    18,   410,     0,     0,   274,   267,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,   573,   574,   572,     0,   575,
+       0,     0,   237,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   298,     0,
+       0,     0,   272,   273,   532,   344,   309,   307,   307,   335,
+     338,   336,   342,     0,   226,     0,     0,   143,   142,   141,
+     139,     0,     0,    30,   428,     0,   417,   437,     0,   591,
+     594,   589,   525,   526,     0,   304,     0,   522,   524,   541,
+     378,   332,   237,   304,   592,   594,   596,     0,    59,    66,
+      67,    70,    65,    71,    68,    73,    74,    75,    76,    77,
+      72,    78,    79,    80,    81,    82,    83,    84,    85,    86,
+      87,    69,    88,    89,    60,     0,   132,     0,    98,     0,
+       0,     0,     0,   202,   196,   201,   172,   129,     0,     0,
+       0,     0,   129,     0,     0,   156,    10,    14,    15,    33,
+      33,     0,     0,     0,   117,   156,     0,   120,   115,   134,
+     156,   226,   226,   156,   153,     0,   147,   210,   212,   226,
+     214,     0,   216,   217,   218,   219,   220,     0,   208,   211,
+      33,     0,   102,   226,   174,     0,   328,     0,   203,   332,
+       0,   192,   194,     0,   226,     0,   401,   438,     0,   444,
+       0,     0,   463,     0,   494,   495,     0,   493,     0,   506,
+       0,   500,   504,   551,   552,   554,   553,   557,   556,   555,
+       0,   524,     0,   569,   569,   569,   512,   511,   562,     0,
+     513,     0,     0,     0,     0,     0,   549,   405,   467,     0,
+     242,     0,     0,     0,   241,   248,   245,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   262,
+       0,   264,     0,     0,     0,   237,     0,     0,     0,     0,
+     314,     0,     0,   240,     0,     0,   303,   297,   292,   282,
+     293,   294,   295,   291,   281,   289,   290,   283,   288,   277,
+     278,   279,     0,     0,   299,   296,   280,     0,   285,     0,
+     284,     0,     0,   315,     0,     0,     0,    95,    96,    94,
+      58,     0,     0,     0,     0,   436,     0,     0,     0,     0,
+     530,   531,   307,   226,     0,   516,   518,   520,   517,     0,
+       0,     0,   387,     0,   155,     0,    91,     0,   163,    44,
+     197,     0,   112,     0,   130,     0,     0,   108,   121,   123,
+       0,     0,     0,   156,   431,     0,    25,    23,   160,    47,
+     159,   119,   231,   235,     0,   228,   230,   236,     0,   187,
+     187,     0,   152,   213,     0,     0,   207,   103,   226,   187,
+       0,     0,   203,   176,     0,   179,     0,   193,   490,     0,
+       0,   353,   357,   396,   409,   407,   408,   403,     0,   406,
+     419,   441,   481,   422,   439,   440,     0,   448,   445,     0,
+     473,     0,   468,   470,   464,   461,   418,   489,   507,   498,
+       0,   558,   542,     0,   570,   566,   564,   567,     0,   515,
+     550,   546,   547,   548,   545,   397,   268,   243,   244,   247,
+     251,   252,   253,   254,   255,   250,   256,   257,   258,   259,
+     260,   261,   263,   265,   266,   246,     0,     0,     0,   576,
+     577,   580,   581,   578,   579,   249,   237,   302,   300,   301,
+     287,   286,   313,   344,   327,   319,   316,   317,   320,   310,
+     312,   226,   145,   144,     0,     0,   453,     0,   460,     0,
+       0,     0,   590,   380,     0,     0,   532,   527,   523,   593,
+     381,   597,    90,    99,     0,   109,   129,   129,   129,   129,
+     129,   124,   122,     0,     0,   110,     0,     0,   427,    42,
+      41,    34,     0,    39,    36,    27,   116,   233,     0,   227,
+     232,   133,     0,   136,   137,   148,   222,   223,   221,     0,
+     209,   187,   348,   175,   203,   177,     0,   195,     0,     0,
+       0,     0,     0,     0,   400,   420,   442,     0,   456,   446,
+       0,   449,     0,   418,     0,   480,     0,   474,   476,   469,
+     471,   465,   226,   505,     0,   569,   571,   563,   328,     0,
+       0,     0,   351,     0,     0,   325,   326,     0,   311,    97,
+       0,     0,     0,   435,     0,     0,   529,     0,    92,   113,
+     125,   126,   127,   128,     0,     0,   466,     0,     0,    35,
+       0,    24,   229,   234,   236,     0,   188,   189,   215,   348,
+       0,     0,   166,   178,   204,   363,   354,   355,   360,   359,
+     358,     0,   413,   415,     0,   398,   399,     0,   457,   458,
+     450,   443,   418,   447,   478,     0,   472,   477,   226,     0,
+     565,   582,   583,   584,   343,   324,     0,   321,   318,     0,
+       0,     0,   433,   595,   528,     0,   129,   452,    40,    37,
+       0,     0,   167,   349,   350,     0,     0,   411,   414,   416,
+     399,   402,     0,   459,   451,   475,   479,   491,   568,   323,
+       0,   587,     0,     0,     0,     0,     0,    38,   190,   362,
+     361,   412,   404,   454,   322,   434,   585,   111,   455,     0,
+     586
 };
 
@@ -1414,129 +1301,138 @@
 static const yytype_int16 yydefgoto[] =
 {
-      -1,     1,    11,    93,    94,    95,   259,    12,   260,    13,
-      18,    15,    96,    97,   147,    14,    98,   265,   693,   907,
-     833,   834,    99,   255,   477,   478,   245,   208,   209,   426,
-     481,   215,   293,   294,   100,   101,   272,   698,   102,   103,
-     277,   273,   699,   700,   104,   105,   280,   106,   107,   108,
-     109,   110,   432,   111,   112,   287,   288,   242,   275,   269,
-     270,   113,   252,   114,   530,   295,   529,   115,   116,   302,
-     539,   117,   118,   119,   853,   918,   305,   542,   299,   540,
-     732,   296,   523,   524,   859,   525,   503,   710,   711,   712,
-     355,   190,   356,   191,   192,   411,   653,   635,   193,   661,
-     194,   195,   196,   197,   663,   811,   812,   813,   198,   199,
-     200,   420,   415,   212,   206,   956,   957,   201,   121,   122,
-     310,   738,   739,   927,   928,   123,   124,   125,   126,   127,
-     202,   128,   551,   316,   222,   228,   129,   130,   131,   308,
-     132,   133,   321,   134,   324,   559,   135,   136,   560,   561,
-     137,   138,   580,   341,   585,   328,   235,   566,   567,   139,
-     343,   140,   141,   344,   569,   346,   581,   582,   583,   757,
-     386,   387,   388,   889,   225,   142,   441,   442,   443,   449,
-     677,   451,   143,   552
+      -1,     1,    70,    71,    72,    73,   250,    74,   865,    75,
+     205,   129,   127,   696,   951,   862,   863,    76,   237,   463,
+     464,   228,   189,   190,   403,   467,   196,   281,   282,    77,
+      78,   246,   247,   681,    79,    80,   267,   248,   682,   683,
+      81,    82,    83,    84,    85,   409,    86,    87,   275,   276,
+     225,   206,   261,   262,    88,   233,    89,   283,   522,    90,
+     287,   527,    91,    92,   873,   956,   290,   531,   242,   528,
+     725,   284,   517,   518,   879,   519,   497,   704,   705,   706,
+     337,   175,   338,   176,   177,   392,   635,   617,   178,   643,
+     179,   180,   181,   182,   645,   816,   817,   818,   183,   184,
+     185,   401,   396,   193,   186,   962,   187,    94,    95,   731,
+     732,   967,   968,   740,    97,    98,   734,    99,   100,   536,
+     737,   892,   101,   738,   739,   334,   893,   974,   975,   655,
+     537,   102,   103,   104,   105,   106,   207,   418,   538,   743,
+     744,   107,   747,   748,   900,   901,   108,   749,   902,   981,
+     109,   110,   541,   542,   111,   543,   755,   752,   906,   907,
+     908,   745,   112,   113,   114,   115,   116,   211,   291,   117,
+     118,   303,   119,   306,   550,   120,   121,   551,   552,   122,
+     566,   326,   570,   214,   218,   426,   427,   546,   123,   328,
+     124,   428,   429,   331,   567,   568,   765,   368,   369,   854,
+     125,   420,   421,   435,   658,   437
 };
 
 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
    STATE-NUM.  */
-#define YYPACT_NINF -711
+#define YYPACT_NINF -845
 static const yytype_int16 yypact[] =
 {
-    -711,   923,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,   -98,  5724,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,   -51,  -711,   -47,  -711,  -711,  4731,    54,  2666,    70,
-     115,  -711,  4731,    34,    40,  2666,   117,  -711,   -63,  -711,
-       7,  4731,  -711,  -711,   -39,    66,   -63,  -711,   137,  -711,
-    -711,  -711,  -711,  -711,   184,   141,   170,  -711,  -711,   199,
-     199,   155,  -711,   175,  -711,  -711,    37,  -711,  -711,    92,
-     -63,   -63,  -711,   129,  -711,  -711,   116,  -711,   -63,  -711,
-    -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  -711,   217,  -711,  -711,    31,  -711,    96,  -711,
-     -64,   187,    97,   156,  -711,   149,  -711,   384,   390,  -711,
-    -711,   395,   165,  -711,  -711,    91,   -15,    80,   125,   372,
-     416,  -711,   253,   -98,   -63,  -711,   -63,   -63,  -711,   247,
-    4731,  -711,    24,   434,  -711,   267,   278,  2666,  -711,   270,
-    5575,   270,  -711,  2341,  -711,  -711,  -711,  -711,  4731,  4731,
-    -711,  -711,  4731,   276,   279,   280,  4731,  4731,  4731,   285,
-     291,   292,   296,   299,   301,   309,   310,   313,   316,   317,
-     318,  4731,   319,   325,   328,   329,   330,  4859,  -711,  -711,
-     331,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  4731,  2530,
-    -711,  -711,  4731,   304,  -711,   334,   342,  -711,   343,   354,
-     -33,  -711,    43,  4731,  -711,  2530,  -711,   356,   528,  -711,
-    4731,  2530,  -711,   534,  -711,   376,  -711,   376,  -711,  4731,
-    -711,  -711,  -711,  -711,  4731,  -711,  1494,  -711,  -711,  -711,
-    -711,   356,  -711,  -711,  4987,  -711,   356,   356,   376,  2588,
-    -711,   377,   356,  -711,  4731,   544,  -711,  -711,  -711,  -711,
-    -711,  -711,   546,  -711,  -711,   199,  -711,  -711,  5724,  -711,
-     -98,   -51,   -51,  -711,  -711,  -711,  -711,   557,   394,   561,
-    -711,    21,    33,   144,   397,   139,   388,  -711,   397,   356,
-    -711,   139,  -711,   399,   402,   139,   388,   571,  -711,   407,
-     733,   575,  -711,  -711,   -51,   572,  -711,  3067,  -711,   401,
-     215,  3963,  -711,  5115,   -15,  -711,   425,  -711,   388,  -711,
-     601,  -711,  -711,  -711,  -711,   384,   356,  2530,  4731,  4731,
-     356,  -711,   429,  4091,  -711,  -711,  -711,  5430,  -711,  -711,
-    -711,  -711,  4731,  4731,  4731,  4731,   610,  5430,  -711,   304,
-     354,  -711,  1098,   616,   588,   618,  5621,  4859,  -711,   441,
-     443,  -711,  -711,  1515,   670,  2530,    27,  4731,  4731,  4731,
-      36,  1550,    45,  4731,  4731,  4731,  4731,  4731,  4731,  4731,
-    4731,  4731,  4731,  4731,  4731,  1572,  4731,  4731,  4731,  4731,
-    4731,  4859,  2530,  1594,   782,  -711,   500,   630,   631,  4731,
-    1615,   633,  3451,  4731,  4731,  4731,  4731,  4731,  4731,  4731,
-    4731,  4731,  4731,  4731,  4731,  4731,  4731,  3195,  4731,  3579,
-    3707,  -711,   128,   356,  4731,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  4731,  4731,  -711,  1637,    48,   388,    70,  1697,
-    -711,  -711,   641,   641,  1819,  1173,  -711,   304,   -24,    -1,
-     457,   647,  -711,  -711,   471,   472,   151,    -1,  -711,   650,
-    -711,    62,   641,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,   651,   634,
-    -711,    71,  2530,   476,   488,   -63,  -711,  -711,   480,   480,
-    -711,  4731,    72,   394,   314,  4731,  -711,   491,   495,   314,
-    -711,   384,  2538,  -711,  -711,  -711,   384,   388,   388,   384,
-    -711,   407,   571,  -711,  -711,   388,  -711,   486,  -711,  -711,
-    -711,  -711,  -711,   358,  -711,  -711,  -711,   480,  -711,  -711,
-     497,  4219,  -711,  -711,  2530,  -711,  -711,  3963,  3323,   487,
-     665,  4347,  -711,  2530,   489,  -711,   388,    23,  -711,  -711,
-    -711,  -711,   667,  2530,  2530,  -711,  -711,   498,  2530,   493,
-     672,  -711,  -711,  -711,  5621,  3835,    75,  -711,   119,  -711,
-    2530,  2530,  2530,  2530,  4731,   530,  5850,  2530,   304,  1840,
-    -711,   674,  2530,  -711,  5850,  -711,  5621,  5621,  5621,  5621,
-    5621,   654,  -711,   356,   356,  2666,  4731,  -711,    84,    85,
-    1879,  -711,  -711,  -711,  1900,  1921,  1942,  1963,  2006,  2027,
-    2145,  2209,  2230,  2251,  2272,  2293,  -711,    86,    88,    89,
-      90,    98,  2327,   678,   687,   693,  4859,  -711,  4859,  4859,
-      99,  -711,  4731,  4731,  2530,  -711,   710,   710,   569,   569,
-     670,   814,   814,   814,   814,   814,   814,   133,   133,   128,
-    4731,  4731,  2530,  -711,   128,  4731,   814,  4731,   814,   304,
-     695,  2811,   517,   520,  2530,  2530,  -711,   356,  -711,  -711,
-    -711,  -711,   532,   619,  4731,  2811,   -49,   526,  -711,  -711,
-    -711,   -49,   527,   356,  -711,  2588,  -711,  4731,  -711,  4731,
-    -711,  -711,    67,  -711,   681,  2530,  -711,  -711,   689,    50,
-     716,  -711,  2348,   691,   538,  -711,   705,   397,  4731,  -711,
-     105,  -711,  -711,  1384,   356,   707,   707,   407,  -711,  -711,
-     287,   733,   732,  -711,   568,   388,  -711,   558,  4219,   665,
-    -711,   570,  -711,   560,  -711,  -711,   738,   617,   741,  -711,
-    4731,   388,  -711,  -711,  4091,   536,  -711,  -711,  2811,   519,
-    5430,  -711,  -711,  2530,   727,   106,  -711,  2530,  2530,  5850,
-    2530,   674,   574,   654,   654,   654,   406,   647,   650,  -711,
-    2530,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  5243,  5243,  5243,  2530,  -711,  2530,  -711,  2530,
-    -711,  -711,   573,   814,   814,   128,   814,   814,  4731,  2939,
-    1406,   745,  -711,  -711,   334,  -711,   388,  -711,  -711,  2475,
-     107,   744,  -711,  -711,  -711,  -711,  -711,  -711,  2530,   109,
-    -711,  -711,  -711,   110,  -711,   577,  -711,   314,   314,   314,
-     314,   314,   354,  -711,   314,  -711,  -711,  2530,  2538,  -711,
-    4475,  -711,  5371,  -711,  -711,   571,  -711,  -711,  -711,   579,
-    -711,  -711,   388,   707,  -711,   665,  -711,  4219,  -711,   -50,
-     581,   582,  1196,   388,  -711,  -711,  1362,   580,   356,  -711,
-    -711,   588,  5891,  2530,  -711,  -711,   583,   584,   747,   585,
-     590,   591,  -711,   592,  4731,  1428,  4731,  2811,  -711,  -711,
-     754,  -711,   356,  -711,    26,  -711,    93,  -711,  -711,    29,
-      29,   586,   113,   737,  -711,  -711,  2530,  4603,  -711,  2530,
-    -711,   707,    64,  -711,  -711,   649,  -711,   770,  -711,  -711,
-    -711,  4731,  -711,  -711,   457,   596,  2530,  -711,  -711,  4731,
-    -711,  -711,  -711,  -711,  2530,  4731,  1471,  -711,  4731,  -711,
-    -711,  -711,   111,  -711,   597,    64,  -711,   162,   609,   611,
-    1282,  -711,  1305,  2530,  4731,  2530,  -711,  -711,  -711,  4731,
-    4731,  -711,  -711,  4731,  4731,  2530,  2530,  2530,  2530,  1328,
-    4731,  2530
+    -845,   967,  -845,  -845,  -845,  -845,   -22,    45,  -845,    94,
+     186,  3621,   199,   238,  -845,  4658,    16,    36,  3621,  -845,
+     369,   256,    56,  -845,   299,   280,   268,  -845,  -845,  -845,
+     306,  -845,  -845,   409,   311,   350,  -845,   357,   357,   119,
+     354,  -845,  -845,    53,  -845,  -845,   420,  -845,   386,  -845,
+    -845,  5758,   363,   274,   280,  -845,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,  -845,   237,  -845,  -845,   549,  -845,  -845,
+    -845,   122,   563,  -845,   440,  -845,  -845,   319,   433,   436,
+     159,   495,   622,   624,  -845,  -845,   523,   329,  -845,  -845,
+     398,   102,   163,  -845,  -845,   471,  -845,  -845,  -845,  -845,
+    -845,   215,  -845,  -845,   215,  -845,  -845,  -845,   215,  -845,
+    -845,   215,  -845,   280,  -845,   280,   280,    20,   630,  -845,
+     472,    44,  3621,   306,  5477,  -845,  -845,  -845,  -845,  -845,
+    4658,  4658,  4658,  -845,  -845,  4658,   473,   474,   477,  -845,
+    4658,  4658,  4658,   478,   484,   486,   487,   488,   494,   496,
+     497,   498,   499,   500,   501,  4658,   505,  4658,   507,   508,
+     511,  4767,  -845,  -845,  -845,   512,  -845,  -845,  -845,  -845,
+    -845,  -845,  4658,  -845,  2490,  -845,  -845,  4658,   470,  -845,
+     513,   515,  -845,   516,   522,   270,  -845,  -845,   524,   654,
+    -845,  4658,  2490,  -845,  -845,  -845,   277,  -845,   277,  -845,
+    -845,  4658,  4658,  -845,  -845,   110,   326,  -845,  -845,  -845,
+    -845,  -845,   524,  5347,  4767,  -845,  -845,  4876,  -845,   524,
+     524,   277,  2573,  -845,   527,   524,  -845,  4658,   665,  -845,
+    -845,  -845,  -845,   680,   563,  -845,  -845,   357,  -845,  -845,
+    2967,  -845,   526,  -845,    88,   524,    32,  -845,   384,    82,
+    -845,  -845,  -845,  -845,  5621,    45,    45,  -845,  -845,   687,
+     533,   691,  -845,  -845,   535,   442,   534,  -845,   535,   524,
+     442,   537,   539,   442,   534,   699,  -845,   545,   847,  -845,
+    -845,  -845,    45,   714,   564,   434,  3874,  -845,  4985,   274,
+    -845,   534,   727,   122,   122,   122,   258,  -845,  -845,  -845,
+    4658,  4658,  -845,  -845,   571,  3983,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,  -845,  4658,  4658,  4658,  4658,  4658,  4658,
+    4658,   726,  5347,  -845,   470,   522,  -845,  1249,   730,   555,
+     561,  5523,  -845,  2490,   572,  1332,   875,  2490,    38,  4658,
+    4658,  4658,    48,  1353,    61,  4658,  4658,  4658,  4658,  4658,
+    4658,  4658,  4658,  4658,  4658,  4658,  4658,  1514,  4658,    68,
+    4658,  4658,  4658,  4767,  2490,  1533,   753,  1552,   278,   731,
+    4658,  1616,   733,  3294,  4658,  4658,  4658,  4658,  4658,  4658,
+    4658,  4658,  4658,  4658,  4658,  4658,  4658,  4658,  3076,  4658,
+    3403,  3512,  -845,   185,  -845,  4658,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,    69,   534,   199,  1635,  -845,  -845,   734,
+     734,  1129,  1713,  -845,  -845,   576,  -845,  -845,   736,   470,
+     739,  -845,  -845,  -845,  5523,  3765,    79,  -845,   555,  -845,
+     740,   581,   582,   439,  -845,   743,  -845,   105,   734,  -845,
+    -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,  -845,   744,   717,  -845,   106,  2490,   588,
+     591,   280,  4092,  -845,  -845,  2490,  -845,   598,  4658,    31,
+     237,   594,   598,   595,   602,   125,  -845,  -845,  -845,   609,
+     609,  4658,   109,   533,  -845,   622,  2531,  -845,  -845,  -845,
+     622,   534,   534,   622,  -845,   545,   699,  -845,  -845,   534,
+    -845,   615,  -845,  -845,  -845,  -845,  -845,   123,  -845,  -845,
+     609,   618,  -845,   534,  -845,  3874,  3185,   585,   750,    34,
+    4201,  -845,  2490,   592,   534,    80,  4331,  5955,    78,  5879,
+      13,    85,  -845,   215,  2490,  2490,   524,  -845,   619,  2490,
+     616,   778,  -845,  2490,  2490,  2490,  2490,  2490,  2490,  2490,
+    4658,   337,  1249,  2490,   706,  1732,  -845,   779,  -845,  1249,
+    -845,  5523,  5523,  5523,  5523,  5523,   760,  4658,  -845,  4658,
+    -845,   111,   115,  1751,  -845,  -845,  -845,  1796,  1815,  1834,
+    1912,  1931,  1995,  2014,  2033,  2092,  2111,  2130,  2194,  -845,
+     121,  -845,   130,   136,   149,   781,   785,   786,  4767,  4767,
+    -845,  4767,   150,  -845,  4658,  4658,  2490,  -845,   542,   542,
+     806,   806,   875,   887,   887,   887,   887,   887,   887,   164,
+     164,   185,  4658,  4658,  2490,  -845,   185,  4658,   887,  4658,
+     887,   524,   787,  2640,   627,   629,   524,  -845,  -845,  -845,
+    -845,   295,  4658,  6031,  4658,  -845,  4658,    19,   631,   337,
+    -845,  -845,  2640,    83,  5347,  -845,  -845,  -845,  -845,    19,
+     632,   524,  -845,  2573,  -845,  4658,  -845,  4658,  -845,  -845,
+    -845,   771,    42,   547,  -845,  2213,   636,  -845,   637,  -845,
+     776,  4658,  4658,   135,  -845,   242,  -845,   774,  2490,  -845,
+    -845,   535,  4658,  -845,   151,  -845,  -845,  1253,   524,   780,
+     780,   545,  -845,  -845,   476,   847,  -845,  -845,   534,   780,
+     641,  4092,   750,  -845,   645,  -845,   644,  -845,  -845,   804,
+     688,   809,  -845,  2490,  -845,  -845,  -845,   773,   215,  -845,
+     215,   653,  -845,  -845,  -845,  -845,   652,   536,  -845,   215,
+    -845,  2749,   655,   664,  -845,  -845,   122,  -845,  -845,  -845,
+    3983,  2490,  -845,   152,  -845,  2490,  2490,  2490,  1249,   779,
+     570,   760,   760,   760,   593,  -845,  2490,  -845,  -845,  -845,
+    -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,  -845,  -845,  -845,  5094,  5094,  5094,  2490,
+    -845,  2490,  -845,  2490,  -845,  -845,   667,   887,   887,   185,
+     887,   887,   470,  4658,  2858,  1415,   828,  -845,  -845,   513,
+    -845,   534,  -845,  -845,  2291,   670,  -845,   671,  -845,  2310,
+    1150,   829,  -845,  -845,  1233,   672,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,  2490,   153,  -845,   598,   598,   598,   598,
+     598,   522,  -845,   832,   676,  -845,  2329,  2374,  -845,  -845,
+    -845,  -845,   154,  -845,   678,  -845,  -845,  2490,  2531,  -845,
+    4440,  -845,  5203,  -845,  -845,   699,  -845,  -845,  -845,   679,
+    -845,   780,   231,  -845,   750,  -845,  4092,  -845,   291,   681,
+     683,  4658,   586,   215,   122,   122,  -845,  4658,   685,  -845,
+     454,  -845,   215,   122,  4658,  2490,   155,  -845,   842,  -845,
+    -845,  5955,   534,  -845,  1831,  2490,  -845,  -845,   832,   684,
+     686,   689,  -845,   690,  4658,  1435,  4658,  2640,  -845,  -845,
+     845,  4658,  4658,  -845,  4658,   524,  -845,   524,  -845,  -845,
+      66,    66,   693,   143,  4658,   833,  -845,   768,    60,  -845,
+     259,  -845,  -845,  -845,  2490,  4549,  -845,  2490,  -845,   231,
+    4658,  4658,  -845,  -845,  -845,   729,  -845,   851,  -845,  -845,
+    -845,   695,   696,   702,   215,  -845,   122,  2393,  -845,   703,
+    -845,  -845,   122,  5955,  -845,  2749,  -845,  4658,   534,   701,
+    2490,  -845,  -845,  -845,  -845,  2490,  4658,  1455,  -845,  4658,
+     704,  2412,  1171,   470,   697,  1192,   598,  -845,  -845,  -845,
+     157,   705,  -845,  2490,  2490,   709,   713,   716,  -845,  -845,
+     122,  4331,   784,  -845,  5955,  -845,  -845,  -845,  -845,  2490,
+    4658,  2490,  4658,  6107,  4658,  4658,   855,  -845,  -845,  -845,
+    -845,  -845,  4331,   719,  2490,  2490,  1213,  -845,  -845,  4658,
+    2490
 };
 
@@ -1544,1252 +1440,1297 @@
 static const yytype_int16 yypgoto[] =
 {
-    -711,  -711,  -711,  -711,   523,  -711,    30,  -711,   774,  -711,
-     -66,   772,  -711,  -711,    65,     6,  -711,  -711,  -430,  -711,
-    -118,  -110,  -711,  -711,   123,  -711,  -711,  -711,   373,  -711,
-     120,     1,  -711,  -711,  -711,  -711,  -711,  -480,  -711,  -711,
-    -264,   312,  -439,  -711,  -711,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,   -68,  -711,  -711,  -276,   300,   -35,   -85,   548,
-     324,  -711,  -711,  -711,   274,  -711,  -711,  -711,  -711,  -711,
-     281,  -711,  -711,  -711,  -699,  -711,  -711,  -711,   515,  -290,
-    -666,  -711,  -711,   100,  -711,   749,  -104,  -711,   -25,   -17,
-     -26,  -136,    56,  -176,  -432,  -497,  -711,  -711,  -103,  -711,
-    -711,  -711,  -204,  -711,   404,   159,   -57,    95,    -5,   -70,
-    -711,  -711,  -197,  -398,   -30,  -108,  -711,  -166,  -711,  -711,
-    -711,  -711,   -23,  -711,  -105,  -711,  -711,  -711,  -711,  -711,
-    -711,  -711,  -711,  -711,   -28,  -711,  -711,  -711,   708,   302,
-    -208,  -711,  -711,  -711,  -711,  -711,  -711,  -711,  -711,   118,
-    -711,  -711,  -711,  -711,  -711,   277,  -711,  -711,   114,  -711,
-    -711,  -711,  -711,  -306,   720,  -263,  -226,  -711,  -673,  -554,
-     514,   482,  -326,  -710,   308,  -711,   273,  -202,  -711,   275,
-    -416,  -711,  -711,  -711
+    -845,  -845,  -845,   -96,   830,   628,   -26,  -845,  -845,  -845,
+     399,   156,  -845,   -94,  -845,   -67,   -63,  -845,  -845,   232,
+    -845,  -845,  -845,   509,  -845,   234,    30,  -845,  -845,  -845,
+    -845,  -845,   444,  -464,  -845,  -845,  -238,   438,  -242,  -845,
+    -845,  -845,  -845,  -845,  -845,   -47,  -845,  -845,  -263,   417,
+     -27,   -50,   668,   437,  -845,  -845,  -845,  -845,  -845,  -845,
+    -845,   404,  -845,  -845,  -671,  -845,  -845,  -845,   642,  -231,
+    -656,  -845,  -845,   217,  -845,   882,  -236,  -845,    67,    70,
+     -11,   -78,    55,  -144,  -458,  -507,  -845,  -845,   -97,  -845,
+    -845,  -845,  -845,  -845,   540,  -845,     9,   279,     1,   -70,
+    -845,  -845,  -182,  -382,   365,   -20,  -128,  -845,  -845,  -845,
+      52,  -845,   -73,    43,  -845,  -630,  -845,  -515,  -514,  -844,
+    -845,  -845,  -845,  -845,  -566,  -718,  -845,  -845,  -845,  -845,
+    -294,  -845,  -845,  -845,  -845,  -845,  -185,  -845,  -845,  -845,
+    -845,  -845,  -845,  -663,  -845,  -845,  -845,  -845,  -845,  -845,
+    -845,  -845,  -845,   405,  -845,  -845,  -845,  -845,  -845,   -40,
+    -787,  -845,  -845,  -845,  -845,  -845,  -845,   -38,   190,    11,
+    -845,  -845,  -845,  -845,  -845,  -845,  -845,  -845,   191,  -845,
+    -845,  -845,  -845,   506,  -845,  -845,   288,  -384,  -845,  -845,
+    -845,   -39,   834,  -250,  -126,  -699,  -522,  -140,  -287,  -465,
+    -845,  -845,  -213,  -845,   519,  -845
 };
 
 /* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
    positive, shift that token.  If negative, reduce the rule which
-   number is the opposite.  If zero, do what YYDEFACT says.
-   If YYTABLE_NINF, syntax error.  */
-#define YYTABLE_NINF -511
+   number is the opposite.  If YYTABLE_NINF, syntax error.  */
+#define YYTABLE_NINF -542
 static const yytype_int16 yytable[] =
 {
-     189,   384,   205,   421,   338,   218,   211,   533,   120,   205,
-     500,   385,   391,   512,   504,   226,   660,   854,   230,   706,
-     281,   568,   283,   440,   145,   758,   285,   438,   760,   318,
-     596,   575,   438,   682,   448,   217,   282,   339,   213,   596,
-     591,   383,   249,   250,   213,   494,   422,   423,   596,   830,
-     257,   667,   840,   837,   736,   625,   243,   311,   445,   694,
-     238,   239,   701,   866,   261,   683,   262,   701,   278,  -361,
-     340,   838,   839,   840,   687,   493,   821,   289,   750,    17,
-     756,   590,   756,   890,   891,   756,   885,   596,   596,   596,
-     830,   596,   596,   596,   290,   291,   312,   723,   313,   314,
-     274,   596,   596,   300,   317,   267,   220,   326,   848,   882,
-     897,   205,   687,   904,   904,   268,   830,  -164,   146,   925,
-      91,  -164,   353,   354,   221,   419,   292,   263,   437,   266,
-     227,   361,   148,   437,   838,   839,   840,   926,   351,   586,
-     329,   330,   587,   588,   589,   375,   414,   498,   303,   433,
-     319,   382,   279,   408,   297,   416,   406,   407,   408,   240,
-     246,   298,   390,   241,   922,  -315,   412,   969,   499,  -164,
-     452,   384,   935,  -164,   247,   240,   240,   425,   675,   241,
-     241,   385,   510,   223,   429,   240,   224,   497,  -314,   241,
-    -361,   338,   737,   434,   487,   831,   253,   254,   435,   923,
-     495,   338,   427,   213,   546,   623,   577,   597,   382,   885,
-     338,   383,   360,   320,   362,   385,   601,   841,   482,   248,
-     496,   214,   955,   424,   339,   603,   439,   216,   668,   446,
-     549,   447,   450,   203,   339,   229,   831,   480,   841,   578,
-     501,   726,   684,   339,   258,   383,   506,   832,   729,   207,
-     509,   688,   696,   120,   264,   751,   485,   340,   745,   301,
-     884,   884,   831,   884,   771,   772,   786,   340,   787,   788,
-     789,   534,   579,   951,   505,   534,   340,   543,   790,   801,
-     762,   763,   764,   765,   766,   849,   883,   901,   970,   903,
-     905,   966,   553,   554,   210,   490,   219,   558,   251,   752,
-     796,   841,   798,   800,   304,   590,   570,   571,   572,   573,
-     659,   550,   590,   409,   410,   555,   231,   548,   409,   410,
-     236,   382,   565,   669,    91,   276,   488,   489,   590,   936,
-     417,   680,   565,   600,   286,   150,   151,   604,   605,   606,
-     607,   608,   609,   610,   611,   612,   613,   614,   615,   237,
-     755,   886,   887,   232,   244,   622,   271,   908,   761,   527,
-     233,   721,   722,   234,   913,   391,   634,   636,   637,   638,
-     639,   640,   641,   642,   643,   644,   645,   646,   647,   648,
-     649,   652,   654,   656,   658,   440,   756,   282,   211,   438,
-     438,   536,   448,   284,   537,   306,   664,   665,   282,   909,
-     910,   911,   912,   715,   716,   701,   701,   701,   701,   701,
-     893,   719,   701,   598,   599,  -164,   707,   342,   347,  -164,
-     307,   714,   309,   315,   717,   856,   857,   858,   338,   587,
-     588,   589,   617,   618,   619,   620,   621,   322,   865,   884,
-     577,   855,   735,   846,   881,   630,   323,   325,   577,   327,
-     338,   338,   338,   338,   338,   357,   802,   691,   358,   359,
-     385,   339,   385,   385,   363,   695,   796,   798,   800,   702,
-     364,   365,   438,   578,   822,   366,   713,   438,   367,   824,
-     368,   578,   590,   339,   339,   339,   339,   339,   369,   370,
-     437,   437,   371,   413,   340,   372,   373,   374,   376,   590,
-     590,   590,   590,   590,   377,   534,   579,   378,   379,   380,
-     389,   534,   534,   414,   579,   390,   340,   340,   340,   340,
-     340,   416,   417,   418,   392,    91,   393,   394,   395,   396,
-     397,   428,   398,   399,   400,   401,   402,   403,   430,   749,
-     404,   405,   406,   407,   408,   431,   479,   483,   753,   484,
-     586,   329,   330,   587,   588,   589,   586,   329,   330,   587,
-     588,   589,   491,   267,   493,   769,   276,   502,   507,   205,
-     770,   508,   391,   437,   511,   528,   286,   924,   437,   526,
-     397,   535,   398,   399,   400,   401,   402,   403,   439,   447,
-     404,   405,   406,   407,   408,   329,   330,   587,   588,   589,
-     795,   545,   797,   799,   547,   556,   382,   803,   586,   329,
-     330,   587,   588,   589,   338,   574,   802,   898,   590,   584,
-     593,   863,   594,   577,   804,   805,   385,   385,   385,   806,
-     842,   807,   627,   628,   629,   810,   632,   873,  -490,  -490,
-    -490,  -490,  -490,  -490,   672,   879,   320,   339,   819,   810,
-     676,   678,   679,   681,   685,   689,   578,   690,   686,   692,
-     703,   828,   816,   482,   704,   720,   725,   730,   731,   734,
-     934,   447,   740,   743,   223,   744,   447,   759,   826,   589,
-     340,   792,   847,   398,   399,   400,   401,   402,   403,   579,
-     793,   404,   405,   406,   407,   408,   794,   814,   502,   808,
-     815,   817,   534,   818,   409,   410,   823,   825,   878,   851,
-     754,   835,   899,   836,   872,   844,   875,   495,   558,   395,
-     396,   397,   876,   398,   399,   400,   401,   402,   403,   845,
-     852,   404,   405,   406,   407,   408,   861,   862,   864,   867,
-     868,   391,   869,   870,   871,   565,   577,  -491,   897,   902,
-     929,   737,   939,   892,   409,   410,   906,   948,   921,   920,
-     933,   953,   513,   937,   938,   940,   795,   797,   799,   932,
-     941,   942,   943,   959,   841,   958,   961,   967,   971,   578,
-     925,   486,   211,   895,    16,   626,   144,  -247,   952,  -247,
-    -247,  -247,  -247,  -247,   950,  -247,  -247,  -247,  -247,  -247,
-    -247,   670,   724,  -247,  -247,  -247,  -247,  -247,   827,   829,
-     705,   718,   579,   253,   254,   514,   492,   697,   727,   544,
-     662,   860,   713,   914,   916,   256,   919,  -511,  -511,  -511,
-    -511,  -511,  -511,   915,   820,   404,   405,   406,   407,   408,
-     947,   534,   515,   877,   516,   517,   518,   968,   930,   519,
-     520,   352,   521,   522,   972,   409,   410,   741,   178,   179,
-     345,   592,   874,   624,   880,   742,   767,     0,   944,   768,
-     946,   810,     0,   351,   181,   182,     0,     0,   183,   184,
-     185,   186,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,   390,   187,     0,     0,   409,   410,   949,     0,     0,
-       0,     0,     0,     0,     0,   960,     0,     0,     0,     0,
-       0,     0,     0,   962,     0,     0,     0,     0,     0,   963,
-       0,     0,   965,     2,     3,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   975,     0,
-       0,     0,     0,   976,   977,     0,     0,   978,   979,     0,
-     -23,     0,   -23,     0,   981,   -23,   -23,   -23,   -23,     4,
-       5,   -23,     0,     0,   -23,   -23,   -23,  -247,  -247,     0,
-       0,   -23,   -23,     0,     0,     0,     6,     7,     0,     0,
-       0,     0,     0,     0,     0,     0,   -23,     0,     0,     0,
-     -23,   -23,     0,     0,     0,   -23,     0,     0,     0,   409,
-     410,   -23,     0,   -23,   -23,     0,   -23,     0,   -23,   -23,
-     -23,   -23,   -23,     0,   -23,   -23,   -23,   -23,   -23,   -23,
-     -23,   -23,   -23,   -23,   -23,   -23,   -23,   -23,   -23,   -23,
-       0,     0,   -23,   -23,   -23,     0,   -23,   -23,   -23,     0,
-     -23,   -23,   -23,     0,     0,   -23,     0,   -23,     0,     0,
-     -23,   -23,   -23,   -23,     0,     0,   -23,   -23,   -23,     0,
-       0,     0,     0,     0,   -23,     0,     0,     8,   -23,   -23,
-     -23,   -23,   -23,   -23,   -23,     0,   -23,   -23,   -23,   -23,
-     -23,     0,     0,   -23,     0,     0,     0,     0,     0,     0,
-     -23,   -23,   -23,     0,     0,     0,     0,     0,     0,   -23,
-       9,  -510,     0,  -510,     0,  -510,  -510,  -510,  -510,  -510,
-      10,  -510,  -510,  -510,  -510,  -510,  -510,     0,     0,  -510,
-    -510,  -510,  -510,  -510,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   152,   153,     0,
-       0,     0,   154,   155,   156,   157,     0,     0,     0,     0,
-       0,     0,     0,     0,   158,   159,   160,   161,   162,   163,
-     164,     0,   165,   166,   167,     0,     0,   168,   169,   170,
-       0,   171,   172,   173,   174,   175,   674,   176,   392,     0,
-     393,   394,   395,   396,   397,     0,   398,   399,   400,   401,
-     402,   403,     0,     0,   404,   405,   406,   407,   408,   931,
-       0,   392,     0,   393,   394,   395,   396,   397,     0,   398,
-     399,   400,   401,   402,   403,     0,     0,   404,   405,   406,
-     407,   408,     0,     0,     0,     0,     0,     0,     0,     0,
+     174,   539,    93,   402,   192,   293,   434,   174,   294,   474,
+     641,   775,   295,   642,   506,   296,   243,   366,   690,   684,
+     414,   735,   736,   828,   684,   300,   494,   324,   372,   265,
+     498,   270,   271,   367,   686,   203,   273,  -171,   504,   874,
+     226,   579,   766,   767,    96,   846,   323,   198,   882,   257,
+     258,   579,    93,   268,   325,   534,   764,   764,   764,   203,
+     277,   847,   848,   849,   579,  -171,   885,   221,   222,   917,
+     366,   579,   646,   432,   430,   297,   607,   298,   299,   575,
+    -430,   859,   664,   365,   899,   329,   367,   849,   373,   374,
+     375,   376,   377,   378,    96,   379,   380,   381,   382,   383,
+     384,   332,   385,   386,   387,   388,   389,   729,   671,   675,
+     477,   174,   493,   203,   579,   419,   324,   984,   579,   333,
+     335,   336,   419,   285,   579,   750,   715,   483,   203,   540,
+     343,   126,  1021,   579,  -426,   323,   365,   223,   203,   579,
+     831,   224,   301,   325,   357,   307,   251,   194,   479,  -429,
+     364,   410,   579,   579,   868,   914,   675,   948,   985,  -425,
+     948,   371,   847,   848,   849,  -171,   393,   194,   648,   741,
+     484,   485,   229,   971,   438,   751,  1042,   223,   575,   170,
+     406,   224,   195,   230,   288,   387,   388,   389,   302,   404,
+     411,   412,   753,   742,  -171,   342,   480,   344,  -106,   394,
+    1026,   580,   197,   364,   308,   128,   364,   417,   389,   850,
+     959,   584,   359,  1000,   425,   917,   468,   204,   433,   605,
+     860,   436,  -430,   606,   586,   324,   466,   486,   963,   475,
+     564,   601,   647,   850,   324,   367,   960,   980,   495,     4,
+     730,   680,   665,   500,   323,   496,   503,   390,   391,   563,
+     478,   836,   325,   323,   716,    93,   130,   565,   916,   916,
+     916,   325,   252,   859,   286,   709,   710,   471,   672,   676,
+     499,   413,   699,   713,   777,   475,  -426,   532,   778,   170,
+     859,   609,   251,   561,   792,   365,   204,   719,   253,   544,
+     545,  -429,   576,   793,   549,   722,   413,    96,   728,   794,
+     694,  -425,   540,   553,   554,   555,   556,   557,   558,   559,
+     850,   575,   795,   805,   869,   915,   938,   949,   986,   266,
+    1037,   800,   802,   425,   804,   289,   575,   324,   390,   391,
+     583,   919,   920,   921,   587,   588,   589,   590,   591,   592,
+     593,   594,   595,   596,   597,   598,   323,   223,   131,   390,
+     391,   224,   371,   961,   325,   571,   311,   312,   572,   573,
+     574,   188,   616,   618,   619,   620,   621,   622,   623,   624,
+     625,   626,   627,   628,   629,   630,   631,   634,   636,   638,
+     640,    69,   939,   199,   192,   659,   372,   481,   684,   684,
+     684,   684,   684,   990,   581,   582,   697,   244,   252,   245,
+     191,   278,   860,   828,   610,   861,   482,   239,   764,   575,
+     407,   489,   490,   600,   663,   602,   603,   604,   202,   860,
+     415,   416,  1009,   400,   253,   612,   717,   837,   822,   279,
+     212,   923,   395,   679,   240,   241,   763,   408,   520,   264,
+     209,   235,   236,   769,   832,   701,   210,   756,   875,   989,
+     708,   965,   937,   711,  -156,   823,   839,   966,  -156,   208,
+     223,   475,   911,   866,   224,   564,   775,   685,   213,   255,
+     806,   256,   564,   219,   324,   324,   324,   324,   324,   259,
+     698,   260,   881,   916,   563,   707,   170,   309,   194,   274,
+     884,   563,   565,   323,   323,   323,   323,   323,   269,   565,
+     762,   325,   325,   325,   325,   325,   735,   736,   858,   800,
+     802,   804,   220,  -156,   475,   475,   227,  -156,   372,   371,
+     575,   575,   575,   575,   575,   733,   203,   735,   736,   280,
+     200,   201,   770,   771,   772,   773,   774,   746,    93,   979,
+      93,  -156,  1036,   231,   812,  -156,   232,   757,   684,   761,
+     376,   377,   378,   249,   379,   380,   381,   382,   383,   384,
+     419,   385,   386,   387,   388,   389,   733,   324,   776,   215,
+     216,   217,   419,   571,   311,   312,   572,   573,   574,  -541,
+    -541,  -541,  -541,  -541,  -541,   929,   323,   254,   139,   311,
+     312,   572,   573,   574,   325,   524,   525,   799,   801,   263,
+     803,   398,   668,   364,   807,   940,   941,   942,   943,   983,
+     876,   877,   878,   851,   572,   573,   574,   133,   134,   746,
+     898,   808,   809,   972,   973,   203,   810,   272,   811,   310,
+     327,   292,   815,   304,   305,   339,   340,   928,   394,   341,
+     345,   824,   894,   829,   895,   830,   346,   821,   347,   348,
+     349,   834,   806,   903,    93,   964,   350,   405,   351,   352,
+     353,   354,   355,   356,   843,   425,   468,   358,   469,   360,
+     361,   564,   841,   362,   370,   395,   988,   397,   398,   162,
+     856,   857,   399,   470,   170,   163,   164,   465,  1024,   476,
+     563,   867,   491,   259,   493,   266,   496,   501,   565,   502,
+     166,   167,   505,   168,   169,   274,   390,   391,   171,   871,
+     475,   373,   374,   375,   376,   377,   378,   521,   379,   380,
+     381,   382,   383,   384,   523,   385,   386,   387,   388,   389,
+     535,   560,   547,   569,   611,   577,   614,   651,   654,   674,
+     905,   656,   657,   609,   666,   667,   669,   673,   723,   549,
+     677,   678,  1027,   724,   688,   727,   608,   691,  -237,  -237,
+    -237,  -237,  -237,  -237,   692,  -237,  -237,  -237,  -237,  -237,
+    -237,   695,  -237,  -237,  -237,  -237,  -237,   714,   718,   759,
+     758,   760,   768,   574,   796,   799,   801,   803,   797,   798,
+     819,   813,   820,   845,   833,   840,   853,   976,   855,   478,
+     864,   872,   192,   925,   883,   886,   982,   887,   888,   891,
+     889,   372,   890,   896,   897,   909,   378,   564,   379,   380,
+     381,   382,   383,   384,   910,   385,   386,   387,   388,   389,
+     922,   927,   931,   932,   935,   936,   563,   944,  1003,   945,
+     950,   969,   958,   730,   565,   978,   987,   991,   999,   992,
+    1007,  1015,   993,   994,  1016,  1006,  1018,   707,  1017,   954,
+     850,   957,  1019,  1023,  1028,   302,  1043,  1032,  1038,  1039,
+     390,   391,   507,   965,   394,   475,  1041,  1047,  1020,  1048,
+     333,   234,   488,  1010,   693,  1008,   977,   379,   380,   381,
+     382,   383,   384,   905,   385,   386,   387,   388,   389,  -542,
+    -542,  -542,  -542,  -542,  -542,   842,   385,   386,   387,   388,
+     389,   844,    93,   995,   649,   997,   815,  -237,  -237,   689,
+     333,  1001,   712,  1002,   687,   235,   236,   508,   492,   720,
+     700,   533,   880,  1005,   238,   952,   998,   644,    93,  1012,
+     953,   835,   970,  1040,   371,  1025,   754,   912,  1004,  1013,
+    1014,   913,   838,   509,   670,   510,   511,   512,   330,     0,
+     513,   514,     0,   515,   516,     0,     0,     2,     3,     0,
+     390,   391,     0,     0,   905,     0,   905,     0,     0,     0,
+       0,     0,     0,     0,    93,  1029,     0,     0,  1031,     0,
+       0,     4,     5,     0,     0,     6,   -21,     7,   -21,     8,
+       0,     0,     9,     0,     0,     0,     0,     0,     0,     0,
+     733,     0,    10,     0,     0,     0,     0,     0,     0,  1044,
+       0,   733,     0,  1045,  1046,    93,     0,     0,    11,     0,
+       0,   733,    12,    13,    93,     0,     0,    14,  1050,   390,
+     391,     0,     0,    15,     0,    16,    17,     0,    18,     0,
+       0,   390,   391,    19,    20,    21,    22,    23,     0,    24,
+      25,     0,     0,    26,    27,    28,    29,    30,    31,    32,
+      33,    34,    35,    36,     0,    37,     0,    38,    39,     0,
+       0,    40,    41,    42,     0,    43,     0,    44,     0,     0,
+      45,    46,     0,     0,    47,    48,    49,     0,     0,     0,
+       0,     0,     0,     0,    50,     0,     0,    51,    52,    53,
+      54,    55,    56,    57,    58,    59,    60,    61,    62,    63,
+       0,     0,    64,     0,     0,    65,    66,    67,    68,     0,
+       0,     0,   652,    69,   373,   374,   375,   376,   377,   378,
+       0,   379,   380,   381,   382,   383,   384,     0,   385,   386,
+     387,   388,   389,   934,     0,   373,   374,   375,   376,   377,
+     378,     0,   379,   380,   381,   382,   383,   384,     0,   385,
+     386,   387,   388,   389,  1034,     0,   373,   374,   375,   376,
+     377,   378,     0,   379,   380,   381,   382,   383,   384,     0,
+     385,   386,   387,   388,   389,  1035,     0,   373,   374,   375,
+     376,   377,   378,     0,   379,   380,   381,   382,   383,   384,
+       0,   385,   386,   387,   388,   389,  1049,     0,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,   926,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,   870,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,     0,     0,     0,
+       0,     0,   135,   136,     0,     0,     0,     0,   137,   138,
+     139,   140,   141,   390,   391,     0,     0,     0,     0,     0,
+       0,     0,     0,   142,   143,   144,   145,   146,   147,   148,
+       0,   149,   150,   151,   390,   391,   152,   153,   154,     0,
+     155,   156,   157,   158,   159,     0,   160,     0,     0,     0,
+       0,     0,     0,     0,     0,   390,   391,   373,   374,   375,
+     376,   377,   378,     0,   379,   380,   381,   382,   383,   384,
+       0,   385,   386,   387,   388,   389,   390,   391,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,   390,   391,     0,
+       0,   162,     0,     0,     0,     0,     0,   163,   164,     0,
+       0,     0,     0,   165,     0,     0,   613,   390,   391,     0,
+       0,     0,   166,   167,     0,   168,   169,     0,     0,   170,
+     171,   562,     0,     0,     0,     0,     0,   390,   391,   926,
+     373,   374,   375,   376,   377,   378,     0,   379,   380,   381,
+     382,   383,   384,     0,   385,   386,   387,   388,   389,   996,
+     373,   374,   375,   376,   377,   378,     0,   379,   380,   381,
+     382,   383,   384,     0,   385,   386,   387,   388,   389,  1030,
+     373,   374,   375,   376,   377,   378,     0,   379,   380,   381,
+     382,   383,   384,     0,   385,   386,   387,   388,   389,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-     178,   179,     0,     0,     0,     0,   180,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   181,   182,     0,     0,
-     183,   184,   185,   186,     0,     0,     0,    91,     0,     0,
-       0,     0,     0,     0,   187,     0,     0,   576,     0,     0,
-       0,     0,     0,  -510,  -510,   973,     0,   392,     0,   393,
-     394,   395,   396,   397,     0,   398,   399,   400,   401,   402,
-     403,     0,     0,   404,   405,   406,   407,   408,   974,     0,
-     392,     0,   393,   394,   395,   396,   397,     0,   398,   399,
-     400,   401,   402,   403,     0,     0,   404,   405,   406,   407,
-     408,   980,     0,   392,     0,   393,   394,   395,   396,   397,
-       0,   398,   399,   400,   401,   402,   403,     0,     0,   404,
-     405,   406,   407,   408,     0,     0,     0,     0,   409,   410,
-       0,     0,     0,     0,     0,     0,   896,   392,     0,   393,
-     394,   395,   396,   397,     0,   398,   399,   400,   401,   402,
-     403,   409,   410,   404,   405,   406,   407,   408,   850,   392,
-       0,   393,   394,   395,   396,   397,     0,   398,   399,   400,
-     401,   402,   403,     0,     0,   404,   405,   406,   407,   408,
-     896,   392,     0,   393,   394,   395,   396,   397,     0,   398,
-     399,   400,   401,   402,   403,     0,     0,   404,   405,   406,
-     407,   408,   945,   392,     0,   393,   394,   395,   396,   397,
-       0,   398,   399,   400,   401,   402,   403,     0,     0,   404,
-     405,   406,   407,   408,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   409,   410,     0,
-       0,     0,     0,     0,     0,   964,   392,     0,   393,   394,
-     395,   396,   397,     0,   398,   399,   400,   401,   402,   403,
-     409,   410,   404,   405,   406,   407,   408,     0,     0,   392,
-       0,   393,   394,   395,   396,   397,     0,   398,   399,   400,
-     401,   402,   403,   409,   410,   404,   405,   406,   407,   408,
-     392,     0,   393,   394,   395,   396,   397,     0,   398,   399,
-     400,   401,   402,   403,     0,     0,   404,   405,   406,   407,
-     408,     0,   631,     0,     0,     0,     0,   409,   410,     0,
-       0,     0,     0,     0,     0,   392,     0,   393,   394,   395,
-     396,   397,     0,   398,   399,   400,   401,   402,   403,   409,
-     410,   404,   405,   406,   407,   408,     0,   392,     0,   393,
-     394,   395,   396,   397,     0,   398,   399,   400,   401,   402,
-     403,   409,   410,   404,   405,   406,   407,   408,     0,  -250,
-       0,  -250,  -250,  -250,  -250,  -250,     0,  -250,  -250,  -250,
-    -250,  -250,  -250,   409,   410,  -250,  -250,  -250,  -250,  -250,
-     392,     0,   393,   394,   395,   396,   397,     0,   398,   399,
-     400,   401,   402,   403,     0,     0,   404,   405,   406,   407,
-     408,     0,   392,     0,   393,   394,   395,   396,   397,     0,
-     398,   399,   400,   401,   402,   403,   409,   410,   404,   405,
-     406,   407,   408,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,   436,     0,     0,     0,     0,   409,
-     410,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,   595,     0,     0,     0,     0,
-     409,   410,   392,     0,   393,   394,   395,   396,   397,     0,
-     398,   399,   400,   401,   402,   403,     0,     0,   404,   405,
-     406,   407,   408,     0,     0,     0,     0,     0,     0,     0,
-     602,     0,     0,     0,     0,   409,   410,     0,     0,     0,
+       0,     0,     0,     0,     0,   578,   390,   391,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   616,     0,     0,     0,     0,   409,   410,     0,
+       0,     0,     0,     0,     0,     0,   585,   390,   391,   373,
+     374,   375,   376,   377,   378,     0,   379,   380,   381,   382,
+     383,   384,     0,   385,   386,   387,   388,   389,  -239,  -239,
+    -239,  -239,  -239,  -239,     0,  -239,  -239,  -239,  -239,  -239,
+    -239,     0,  -239,  -239,  -239,  -239,  -239,  -238,  -238,  -238,
+    -238,  -238,  -238,     0,  -238,  -238,  -238,  -238,  -238,  -238,
+       0,  -238,  -238,  -238,  -238,  -238,     0,     0,     0,   390,
+     391,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   390,
+     391,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   390,
+     391,   373,   374,   375,   376,   377,   378,     0,   379,   380,
+     381,   382,   383,   384,     0,   385,   386,   387,   388,   389,
+     373,   374,   375,   376,   377,   378,     0,   379,   380,   381,
+     382,   383,   384,     0,   385,   386,   387,   388,   389,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,  -250,     0,     0,     0,     0,  -250,
-    -250,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,   631,     0,     0,     0,     0,
-     409,   410,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   666,     0,     0,
-       0,     0,   409,   410,   392,     0,   393,   394,   395,   396,
-     397,     0,   398,   399,   400,   401,   402,   403,     0,     0,
-     404,   405,   406,   407,   408,   392,     0,   393,   394,   395,
-     396,   397,     0,   398,   399,   400,   401,   402,   403,     0,
-       0,   404,   405,   406,   407,   408,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   671,     0,     0,
-       0,     0,   409,   410,   392,     0,   393,   394,   395,   396,
-     397,     0,   398,   399,   400,   401,   402,   403,     0,     0,
-     404,   405,   406,   407,   408,   392,     0,   393,   394,   395,
-     396,   397,     0,   398,   399,   400,   401,   402,   403,     0,
-       0,   404,   405,   406,   407,   408,   392,     0,   393,   394,
-     395,   396,   397,     0,   398,   399,   400,   401,   402,   403,
-       0,     0,   404,   405,   406,   407,   408,   392,     0,   393,
-     394,   395,   396,   397,     0,   398,   399,   400,   401,   402,
-     403,     0,     0,   404,   405,   406,   407,   408,   392,     0,
-     393,   394,   395,   396,   397,     0,   398,   399,   400,   401,
-     402,   403,     0,     0,   404,   405,   406,   407,   408,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,   673,
-       0,     0,     0,     0,   409,   410,     0,     0,     0,   418,
-       0,   392,     0,   393,   394,   395,   396,   397,     0,   398,
-     399,   400,   401,   402,   403,   409,   410,   404,   405,   406,
-     407,   408,   392,     0,   393,   394,   395,   396,   397,     0,
-     398,   399,   400,   401,   402,   403,     0,     0,   404,   405,
-     406,   407,   408,     0,     0,     0,     0,     0,     0,   773,
-       0,     0,     0,     0,   409,   410,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,   599,   390,   391,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-     774,     0,     0,     0,     0,   409,   410,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,  -239,  -239,  -239,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,   775,     0,     0,     0,     0,   409,   410,     0,     0,
+       0,     0,     0,     0,     0,  -238,  -238,  -238,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,   373,   374,   375,
+     376,   377,   378,     0,   379,   380,   381,   382,   383,   384,
+       0,   385,   386,   387,   388,   389,   373,   374,   375,   376,
+     377,   378,     0,   379,   380,   381,   382,   383,   384,     0,
+     385,   386,   387,   388,   389,     0,     0,     0,     0,   613,
+     390,   391,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   650,   390,
+     391,   373,   374,   375,   376,   377,   378,     0,   379,   380,
+     381,   382,   383,   384,     0,   385,   386,   387,   388,   389,
+     373,   374,   375,   376,   377,   378,     0,   379,   380,   381,
+     382,   383,   384,     0,   385,   386,   387,   388,   389,   373,
+     374,   375,   376,   377,   378,     0,   379,   380,   381,   382,
+     383,   384,     0,   385,   386,   387,   388,   389,     0,     0,
+       0,     0,     0,     0,   135,   136,     0,     0,     0,     0,
+     137,   138,   139,   140,   141,     0,   653,   390,   391,     0,
+       0,     0,     0,     0,     0,   142,   143,   144,   145,   146,
+     147,   148,   399,   149,   150,   151,   390,   391,   152,   153,
+     154,     0,   155,   156,   157,   158,   159,     0,   160,     0,
+       0,     0,     0,     0,   779,   390,   391,   373,   374,   375,
+     376,   377,   378,     0,   379,   380,   381,   382,   383,   384,
+       0,   385,   386,   387,   388,   389,   373,   374,   375,   376,
+     377,   378,     0,   379,   380,   381,   382,   383,   384,     0,
+     385,   386,   387,   388,   389,     0,     0,     0,     0,   780,
+     390,   391,     0,   162,     0,     0,     0,     0,     0,   163,
+     164,     0,     0,     0,     0,   165,     0,     0,   781,   390,
+     391,     0,     0,     0,   166,   167,     0,   168,   169,     0,
+       0,   918,   171,   562,     0,     0,     0,   782,   390,   391,
+     373,   374,   375,   376,   377,   378,     0,   379,   380,   381,
+     382,   383,   384,     0,   385,   386,   387,   388,   389,   373,
+     374,   375,   376,   377,   378,     0,   379,   380,   381,   382,
+     383,   384,     0,   385,   386,   387,   388,   389,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   776,     0,     0,     0,     0,   409,   410,     0,
+       0,     0,     0,     0,     0,   783,   390,   391,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,   777,     0,     0,     0,     0,   409,   410,
-     392,     0,   393,   394,   395,   396,   397,     0,   398,   399,
-     400,   401,   402,   403,     0,     0,   404,   405,   406,   407,
-     408,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   778,     0,     0,     0,
-       0,   409,   410,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   779,     0,     0,
-       0,     0,   409,   410,   392,     0,   393,   394,   395,   396,
-     397,     0,   398,   399,   400,   401,   402,   403,     0,     0,
-     404,   405,   406,   407,   408,   392,     0,   393,   394,   395,
-     396,   397,     0,   398,   399,   400,   401,   402,   403,     0,
-       0,   404,   405,   406,   407,   408,   392,     0,   393,   394,
-     395,   396,   397,     0,   398,   399,   400,   401,   402,   403,
-       0,     0,   404,   405,   406,   407,   408,   392,     0,   393,
-     394,   395,   396,   397,     0,   398,   399,   400,   401,   402,
-     403,     0,     0,   404,   405,   406,   407,   408,   392,     0,
-     393,   394,   395,   396,   397,     0,   398,   399,   400,   401,
-     402,   403,     0,     0,   404,   405,   406,   407,   408,     0,
-       0,     0,     0,     0,     0,   780,     0,     0,     0,     0,
-     409,   410,   392,     0,   393,   394,   395,   396,   397,     0,
-     398,   399,   400,   401,   402,   403,     0,     0,   404,   405,
-     406,   407,   408,   392,     0,   393,   394,   395,   396,   397,
-       0,   398,   399,   400,   401,   402,   403,     0,     0,   404,
-     405,   406,   407,   408,     0,     0,     0,     0,     0,    22,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,   781,
-       0,     0,     0,     0,   409,   410,     0,     0,     0,     0,
-       0,     0,     0,     0,    28,     0,     0,     0,     0,     0,
-     782,     0,     0,     0,     0,   409,   410,     0,     0,    32,
-       0,     0,     0,     0,    35,   348,     0,     0,     0,    39,
-      40,   783,     0,     0,     0,     0,   409,   410,     0,   349,
-      49,    50,    51,    52,    53,    54,   350,     0,     0,     0,
-       0,     0,   784,     0,     0,     0,     0,   409,   410,    64,
-       0,     0,     0,     0,     0,    67,     0,     0,     0,     0,
-       0,     0,     0,   785,    72,     0,    74,     0,   409,   410,
-     392,     0,   393,   394,   395,   396,   397,     0,   398,   399,
-     400,   401,   402,   403,     0,     0,   404,   405,   406,   407,
-     408,     0,     0,     0,     0,     0,     0,   791,     0,     0,
-      91,     0,   409,   410,     0,     0,     0,    92,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   843,     0,
-       0,     0,     0,   409,   410,   392,     0,   393,   394,   395,
-     396,   397,   708,   398,   399,   400,   401,   402,   403,     0,
-     149,   404,   405,   406,   407,   408,     0,     0,     0,   150,
-     151,   709,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   152,   153,     0,
-       0,     0,   154,   155,   156,   157,     0,     0,     0,     0,
-       0,     0,     0,     0,   158,   159,   160,   161,   162,   163,
-     164,     0,   165,   166,   167,     0,     0,   168,   169,   170,
-       0,   171,   172,   173,   174,   175,     0,   176,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   453,     0,
-       0,     0,   454,   455,   456,   457,     0,     0,     0,     0,
-       0,     0,     0,     0,   458,   459,   460,   461,   462,   463,
-     464,     0,   465,   466,   467,   900,     0,   468,   469,   470,
-     409,   410,   471,   472,   473,   474,     0,   475,     0,   177,
-       0,     0,     0,     0,     0,     0,     0,     0,   149,     0,
-     178,   179,     0,     0,     0,     0,   180,   150,   151,     0,
-       0,     0,     0,     0,     0,     0,   181,   182,     0,     0,
-     183,   184,   185,   186,     0,   152,   153,    91,     0,     0,
-     154,   155,   156,   157,   187,   409,   410,   188,     0,     0,
-       0,     0,   158,   159,   160,   161,   162,   163,   164,     0,
-     165,   166,   167,     0,     0,   168,   169,   170,     0,   171,
-     172,   173,   174,   175,     0,   176,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   476,     0,     0,
+       0,     0,     0,     0,   784,   390,   391,   373,   374,   375,
+     376,   377,   378,     0,   379,   380,   381,   382,   383,   384,
+       0,   385,   386,   387,   388,   389,   373,   374,   375,   376,
+     377,   378,     0,   379,   380,   381,   382,   383,   384,     0,
+     385,   386,   387,   388,   389,   373,   374,   375,   376,   377,
+     378,     0,   379,   380,   381,   382,   383,   384,     0,   385,
+     386,   387,   388,   389,     0,     0,     0,     0,   785,   390,
+     391,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,   786,   390,   391,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,   787,   390,   391,   373,
+     374,   375,   376,   377,   378,     0,   379,   380,   381,   382,
+     383,   384,     0,   385,   386,   387,   388,   389,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,   788,   390,   391,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,   789,   390,   391,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,   790,   390,   391,   373,   374,   375,   376,
+     377,   378,     0,   379,   380,   381,   382,   383,   384,     0,
+     385,   386,   387,   388,   389,   373,   374,   375,   376,   377,
+     378,     0,   379,   380,   381,   382,   383,   384,     0,   385,
+     386,   387,   388,   389,   373,   374,   375,   376,   377,   378,
+       0,   379,   380,   381,   382,   383,   384,     0,   385,   386,
+     387,   388,   389,     0,     0,     0,     0,   791,   390,   391,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,   852,   390,   391,   373,
+     374,   375,   376,   377,   378,     0,   379,   380,   381,   382,
+     383,   384,     0,   385,   386,   387,   388,   389,   373,   374,
+     375,   376,   377,   378,     0,   379,   380,   381,   382,   383,
+     384,     0,   385,   386,   387,   388,   389,   373,   374,   375,
+     376,   377,   378,     0,   379,   380,   381,   382,   383,   384,
+       0,   385,   386,   387,   388,   389,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,   930,   390,   391,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,   933,   390,   391,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,   946,   390,   391,   373,   374,   375,   376,   377,
+     378,     0,   379,   380,   381,   382,   383,   384,     0,   385,
+     386,   387,   388,   389,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,   702,     0,   947,   390,   391,
+       0,     0,   132,     0,     0,     0,     0,     0,     0,     0,
+     133,   134,   703,     0,     0,     0,  1022,   390,   391,     0,
+       0,     0,     0,     0,   135,   136,     0,     0,     0,     0,
+     137,   138,   139,   140,   141,  1033,   390,   391,     0,     0,
+       0,     0,     0,     0,     0,   142,   143,   144,   145,   146,
+     147,   148,     0,   149,   150,   151,     0,     0,   152,   153,
+     154,     0,   155,   156,   157,   158,   159,   439,   160,     0,
+       0,     0,   440,   441,     0,   442,   443,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,   444,   445,   446,
+     447,   448,   449,   450,     0,   451,   452,   453,     0,     0,
+     454,   455,   456,     0,   814,   457,   458,   459,   460,     0,
+     461,   132,     0,     0,   390,   391,   161,     0,     0,   133,
+     134,     0,     0,   162,     0,     0,     0,     0,     0,   163,
+     164,     0,     0,   135,   136,   165,     0,     0,     0,   137,
+     138,   139,   140,   141,   166,   167,     0,   168,   169,     0,
+       0,   170,   171,   172,   142,   143,   144,   145,   146,   147,
+     148,     0,   149,   150,   151,     0,     0,   152,   153,   154,
+       0,   155,   156,   157,   158,   159,     0,   160,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,   462,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,   904,     0,     0,     0,     0,     0,     0,
+     132,     0,     0,     0,     0,   161,     0,     0,   133,   134,
+       0,     0,   162,     0,     0,     0,     0,     0,   163,   164,
+       0,     0,   135,   136,   165,     0,     0,     0,   137,   138,
+     139,   140,   141,   166,   167,     0,   168,   169,     0,     0,
+     170,   171,   172,   142,   143,   144,   145,   146,   147,   148,
+       0,   149,   150,   151,     0,     0,   152,   153,   154,     0,
+     155,   156,   157,   158,   159,     0,   160,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   177,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   178,   179,
-       0,     0,     0,     0,   180,   809,     0,     0,     0,     0,
-       0,     0,     0,   149,   181,   182,     0,     0,   183,   184,
-     185,   186,   150,   151,     0,    91,     0,     0,     0,     0,
-       0,     0,   187,     0,     0,   188,     0,     0,     0,     0,
-     152,   153,     0,   204,     0,   154,   155,   156,   157,     0,
-       0,     0,     0,     0,     0,     0,     0,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,   924,     0,     0,     0,     0,     0,     0,   132,
+       0,     0,     0,     0,   161,     0,     0,   133,   134,     0,
+       0,   162,     0,     0,     0,     0,     0,   163,   164,     0,
+       0,   135,   136,   165,     0,     0,     0,   137,   138,   139,
+     140,   141,   166,   167,     0,   168,   169,     0,     0,   170,
+     171,   172,   142,   143,   144,   145,   146,   147,   148,     0,
+     149,   150,   151,     0,     0,   152,   153,   154,     0,   155,
+     156,   157,   158,   159,     0,   160,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,   472,     0,     0,     0,     0,     0,   132,     0,
+       0,     0,     0,   161,     0,     0,   133,   134,   473,     0,
+     162,     0,     0,     0,     0,     0,   163,   164,     0,     0,
+     135,   136,   165,     0,     0,     0,   137,   138,   139,   140,
+     141,   166,   167,     0,   168,   169,     0,     0,   170,   171,
+     172,   142,   143,   144,   145,   146,   147,   148,     0,   149,
+     150,   151,     0,     0,   152,   153,   154,     0,   155,   156,
+     157,   158,   159,     0,   160,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,   632,     0,     0,     0,     0,     0,   132,     0,     0,
+       0,     0,   161,     0,     0,   133,   134,     0,   633,   162,
+       0,     0,     0,     0,     0,   163,   164,     0,     0,   135,
+     136,   165,     0,     0,     0,   137,   138,   139,   140,   141,
+     166,   167,     0,   168,   169,     0,     0,   170,   171,   172,
+     142,   143,   144,   145,   146,   147,   148,     0,   149,   150,
+     151,     0,     0,   152,   153,   154,     0,   155,   156,   157,
+     158,   159,     0,   160,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+     721,     0,     0,     0,     0,     0,   132,     0,     0,     0,
+       0,   161,     0,     0,   133,   134,   473,     0,   162,     0,
+       0,     0,     0,     0,   163,   164,     0,     0,   135,   136,
+     165,     0,     0,     0,   137,   138,   139,   140,   141,   166,
+     167,     0,   168,   169,     0,     0,   170,   171,   172,   142,
+     143,   144,   145,   146,   147,   148,     0,   149,   150,   151,
+       0,     0,   152,   153,   154,     0,   155,   156,   157,   158,
+     159,     0,   160,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   615,
+       0,     0,     0,     0,     0,   132,     0,     0,     0,     0,
+     161,     0,     0,   133,   134,     0,     0,   162,     0,     0,
+       0,     0,     0,   163,   164,     0,     0,   135,   136,   165,
+       0,     0,     0,   137,   138,   139,   140,   141,   166,   167,
+       0,   168,   169,     0,     0,   170,   171,   172,   142,   143,
+     144,   145,   146,   147,   148,     0,   149,   150,   151,     0,
+       0,   152,   153,   154,     0,   155,   156,   157,   158,   159,
+       0,   160,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   637,     0,
+       0,     0,     0,     0,   132,     0,     0,     0,     0,   161,
+       0,     0,   133,   134,     0,     0,   162,     0,     0,     0,
+       0,     0,   163,   164,     0,     0,   135,   136,   165,     0,
+       0,     0,   137,   138,   139,   140,   141,   166,   167,     0,
+     168,   169,     0,     0,   170,   171,   172,   142,   143,   144,
+     145,   146,   147,   148,     0,   149,   150,   151,     0,     0,
+     152,   153,   154,     0,   155,   156,   157,   158,   159,     0,
+     160,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,   639,     0,     0,
+       0,     0,     0,   132,     0,     0,     0,     0,   161,     0,
+       0,   133,   134,     0,     0,   162,     0,     0,     0,     0,
+       0,   163,   164,     0,     0,   135,   136,   165,     0,     0,
+       0,   137,   138,   139,   140,   141,   166,   167,     0,   168,
+     169,     0,     0,   170,   171,   172,   142,   143,   144,   145,
+     146,   147,   148,     0,   149,   150,   151,     0,     0,   152,
+     153,   154,     0,   155,   156,   157,   158,   159,     0,   160,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   177,   894,     0,     0,     0,     0,     0,     0,
-       0,   149,     0,   178,   179,     0,     0,     0,     0,   180,
-     150,   151,     0,     0,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,     0,   152,   153,
-      91,     0,     0,   154,   155,   156,   157,   187,     0,     0,
-     188,     0,     0,     0,     0,   158,   159,   160,   161,   162,
-     163,   164,     0,   165,   166,   167,     0,     0,   168,   169,
-     170,     0,   171,   172,   173,   174,   175,     0,   176,     0,
+       0,     0,   132,     0,     0,     0,     0,   161,     0,     0,
+     133,   134,     0,     0,   162,     0,     0,     0,     0,     0,
+     163,   164,     0,     0,   135,   136,   165,     0,     0,     0,
+     137,   138,   139,   140,   141,   166,   167,     0,   168,   169,
+       0,     0,   170,   171,   172,   142,   143,   144,   145,   146,
+     147,   148,     0,   149,   150,   151,     0,     0,   152,   153,
+     154,     0,   155,   156,   157,   158,   159,     0,   160,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,   161,     0,     0,     0,
+       0,     0,     0,   162,     0,     0,     0,     0,     0,   163,
+     164,     0,     0,     0,     0,   165,     0,     0,     0,     0,
+       0,     0,     0,     0,   166,   167,   132,   168,   169,     0,
+       0,   170,   171,   172,   133,   134,   660,   173,   661,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   135,   136,
+       0,     0,     0,     0,   137,   138,   139,   140,   141,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   142,
+     143,   144,   145,   146,   147,   148,     0,   149,   150,   151,
+       0,     0,   152,   153,   154,     0,   155,   156,   157,   158,
+     159,     0,   160,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-     177,     0,   531,     0,     0,     0,     0,     0,     0,   149,
-       0,   178,   179,     0,     0,     0,     0,   180,   150,   151,
-     532,     0,     0,     0,     0,     0,     0,   181,   182,     0,
-       0,   183,   184,   185,   186,     0,   152,   153,    91,     0,
-       0,   154,   155,   156,   157,   187,     0,     0,   188,     0,
-       0,     0,     0,   158,   159,   160,   161,   162,   163,   164,
-       0,   165,   166,   167,     0,     0,   168,   169,   170,     0,
-     171,   172,   173,   174,   175,     0,   176,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,   132,     0,     0,     0,     0,
+     161,     0,     0,   133,   134,   473,     0,   162,     0,     0,
+       0,     0,     0,   163,   164,     0,     0,   135,   136,   165,
+       0,     0,     0,   137,   138,   139,   140,   141,   166,   167,
+       0,   168,   169,     0,     0,   170,   171,   662,   142,   143,
+     144,   145,   146,   147,   148,     0,   149,   150,   151,     0,
+       0,   152,   153,   154,     0,   155,   156,   157,   158,   159,
+       0,   160,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,   132,     0,     0,     0,     0,   161,
+       0,     0,   133,   134,   548,     0,   162,     0,     0,     0,
+       0,     0,   163,   164,     0,     0,   135,   136,   165,     0,
+       0,     0,   137,   138,   139,   140,   141,   166,   167,     0,
+     168,   169,     0,     0,   526,   171,   172,   142,   143,   144,
+     145,   146,   147,   148,     0,   149,   150,   151,     0,     0,
+     152,   153,   154,     0,   155,   156,   157,   158,   159,     0,
+     160,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,   132,     0,     0,     0,     0,   161,     0,
+       0,   133,   134,   473,     0,   162,     0,     0,     0,     0,
+       0,   163,   164,     0,     0,   135,   136,   165,     0,     0,
+       0,   137,   138,   139,   140,   141,   166,   167,     0,   168,
+     169,     0,     0,   170,   171,   172,   142,   143,   144,   145,
+     146,   147,   148,     0,   149,   150,   151,     0,     0,   152,
+     153,   154,     0,   155,   156,   157,   158,   159,     0,   160,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   177,     0,
-     650,     0,     0,     0,     0,     0,     0,   149,     0,   178,
-     179,     0,     0,     0,     0,   180,   150,   151,     0,   651,
-       0,     0,     0,     0,     0,   181,   182,     0,     0,   183,
-     184,   185,   186,     0,   152,   153,    91,     0,     0,   154,
-     155,   156,   157,   187,     0,     0,   188,     0,     0,     0,
-       0,   158,   159,   160,   161,   162,   163,   164,     0,   165,
-     166,   167,     0,     0,   168,   169,   170,     0,   171,   172,
-     173,   174,   175,     0,   176,     0,     0,     0,     0,     0,
+       0,     0,   132,     0,     0,     0,     0,   161,     0,     0,
+     133,   134,   726,     0,   162,     0,     0,     0,     0,     0,
+     163,   164,     0,     0,   135,   136,   165,     0,     0,     0,
+     137,   138,   139,   140,   141,   166,   167,     0,   168,   169,
+       0,     0,   170,   171,   172,   142,   143,   144,   145,   146,
+     147,   148,     0,   149,   150,   151,     0,     0,   152,   153,
+     154,     0,   155,   156,   157,   158,   159,     0,   160,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   177,     0,   728,     0,
-       0,     0,     0,     0,     0,   149,     0,   178,   179,     0,
-       0,     0,     0,   180,   150,   151,   532,     0,     0,     0,
-       0,     0,     0,   181,   182,     0,     0,   183,   184,   185,
-     186,     0,   152,   153,    91,     0,     0,   154,   155,   156,
-     157,   187,     0,     0,   188,     0,     0,     0,     0,   158,
-     159,   160,   161,   162,   163,   164,     0,   165,   166,   167,
-       0,     0,   168,   169,   170,     0,   171,   172,   173,   174,
-     175,     0,   176,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,   161,     0,     0,     0,
+       0,     0,     0,   162,     0,     0,     0,     0,     0,   163,
+     164,     0,   132,     0,     0,   165,     0,     0,     0,     0,
+     133,   134,     0,     0,   166,   167,     0,   168,   169,     0,
+       0,   170,   171,   172,   135,   136,     9,     0,     0,     0,
+     137,   138,   139,   140,   141,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,   142,   143,   144,   145,   146,
+     147,   148,     0,   149,   150,   151,     0,     0,   152,   153,
+     154,     0,   155,   156,   157,   158,   159,     0,   160,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,   177,     0,   633,     0,     0,     0,
-       0,     0,     0,   149,     0,   178,   179,     0,     0,     0,
-       0,   180,   150,   151,     0,     0,     0,     0,     0,     0,
-       0,   181,   182,     0,     0,   183,   184,   185,   186,     0,
-     152,   153,    91,     0,     0,   154,   155,   156,   157,   187,
-       0,     0,   188,     0,     0,     0,     0,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,   132,     0,     0,     0,     0,   161,     0,     0,   133,
+     134,   703,     0,   162,     0,     0,     0,     0,     0,   163,
+     164,     0,     0,   135,   136,   165,     0,     0,     0,   137,
+     138,   139,   140,   141,   166,   167,     0,   168,   169,     0,
+       0,   170,   171,   172,   142,   143,   144,   145,   146,   147,
+     148,     0,   149,   150,   151,     0,     0,   152,   153,   154,
+       0,   155,   156,   157,   158,   159,     0,   160,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   177,     0,   655,     0,     0,     0,     0,     0,
-       0,   149,     0,   178,   179,     0,     0,     0,     0,   180,
-     150,   151,     0,     0,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,     0,   152,   153,
-      91,     0,     0,   154,   155,   156,   157,   187,     0,     0,
-     188,     0,     0,     0,     0,   158,   159,   160,   161,   162,
-     163,   164,     0,   165,   166,   167,     0,     0,   168,   169,
-     170,     0,   171,   172,   173,   174,   175,     0,   176,     0,
+     132,     0,     0,     0,     0,   161,     0,     0,   133,   134,
+    1011,     0,   162,     0,     0,     0,     0,     0,   163,   164,
+       0,     0,   135,   136,   165,     0,     0,     0,   137,   138,
+     139,   140,   141,   166,   167,     0,   168,   169,     0,     0,
+     170,   171,   172,   142,   143,   144,   145,   146,   147,   148,
+       0,   149,   150,   151,     0,     0,   152,   153,   154,     0,
+     155,   156,   157,   158,   159,     0,   160,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   132,
+       0,     0,     0,     0,   161,     0,     0,   133,   134,     0,
+       0,   162,     0,     0,     0,     0,     0,   163,   164,     0,
+       0,   135,   136,   165,     0,     0,     0,   137,   138,   139,
+     140,   141,   166,   167,     0,   168,   169,     0,     0,   170,
+     171,   172,   142,   143,   144,   145,   146,   147,   148,     0,
+     149,   150,   151,     0,     0,   152,   153,   154,     0,   155,
+     156,   157,   158,   159,     0,   160,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   132,     0,
+       0,     0,     0,   161,     0,     0,   133,   134,     0,     0,
+     162,     0,     0,     0,     0,     0,   163,   164,     0,     0,
+     135,   136,   165,     0,     0,     0,   137,   138,   139,   140,
+     141,   166,   167,     0,   168,   169,     0,     0,   170,   171,
+     172,   142,   143,   144,   145,   146,   147,   148,     0,   149,
+     150,   151,     0,     0,   152,   153,   154,     0,   155,   156,
+     157,   158,   159,     0,   160,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,   132,     0,     0,
+       0,     0,   161,     0,     0,   133,   134,     0,     0,   162,
+       0,     0,     0,     0,     0,   163,   164,     0,     0,   135,
+     136,   165,     0,     0,     0,   137,   138,   139,   140,   141,
+     166,   167,     0,   168,   169,     0,     0,   170,   171,   363,
+     142,   143,   144,   145,   146,   147,   148,     0,   149,   150,
+     151,     0,     0,   152,   153,   154,     0,   155,   156,   157,
+     158,   159,     0,   160,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,   132,     0,     0,     0,
+       0,   161,     0,     0,   133,   134,     0,     0,   162,     0,
+       0,     0,     0,     0,   163,   164,     0,     0,   135,   136,
+     165,     0,     0,     0,   137,   138,   139,   140,   141,   166,
+     167,     0,   168,   169,     0,     0,   170,   431,   172,   142,
+     143,   144,   145,   146,   147,   148,     0,   149,   150,   151,
+       0,     0,   152,   153,   154,     0,   155,   156,   157,   158,
+     159,     0,   160,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,   132,     0,     0,     0,     0,
+     161,     0,     0,   133,   134,     0,     0,   162,     0,     0,
+       0,     0,     0,   163,   164,     0,     0,   135,   136,   165,
+       0,     0,     0,   137,   138,   139,   140,   141,   166,   167,
+       0,   168,   169,     0,     0,   170,   529,   530,   142,   143,
+     144,   145,   146,   147,   148,     0,   149,   150,   151,     0,
+       0,   152,   153,   154,     0,   155,   156,   157,   158,   159,
+       0,   160,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,   132,     0,     0,     0,     0,   161,
+       0,     0,   133,   134,     0,     0,   162,     0,     0,     0,
+       0,     0,   163,   164,     0,     0,   135,   136,   165,     0,
+       0,     0,   137,   138,   139,   140,   141,   166,   167,     0,
+     168,   169,     0,     0,   918,   171,   363,   142,   143,   144,
+     145,   146,   147,   148,     0,   149,   150,   151,     0,     0,
+     152,   153,   154,     0,   155,   156,   157,   158,   159,     0,
+     160,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   161,     0,
+       0,     0,     0,     0,     0,   162,     0,     0,     0,     0,
+       0,   163,   164,     0,     0,     0,     0,   165,     0,     0,
+       0,     0,     0,     0,     0,     0,   166,   167,     0,   168,
+     169,     0,     0,   170,   171,   955,   311,   312,   422,     0,
+     423,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+     135,   136,     0,     0,     0,     0,   137,   138,   139,   140,
+     141,     0,     0,   314,   315,   316,   317,   318,     0,   319,
+     320,   142,   143,   144,   145,   146,   147,   148,     0,   149,
+     150,   151,     0,     0,   152,   153,   154,     0,   155,   156,
+     157,   158,   159,     0,   160,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,   162,
+       0,     0,     0,     0,     0,   163,   164,     0,     0,     0,
+       0,   165,     0,     0,     0,     0,   311,   312,   313,     0,
+     166,   167,     0,   168,   169,     0,     0,   321,   171,   424,
+     135,   136,     0,     0,     0,     0,   137,   138,   139,   140,
+     141,     0,     0,   314,   315,   316,   317,   318,     0,   319,
+     320,   142,   143,   144,   145,   146,   147,   148,     0,   149,
+     150,   151,   311,   312,   152,   153,   154,     0,   155,   156,
+     157,   158,   159,     0,   160,     0,   135,   136,     0,     0,
+       0,     0,   137,   138,   139,   140,   141,     0,     0,   314,
+     315,   316,   317,   318,     0,   319,   320,   142,   143,   144,
+     145,   146,   147,   148,     0,   149,   150,   151,     0,     0,
+     152,   153,   154,     0,   155,   156,   157,   158,   159,     0,
+     160,     0,     0,     0,     0,     0,     0,     0,     0,   162,
+       0,     0,     0,     0,     0,   163,   164,     0,     0,     0,
+       0,   165,     0,     0,     0,     0,     0,     0,     0,     0,
+     166,   167,     0,   168,   169,     0,     0,   321,   171,   322,
+       0,     0,     0,     0,     0,     0,     5,     0,     0,     6,
+       0,     7,     0,     8,     0,   162,     9,     0,     0,     0,
+       0,   163,   164,     0,     0,     0,    10,   165,     0,     0,
+       0,     0,     0,     0,     0,     0,   166,   167,     0,   168,
+     169,     0,    11,   321,   171,   424,    12,    13,     0,     0,
+       0,    14,     0,     0,     0,     0,     0,    15,     0,    16,
+      17,     0,    18,     0,     0,     0,     0,    19,    20,    21,
+      22,    23,     0,    24,    25,     0,     0,    26,    27,    28,
+      29,    30,    31,    32,    33,    34,    35,    36,     0,    37,
+       0,    38,    39,     0,     0,    40,    41,    42,     0,    43,
+       0,    44,     0,     0,    45,    46,     0,     0,    47,    48,
+      49,     0,     0,     0,     0,     0,     0,     0,    50,     0,
+       0,     0,    52,    53,    54,    55,    56,    57,    58,    59,
+      60,    61,    62,    63,     0,     0,    64,     0,     0,    65,
+      66,    67,    68,     5,     0,     0,     6,   487,     7,     0,
+       8,     0,     0,     9,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,    10,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,    11,
+       0,     0,     0,    12,    13,     0,     0,     0,    14,     0,
+       0,     0,     0,     0,    15,     0,    16,    17,     0,    18,
+       0,     0,     0,     0,    19,    20,    21,    22,    23,     0,
+      24,    25,     0,     0,    26,    27,    28,    29,    30,    31,
+      32,    33,    34,    35,    36,     0,    37,     0,    38,    39,
+       0,     0,    40,    41,    42,     0,    43,     0,    44,     0,
+       0,    45,    46,     0,     0,    47,    48,    49,     0,     0,
+       0,     0,     0,     0,     0,    50,     0,     0,     0,    52,
+      53,    54,    55,    56,    57,    58,    59,    60,    61,    62,
+      63,     8,     0,    64,     9,     0,    65,    66,    67,    68,
+       0,     0,     0,     0,    10,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-     177,     0,   657,     0,     0,     0,     0,     0,     0,   149,
-       0,   178,   179,     0,     0,     0,     0,   180,   150,   151,
-       0,     0,     0,     0,     0,     0,     0,   181,   182,     0,
-       0,   183,   184,   185,   186,     0,   152,   153,    91,     0,
-       0,   154,   155,   156,   157,   187,     0,     0,   188,     0,
-       0,     0,     0,   158,   159,   160,   161,   162,   163,   164,
-       0,   165,   166,   167,     0,     0,   168,   169,   170,     0,
-     171,   172,   173,   174,   175,     0,   176,     0,     0,     0,
+      11,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,    15,     0,     0,     0,     0,
+      18,     0,   746,     0,     0,    19,    20,    21,    22,    23,
+       0,     0,    25,     0,     0,    26,    27,    28,    29,    30,
+      31,    32,    33,    34,    35,     0,     0,     8,     0,     0,
+       9,     0,     0,     0,    41,     0,     0,     0,     0,    44,
+      10,     0,     0,     0,     0,     0,    47,     0,    49,     0,
+       0,     0,     0,     0,     0,     0,    11,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,    59,    60,    61,
+      62,    15,     0,     0,     0,     0,    18,     0,     0,    67,
+      68,    19,    20,    21,    22,    23,     0,     0,    25,     0,
+       0,    26,    27,    28,    29,    30,    31,    32,    33,    34,
+      35,     0,     0,     0,     0,     0,   825,     0,     0,     0,
+      41,     0,     0,     0,     0,    44,     0,     0,     0,     0,
+       0,     0,    47,     0,    49,     0,     0,     0,     0,     0,
+       0,     0,    11,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,    59,    60,    61,    62,    15,     0,     0,
+       0,     0,    18,   826,     0,    67,    68,    19,    20,   827,
+       0,    23,     0,     0,    25,     0,     0,    26,    27,    28,
+      29,    30,    31,    32,    33,    34,    35,     0,     0,     0,
+       0,     0,   825,     0,     0,     0,    41,     0,     0,     0,
+       0,    44,     0,     0,     0,     0,     0,     0,    47,     0,
+      49,     0,     0,     0,     0,     0,     0,     0,    11,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,    59,
+      60,    61,    62,    15,     0,     0,     0,     0,    18,     0,
+       0,   170,    68,    19,    20,   827,     0,    23,     0,     0,
+      25,     0,     0,    26,    27,    28,    29,    30,    31,    32,
+      33,    34,    35,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,    41,     0,     0,     0,     0,    44,     0,     0,
+       0,     0,     0,     0,    47,     0,    49,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   177,     0,
-       0,     0,     0,     0,     0,     0,     0,   149,     0,   178,
-     179,     0,     0,     0,     0,   180,   150,   151,   746,     0,
-     747,     0,     0,     0,     0,   181,   182,     0,     0,   183,
-     184,   185,   186,     0,   152,   153,    91,     0,     0,   154,
-     155,   156,   157,   187,     0,     0,   188,     0,     0,     0,
-       0,   158,   159,   160,   161,   162,   163,   164,     0,   165,
-     166,   167,     0,     0,   168,   169,   170,     0,   171,   172,
-     173,   174,   175,     0,   176,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   177,     0,     0,     0,
-       0,     0,     0,     0,     0,   149,     0,   178,   179,     0,
-       0,     0,     0,   180,   150,   151,   532,     0,     0,     0,
-       0,     0,     0,   181,   182,     0,     0,   183,   184,   185,
-     186,     0,   152,   153,    91,     0,     0,   154,   155,   156,
-     157,   187,     0,     0,   748,     0,     0,     0,     0,   158,
-     159,   160,   161,   162,   163,   164,     0,   165,   166,   167,
-       0,     0,   168,   169,   170,     0,   171,   172,   173,   174,
-     175,     0,   176,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,   177,     0,     0,     0,     0,     0,
-       0,     0,     0,   149,     0,   178,   179,     0,     0,     0,
-       0,   180,   150,   151,   557,     0,     0,     0,     0,     0,
-       0,   181,   182,     0,     0,   183,   184,   185,   186,     0,
-     152,   153,   538,     0,     0,   154,   155,   156,   157,   187,
-       0,     0,   188,     0,     0,     0,     0,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   177,     0,     0,     0,     0,     0,     0,     0,
-       0,   149,     0,   178,   179,     0,     0,     0,     0,   180,
-     150,   151,   532,     0,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,     0,   152,   153,
-      91,     0,     0,   154,   155,   156,   157,   187,     0,     0,
-     188,     0,     0,     0,     0,   158,   159,   160,   161,   162,
-     163,   164,     0,   165,   166,   167,     0,     0,   168,   169,
-     170,     0,   171,   172,   173,   174,   175,     0,   176,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-     177,     0,     0,     0,     0,     0,     0,     0,     0,   149,
-       0,   178,   179,     0,     0,     0,     0,   180,   150,   151,
-     733,     0,     0,     0,     0,     0,     0,   181,   182,     0,
-       0,   183,   184,   185,   186,     0,   152,   153,    91,     0,
-       0,   154,   155,   156,   157,   187,     0,     0,   188,     0,
-       0,     0,     0,   158,   159,   160,   161,   162,   163,   164,
-       0,   165,   166,   167,     0,     0,   168,   169,   170,     0,
-     171,   172,   173,   174,   175,     0,   176,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   177,     0,
-       0,     0,     0,     0,     0,     0,     0,   149,     0,   178,
-     179,     0,     0,     0,     0,   180,   150,   151,   709,     0,
-       0,     0,     0,     0,     0,   181,   182,     0,     0,   183,
-     184,   185,   186,     0,   152,   153,    91,     0,     0,   154,
-     155,   156,   157,   187,     0,     0,   188,     0,     0,     0,
-       0,   158,   159,   160,   161,   162,   163,   164,     0,   165,
-     166,   167,     0,     0,   168,   169,   170,     0,   171,   172,
-     173,   174,   175,     0,   176,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   177,     0,     0,     0,
-       0,     0,     0,     0,     0,   149,     0,   178,   179,     0,
-       0,     0,     0,   180,   150,   151,   954,     0,     0,     0,
-       0,     0,     0,   181,   182,     0,     0,   183,   184,   185,
-     186,     0,   152,   153,    91,     0,     0,   154,   155,   156,
-     157,   187,     0,     0,   188,     0,     0,     0,     0,   158,
-     159,   160,   161,   162,   163,   164,     0,   165,   166,   167,
-       0,     0,   168,   169,   170,     0,   171,   172,   173,   174,
-     175,     0,   176,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,   177,     0,     0,     0,     0,     0,
-       0,     0,     0,   149,     0,   178,   179,     0,     0,     0,
-       0,   180,   150,   151,     0,     0,     0,     0,     0,     0,
-       0,   181,   182,     0,     0,   183,   184,   185,   186,     0,
-     152,   153,    91,     0,     0,   154,   155,   156,   157,   187,
-       0,     0,   188,     0,     0,     0,     0,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   177,     0,     0,     0,     0,     0,     0,     0,
-       0,   149,     0,   178,   179,     0,     0,     0,     0,   180,
-     150,   151,     0,     0,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,     0,   152,   153,
-      91,     0,     0,   154,   155,   156,   157,   187,     0,     0,
-     188,     0,     0,     0,     0,   158,   159,   160,   161,   162,
-     163,   164,     0,   165,   166,   167,     0,     0,   168,   169,
-     170,     0,   171,   172,   173,   174,   175,     0,   176,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-     177,     0,     0,     0,     0,     0,     0,     0,     0,   149,
-       0,   178,   179,     0,     0,     0,     0,   180,   150,   151,
-       0,     0,     0,     0,     0,     0,     0,   181,   182,     0,
-       0,   183,   184,   185,   186,     0,   152,   153,    91,     0,
-       0,   154,   155,   156,   157,   187,     0,     0,   381,     0,
-       0,     0,     0,   158,   159,   160,   161,   162,   163,   164,
-       0,   165,   166,   167,     0,     0,   168,   169,   170,     0,
-     171,   172,   173,   174,   175,     0,   176,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   177,     0,
-       0,     0,     0,     0,     0,     0,     0,   149,     0,   178,
-     179,     0,     0,     0,     0,   180,   150,   151,     0,     0,
-       0,     0,     0,     0,     0,   181,   182,     0,     0,   183,
-     184,   185,   186,     0,   152,   153,    91,     0,     0,   154,
-     155,   156,   157,   444,     0,     0,   188,     0,     0,     0,
-       0,   158,   159,   160,   161,   162,   163,   164,     0,   165,
-     166,   167,     0,     0,   168,   169,   170,     0,   171,   172,
-     173,   174,   175,     0,   176,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,   177,     0,     0,     0,
-       0,     0,     0,     0,     0,   149,     0,   178,   179,     0,
-       0,     0,     0,   180,   150,   151,     0,     0,     0,     0,
-       0,     0,     0,   181,   182,     0,     0,   183,   184,   185,
-     186,     0,   152,   153,    91,     0,     0,   154,   155,   156,
-     157,   187,     0,     0,   541,     0,     0,     0,     0,   158,
-     159,   160,   161,   162,   163,   164,     0,   165,   166,   167,
-       0,     0,   168,   169,   170,     0,   171,   172,   173,   174,
-     175,     0,   176,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,   177,     0,     0,     0,     0,     0,
-       0,     0,     0,   149,     0,   178,   179,     0,     0,     0,
-       0,   180,   150,   151,     0,     0,     0,     0,     0,     0,
-       0,   181,   182,     0,     0,   183,   184,   185,   186,     0,
-     152,   153,   888,     0,     0,   154,   155,   156,   157,   187,
-       0,     0,   381,     0,     0,     0,     0,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,   329,   330,   562,     0,   563,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,   152,
-     153,     0,     0,     0,   154,   155,   156,   157,     0,     0,
-     332,   333,   334,     0,     0,   335,   158,   159,   160,   161,
-     162,   163,   164,     0,   165,   166,   167,     0,     0,   168,
-     169,   170,   177,   171,   172,   173,   174,   175,     0,   176,
-       0,     0,     0,   178,   179,     0,     0,     0,     0,   180,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,     0,     0,     0,
-      91,     0,     0,     0,     0,     0,     0,   187,     0,     0,
-     917,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   178,   179,     0,     0,     0,     0,   180,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   181,   182,
-       0,     0,   183,   184,   185,   186,   329,   330,   331,   336,
-       0,     0,     0,     0,     0,     0,   187,     0,     0,   564,
-       0,     0,     0,     0,   152,   153,     0,     0,     0,   154,
-     155,   156,   157,     0,     0,   332,   333,   334,     0,     0,
-     335,   158,   159,   160,   161,   162,   163,   164,     0,   165,
-     166,   167,   329,   330,   168,   169,   170,     0,   171,   172,
-     173,   174,   175,     0,   176,     0,     0,     0,     0,     0,
-     152,   153,     0,     0,     0,   154,   155,   156,   157,     0,
-       0,   332,   333,   334,     0,     0,   335,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,   178,   179,     0,
-       0,     0,     0,   180,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,   181,   182,     0,     0,   183,   184,   185,
-     186,     0,     0,     0,   336,     0,     0,     0,     0,     0,
-       0,   187,     0,    19,   337,     0,    20,   -28,    21,   -28,
-       0,     0,    22,   178,   179,    23,    24,    25,     0,   180,
-       0,     0,    26,    27,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,    28,     0,     0,
-     336,    29,    30,     0,     0,     0,    31,   187,     0,     0,
-     564,     0,    32,     0,    33,    34,     0,    35,     0,    36,
-      37,    38,    39,    40,     0,    41,    42,    43,    44,    45,
-      46,    47,    48,    49,    50,    51,    52,    53,    54,    55,
-      56,     0,     0,    57,    58,    59,     0,    60,    61,    62,
-       0,    63,    64,    65,     0,     0,    66,     0,    67,     0,
-       0,    68,    69,    70,    71,     0,     0,    72,    73,    74,
-       0,     0,     0,     0,     0,    75,     0,     0,     0,    76,
-      77,    78,    79,    80,    81,    82,     0,    83,    84,    85,
-      86,    87,     0,     0,    88,     0,     0,     0,     0,   152,
-     153,    89,    90,    91,   154,   155,   156,   157,     0,     0,
-      92,     0,     0,     0,     0,     0,   158,   159,   160,   161,
-     162,   163,   164,     0,   165,   166,   167,     0,     0,   168,
-     169,   170,     0,   171,   172,   173,   174,   175,     0,   176,
-     152,   153,     0,     0,     0,   154,   155,   156,   157,     0,
-       0,     0,     0,     0,     0,     0,     0,   158,   159,   160,
-     161,   162,   163,   164,     0,   165,   166,   167,     0,     0,
-     168,   169,   170,     0,   171,   172,   173,   174,   175,     0,
-     176,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,   178,   179,     0,     0,     0,     0,   180,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,   181,   182,
-       0,     0,   183,   184,   185,   186,     0,     0,     0,    91,
-       0,     0,     0,     0,     0,     0,   187,     0,     0,   576,
-       0,     0,     0,   178,   179,     0,     0,     0,     0,   180,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,   181,
-     182,     0,     0,   183,   184,   185,   186,     0,     0,     0,
-     888,     0,     0,     0,     0,     0,     0,   187,     0,     0,
-     576
+       0,     0,     0,     0,     0,    59,    60,    61,    62,     0,
+       0,     0,     0,     0,     0,     0,     0,   170,    68
 };
+
+#define yypact_value_is_default(Yystate) \
+  (!!((Yystate) == (-845)))
+
+#define yytable_value_is_error(Yytable_value) \
+  (!!((Yytable_value) == (-542)))
 
 static const yytype_int16 yycheck[] =
 {
-      26,   177,    28,   200,   140,    35,    32,   297,    13,    35,
-     274,   177,   188,   289,   278,    41,   414,   716,    46,   499,
-     105,   327,   107,   231,    18,   579,   111,   231,   582,     5,
-       3,   337,   236,   449,   236,    34,     3,   140,     4,     3,
-     346,   177,    70,    71,     4,    24,     3,     4,     3,    23,
-      78,     3,    23,     3,    31,   381,    61,   123,   234,   489,
-      59,    60,   494,   729,    33,     3,    35,   499,   103,     5,
-     140,    21,    22,    23,     3,     3,   125,   112,     3,   177,
-     577,   344,   579,   793,   794,   582,   759,     3,     3,     3,
-      23,     3,     3,     3,     3,     4,   124,   527,   126,   127,
-       3,     3,     3,    23,   130,   169,   169,   137,     3,     3,
-       3,   137,     3,     3,     3,   179,    23,    20,   169,   169,
-     169,    24,   148,   149,   187,   158,    35,    97,   231,    99,
-     169,   157,   179,   236,    21,    22,    23,   187,   143,    20,
-      21,    22,    23,    24,    25,   171,   179,     3,    23,   217,
-     126,   177,     3,    25,   169,   179,    23,    24,    25,    20,
-     123,   176,   188,    24,   863,   189,   192,     5,    24,    20,
-     238,   347,   882,    24,   137,    20,    20,   203,   179,    24,
-      24,   347,   286,   176,   210,    20,   179,   272,   189,    24,
-     126,   327,   169,   219,   260,   169,    80,    81,   224,   865,
-     179,   337,   207,     4,   308,   381,   342,   180,   234,   882,
-     346,   347,   156,   189,   158,   381,   180,   188,   244,   127,
-     187,   187,   921,   180,   327,   180,   231,   187,   180,   234,
-     315,   236,   237,   179,   337,   169,   169,   242,   188,   342,
-     275,   531,   180,   346,    27,   381,   281,   180,   538,   179,
-     285,   180,   180,   258,   158,   180,   255,   327,   564,   179,
-     757,   758,   169,   760,   180,   180,   180,   337,   180,   180,
-     180,   297,   342,   180,   279,   301,   346,   303,   180,   180,
-     586,   587,   588,   589,   590,   180,   180,   180,   126,   180,
-     180,   180,   318,   319,   179,   265,   179,   323,   169,   180,
-     626,   188,   628,   629,   179,   568,   332,   333,   334,   335,
-     413,   316,   575,   185,   186,   320,   179,   311,   185,   186,
-     179,   347,   327,   427,   169,   169,   261,   262,   591,   883,
-     179,   180,   337,   359,   169,    21,    22,   363,   364,   365,
-     366,   367,   368,   369,   370,   371,   372,   373,   374,   179,
-     576,   767,   768,   169,   179,   381,   169,   837,   584,   294,
-     176,     3,     4,   179,   844,   541,   392,   393,   394,   395,
-     396,   397,   398,   399,   400,   401,   402,   403,   404,   405,
-     406,   407,   408,   409,   410,   593,   883,     3,   414,   593,
-     594,   176,   594,     3,   179,    23,   422,   423,     3,   838,
-     839,   840,   841,   507,   508,   837,   838,   839,   840,   841,
-     808,   515,   844,   357,   358,    20,   501,   140,   141,    24,
-       4,   506,   169,   176,   509,   138,   139,   140,   564,    23,
-      24,    25,   376,   377,   378,   379,   380,     3,   728,   936,
-     576,   717,   546,   707,   750,   389,   179,   169,   584,   179,
-     586,   587,   588,   589,   590,   179,   632,   485,   179,   179,
-     626,   564,   628,   629,   179,   491,   792,   793,   794,   495,
-     179,   179,   676,   576,   676,   179,   502,   681,   179,   681,
-     179,   584,   745,   586,   587,   588,   589,   590,   179,   179,
-     593,   594,   179,   189,   564,   179,   179,   179,   179,   762,
-     763,   764,   765,   766,   179,   531,   576,   179,   179,   179,
-     179,   537,   538,   179,   584,   541,   586,   587,   588,   589,
-     590,   179,   179,   169,     5,   169,     7,     8,     9,    10,
-      11,     3,    13,    14,    15,    16,    17,    18,     4,   565,
-      21,    22,    23,    24,    25,   169,   169,     3,   574,     3,
-      20,    21,    22,    23,    24,    25,    20,    21,    22,    23,
-      24,    25,     5,   169,     3,   595,   169,   179,   169,   595,
-     596,   169,   748,   676,     3,     3,   169,   867,   681,     4,
-      11,   180,    13,    14,    15,    16,    17,    18,   593,   594,
-      21,    22,    23,    24,    25,    21,    22,    23,    24,    25,
-     626,   176,   628,   629,     3,   176,   632,   633,    20,    21,
-      22,    23,    24,    25,   750,     5,   792,   814,   881,     3,
-     179,   725,   179,   759,   650,   651,   792,   793,   794,   655,
-     700,   657,   132,     3,     3,   661,     3,   741,    20,    21,
-      22,    23,    24,    25,     3,   749,   189,   750,   674,   675,
-       3,   180,   180,     3,     3,   179,   759,   169,    24,   179,
-     169,   687,   667,   689,   169,   179,   169,   180,     3,   180,
-     878,   676,     5,   180,   176,     3,   681,     3,   683,    25,
-     750,     3,   708,    13,    14,    15,    16,    17,    18,   759,
-       3,    21,    22,    23,    24,    25,     3,   180,   179,     4,
-     180,   169,   728,    84,   185,   186,   180,   180,   189,   714,
-     180,    30,   816,    24,   740,    24,   180,   179,   744,     9,
-      10,    11,   748,    13,    14,    15,    16,    17,    18,    24,
-      23,    21,    22,    23,    24,    25,     4,   169,   180,   169,
-     180,   917,     4,   126,     3,   750,   882,    20,     3,     5,
-     169,   169,     5,   180,   185,   186,   179,     3,   862,   180,
-     180,    24,    29,   180,   180,   180,   792,   793,   794,   873,
-     180,   180,   180,     3,   188,   126,   180,   180,   169,   882,
-     169,   258,   808,   809,    10,     3,    14,     5,   906,     7,
-       8,     9,    10,    11,   904,    13,    14,    15,    16,    17,
-      18,   428,   528,    21,    22,    23,    24,    25,   685,   689,
-     498,   511,   882,    80,    81,    82,   268,   493,   537,   304,
-     416,   721,   848,   848,   850,    76,   852,    13,    14,    15,
-      16,    17,    18,   850,   675,    21,    22,    23,    24,    25,
-     897,   867,   109,   748,   111,   112,   113,   955,   871,   116,
-     117,   143,   119,   120,   959,   185,   186,   555,   142,   143,
-     140,   347,   744,   381,   750,   557,   593,    -1,   894,   594,
-     896,   897,    -1,   878,   158,   159,    -1,    -1,   162,   163,
+      11,   295,     1,   185,    15,   101,   219,    18,   104,   240,
+     394,   577,   108,   395,   277,   111,    54,   161,   482,   477,
+     205,   536,   536,   653,   482,     5,   264,   124,   172,    79,
+     268,    81,    82,   161,     3,     3,    86,     3,   274,   710,
+      39,     3,   564,   565,     1,     3,   124,    17,   719,    75,
+      76,     3,    51,    80,   124,   291,   563,   564,   565,     3,
+      87,    19,    20,    21,     3,    31,   722,    37,    38,   768,
+     214,     3,     3,   217,   214,   113,   363,   115,   116,   329,
+      24,    21,     3,   161,   747,   124,   214,    21,     5,     6,
+       7,     8,     9,    10,    51,    12,    13,    14,    15,    16,
+      17,   127,    19,    20,    21,    22,    23,    27,     3,     3,
+      22,   122,     3,     3,     3,   212,   213,   904,     3,   130,
+     131,   132,   219,    21,     3,   112,     3,    45,     3,    44,
+     141,   153,   976,     3,    24,   213,   214,    18,     3,     3,
+     121,    22,   122,   213,   155,   101,    24,   131,   245,    24,
+     161,   198,     3,     3,     3,     3,     3,     3,     3,    24,
+       3,   172,    19,    20,    21,   131,   177,   131,   404,    91,
+      88,    89,   119,   891,   221,   162,  1020,    18,   428,   160,
+     191,    22,   166,   130,    21,    21,    22,    23,   168,   188,
+     201,   202,   107,   115,   160,   140,   246,   142,   166,   168,
+     987,   163,   166,   214,   160,   160,   217,   206,    23,   167,
+     881,   163,   157,   931,   213,   914,   227,   161,   217,   363,
+     160,   220,   166,   363,   163,   322,   225,   253,   884,   240,
+     327,   163,   163,   167,   331,   363,     5,   900,   265,    24,
+     160,   472,   163,   270,   322,   162,   273,   164,   165,   327,
+     162,   168,   322,   331,   131,   254,   162,   327,   765,   766,
+     767,   331,   140,    21,   162,   501,   502,   237,   163,   163,
+     269,   161,   163,   509,   163,   286,   166,   288,   163,   160,
+      21,     3,    24,   322,   163,   363,   161,   523,   166,   300,
+     301,   166,   331,   163,   305,   526,   161,   254,   534,   163,
+     485,   166,    44,   314,   315,   316,   317,   318,   319,   320,
+     167,   561,   163,   163,   163,   163,   163,   163,   163,   160,
+     163,   608,   609,   322,   611,   162,   576,   424,   164,   165,
+     341,   796,   797,   798,   345,   346,   347,   348,   349,   350,
+     351,   352,   353,   354,   355,   356,   424,    18,   162,   164,
+     165,    22,   363,   122,   424,    18,    19,    20,    21,    22,
+      23,   162,   373,   374,   375,   376,   377,   378,   379,   380,
+     381,   382,   383,   384,   385,   386,   387,   388,   389,   390,
+     391,   166,   846,    18,   395,   424,   530,     3,   846,   847,
+     848,   849,   850,   915,   339,   340,   490,   160,   140,   162,
+     162,     3,   160,  1033,   126,   163,    22,   133,   915,   659,
+     133,   255,   256,   358,   425,   360,   361,   362,   162,   160,
+      94,    95,   163,   153,   166,   370,   520,   663,   133,    31,
+     162,   813,   162,   471,   160,   161,   562,   160,   282,     3,
+     160,    78,    79,   569,   657,   495,   166,   543,   711,   914,
+     500,   160,   836,   503,    18,   160,   669,   166,    22,   160,
+      18,   472,   756,   701,    22,   562,  1032,   478,   162,    29,
+     614,    31,   569,   162,   571,   572,   573,   574,   575,   160,
+     491,   162,   718,   990,   562,   496,   160,   122,   131,   160,
+     721,   569,   562,   571,   572,   573,   574,   575,     3,   569,
+     163,   571,   572,   573,   574,   575,  1021,  1021,   693,   796,
+     797,   798,   162,    18,   525,   526,   162,    22,   662,   530,
+     770,   771,   772,   773,   774,   536,     3,  1042,  1042,   131,
+     161,   162,   571,   572,   573,   574,   575,    83,   537,    85,
+     539,    18,  1006,   123,   641,    22,   160,   546,  1006,   560,
+       8,     9,    10,     4,    12,    13,    14,    15,    16,    17,
+     657,    19,    20,    21,    22,    23,   577,   664,   579,   160,
+     161,   162,   669,    18,    19,    20,    21,    22,    23,    18,
+      19,    20,    21,    22,    23,   821,   664,    24,    41,    19,
+      20,    21,    22,    23,   664,   161,   162,   608,   609,   166,
+     611,   162,   163,   614,   615,   847,   848,   849,   850,   903,
+     134,   135,   136,   683,    21,    22,    23,    19,    20,    83,
+      84,   632,   633,    37,    38,     3,   637,     3,   639,   123,
+     124,   160,   643,     3,   162,   162,   162,   819,   168,   162,
+     162,   652,   738,   654,   740,   656,   162,   646,   162,   162,
+     162,   662,   796,   749,   653,   886,   162,     3,   162,   162,
+     162,   162,   162,   162,   675,   664,   677,   162,     3,   162,
+     162,   768,   671,   162,   162,   162,   912,   162,   162,   132,
+     691,   692,   160,     3,   160,   138,   139,   160,   982,   163,
+     768,   702,     5,   160,     3,   160,   162,   160,   768,   160,
+     153,   154,     3,   156,   157,   160,   164,   165,   161,   708,
+     721,     5,     6,     7,     8,     9,    10,     3,    12,    13,
+      14,    15,    16,    17,   160,    19,    20,    21,    22,    23,
+       3,     5,   161,     3,     3,   163,     3,     3,   162,    22,
+     751,     5,     3,     3,   163,   163,     3,     3,   163,   760,
+     162,   160,   988,     3,   160,   163,     3,   162,     5,     6,
+       7,     8,     9,    10,   162,    12,    13,    14,    15,    16,
+      17,   162,    19,    20,    21,    22,    23,   162,   160,   163,
+     161,     3,     3,    23,     3,   796,   797,   798,     3,     3,
+     163,     4,   163,    22,   163,   163,   160,   893,    22,   162,
+      26,    21,   813,   814,   163,   160,   902,   163,     4,    36,
+     122,   955,     3,   160,   162,   160,    10,   914,    12,    13,
+      14,    15,    16,    17,   160,    19,    20,    21,    22,    23,
+     163,     3,   162,   162,     5,   163,   914,     5,   935,   163,
+     162,   160,   163,   160,   914,   160,     4,   163,     3,   163,
+      82,   122,   163,   163,     3,    22,   160,   868,   163,   870,
+     167,   872,   160,   160,   163,   168,    82,   163,   163,   160,
+     164,   165,    25,   160,   168,   886,   160,    22,   974,   160,
+     891,    51,   254,   950,   485,   948,   897,    12,    13,    14,
+      15,    16,    17,   904,    19,    20,    21,    22,    23,    12,
+      13,    14,    15,    16,    17,   673,    19,    20,    21,    22,
+      23,   677,   911,   924,   405,   926,   927,   164,   165,   481,
+     931,   932,   505,   934,   480,    78,    79,    80,   260,   525,
+     493,   289,   715,   944,    52,   868,   927,   397,   937,   959,
+     870,   662,   890,  1016,   955,   985,   541,   757,   937,   960,
+     961,   760,   664,   106,   435,   108,   109,   110,   124,    -1,
+     113,   114,    -1,   116,   117,    -1,    -1,     0,     1,    -1,
+     164,   165,    -1,    -1,   985,    -1,   987,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,   983,   996,    -1,    -1,   999,    -1,
+      -1,    24,    25,    -1,    -1,    28,    29,    30,    31,    32,
+      -1,    -1,    35,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+    1021,    -1,    45,    -1,    -1,    -1,    -1,    -1,    -1,  1030,
+      -1,  1032,    -1,  1034,  1035,  1024,    -1,    -1,    61,    -1,
+      -1,  1042,    65,    66,  1033,    -1,    -1,    70,  1049,   164,
+     165,    -1,    -1,    76,    -1,    78,    79,    -1,    81,    -1,
+      -1,   164,   165,    86,    87,    88,    89,    90,    -1,    92,
+      93,    -1,    -1,    96,    97,    98,    99,   100,   101,   102,
+     103,   104,   105,   106,    -1,   108,    -1,   110,   111,    -1,
+      -1,   114,   115,   116,    -1,   118,    -1,   120,    -1,    -1,
+     123,   124,    -1,    -1,   127,   128,   129,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,   137,    -1,    -1,   140,   141,   142,
+     143,   144,   145,   146,   147,   148,   149,   150,   151,   152,
+      -1,    -1,   155,    -1,    -1,   158,   159,   160,   161,    -1,
+      -1,    -1,     3,   166,     5,     6,     7,     8,     9,    10,
+      -1,    12,    13,    14,    15,    16,    17,    -1,    19,    20,
+      21,    22,    23,     3,    -1,     5,     6,     7,     8,     9,
+      10,    -1,    12,    13,    14,    15,    16,    17,    -1,    19,
+      20,    21,    22,    23,     3,    -1,     5,     6,     7,     8,
+       9,    10,    -1,    12,    13,    14,    15,    16,    17,    -1,
+      19,    20,    21,    22,    23,     3,    -1,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,     3,    -1,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,     4,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,     4,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,    -1,    -1,    -1,
+      -1,    -1,    33,    34,    -1,    -1,    -1,    -1,    39,    40,
+      41,    42,    43,   164,   165,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    54,    55,    56,    57,    58,    59,    60,
+      -1,    62,    63,    64,   164,   165,    67,    68,    69,    -1,
+      71,    72,    73,    74,    75,    -1,    77,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,   164,   165,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,   164,   165,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,   164,   165,    -1,
+      -1,   132,    -1,    -1,    -1,    -1,    -1,   138,   139,    -1,
+      -1,    -1,    -1,   144,    -1,    -1,   163,   164,   165,    -1,
+      -1,    -1,   153,   154,    -1,   156,   157,    -1,    -1,   160,
+     161,   162,    -1,    -1,    -1,    -1,    -1,   164,   165,     4,
+       5,     6,     7,     8,     9,    10,    -1,    12,    13,    14,
+      15,    16,    17,    -1,    19,    20,    21,    22,    23,     4,
+       5,     6,     7,     8,     9,    10,    -1,    12,    13,    14,
+      15,    16,    17,    -1,    19,    20,    21,    22,    23,     4,
+       5,     6,     7,     8,     9,    10,    -1,    12,    13,    14,
+      15,    16,    17,    -1,    19,    20,    21,    22,    23,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,   163,   164,   165,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   163,   164,   165,     5,
+       6,     7,     8,     9,    10,    -1,    12,    13,    14,    15,
+      16,    17,    -1,    19,    20,    21,    22,    23,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,    -1,    -1,    -1,   164,
+     165,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   164,
+     165,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   164,
+     165,     5,     6,     7,     8,     9,    10,    -1,    12,    13,
+      14,    15,    16,    17,    -1,    19,    20,    21,    22,    23,
+       5,     6,     7,     8,     9,    10,    -1,    12,    13,    14,
+      15,    16,    17,    -1,    19,    20,    21,    22,    23,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,   163,   164,   165,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   163,   164,   165,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,   163,   164,   165,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,     5,     6,     7,     8,
+       9,    10,    -1,    12,    13,    14,    15,    16,    17,    -1,
+      19,    20,    21,    22,    23,    -1,    -1,    -1,    -1,   163,
      164,   165,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,   917,   176,    -1,    -1,   185,   186,   902,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,   931,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,   939,    -1,    -1,    -1,    -1,    -1,   945,
-      -1,    -1,   948,     0,     1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   964,    -1,
-      -1,    -1,    -1,   969,   970,    -1,    -1,   973,   974,    -1,
-      27,    -1,    29,    -1,   980,    32,    33,    34,    35,    36,
-      37,    38,    -1,    -1,    41,    42,    43,   185,   186,    -1,
-      -1,    48,    49,    -1,    -1,    -1,    53,    54,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    63,    -1,    -1,    -1,
-      67,    68,    -1,    -1,    -1,    72,    -1,    -1,    -1,   185,
-     186,    78,    -1,    80,    81,    -1,    83,    -1,    85,    86,
-      87,    88,    89,    -1,    91,    92,    93,    94,    95,    96,
-      97,    98,    99,   100,   101,   102,   103,   104,   105,   106,
-      -1,    -1,   109,   110,   111,    -1,   113,   114,   115,    -1,
-     117,   118,   119,    -1,    -1,   122,    -1,   124,    -1,    -1,
-     127,   128,   129,   130,    -1,    -1,   133,   134,   135,    -1,
-      -1,    -1,    -1,    -1,   141,    -1,    -1,   144,   145,   146,
-     147,   148,   149,   150,   151,    -1,   153,   154,   155,   156,
-     157,    -1,    -1,   160,    -1,    -1,    -1,    -1,    -1,    -1,
-     167,   168,   169,    -1,    -1,    -1,    -1,    -1,    -1,   176,
-     177,     3,    -1,     5,    -1,     7,     8,     9,    10,    11,
-     187,    13,    14,    15,    16,    17,    18,    -1,    -1,    21,
-      22,    23,    24,    25,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    39,    40,    -1,
-      -1,    -1,    44,    45,    46,    47,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,    61,
-      62,    -1,    64,    65,    66,    -1,    -1,    69,    70,    71,
-      -1,    73,    74,    75,    76,    77,     3,    79,     5,    -1,
-       7,     8,     9,    10,    11,    -1,    13,    14,    15,    16,
-      17,    18,    -1,    -1,    21,    22,    23,    24,    25,     3,
-      -1,     5,    -1,     7,     8,     9,    10,    11,    -1,    13,
-      14,    15,    16,    17,    18,    -1,    -1,    21,    22,    23,
-      24,    25,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   163,   164,
+     165,     5,     6,     7,     8,     9,    10,    -1,    12,    13,
+      14,    15,    16,    17,    -1,    19,    20,    21,    22,    23,
+       5,     6,     7,     8,     9,    10,    -1,    12,    13,    14,
+      15,    16,    17,    -1,    19,    20,    21,    22,    23,     5,
+       6,     7,     8,     9,    10,    -1,    12,    13,    14,    15,
+      16,    17,    -1,    19,    20,    21,    22,    23,    -1,    -1,
+      -1,    -1,    -1,    -1,    33,    34,    -1,    -1,    -1,    -1,
+      39,    40,    41,    42,    43,    -1,   163,   164,   165,    -1,
+      -1,    -1,    -1,    -1,    -1,    54,    55,    56,    57,    58,
+      59,    60,   160,    62,    63,    64,   164,   165,    67,    68,
+      69,    -1,    71,    72,    73,    74,    75,    -1,    77,    -1,
+      -1,    -1,    -1,    -1,   163,   164,   165,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,     5,     6,     7,     8,
+       9,    10,    -1,    12,    13,    14,    15,    16,    17,    -1,
+      19,    20,    21,    22,    23,    -1,    -1,    -1,    -1,   163,
+     164,   165,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,
+     139,    -1,    -1,    -1,    -1,   144,    -1,    -1,   163,   164,
+     165,    -1,    -1,    -1,   153,   154,    -1,   156,   157,    -1,
+      -1,   160,   161,   162,    -1,    -1,    -1,   163,   164,   165,
+       5,     6,     7,     8,     9,    10,    -1,    12,    13,    14,
+      15,    16,    17,    -1,    19,    20,    21,    22,    23,     5,
+       6,     7,     8,     9,    10,    -1,    12,    13,    14,    15,
+      16,    17,    -1,    19,    20,    21,    22,    23,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     142,   143,    -1,    -1,    -1,    -1,   148,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   158,   159,    -1,    -1,
-     162,   163,   164,   165,    -1,    -1,    -1,   169,    -1,    -1,
-      -1,    -1,    -1,    -1,   176,    -1,    -1,   179,    -1,    -1,
-      -1,    -1,    -1,   185,   186,     3,    -1,     5,    -1,     7,
-       8,     9,    10,    11,    -1,    13,    14,    15,    16,    17,
-      18,    -1,    -1,    21,    22,    23,    24,    25,     3,    -1,
-       5,    -1,     7,     8,     9,    10,    11,    -1,    13,    14,
-      15,    16,    17,    18,    -1,    -1,    21,    22,    23,    24,
-      25,     3,    -1,     5,    -1,     7,     8,     9,    10,    11,
-      -1,    13,    14,    15,    16,    17,    18,    -1,    -1,    21,
-      22,    23,    24,    25,    -1,    -1,    -1,    -1,   185,   186,
-      -1,    -1,    -1,    -1,    -1,    -1,     4,     5,    -1,     7,
-       8,     9,    10,    11,    -1,    13,    14,    15,    16,    17,
-      18,   185,   186,    21,    22,    23,    24,    25,     4,     5,
-      -1,     7,     8,     9,    10,    11,    -1,    13,    14,    15,
-      16,    17,    18,    -1,    -1,    21,    22,    23,    24,    25,
-       4,     5,    -1,     7,     8,     9,    10,    11,    -1,    13,
-      14,    15,    16,    17,    18,    -1,    -1,    21,    22,    23,
-      24,    25,     4,     5,    -1,     7,     8,     9,    10,    11,
-      -1,    13,    14,    15,    16,    17,    18,    -1,    -1,    21,
-      22,    23,    24,    25,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   185,   186,    -1,
-      -1,    -1,    -1,    -1,    -1,     4,     5,    -1,     7,     8,
-       9,    10,    11,    -1,    13,    14,    15,    16,    17,    18,
-     185,   186,    21,    22,    23,    24,    25,    -1,    -1,     5,
-      -1,     7,     8,     9,    10,    11,    -1,    13,    14,    15,
-      16,    17,    18,   185,   186,    21,    22,    23,    24,    25,
-       5,    -1,     7,     8,     9,    10,    11,    -1,    13,    14,
-      15,    16,    17,    18,    -1,    -1,    21,    22,    23,    24,
-      25,    -1,   180,    -1,    -1,    -1,    -1,   185,   186,    -1,
-      -1,    -1,    -1,    -1,    -1,     5,    -1,     7,     8,     9,
-      10,    11,    -1,    13,    14,    15,    16,    17,    18,   185,
-     186,    21,    22,    23,    24,    25,    -1,     5,    -1,     7,
-       8,     9,    10,    11,    -1,    13,    14,    15,    16,    17,
-      18,   185,   186,    21,    22,    23,    24,    25,    -1,     5,
-      -1,     7,     8,     9,    10,    11,    -1,    13,    14,    15,
-      16,    17,    18,   185,   186,    21,    22,    23,    24,    25,
-       5,    -1,     7,     8,     9,    10,    11,    -1,    13,    14,
-      15,    16,    17,    18,    -1,    -1,    21,    22,    23,    24,
-      25,    -1,     5,    -1,     7,     8,     9,    10,    11,    -1,
-      13,    14,    15,    16,    17,    18,   185,   186,    21,    22,
-      23,    24,    25,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,   180,    -1,    -1,    -1,    -1,   185,
-     186,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,    -1,    -1,
-     185,   186,     5,    -1,     7,     8,     9,    10,    11,    -1,
-      13,    14,    15,    16,    17,    18,    -1,    -1,    21,    22,
-      23,    24,    25,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     180,    -1,    -1,    -1,    -1,   185,   186,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,   163,   164,   165,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   180,    -1,    -1,    -1,    -1,   185,   186,    -1,
+      -1,    -1,    -1,    -1,   163,   164,   165,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,     5,     6,     7,     8,
+       9,    10,    -1,    12,    13,    14,    15,    16,    17,    -1,
+      19,    20,    21,    22,    23,     5,     6,     7,     8,     9,
+      10,    -1,    12,    13,    14,    15,    16,    17,    -1,    19,
+      20,    21,    22,    23,    -1,    -1,    -1,    -1,   163,   164,
+     165,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,   163,   164,   165,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,   180,    -1,    -1,    -1,    -1,   185,
-     186,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,    -1,    -1,
-     185,   186,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,
-      -1,    -1,   185,   186,     5,    -1,     7,     8,     9,    10,
-      11,    -1,    13,    14,    15,    16,    17,    18,    -1,    -1,
-      21,    22,    23,    24,    25,     5,    -1,     7,     8,     9,
-      10,    11,    -1,    13,    14,    15,    16,    17,    18,    -1,
-      -1,    21,    22,    23,    24,    25,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,
-      -1,    -1,   185,   186,     5,    -1,     7,     8,     9,    10,
-      11,    -1,    13,    14,    15,    16,    17,    18,    -1,    -1,
-      21,    22,    23,    24,    25,     5,    -1,     7,     8,     9,
-      10,    11,    -1,    13,    14,    15,    16,    17,    18,    -1,
-      -1,    21,    22,    23,    24,    25,     5,    -1,     7,     8,
-       9,    10,    11,    -1,    13,    14,    15,    16,    17,    18,
-      -1,    -1,    21,    22,    23,    24,    25,     5,    -1,     7,
-       8,     9,    10,    11,    -1,    13,    14,    15,    16,    17,
-      18,    -1,    -1,    21,    22,    23,    24,    25,     5,    -1,
-       7,     8,     9,    10,    11,    -1,    13,    14,    15,    16,
-      17,    18,    -1,    -1,    21,    22,    23,    24,    25,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   180,
-      -1,    -1,    -1,    -1,   185,   186,    -1,    -1,    -1,   169,
-      -1,     5,    -1,     7,     8,     9,    10,    11,    -1,    13,
-      14,    15,    16,    17,    18,   185,   186,    21,    22,    23,
-      24,    25,     5,    -1,     7,     8,     9,    10,    11,    -1,
-      13,    14,    15,    16,    17,    18,    -1,    -1,    21,    22,
-      23,    24,    25,    -1,    -1,    -1,    -1,    -1,    -1,   180,
-      -1,    -1,    -1,    -1,   185,   186,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   163,   164,   165,     5,
+       6,     7,     8,     9,    10,    -1,    12,    13,    14,    15,
+      16,    17,    -1,    19,    20,    21,    22,    23,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     180,    -1,    -1,    -1,    -1,   185,   186,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,   163,   164,   165,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,   180,    -1,    -1,    -1,    -1,   185,   186,    -1,    -1,
+      -1,    -1,    -1,    -1,   163,   164,   165,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   180,    -1,    -1,    -1,    -1,   185,   186,    -1,
+      -1,    -1,    -1,   163,   164,   165,     5,     6,     7,     8,
+       9,    10,    -1,    12,    13,    14,    15,    16,    17,    -1,
+      19,    20,    21,    22,    23,     5,     6,     7,     8,     9,
+      10,    -1,    12,    13,    14,    15,    16,    17,    -1,    19,
+      20,    21,    22,    23,     5,     6,     7,     8,     9,    10,
+      -1,    12,    13,    14,    15,    16,    17,    -1,    19,    20,
+      21,    22,    23,    -1,    -1,    -1,    -1,   163,   164,   165,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,   180,    -1,    -1,    -1,    -1,   185,   186,
-       5,    -1,     7,     8,     9,    10,    11,    -1,    13,    14,
-      15,    16,    17,    18,    -1,    -1,    21,    22,    23,    24,
-      25,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,    -1,
-      -1,   185,   186,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,
-      -1,    -1,   185,   186,     5,    -1,     7,     8,     9,    10,
-      11,    -1,    13,    14,    15,    16,    17,    18,    -1,    -1,
-      21,    22,    23,    24,    25,     5,    -1,     7,     8,     9,
-      10,    11,    -1,    13,    14,    15,    16,    17,    18,    -1,
-      -1,    21,    22,    23,    24,    25,     5,    -1,     7,     8,
-       9,    10,    11,    -1,    13,    14,    15,    16,    17,    18,
-      -1,    -1,    21,    22,    23,    24,    25,     5,    -1,     7,
-       8,     9,    10,    11,    -1,    13,    14,    15,    16,    17,
-      18,    -1,    -1,    21,    22,    23,    24,    25,     5,    -1,
-       7,     8,     9,    10,    11,    -1,    13,    14,    15,    16,
-      17,    18,    -1,    -1,    21,    22,    23,    24,    25,    -1,
-      -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,    -1,    -1,
-     185,   186,     5,    -1,     7,     8,     9,    10,    11,    -1,
-      13,    14,    15,    16,    17,    18,    -1,    -1,    21,    22,
-      23,    24,    25,     5,    -1,     7,     8,     9,    10,    11,
-      -1,    13,    14,    15,    16,    17,    18,    -1,    -1,    21,
-      22,    23,    24,    25,    -1,    -1,    -1,    -1,    -1,    38,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   180,
-      -1,    -1,    -1,    -1,   185,   186,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    63,    -1,    -1,    -1,    -1,    -1,
-     180,    -1,    -1,    -1,    -1,   185,   186,    -1,    -1,    78,
-      -1,    -1,    -1,    -1,    83,    84,    -1,    -1,    -1,    88,
-      89,   180,    -1,    -1,    -1,    -1,   185,   186,    -1,    98,
-      99,   100,   101,   102,   103,   104,   105,    -1,    -1,    -1,
-      -1,    -1,   180,    -1,    -1,    -1,    -1,   185,   186,   118,
-      -1,    -1,    -1,    -1,    -1,   124,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,   180,   133,    -1,   135,    -1,   185,   186,
-       5,    -1,     7,     8,     9,    10,    11,    -1,    13,    14,
-      15,    16,    17,    18,    -1,    -1,    21,    22,    23,    24,
-      25,    -1,    -1,    -1,    -1,    -1,    -1,   180,    -1,    -1,
-     169,    -1,   185,   186,    -1,    -1,    -1,   176,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   180,    -1,
-      -1,    -1,    -1,   185,   186,     5,    -1,     7,     8,     9,
-      10,    11,     4,    13,    14,    15,    16,    17,    18,    -1,
-      12,    21,    22,    23,    24,    25,    -1,    -1,    -1,    21,
-      22,    23,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    39,    40,    -1,
-      -1,    -1,    44,    45,    46,    47,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,    61,
-      62,    -1,    64,    65,    66,    -1,    -1,    69,    70,    71,
-      -1,    73,    74,    75,    76,    77,    -1,    79,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    40,    -1,
-      -1,    -1,    44,    45,    46,    47,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,    61,
-      62,    -1,    64,    65,    66,   180,    -1,    69,    70,    71,
-     185,   186,    74,    75,    76,    77,    -1,    79,    -1,   131,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    12,    -1,
-     142,   143,    -1,    -1,    -1,    -1,   148,    21,    22,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   158,   159,    -1,    -1,
-     162,   163,   164,   165,    -1,    39,    40,   169,    -1,    -1,
-      44,    45,    46,    47,   176,   185,   186,   179,    -1,    -1,
-      -1,    -1,    56,    57,    58,    59,    60,    61,    62,    -1,
-      64,    65,    66,    -1,    -1,    69,    70,    71,    -1,    73,
-      74,    75,    76,    77,    -1,    79,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   169,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   163,   164,   165,     5,
+       6,     7,     8,     9,    10,    -1,    12,    13,    14,    15,
+      16,    17,    -1,    19,    20,    21,    22,    23,     5,     6,
+       7,     8,     9,    10,    -1,    12,    13,    14,    15,    16,
+      17,    -1,    19,    20,    21,    22,    23,     5,     6,     7,
+       8,     9,    10,    -1,    12,    13,    14,    15,    16,    17,
+      -1,    19,    20,    21,    22,    23,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,   163,   164,   165,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,   163,   164,   165,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,   163,   164,   165,     5,     6,     7,     8,     9,
+      10,    -1,    12,    13,    14,    15,    16,    17,    -1,    19,
+      20,    21,    22,    23,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,     4,    -1,   163,   164,   165,
+      -1,    -1,    11,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      19,    20,    21,    -1,    -1,    -1,   163,   164,   165,    -1,
+      -1,    -1,    -1,    -1,    33,    34,    -1,    -1,    -1,    -1,
+      39,    40,    41,    42,    43,   163,   164,   165,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    54,    55,    56,    57,    58,
+      59,    60,    -1,    62,    63,    64,    -1,    -1,    67,    68,
+      69,    -1,    71,    72,    73,    74,    75,    34,    77,    -1,
+      -1,    -1,    39,    40,    -1,    42,    43,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    54,    55,    56,
+      57,    58,    59,    60,    -1,    62,    63,    64,    -1,    -1,
+      67,    68,    69,    -1,     4,    72,    73,    74,    75,    -1,
+      77,    11,    -1,    -1,   164,   165,   125,    -1,    -1,    19,
+      20,    -1,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,
+     139,    -1,    -1,    33,    34,   144,    -1,    -1,    -1,    39,
+      40,    41,    42,    43,   153,   154,    -1,   156,   157,    -1,
+      -1,   160,   161,   162,    54,    55,    56,    57,    58,    59,
+      60,    -1,    62,    63,    64,    -1,    -1,    67,    68,    69,
+      -1,    71,    72,    73,    74,    75,    -1,    77,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,   160,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,     4,    -1,    -1,    -1,    -1,    -1,    -1,
+      11,    -1,    -1,    -1,    -1,   125,    -1,    -1,    19,    20,
+      -1,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,   139,
+      -1,    -1,    33,    34,   144,    -1,    -1,    -1,    39,    40,
+      41,    42,    43,   153,   154,    -1,   156,   157,    -1,    -1,
+     160,   161,   162,    54,    55,    56,    57,    58,    59,    60,
+      -1,    62,    63,    64,    -1,    -1,    67,    68,    69,    -1,
+      71,    72,    73,    74,    75,    -1,    77,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   142,   143,
-      -1,    -1,    -1,    -1,   148,     4,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    12,   158,   159,    -1,    -1,   162,   163,
-     164,   165,    21,    22,    -1,   169,    -1,    -1,    -1,    -1,
-      -1,    -1,   176,    -1,    -1,   179,    -1,    -1,    -1,    -1,
-      39,    40,    -1,   187,    -1,    44,    45,    46,    47,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,     4,    -1,    -1,    -1,    -1,    -1,    -1,    11,
+      -1,    -1,    -1,    -1,   125,    -1,    -1,    19,    20,    -1,
+      -1,   132,    -1,    -1,    -1,    -1,    -1,   138,   139,    -1,
+      -1,    33,    34,   144,    -1,    -1,    -1,    39,    40,    41,
+      42,    43,   153,   154,    -1,   156,   157,    -1,    -1,   160,
+     161,   162,    54,    55,    56,    57,    58,    59,    60,    -1,
+      62,    63,    64,    -1,    -1,    67,    68,    69,    -1,    71,
+      72,    73,    74,    75,    -1,    77,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,     5,    -1,    -1,    -1,    -1,    -1,    11,    -1,
+      -1,    -1,    -1,   125,    -1,    -1,    19,    20,    21,    -1,
+     132,    -1,    -1,    -1,    -1,    -1,   138,   139,    -1,    -1,
+      33,    34,   144,    -1,    -1,    -1,    39,    40,    41,    42,
+      43,   153,   154,    -1,   156,   157,    -1,    -1,   160,   161,
+     162,    54,    55,    56,    57,    58,    59,    60,    -1,    62,
+      63,    64,    -1,    -1,    67,    68,    69,    -1,    71,    72,
+      73,    74,    75,    -1,    77,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,     5,    -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,
+      -1,    -1,   125,    -1,    -1,    19,    20,    -1,    22,   132,
+      -1,    -1,    -1,    -1,    -1,   138,   139,    -1,    -1,    33,
+      34,   144,    -1,    -1,    -1,    39,    40,    41,    42,    43,
+     153,   154,    -1,   156,   157,    -1,    -1,   160,   161,   162,
+      54,    55,    56,    57,    58,    59,    60,    -1,    62,    63,
+      64,    -1,    -1,    67,    68,    69,    -1,    71,    72,    73,
+      74,    75,    -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+       5,    -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,
+      -1,   125,    -1,    -1,    19,    20,    21,    -1,   132,    -1,
+      -1,    -1,    -1,    -1,   138,   139,    -1,    -1,    33,    34,
+     144,    -1,    -1,    -1,    39,    40,    41,    42,    43,   153,
+     154,    -1,   156,   157,    -1,    -1,   160,   161,   162,    54,
+      55,    56,    57,    58,    59,    60,    -1,    62,    63,    64,
+      -1,    -1,    67,    68,    69,    -1,    71,    72,    73,    74,
+      75,    -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,     5,
+      -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,
+     125,    -1,    -1,    19,    20,    -1,    -1,   132,    -1,    -1,
+      -1,    -1,    -1,   138,   139,    -1,    -1,    33,    34,   144,
+      -1,    -1,    -1,    39,    40,    41,    42,    43,   153,   154,
+      -1,   156,   157,    -1,    -1,   160,   161,   162,    54,    55,
+      56,    57,    58,    59,    60,    -1,    62,    63,    64,    -1,
+      -1,    67,    68,    69,    -1,    71,    72,    73,    74,    75,
+      -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,     5,    -1,
+      -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,   125,
+      -1,    -1,    19,    20,    -1,    -1,   132,    -1,    -1,    -1,
+      -1,    -1,   138,   139,    -1,    -1,    33,    34,   144,    -1,
+      -1,    -1,    39,    40,    41,    42,    43,   153,   154,    -1,
+     156,   157,    -1,    -1,   160,   161,   162,    54,    55,    56,
+      57,    58,    59,    60,    -1,    62,    63,    64,    -1,    -1,
+      67,    68,    69,    -1,    71,    72,    73,    74,    75,    -1,
+      77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,     5,    -1,    -1,
+      -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,   125,    -1,
+      -1,    19,    20,    -1,    -1,   132,    -1,    -1,    -1,    -1,
+      -1,   138,   139,    -1,    -1,    33,    34,   144,    -1,    -1,
+      -1,    39,    40,    41,    42,    43,   153,   154,    -1,   156,
+     157,    -1,    -1,   160,   161,   162,    54,    55,    56,    57,
+      58,    59,    60,    -1,    62,    63,    64,    -1,    -1,    67,
+      68,    69,    -1,    71,    72,    73,    74,    75,    -1,    77,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   131,     4,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    12,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,
-      21,    22,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    -1,    39,    40,
-     169,    -1,    -1,    44,    45,    46,    47,   176,    -1,    -1,
-     179,    -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,
-      61,    62,    -1,    64,    65,    66,    -1,    -1,    69,    70,
-      71,    -1,    73,    74,    75,    76,    77,    -1,    79,    -1,
+      -1,    -1,    11,    -1,    -1,    -1,    -1,   125,    -1,    -1,
+      19,    20,    -1,    -1,   132,    -1,    -1,    -1,    -1,    -1,
+     138,   139,    -1,    -1,    33,    34,   144,    -1,    -1,    -1,
+      39,    40,    41,    42,    43,   153,   154,    -1,   156,   157,
+      -1,    -1,   160,   161,   162,    54,    55,    56,    57,    58,
+      59,    60,    -1,    62,    63,    64,    -1,    -1,    67,    68,
+      69,    -1,    71,    72,    73,    74,    75,    -1,    77,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   125,    -1,    -1,    -1,
+      -1,    -1,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,
+     139,    -1,    -1,    -1,    -1,   144,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,   153,   154,    11,   156,   157,    -1,
+      -1,   160,   161,   162,    19,    20,    21,   166,    23,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    33,    34,
+      -1,    -1,    -1,    -1,    39,    40,    41,    42,    43,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    54,
+      55,    56,    57,    58,    59,    60,    -1,    62,    63,    64,
+      -1,    -1,    67,    68,    69,    -1,    71,    72,    73,    74,
+      75,    -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     131,    -1,     5,    -1,    -1,    -1,    -1,    -1,    -1,    12,
-      -1,   142,   143,    -1,    -1,    -1,    -1,   148,    21,    22,
-      23,    -1,    -1,    -1,    -1,    -1,    -1,   158,   159,    -1,
-      -1,   162,   163,   164,   165,    -1,    39,    40,   169,    -1,
-      -1,    44,    45,    46,    47,   176,    -1,    -1,   179,    -1,
-      -1,    -1,    -1,    56,    57,    58,    59,    60,    61,    62,
-      -1,    64,    65,    66,    -1,    -1,    69,    70,    71,    -1,
-      73,    74,    75,    76,    77,    -1,    79,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,
+     125,    -1,    -1,    19,    20,    21,    -1,   132,    -1,    -1,
+      -1,    -1,    -1,   138,   139,    -1,    -1,    33,    34,   144,
+      -1,    -1,    -1,    39,    40,    41,    42,    43,   153,   154,
+      -1,   156,   157,    -1,    -1,   160,   161,   162,    54,    55,
+      56,    57,    58,    59,    60,    -1,    62,    63,    64,    -1,
+      -1,    67,    68,    69,    -1,    71,    72,    73,    74,    75,
+      -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,   125,
+      -1,    -1,    19,    20,    21,    -1,   132,    -1,    -1,    -1,
+      -1,    -1,   138,   139,    -1,    -1,    33,    34,   144,    -1,
+      -1,    -1,    39,    40,    41,    42,    43,   153,   154,    -1,
+     156,   157,    -1,    -1,   160,   161,   162,    54,    55,    56,
+      57,    58,    59,    60,    -1,    62,    63,    64,    -1,    -1,
+      67,    68,    69,    -1,    71,    72,    73,    74,    75,    -1,
+      77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,   125,    -1,
+      -1,    19,    20,    21,    -1,   132,    -1,    -1,    -1,    -1,
+      -1,   138,   139,    -1,    -1,    33,    34,   144,    -1,    -1,
+      -1,    39,    40,    41,    42,    43,   153,   154,    -1,   156,
+     157,    -1,    -1,   160,   161,   162,    54,    55,    56,    57,
+      58,    59,    60,    -1,    62,    63,    64,    -1,    -1,    67,
+      68,    69,    -1,    71,    72,    73,    74,    75,    -1,    77,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,
-       5,    -1,    -1,    -1,    -1,    -1,    -1,    12,    -1,   142,
-     143,    -1,    -1,    -1,    -1,   148,    21,    22,    -1,    24,
-      -1,    -1,    -1,    -1,    -1,   158,   159,    -1,    -1,   162,
-     163,   164,   165,    -1,    39,    40,   169,    -1,    -1,    44,
-      45,    46,    47,   176,    -1,    -1,   179,    -1,    -1,    -1,
-      -1,    56,    57,    58,    59,    60,    61,    62,    -1,    64,
-      65,    66,    -1,    -1,    69,    70,    71,    -1,    73,    74,
-      75,    76,    77,    -1,    79,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    11,    -1,    -1,    -1,    -1,   125,    -1,    -1,
+      19,    20,    21,    -1,   132,    -1,    -1,    -1,    -1,    -1,
+     138,   139,    -1,    -1,    33,    34,   144,    -1,    -1,    -1,
+      39,    40,    41,    42,    43,   153,   154,    -1,   156,   157,
+      -1,    -1,   160,   161,   162,    54,    55,    56,    57,    58,
+      59,    60,    -1,    62,    63,    64,    -1,    -1,    67,    68,
+      69,    -1,    71,    72,    73,    74,    75,    -1,    77,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,     5,    -1,
-      -1,    -1,    -1,    -1,    -1,    12,    -1,   142,   143,    -1,
-      -1,    -1,    -1,   148,    21,    22,    23,    -1,    -1,    -1,
-      -1,    -1,    -1,   158,   159,    -1,    -1,   162,   163,   164,
-     165,    -1,    39,    40,   169,    -1,    -1,    44,    45,    46,
-      47,   176,    -1,    -1,   179,    -1,    -1,    -1,    -1,    56,
-      57,    58,    59,    60,    61,    62,    -1,    64,    65,    66,
-      -1,    -1,    69,    70,    71,    -1,    73,    74,    75,    76,
-      77,    -1,    79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   125,    -1,    -1,    -1,
+      -1,    -1,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,
+     139,    -1,    11,    -1,    -1,   144,    -1,    -1,    -1,    -1,
+      19,    20,    -1,    -1,   153,   154,    -1,   156,   157,    -1,
+      -1,   160,   161,   162,    33,    34,    35,    -1,    -1,    -1,
+      39,    40,    41,    42,    43,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    54,    55,    56,    57,    58,
+      59,    60,    -1,    62,    63,    64,    -1,    -1,    67,    68,
+      69,    -1,    71,    72,    73,    74,    75,    -1,    77,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,   131,    -1,     5,    -1,    -1,    -1,
-      -1,    -1,    -1,    12,    -1,   142,   143,    -1,    -1,    -1,
-      -1,   148,    21,    22,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,   158,   159,    -1,    -1,   162,   163,   164,   165,    -1,
-      39,    40,   169,    -1,    -1,    44,    45,    46,    47,   176,
-      -1,    -1,   179,    -1,    -1,    -1,    -1,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    11,    -1,    -1,    -1,    -1,   125,    -1,    -1,    19,
+      20,    21,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,
+     139,    -1,    -1,    33,    34,   144,    -1,    -1,    -1,    39,
+      40,    41,    42,    43,   153,   154,    -1,   156,   157,    -1,
+      -1,   160,   161,   162,    54,    55,    56,    57,    58,    59,
+      60,    -1,    62,    63,    64,    -1,    -1,    67,    68,    69,
+      -1,    71,    72,    73,    74,    75,    -1,    77,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   131,    -1,     5,    -1,    -1,    -1,    -1,    -1,
-      -1,    12,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,
-      21,    22,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    -1,    39,    40,
-     169,    -1,    -1,    44,    45,    46,    47,   176,    -1,    -1,
-     179,    -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,
-      61,    62,    -1,    64,    65,    66,    -1,    -1,    69,    70,
-      71,    -1,    73,    74,    75,    76,    77,    -1,    79,    -1,
+      11,    -1,    -1,    -1,    -1,   125,    -1,    -1,    19,    20,
+      21,    -1,   132,    -1,    -1,    -1,    -1,    -1,   138,   139,
+      -1,    -1,    33,    34,   144,    -1,    -1,    -1,    39,    40,
+      41,    42,    43,   153,   154,    -1,   156,   157,    -1,    -1,
+     160,   161,   162,    54,    55,    56,    57,    58,    59,    60,
+      -1,    62,    63,    64,    -1,    -1,    67,    68,    69,    -1,
+      71,    72,    73,    74,    75,    -1,    77,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    11,
+      -1,    -1,    -1,    -1,   125,    -1,    -1,    19,    20,    -1,
+      -1,   132,    -1,    -1,    -1,    -1,    -1,   138,   139,    -1,
+      -1,    33,    34,   144,    -1,    -1,    -1,    39,    40,    41,
+      42,    43,   153,   154,    -1,   156,   157,    -1,    -1,   160,
+     161,   162,    54,    55,    56,    57,    58,    59,    60,    -1,
+      62,    63,    64,    -1,    -1,    67,    68,    69,    -1,    71,
+      72,    73,    74,    75,    -1,    77,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    11,    -1,
+      -1,    -1,    -1,   125,    -1,    -1,    19,    20,    -1,    -1,
+     132,    -1,    -1,    -1,    -1,    -1,   138,   139,    -1,    -1,
+      33,    34,   144,    -1,    -1,    -1,    39,    40,    41,    42,
+      43,   153,   154,    -1,   156,   157,    -1,    -1,   160,   161,
+     162,    54,    55,    56,    57,    58,    59,    60,    -1,    62,
+      63,    64,    -1,    -1,    67,    68,    69,    -1,    71,    72,
+      73,    74,    75,    -1,    77,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,
+      -1,    -1,   125,    -1,    -1,    19,    20,    -1,    -1,   132,
+      -1,    -1,    -1,    -1,    -1,   138,   139,    -1,    -1,    33,
+      34,   144,    -1,    -1,    -1,    39,    40,    41,    42,    43,
+     153,   154,    -1,   156,   157,    -1,    -1,   160,   161,   162,
+      54,    55,    56,    57,    58,    59,    60,    -1,    62,    63,
+      64,    -1,    -1,    67,    68,    69,    -1,    71,    72,    73,
+      74,    75,    -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,
+      -1,   125,    -1,    -1,    19,    20,    -1,    -1,   132,    -1,
+      -1,    -1,    -1,    -1,   138,   139,    -1,    -1,    33,    34,
+     144,    -1,    -1,    -1,    39,    40,    41,    42,    43,   153,
+     154,    -1,   156,   157,    -1,    -1,   160,   161,   162,    54,
+      55,    56,    57,    58,    59,    60,    -1,    62,    63,    64,
+      -1,    -1,    67,    68,    69,    -1,    71,    72,    73,    74,
+      75,    -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,
+     125,    -1,    -1,    19,    20,    -1,    -1,   132,    -1,    -1,
+      -1,    -1,    -1,   138,   139,    -1,    -1,    33,    34,   144,
+      -1,    -1,    -1,    39,    40,    41,    42,    43,   153,   154,
+      -1,   156,   157,    -1,    -1,   160,   161,   162,    54,    55,
+      56,    57,    58,    59,    60,    -1,    62,    63,    64,    -1,
+      -1,    67,    68,    69,    -1,    71,    72,    73,    74,    75,
+      -1,    77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    11,    -1,    -1,    -1,    -1,   125,
+      -1,    -1,    19,    20,    -1,    -1,   132,    -1,    -1,    -1,
+      -1,    -1,   138,   139,    -1,    -1,    33,    34,   144,    -1,
+      -1,    -1,    39,    40,    41,    42,    43,   153,   154,    -1,
+     156,   157,    -1,    -1,   160,   161,   162,    54,    55,    56,
+      57,    58,    59,    60,    -1,    62,    63,    64,    -1,    -1,
+      67,    68,    69,    -1,    71,    72,    73,    74,    75,    -1,
+      77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   125,    -1,
+      -1,    -1,    -1,    -1,    -1,   132,    -1,    -1,    -1,    -1,
+      -1,   138,   139,    -1,    -1,    -1,    -1,   144,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   153,   154,    -1,   156,
+     157,    -1,    -1,   160,   161,   162,    19,    20,    21,    -1,
+      23,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      33,    34,    -1,    -1,    -1,    -1,    39,    40,    41,    42,
+      43,    -1,    -1,    46,    47,    48,    49,    50,    -1,    52,
+      53,    54,    55,    56,    57,    58,    59,    60,    -1,    62,
+      63,    64,    -1,    -1,    67,    68,    69,    -1,    71,    72,
+      73,    74,    75,    -1,    77,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   132,
+      -1,    -1,    -1,    -1,    -1,   138,   139,    -1,    -1,    -1,
+      -1,   144,    -1,    -1,    -1,    -1,    19,    20,    21,    -1,
+     153,   154,    -1,   156,   157,    -1,    -1,   160,   161,   162,
+      33,    34,    -1,    -1,    -1,    -1,    39,    40,    41,    42,
+      43,    -1,    -1,    46,    47,    48,    49,    50,    -1,    52,
+      53,    54,    55,    56,    57,    58,    59,    60,    -1,    62,
+      63,    64,    19,    20,    67,    68,    69,    -1,    71,    72,
+      73,    74,    75,    -1,    77,    -1,    33,    34,    -1,    -1,
+      -1,    -1,    39,    40,    41,    42,    43,    -1,    -1,    46,
+      47,    48,    49,    50,    -1,    52,    53,    54,    55,    56,
+      57,    58,    59,    60,    -1,    62,    63,    64,    -1,    -1,
+      67,    68,    69,    -1,    71,    72,    73,    74,    75,    -1,
+      77,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   132,
+      -1,    -1,    -1,    -1,    -1,   138,   139,    -1,    -1,    -1,
+      -1,   144,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+     153,   154,    -1,   156,   157,    -1,    -1,   160,   161,   162,
+      -1,    -1,    -1,    -1,    -1,    -1,    25,    -1,    -1,    28,
+      -1,    30,    -1,    32,    -1,   132,    35,    -1,    -1,    -1,
+      -1,   138,   139,    -1,    -1,    -1,    45,   144,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,   153,   154,    -1,   156,
+     157,    -1,    61,   160,   161,   162,    65,    66,    -1,    -1,
+      -1,    70,    -1,    -1,    -1,    -1,    -1,    76,    -1,    78,
+      79,    -1,    81,    -1,    -1,    -1,    -1,    86,    87,    88,
+      89,    90,    -1,    92,    93,    -1,    -1,    96,    97,    98,
+      99,   100,   101,   102,   103,   104,   105,   106,    -1,   108,
+      -1,   110,   111,    -1,    -1,   114,   115,   116,    -1,   118,
+      -1,   120,    -1,    -1,   123,   124,    -1,    -1,   127,   128,
+     129,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   137,    -1,
+      -1,    -1,   141,   142,   143,   144,   145,   146,   147,   148,
+     149,   150,   151,   152,    -1,    -1,   155,    -1,    -1,   158,
+     159,   160,   161,    25,    -1,    -1,    28,   166,    30,    -1,
+      32,    -1,    -1,    35,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    45,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    61,
+      -1,    -1,    -1,    65,    66,    -1,    -1,    -1,    70,    -1,
+      -1,    -1,    -1,    -1,    76,    -1,    78,    79,    -1,    81,
+      -1,    -1,    -1,    -1,    86,    87,    88,    89,    90,    -1,
+      92,    93,    -1,    -1,    96,    97,    98,    99,   100,   101,
+     102,   103,   104,   105,   106,    -1,   108,    -1,   110,   111,
+      -1,    -1,   114,   115,   116,    -1,   118,    -1,   120,    -1,
+      -1,   123,   124,    -1,    -1,   127,   128,   129,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,   137,    -1,    -1,    -1,   141,
+     142,   143,   144,   145,   146,   147,   148,   149,   150,   151,
+     152,    32,    -1,   155,    35,    -1,   158,   159,   160,   161,
+      -1,    -1,    -1,    -1,    45,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     131,    -1,     5,    -1,    -1,    -1,    -1,    -1,    -1,    12,
-      -1,   142,   143,    -1,    -1,    -1,    -1,   148,    21,    22,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,   159,    -1,
-      -1,   162,   163,   164,   165,    -1,    39,    40,   169,    -1,
-      -1,    44,    45,    46,    47,   176,    -1,    -1,   179,    -1,
-      -1,    -1,    -1,    56,    57,    58,    59,    60,    61,    62,
-      -1,    64,    65,    66,    -1,    -1,    69,    70,    71,    -1,
-      73,    74,    75,    76,    77,    -1,    79,    -1,    -1,    -1,
+      61,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    76,    -1,    -1,    -1,    -1,
+      81,    -1,    83,    -1,    -1,    86,    87,    88,    89,    90,
+      -1,    -1,    93,    -1,    -1,    96,    97,    98,    99,   100,
+     101,   102,   103,   104,   105,    -1,    -1,    32,    -1,    -1,
+      35,    -1,    -1,    -1,   115,    -1,    -1,    -1,    -1,   120,
+      45,    -1,    -1,    -1,    -1,    -1,   127,    -1,   129,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    61,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,   148,   149,   150,
+     151,    76,    -1,    -1,    -1,    -1,    81,    -1,    -1,   160,
+     161,    86,    87,    88,    89,    90,    -1,    -1,    93,    -1,
+      -1,    96,    97,    98,    99,   100,   101,   102,   103,   104,
+     105,    -1,    -1,    -1,    -1,    -1,    35,    -1,    -1,    -1,
+     115,    -1,    -1,    -1,    -1,   120,    -1,    -1,    -1,    -1,
+      -1,    -1,   127,    -1,   129,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    61,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,   148,   149,   150,   151,    76,    -1,    -1,
+      -1,    -1,    81,    82,    -1,   160,   161,    86,    87,    88,
+      -1,    90,    -1,    -1,    93,    -1,    -1,    96,    97,    98,
+      99,   100,   101,   102,   103,   104,   105,    -1,    -1,    -1,
+      -1,    -1,    35,    -1,    -1,    -1,   115,    -1,    -1,    -1,
+      -1,   120,    -1,    -1,    -1,    -1,    -1,    -1,   127,    -1,
+     129,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    61,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   148,
+     149,   150,   151,    76,    -1,    -1,    -1,    -1,    81,    -1,
+      -1,   160,   161,    86,    87,    88,    -1,    90,    -1,    -1,
+      93,    -1,    -1,    96,    97,    98,    99,   100,   101,   102,
+     103,   104,   105,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,   115,    -1,    -1,    -1,    -1,   120,    -1,    -1,
+      -1,    -1,    -1,    -1,   127,    -1,   129,    -1,    -1,    -1,
       -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    12,    -1,   142,
-     143,    -1,    -1,    -1,    -1,   148,    21,    22,    23,    -1,
-      25,    -1,    -1,    -1,    -1,   158,   159,    -1,    -1,   162,
-     163,   164,   165,    -1,    39,    40,   169,    -1,    -1,    44,
-      45,    46,    47,   176,    -1,    -1,   179,    -1,    -1,    -1,
-      -1,    56,    57,    58,    59,    60,    61,    62,    -1,    64,
-      65,    66,    -1,    -1,    69,    70,    71,    -1,    73,    74,
-      75,    76,    77,    -1,    79,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    12,    -1,   142,   143,    -1,
-      -1,    -1,    -1,   148,    21,    22,    23,    -1,    -1,    -1,
-      -1,    -1,    -1,   158,   159,    -1,    -1,   162,   163,   164,
-     165,    -1,    39,    40,   169,    -1,    -1,    44,    45,    46,
-      47,   176,    -1,    -1,   179,    -1,    -1,    -1,    -1,    56,
-      57,    58,    59,    60,    61,    62,    -1,    64,    65,    66,
-      -1,    -1,    69,    70,    71,    -1,    73,    74,    75,    76,
-      77,    -1,    79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,   131,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    12,    -1,   142,   143,    -1,    -1,    -1,
-      -1,   148,    21,    22,    23,    -1,    -1,    -1,    -1,    -1,
-      -1,   158,   159,    -1,    -1,   162,   163,   164,   165,    -1,
-      39,    40,   169,    -1,    -1,    44,    45,    46,    47,   176,
-      -1,    -1,   179,    -1,    -1,    -1,    -1,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   131,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    12,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,
-      21,    22,    23,    -1,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    -1,    39,    40,
-     169,    -1,    -1,    44,    45,    46,    47,   176,    -1,    -1,
-     179,    -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,
-      61,    62,    -1,    64,    65,    66,    -1,    -1,    69,    70,
-      71,    -1,    73,    74,    75,    76,    77,    -1,    79,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     131,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    12,
-      -1,   142,   143,    -1,    -1,    -1,    -1,   148,    21,    22,
-      23,    -1,    -1,    -1,    -1,    -1,    -1,   158,   159,    -1,
-      -1,   162,   163,   164,   165,    -1,    39,    40,   169,    -1,
-      -1,    44,    45,    46,    47,   176,    -1,    -1,   179,    -1,
-      -1,    -1,    -1,    56,    57,    58,    59,    60,    61,    62,
-      -1,    64,    65,    66,    -1,    -1,    69,    70,    71,    -1,
-      73,    74,    75,    76,    77,    -1,    79,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    12,    -1,   142,
-     143,    -1,    -1,    -1,    -1,   148,    21,    22,    23,    -1,
-      -1,    -1,    -1,    -1,    -1,   158,   159,    -1,    -1,   162,
-     163,   164,   165,    -1,    39,    40,   169,    -1,    -1,    44,
-      45,    46,    47,   176,    -1,    -1,   179,    -1,    -1,    -1,
-      -1,    56,    57,    58,    59,    60,    61,    62,    -1,    64,
-      65,    66,    -1,    -1,    69,    70,    71,    -1,    73,    74,
-      75,    76,    77,    -1,    79,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    12,    -1,   142,   143,    -1,
-      -1,    -1,    -1,   148,    21,    22,    23,    -1,    -1,    -1,
-      -1,    -1,    -1,   158,   159,    -1,    -1,   162,   163,   164,
-     165,    -1,    39,    40,   169,    -1,    -1,    44,    45,    46,
-      47,   176,    -1,    -1,   179,    -1,    -1,    -1,    -1,    56,
-      57,    58,    59,    60,    61,    62,    -1,    64,    65,    66,
-      -1,    -1,    69,    70,    71,    -1,    73,    74,    75,    76,
-      77,    -1,    79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,   131,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    12,    -1,   142,   143,    -1,    -1,    -1,
-      -1,   148,    21,    22,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,   158,   159,    -1,    -1,   162,   163,   164,   165,    -1,
-      39,    40,   169,    -1,    -1,    44,    45,    46,    47,   176,
-      -1,    -1,   179,    -1,    -1,    -1,    -1,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   131,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    12,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,
-      21,    22,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    -1,    39,    40,
-     169,    -1,    -1,    44,    45,    46,    47,   176,    -1,    -1,
-     179,    -1,    -1,    -1,    -1,    56,    57,    58,    59,    60,
-      61,    62,    -1,    64,    65,    66,    -1,    -1,    69,    70,
-      71,    -1,    73,    74,    75,    76,    77,    -1,    79,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-     131,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    12,
-      -1,   142,   143,    -1,    -1,    -1,    -1,   148,    21,    22,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,   159,    -1,
-      -1,   162,   163,   164,   165,    -1,    39,    40,   169,    -1,
-      -1,    44,    45,    46,    47,   176,    -1,    -1,   179,    -1,
-      -1,    -1,    -1,    56,    57,    58,    59,    60,    61,    62,
-      -1,    64,    65,    66,    -1,    -1,    69,    70,    71,    -1,
-      73,    74,    75,    76,    77,    -1,    79,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    12,    -1,   142,
-     143,    -1,    -1,    -1,    -1,   148,    21,    22,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,   158,   159,    -1,    -1,   162,
-     163,   164,   165,    -1,    39,    40,   169,    -1,    -1,    44,
-      45,    46,    47,   176,    -1,    -1,   179,    -1,    -1,    -1,
-      -1,    56,    57,    58,    59,    60,    61,    62,    -1,    64,
-      65,    66,    -1,    -1,    69,    70,    71,    -1,    73,    74,
-      75,    76,    77,    -1,    79,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,   131,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    12,    -1,   142,   143,    -1,
-      -1,    -1,    -1,   148,    21,    22,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,   158,   159,    -1,    -1,   162,   163,   164,
-     165,    -1,    39,    40,   169,    -1,    -1,    44,    45,    46,
-      47,   176,    -1,    -1,   179,    -1,    -1,    -1,    -1,    56,
-      57,    58,    59,    60,    61,    62,    -1,    64,    65,    66,
-      -1,    -1,    69,    70,    71,    -1,    73,    74,    75,    76,
-      77,    -1,    79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,   131,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    12,    -1,   142,   143,    -1,    -1,    -1,
-      -1,   148,    21,    22,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,   158,   159,    -1,    -1,   162,   163,   164,   165,    -1,
-      39,    40,   169,    -1,    -1,    44,    45,    46,    47,   176,
-      -1,    -1,   179,    -1,    -1,    -1,    -1,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    21,    22,    23,    -1,    25,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    39,
-      40,    -1,    -1,    -1,    44,    45,    46,    47,    -1,    -1,
-      50,    51,    52,    -1,    -1,    55,    56,    57,    58,    59,
-      60,    61,    62,    -1,    64,    65,    66,    -1,    -1,    69,
-      70,    71,   131,    73,    74,    75,    76,    77,    -1,    79,
-      -1,    -1,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    -1,    -1,    -1,
-     169,    -1,    -1,    -1,    -1,    -1,    -1,   176,    -1,    -1,
-     179,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,   159,
-      -1,    -1,   162,   163,   164,   165,    21,    22,    23,   169,
-      -1,    -1,    -1,    -1,    -1,    -1,   176,    -1,    -1,   179,
-      -1,    -1,    -1,    -1,    39,    40,    -1,    -1,    -1,    44,
-      45,    46,    47,    -1,    -1,    50,    51,    52,    -1,    -1,
-      55,    56,    57,    58,    59,    60,    61,    62,    -1,    64,
-      65,    66,    21,    22,    69,    70,    71,    -1,    73,    74,
-      75,    76,    77,    -1,    79,    -1,    -1,    -1,    -1,    -1,
-      39,    40,    -1,    -1,    -1,    44,    45,    46,    47,    -1,
-      -1,    50,    51,    52,    -1,    -1,    55,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,   142,   143,    -1,
-      -1,    -1,    -1,   148,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,   158,   159,    -1,    -1,   162,   163,   164,
-     165,    -1,    -1,    -1,   169,    -1,    -1,    -1,    -1,    -1,
-      -1,   176,    -1,    29,   179,    -1,    32,    33,    34,    35,
-      -1,    -1,    38,   142,   143,    41,    42,    43,    -1,   148,
-      -1,    -1,    48,    49,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    63,    -1,    -1,
-     169,    67,    68,    -1,    -1,    -1,    72,   176,    -1,    -1,
-     179,    -1,    78,    -1,    80,    81,    -1,    83,    -1,    85,
-      86,    87,    88,    89,    -1,    91,    92,    93,    94,    95,
-      96,    97,    98,    99,   100,   101,   102,   103,   104,   105,
-     106,    -1,    -1,   109,   110,   111,    -1,   113,   114,   115,
-      -1,   117,   118,   119,    -1,    -1,   122,    -1,   124,    -1,
-      -1,   127,   128,   129,   130,    -1,    -1,   133,   134,   135,
-      -1,    -1,    -1,    -1,    -1,   141,    -1,    -1,    -1,   145,
-     146,   147,   148,   149,   150,   151,    -1,   153,   154,   155,
-     156,   157,    -1,    -1,   160,    -1,    -1,    -1,    -1,    39,
-      40,   167,   168,   169,    44,    45,    46,    47,    -1,    -1,
-     176,    -1,    -1,    -1,    -1,    -1,    56,    57,    58,    59,
-      60,    61,    62,    -1,    64,    65,    66,    -1,    -1,    69,
-      70,    71,    -1,    73,    74,    75,    76,    77,    -1,    79,
-      39,    40,    -1,    -1,    -1,    44,    45,    46,    47,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    56,    57,    58,
-      59,    60,    61,    62,    -1,    64,    65,    66,    -1,    -1,
-      69,    70,    71,    -1,    73,    74,    75,    76,    77,    -1,
-      79,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,   159,
-      -1,    -1,   162,   163,   164,   165,    -1,    -1,    -1,   169,
-      -1,    -1,    -1,    -1,    -1,    -1,   176,    -1,    -1,   179,
-      -1,    -1,    -1,   142,   143,    -1,    -1,    -1,    -1,   148,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,   158,
-     159,    -1,    -1,   162,   163,   164,   165,    -1,    -1,    -1,
-     169,    -1,    -1,    -1,    -1,    -1,    -1,   176,    -1,    -1,
-     179
+      -1,    -1,    -1,    -1,    -1,   148,   149,   150,   151,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,   160,   161
 };
 
@@ -2798,103 +2739,110 @@
 static const yytype_uint16 yystos[] =
 {
-       0,   191,     0,     1,    36,    37,    53,    54,   144,   177,
-     187,   192,   197,   199,   205,   201,   198,   177,   200,    29,
-      32,    34,    38,    41,    42,    43,    48,    49,    63,    67,
-      68,    72,    78,    80,    81,    83,    85,    86,    87,    88,
-      89,    91,    92,    93,    94,    95,    96,    97,    98,    99,
-     100,   101,   102,   103,   104,   105,   106,   109,   110,   111,
-     113,   114,   115,   117,   118,   119,   122,   124,   127,   128,
-     129,   130,   133,   134,   135,   141,   145,   146,   147,   148,
-     149,   150,   151,   153,   154,   155,   156,   157,   160,   167,
-     168,   169,   176,   193,   194,   195,   202,   203,   206,   212,
-     224,   225,   228,   229,   234,   235,   237,   238,   239,   240,
-     241,   243,   244,   251,   253,   257,   258,   261,   262,   263,
-     298,   308,   309,   315,   316,   317,   318,   319,   321,   326,
-     327,   328,   330,   331,   333,   336,   337,   340,   341,   349,
-     351,   352,   365,   372,   201,   205,   169,   204,   179,    12,
-      21,    22,    39,    40,    44,    45,    46,    47,    56,    57,
-      58,    59,    60,    61,    62,    64,    65,    66,    69,    70,
-      71,    73,    74,    75,    76,    77,    79,   131,   142,   143,
-     148,   158,   159,   162,   163,   164,   165,   176,   179,   280,
-     281,   283,   284,   288,   290,   291,   292,   293,   298,   299,
-     300,   307,   320,   179,   187,   280,   304,   179,   217,   218,
-     179,   280,   303,     4,   187,   221,   187,   221,   304,   179,
-     169,   187,   324,   176,   179,   364,   280,   169,   325,   169,
-     324,   179,   169,   176,   179,   346,   179,   179,   221,   221,
-      20,    24,   247,   298,   179,   216,   123,   137,   127,   324,
-     324,   169,   252,    80,    81,   213,   275,   324,    27,   196,
-     198,    33,    35,   196,   158,   207,   196,   169,   179,   249,
-     250,   169,   226,   231,     3,   248,   169,   230,   247,     3,
-     236,   248,     3,   248,     3,   248,   169,   245,   246,   247,
-       3,     4,    35,   222,   223,   255,   271,   169,   176,   268,
-      23,   179,   259,    23,   179,   266,    23,     4,   329,   169,
-     310,   200,   324,   324,   324,   176,   323,   280,     5,   126,
-     189,   332,     3,   179,   334,   169,   304,   179,   345,    21,
-      22,    23,    50,    51,    52,    55,   169,   179,   281,   288,
-     299,   343,   345,   350,   353,   354,   355,   345,    84,    98,
-     105,   298,   328,   280,   280,   280,   282,   179,   179,   179,
-     282,   280,   282,   179,   179,   179,   179,   179,   179,   179,
-     179,   179,   179,   179,   179,   280,   179,   179,   179,   179,
-     179,   179,   280,   281,   283,   307,   360,   361,   362,   179,
-     280,   283,     5,     7,     8,     9,    10,    11,    13,    14,
-      15,    16,    17,    18,    21,    22,    23,    24,    25,   185,
-     186,   285,   280,   189,   179,   302,   179,   179,   169,   158,
-     301,   302,     3,     4,   180,   280,   219,   298,     3,   280,
-       4,   169,   242,   242,   280,   280,   180,   288,   292,   298,
-     330,   366,   367,   368,   176,   283,   298,   298,   367,   369,
-     298,   371,   242,    40,    44,    45,    46,    47,    56,    57,
-      58,    59,    60,    61,    62,    64,    65,    66,    69,    70,
-      71,    74,    75,    76,    77,    79,   169,   214,   215,   169,
-     298,   220,   280,     3,     3,   221,   194,   200,   204,   204,
-     196,     5,   249,     3,    24,   179,   187,   248,     3,    24,
-     230,   247,   179,   276,   230,   298,   247,   169,   169,   247,
-     276,     3,   245,    29,    82,   109,   111,   112,   113,   116,
-     117,   119,   120,   272,   273,   275,     4,   204,     3,   256,
-     254,     5,    23,   269,   280,   180,   176,   179,   169,   260,
-     269,   179,   267,   280,   268,   176,   276,     3,   205,   248,
-     298,   322,   373,   280,   280,   298,   176,    23,   280,   335,
-     338,   339,    23,    25,   179,   298,   347,   348,   353,   354,
-     280,   280,   280,   280,     5,   353,   179,   281,   288,   299,
-     342,   356,   357,   358,     3,   344,    20,    23,    24,    25,
-     355,   353,   360,   179,   179,   180,     3,   180,   282,   282,
-     280,   180,   180,   180,   280,   280,   280,   280,   280,   280,
-     280,   280,   280,   280,   280,   280,   180,   282,   282,   282,
-     282,   282,   280,   283,   361,   362,     3,   132,     3,     3,
-     282,   180,     3,     5,   280,   287,   280,   280,   280,   280,
-     280,   280,   280,   280,   280,   280,   280,   280,   280,   280,
-       5,    24,   280,   286,   280,     5,   280,     5,   280,   288,
-     303,   289,   294,   294,   280,   280,   180,     3,   180,   276,
-     218,   180,     3,   180,     3,   179,     3,   370,   180,   180,
-     180,     3,   370,     3,   180,     3,    24,     3,   180,   179,
-     169,   324,   179,   208,   208,   280,   180,   250,   227,   232,
-     233,   284,   280,   169,   169,   231,   227,   248,     4,    23,
-     277,   278,   279,   280,   248,   276,   276,   248,   246,   276,
-     179,     3,     4,   208,   254,   169,   269,   260,     5,   269,
-     180,     3,   270,    23,   180,   276,    31,   169,   311,   312,
-       5,   329,   364,   180,     3,   353,    23,    25,   179,   280,
-       3,   180,   180,   280,   180,   356,   285,   359,   359,     3,
-     359,   356,   353,   353,   353,   353,   353,   366,   369,   304,
-     280,   180,   180,   180,   180,   180,   180,   180,   180,   180,
-     180,   180,   180,   180,   180,   180,   180,   180,   180,   180,
-     180,   180,     3,     3,     3,   280,   362,   280,   362,   280,
-     362,   180,   283,   280,   280,   280,   280,   280,     4,     4,
-     280,   295,   296,   297,   180,   180,   298,   169,    84,   280,
-     295,   125,   367,   180,   367,   180,   298,   214,   280,   220,
-      23,   169,   180,   210,   211,    30,    24,     3,    21,    22,
-      23,   188,   299,   180,    24,    24,   230,   280,     3,   180,
-       4,   298,    23,   264,   264,   245,   138,   139,   140,   274,
-     273,     4,   169,   276,   180,   269,   270,   169,   180,     4,
-     126,     3,   280,   276,   339,   180,   280,   297,   189,   276,
-     348,   353,     3,   180,   285,   358,   370,   370,   169,   363,
-     363,   363,   180,   303,     4,   280,     4,     3,   302,   276,
-     180,   180,     5,   180,     3,   180,   179,   209,   227,   232,
-     232,   232,   232,   227,   278,   279,   280,   179,   265,   280,
-     180,   276,   264,   270,   269,   169,   187,   313,   314,   169,
-     312,     3,   276,   180,   330,   363,   359,   180,   180,     5,
-     180,   180,   180,   180,   280,     4,   280,   296,     3,   298,
-     211,   180,   210,    24,    23,   264,   305,   306,   126,     3,
-     280,   180,   280,   280,     4,   280,   180,   180,   305,     5,
-     126,   169,   314,     3,     3,   280,   280,   280,   280,   280,
-       3,   280
+       0,   170,     0,     1,    24,    25,    28,    30,    32,    35,
+      45,    61,    65,    66,    70,    76,    78,    79,    81,    86,
+      87,    88,    89,    90,    92,    93,    96,    97,    98,    99,
+     100,   101,   102,   103,   104,   105,   106,   108,   110,   111,
+     114,   115,   116,   118,   120,   123,   124,   127,   128,   129,
+     137,   140,   141,   142,   143,   144,   145,   146,   147,   148,
+     149,   150,   151,   152,   155,   158,   159,   160,   161,   166,
+     171,   172,   173,   174,   176,   178,   186,   198,   199,   203,
+     204,   209,   210,   211,   212,   213,   215,   216,   223,   225,
+     228,   231,   232,   267,   276,   277,   282,   283,   284,   286,
+     287,   291,   300,   301,   302,   303,   304,   310,   315,   319,
+     320,   323,   331,   332,   333,   334,   335,   338,   339,   341,
+     344,   345,   348,   357,   359,   369,   153,   181,   160,   180,
+     162,   162,    11,    19,    20,    33,    34,    39,    40,    41,
+      42,    43,    54,    55,    56,    57,    58,    59,    60,    62,
+      63,    64,    67,    68,    69,    71,    72,    73,    74,    75,
+      77,   125,   132,   138,   139,   144,   153,   154,   156,   157,
+     160,   161,   162,   166,   249,   250,   252,   253,   257,   259,
+     260,   261,   262,   267,   268,   269,   273,   275,   162,   191,
+     192,   162,   249,   272,   131,   166,   195,   166,   195,   273,
+     161,   162,   162,     3,   161,   179,   220,   305,   160,   160,
+     166,   336,   162,   162,   352,   160,   161,   162,   353,   162,
+     162,   195,   195,    18,    22,   219,   267,   162,   190,   119,
+     130,   123,   160,   224,   173,    78,    79,   187,   244,   133,
+     160,   161,   237,   336,   160,   162,   200,   201,   206,     4,
+     175,    24,   140,   166,    24,    29,    31,   175,   175,   160,
+     162,   221,   222,   166,     3,   220,   160,   205,   219,     3,
+     220,   220,     3,   220,   160,   217,   218,   219,     3,    31,
+     131,   196,   197,   226,   240,    21,   162,   229,    21,   162,
+     235,   337,   160,   172,   172,   172,   172,   336,   336,   336,
+       5,   122,   168,   340,     3,   162,   342,   101,   160,   273,
+     352,    19,    20,    21,    46,    47,    48,    49,    50,    52,
+      53,   160,   162,   250,   257,   268,   350,   352,   358,   360,
+     361,   362,   175,   249,   294,   249,   249,   249,   251,   162,
+     162,   162,   251,   249,   251,   162,   162,   162,   162,   162,
+     162,   162,   162,   162,   162,   162,   162,   249,   162,   251,
+     162,   162,   162,   162,   249,   250,   252,   275,   366,   367,
+     162,   249,   252,     5,     6,     7,     8,     9,    10,    12,
+      13,    14,    15,    16,    17,    19,    20,    21,    22,    23,
+     164,   165,   254,   249,   168,   162,   271,   162,   162,   160,
+     153,   270,   271,   193,   267,     3,   249,   133,   160,   214,
+     214,   249,   249,   161,   305,    94,    95,   267,   306,   257,
+     370,   371,    21,    23,   162,   267,   354,   355,   360,   361,
+     366,   161,   252,   267,   371,   372,   267,   374,   214,    34,
+      39,    40,    42,    43,    54,    55,    56,    57,    58,    59,
+      60,    62,    63,    64,    67,    68,    69,    72,    73,    74,
+      75,    77,   160,   188,   189,   160,   267,   194,   249,     3,
+       3,   195,     5,    21,   238,   249,   163,    22,   162,   257,
+     220,     3,    22,    45,    88,    89,   175,   166,   174,   180,
+     180,     5,   221,     3,   205,   219,   162,   245,   205,   267,
+     219,   160,   160,   219,   245,     3,   217,    25,    80,   106,
+     108,   109,   110,   113,   114,   116,   117,   241,   242,   244,
+     180,     3,   227,   160,   161,   162,   160,   230,   238,   161,
+     162,   236,   249,   237,   245,     3,   288,   299,   307,   299,
+      44,   321,   322,   324,   249,   249,   356,   161,    21,   249,
+     343,   346,   347,   249,   249,   249,   249,   249,   249,   249,
+       5,   360,   162,   250,   257,   268,   349,   363,   364,     3,
+     351,    18,    21,    22,    23,   362,   360,   163,   163,     3,
+     163,   251,   251,   249,   163,   163,   163,   249,   249,   249,
+     249,   249,   249,   249,   249,   249,   249,   249,   249,   163,
+     251,   163,   251,   251,   251,   252,   366,   367,     3,     3,
+     126,     3,   251,   163,     3,     5,   249,   256,   249,   249,
+     249,   249,   249,   249,   249,   249,   249,   249,   249,   249,
+     249,   249,     5,    22,   249,   255,   249,     5,   249,     5,
+     249,   356,   272,   258,   263,   263,     3,   163,   245,   192,
+     163,     3,     3,   163,   162,   298,     5,     3,   373,   360,
+      21,    23,   162,   249,     3,   163,   163,   163,   163,     3,
+     373,     3,   163,     3,    22,     3,   163,   162,   160,   336,
+     238,   202,   207,   208,   253,   249,     3,   201,   160,   206,
+     202,   162,   162,   179,   305,   162,   182,   182,   249,   163,
+     222,   220,     4,    21,   246,   247,   248,   249,   220,   245,
+     245,   220,   218,   245,   162,     3,   131,   182,   160,   245,
+     230,     5,   238,   163,     3,   239,    21,   163,   245,    27,
+     160,   278,   279,   249,   285,   286,   287,   289,   292,   293,
+     282,    91,   115,   308,   309,   330,    83,   311,   312,   316,
+     112,   162,   326,   107,   322,   325,   172,   267,   161,   163,
+       3,   249,   163,   363,   254,   365,   365,   365,     3,   363,
+     360,   360,   360,   360,   360,   293,   249,   163,   163,   163,
+     163,   163,   163,   163,   163,   163,   163,   163,   163,   163,
+     163,   163,   163,   163,   163,   163,     3,     3,     3,   249,
+     367,   249,   367,   249,   367,   163,   252,   249,   249,   249,
+     249,   249,   257,     4,     4,   249,   264,   265,   266,   163,
+     163,   267,   133,   160,   249,    35,    82,    88,   284,   249,
+     249,   121,   371,   163,   249,   266,   168,   245,   355,   371,
+     163,   267,   188,   249,   194,    22,     3,    19,    20,    21,
+     167,   268,   163,   160,   368,    22,   249,   249,   305,    21,
+     160,   163,   184,   185,    26,   177,   205,   249,     3,   163,
+       4,   267,    21,   233,   233,   217,   134,   135,   136,   243,
+     242,   245,   233,   163,   238,   239,   160,   163,     4,   122,
+       3,    36,   290,   295,   172,   172,   160,   162,    84,   312,
+     313,   314,   317,   172,     4,   249,   327,   328,   329,   160,
+     160,   299,   337,   347,     3,   163,   254,   364,   160,   368,
+     368,   368,   163,   272,     4,   249,     4,     3,   271,   245,
+     163,   162,   162,   163,     3,     5,   163,   356,   163,   202,
+     207,   207,   207,   207,     5,   163,   163,   163,     3,   163,
+     162,   183,   247,   248,   249,   162,   234,   249,   163,   233,
+       5,   122,   274,   239,   238,   160,   166,   280,   281,   160,
+     279,   294,    37,    38,   296,   297,   172,   249,   160,    85,
+     312,   318,   172,   299,   329,     3,   163,     4,   245,   368,
+     365,   163,   163,   163,   163,   249,     4,   249,   265,     3,
+     294,   249,   249,   257,   338,   249,    22,    82,   185,   163,
+     184,    21,   274,   249,   249,   122,     3,   163,   160,   160,
+     172,   288,   163,   160,   299,   328,   329,   245,   163,   249,
+       4,   249,   163,   163,     3,     3,   202,   163,   163,   160,
+     281,   160,   288,    82,   249,   249,   249,    22,   160,     3,
+     249
 };
 
@@ -2911,22 +2859,31 @@
 /* Like YYERROR except do call yyerror.  This remains here temporarily
    to ease the transition to the new meaning of YYERROR, for GCC.
-   Once GCC version 2 has supplanted version 1, this can go.  */
+   Once GCC version 2 has supplanted version 1, this can go.  However,
+   YYFAIL appears to be in use.  Nevertheless, it is formally deprecated
+   in Bison 2.4.2's NEWS entry, where a plan to phase it out is
+   discussed.  */
 
 #define YYFAIL		goto yyerrlab
+#if defined YYFAIL
+  /* This is here to suppress warnings from the GCC cpp's
+     -Wunused-macros.  Normally we don't worry about that warning, but
+     some users do, and we want to make it easy for users to remove
+     YYFAIL uses, which will produce warnings from Bison 2.5.  */
+#endif
 
 #define YYRECOVERING()  (!!yyerrstatus)
 
-#define YYBACKUP(Token, Value)					\
-do								\
-  if (yychar == YYEMPTY && yylen == 1)				\
-    {								\
-      yychar = (Token);						\
-      yylval = (Value);						\
-      yytoken = YYTRANSLATE (yychar);				\
-      YYPOPSTACK (1);						\
-      goto yybackup;						\
-    }								\
-  else								\
-    {								\
+#define YYBACKUP(Token, Value)                                  \
+do                                                              \
+  if (yychar == YYEMPTY)                                        \
+    {                                                           \
+      yychar = (Token);                                         \
+      yylval = (Value);                                         \
+      YYPOPSTACK (yylen);                                       \
+      yystate = *yyssp;                                         \
+      goto yybackup;                                            \
+    }                                                           \
+  else                                                          \
+    {                                                           \
       yyerror (YY_("syntax error: cannot back up")); \
       YYERROR;							\
@@ -2934,53 +2891,16 @@
 while (YYID (0))
 
-
+/* Error token number */
 #define YYTERROR	1
 #define YYERRCODE	256
 
 
-/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
-   If N is 0, then set CURRENT to the empty location which ends
-   the previous symbol: RHS[0] (always defined).  */
-
-#define YYRHSLOC(Rhs, K) ((Rhs)[K])
-#ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N)				\
-    do									\
-      if (YYID (N))                                                    \
-	{								\
-	  (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;	\
-	  (Current).first_column = YYRHSLOC (Rhs, 1).first_column;	\
-	  (Current).last_line    = YYRHSLOC (Rhs, N).last_line;		\
-	  (Current).last_column  = YYRHSLOC (Rhs, N).last_column;	\
-	}								\
-      else								\
-	{								\
-	  (Current).first_line   = (Current).last_line   =		\
-	    YYRHSLOC (Rhs, 0).last_line;				\
-	  (Current).first_column = (Current).last_column =		\
-	    YYRHSLOC (Rhs, 0).last_column;				\
-	}								\
-    while (YYID (0))
+/* This macro is provided for backward compatibility. */
+#ifndef YY_LOCATION_PRINT
+# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
 #endif
 
 
-/* YY_LOCATION_PRINT -- Print the location on the stream.
-   This macro was not mandated originally: define only if we know
-   we won't break user code: when these are the locations we know.  */
-
-#ifndef YY_LOCATION_PRINT
-# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
-#  define YY_LOCATION_PRINT(File, Loc)			\
-     fprintf (File, "%d.%d-%d.%d",			\
-	      (Loc).first_line, (Loc).first_column,	\
-	      (Loc).last_line,  (Loc).last_column)
-# else
-#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
-# endif
-#endif
-
-
 /* YYLEX -- calling `yylex' with the right arguments.  */
-
 #ifdef YYLEX_PARAM
 # define YYLEX yylex (YYLEX_PARAM)
@@ -3032,4 +2952,6 @@
 #endif
 {
+  FILE *yyo = yyoutput;
+  YYUSE (yyo);
   if (!yyvaluep)
     return;
@@ -3043,5 +2965,5 @@
     {
       default:
-	break;
+        break;
     }
 }
@@ -3081,15 +3003,18 @@
      || defined __cplusplus || defined _MSC_VER)
 static void
-yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
+yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
 #else
 static void
-yy_stack_print (bottom, top)
-    yytype_int16 *bottom;
-    yytype_int16 *top;
+yy_stack_print (yybottom, yytop)
+    yytype_int16 *yybottom;
+    yytype_int16 *yytop;
 #endif
 {
   YYFPRINTF (stderr, "Stack now");
-  for (; bottom <= top; ++bottom)
-    YYFPRINTF (stderr, " %d", *bottom);
+  for (; yybottom <= yytop; yybottom++)
+    {
+      int yybot = *yybottom;
+      YYFPRINTF (stderr, " %d", yybot);
+    }
   YYFPRINTF (stderr, "\n");
 }
@@ -3125,9 +3050,9 @@
   for (yyi = 0; yyi < yynrhs; yyi++)
     {
-      fprintf (stderr, "   $%d = ", yyi + 1);
+      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
       yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
 		       &(yyvsp[(yyi + 1) - (yynrhs)])
 		       		       );
-      fprintf (stderr, "\n");
+      YYFPRINTF (stderr, "\n");
     }
 }
@@ -3165,6 +3090,4 @@
 # define YYMAXDEPTH 10000
 #endif
-
-
 
 
@@ -3270,114 +3193,143 @@
 # endif
 
-/* Copy into YYRESULT an error message about the unexpected token
-   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
-   including the terminating null byte.  If YYRESULT is null, do not
-   copy anything; just return the number of bytes that would be
-   copied.  As a special case, return 0 if an ordinary "syntax error"
-   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
-   size calculation.  */
-static YYSIZE_T
-yysyntax_error (char *yyresult, int yystate, int yychar)
+/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
+   about the unexpected token YYTOKEN for the state stack whose top is
+   YYSSP.
+
+   Return 0 if *YYMSG was successfully written.  Return 1 if *YYMSG is
+   not large enough to hold the message.  In that case, also set
+   *YYMSG_ALLOC to the required number of bytes.  Return 2 if the
+   required number of bytes is too large to store.  */
+static int
+yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
+                yytype_int16 *yyssp, int yytoken)
 {
-  int yyn = yypact[yystate];
-
-  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
-    return 0;
-  else
+  YYSIZE_T yysize0 = yytnamerr (YY_NULL, yytname[yytoken]);
+  YYSIZE_T yysize = yysize0;
+  enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+  /* Internationalized format string. */
+  const char *yyformat = YY_NULL;
+  /* Arguments of yyformat. */
+  char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+  /* Number of reported tokens (one for the "unexpected", one per
+     "expected"). */
+  int yycount = 0;
+
+  /* There are many possibilities here to consider:
+     - Assume YYFAIL is not used.  It's too flawed to consider.  See
+       <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html>
+       for details.  YYERROR is fine as it does not invoke this
+       function.
+     - If this state is a consistent state with a default action, then
+       the only way this function was invoked is if the default action
+       is an error action.  In that case, don't check for expected
+       tokens because there are none.
+     - The only way there can be no lookahead present (in yychar) is if
+       this state is a consistent state with a default action.  Thus,
+       detecting the absence of a lookahead is sufficient to determine
+       that there is no unexpected or expected token to report.  In that
+       case, just report a simple "syntax error".
+     - Don't assume there isn't a lookahead just because this state is a
+       consistent state with a default action.  There might have been a
+       previous inconsistent state, consistent state with a non-default
+       action, or user semantic action that manipulated yychar.
+     - Of course, the expected token list depends on states to have
+       correct lookahead information, and it depends on the parser not
+       to perform extra reductions after fetching a lookahead from the
+       scanner and before detecting a syntax error.  Thus, state merging
+       (from LALR or IELR) and default reductions corrupt the expected
+       token list.  However, the list is correct for canonical LR with
+       one exception: it will still contain any token that will not be
+       accepted due to an error action in a later state.
+  */
+  if (yytoken != YYEMPTY)
     {
-      int yytype = YYTRANSLATE (yychar);
-      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
-      YYSIZE_T yysize = yysize0;
-      YYSIZE_T yysize1;
-      int yysize_overflow = 0;
-      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
-      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
-      int yyx;
-
-# if 0
-      /* This is so xgettext sees the translatable formats that are
-	 constructed on the fly.  */
-      YY_("syntax error, unexpected %s");
-      YY_("syntax error, unexpected %s, expecting %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
-# endif
-      char *yyfmt;
-      char const *yyf;
-      static char const yyunexpected[] = "syntax error, unexpected %s";
-      static char const yyexpecting[] = ", expecting %s";
-      static char const yyor[] = " or %s";
-      char yyformat[sizeof yyunexpected
-		    + sizeof yyexpecting - 1
-		    + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
-		       * (sizeof yyor - 1))];
-      char const *yyprefix = yyexpecting;
-
-      /* Start YYX at -YYN if negative to avoid negative indexes in
-	 YYCHECK.  */
-      int yyxbegin = yyn < 0 ? -yyn : 0;
-
-      /* Stay within bounds of both yycheck and yytname.  */
-      int yychecklim = YYLAST - yyn + 1;
-      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
-      int yycount = 1;
-
-      yyarg[0] = yytname[yytype];
-      yyfmt = yystpcpy (yyformat, yyunexpected);
-
-      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
-	if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
-	  {
-	    if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
-	      {
-		yycount = 1;
-		yysize = yysize0;
-		yyformat[sizeof yyunexpected - 1] = '\0';
-		break;
-	      }
-	    yyarg[yycount++] = yytname[yyx];
-	    yysize1 = yysize + yytnamerr (0, yytname[yyx]);
-	    yysize_overflow |= (yysize1 < yysize);
-	    yysize = yysize1;
-	    yyfmt = yystpcpy (yyfmt, yyprefix);
-	    yyprefix = yyor;
-	  }
-
-      yyf = YY_(yyformat);
-      yysize1 = yysize + yystrlen (yyf);
-      yysize_overflow |= (yysize1 < yysize);
-      yysize = yysize1;
-
-      if (yysize_overflow)
-	return YYSIZE_MAXIMUM;
-
-      if (yyresult)
-	{
-	  /* Avoid sprintf, as that infringes on the user's name space.
-	     Don't have undefined behavior even if the translation
-	     produced a string with the wrong number of "%s"s.  */
-	  char *yyp = yyresult;
-	  int yyi = 0;
-	  while ((*yyp = *yyf) != '\0')
-	    {
-	      if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
-		{
-		  yyp += yytnamerr (yyp, yyarg[yyi++]);
-		  yyf += 2;
-		}
-	      else
-		{
-		  yyp++;
-		  yyf++;
-		}
-	    }
-	}
-      return yysize;
+      int yyn = yypact[*yyssp];
+      yyarg[yycount++] = yytname[yytoken];
+      if (!yypact_value_is_default (yyn))
+        {
+          /* Start YYX at -YYN if negative to avoid negative indexes in
+             YYCHECK.  In other words, skip the first -YYN actions for
+             this state because they are default actions.  */
+          int yyxbegin = yyn < 0 ? -yyn : 0;
+          /* Stay within bounds of both yycheck and yytname.  */
+          int yychecklim = YYLAST - yyn + 1;
+          int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+          int yyx;
+
+          for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+            if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
+                && !yytable_value_is_error (yytable[yyx + yyn]))
+              {
+                if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+                  {
+                    yycount = 1;
+                    yysize = yysize0;
+                    break;
+                  }
+                yyarg[yycount++] = yytname[yyx];
+                {
+                  YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULL, yytname[yyx]);
+                  if (! (yysize <= yysize1
+                         && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+                    return 2;
+                  yysize = yysize1;
+                }
+              }
+        }
     }
+
+  switch (yycount)
+    {
+# define YYCASE_(N, S)                      \
+      case N:                               \
+        yyformat = S;                       \
+      break
+      YYCASE_(0, YY_("syntax error"));
+      YYCASE_(1, YY_("syntax error, unexpected %s"));
+      YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
+      YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
+      YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
+      YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
+# undef YYCASE_
+    }
+
+  {
+    YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
+    if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+      return 2;
+    yysize = yysize1;
+  }
+
+  if (*yymsg_alloc < yysize)
+    {
+      *yymsg_alloc = 2 * yysize;
+      if (! (yysize <= *yymsg_alloc
+             && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
+        *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
+      return 1;
+    }
+
+  /* Avoid sprintf, as that infringes on the user's name space.
+     Don't have undefined behavior even if the translation
+     produced a string with the wrong number of "%s"s.  */
+  {
+    char *yyp = *yymsg;
+    int yyi = 0;
+    while ((*yyp = *yyformat) != '\0')
+      if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
+        {
+          yyp += yytnamerr (yyp, yyarg[yyi++]);
+          yyformat += 2;
+        }
+      else
+        {
+          yyp++;
+          yyformat++;
+        }
+  }
+  return 0;
 }
 #endif /* YYERROR_VERBOSE */
-
-
 
 /*-----------------------------------------------.
@@ -3408,5 +3360,5 @@
 
       default:
-	break;
+        break;
     }
 }
@@ -3414,31 +3366,22 @@
 
 
-/* Prevent warnings from -Wmissing-prototypes.  */
-
-#ifdef YYPARSE_PARAM
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void *YYPARSE_PARAM);
-#else
-int yyparse ();
+
+/* The lookahead symbol.  */
+int yychar;
+
+
+#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END
 #endif
-#else /* ! YYPARSE_PARAM */
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void);
-#else
-int yyparse ();
+#ifndef YY_INITIAL_VALUE
+# define YY_INITIAL_VALUE(Value) /* Nothing. */
 #endif
-#endif /* ! YYPARSE_PARAM */
-
-
-
-/* The look-ahead symbol.  */
-int yychar;
-
-/* The semantic value of the look-ahead symbol.  */
-YYSTYPE yylval;
+
+/* The semantic value of the lookahead symbol.  */
+YYSTYPE yylval YY_INITIAL_VALUE(yyval_default);
 
 /* Number of syntax errors so far.  */
 int yynerrs;
-
 
 
@@ -3469,12 +3412,35 @@
 #endif
 {
-  
-  int yystate;
+    int yystate;
+    /* Number of tokens to shift before error messages enabled.  */
+    int yyerrstatus;
+
+    /* The stacks and their tools:
+       `yyss': related to states.
+       `yyvs': related to semantic values.
+
+       Refer to the stacks through separate pointers, to allow yyoverflow
+       to reallocate them elsewhere.  */
+
+    /* The state stack.  */
+    yytype_int16 yyssa[YYINITDEPTH];
+    yytype_int16 *yyss;
+    yytype_int16 *yyssp;
+
+    /* The semantic value stack.  */
+    YYSTYPE yyvsa[YYINITDEPTH];
+    YYSTYPE *yyvs;
+    YYSTYPE *yyvsp;
+
+    YYSIZE_T yystacksize;
+
   int yyn;
   int yyresult;
-  /* Number of tokens to shift before error messages enabled.  */
-  int yyerrstatus;
-  /* Look-ahead token as an internal (translated) token number.  */
+  /* Lookahead token as an internal (translated) token number.  */
   int yytoken = 0;
+  /* The variables used to return semantic value and location from the
+     action routines.  */
+  YYSTYPE yyval;
+
 #if YYERROR_VERBOSE
   /* Buffer for error messages, and its allocated size.  */
@@ -3484,32 +3450,5 @@
 #endif
 
-  /* Three stacks and their tools:
-     `yyss': related to states,
-     `yyvs': related to semantic values,
-     `yyls': related to locations.
-
-     Refer to the stacks thru separate pointers, to allow yyoverflow
-     to reallocate them elsewhere.  */
-
-  /* The state stack.  */
-  yytype_int16 yyssa[YYINITDEPTH];
-  yytype_int16 *yyss = yyssa;
-  yytype_int16 *yyssp;
-
-  /* The semantic value stack.  */
-  YYSTYPE yyvsa[YYINITDEPTH];
-  YYSTYPE *yyvs = yyvsa;
-  YYSTYPE *yyvsp;
-
-
-
 #define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
-
-  YYSIZE_T yystacksize = YYINITDEPTH;
-
-  /* The variables used to return semantic value and location from the
-     action routines.  */
-  YYSTYPE yyval;
-
 
   /* The number of symbols on the RHS of the reduced rule.
@@ -3517,4 +3456,8 @@
   int yylen = 0;
 
+  yyssp = yyss = yyssa;
+  yyvsp = yyvs = yyvsa;
+  yystacksize = YYINITDEPTH;
+
   YYDPRINTF ((stderr, "Starting parse\n"));
 
@@ -3522,14 +3465,5 @@
   yyerrstatus = 0;
   yynerrs = 0;
-  yychar = YYEMPTY;		/* Cause a token to be read.  */
-
-  /* Initialize stack pointers.
-     Waste one element of value and location stack
-     so that they stay on the same level as the state stack.
-     The wasted elements are never initialized.  */
-
-  yyssp = yyss;
-  yyvsp = yyvs;
-
+  yychar = YYEMPTY; /* Cause a token to be read.  */
   goto yysetstate;
 
@@ -3558,5 +3492,4 @@
 	yytype_int16 *yyss1 = yyss;
 
-
 	/* Each stack pointer address is followed by the size of the
 	   data in use in that stack, in bytes.  This used to be a
@@ -3566,5 +3499,4 @@
 		    &yyss1, yysize * sizeof (*yyssp),
 		    &yyvs1, yysize * sizeof (*yyvsp),
-
 		    &yystacksize);
 
@@ -3589,7 +3521,6 @@
 	if (! yyptr)
 	  goto yyexhaustedlab;
-	YYSTACK_RELOCATE (yyss);
-	YYSTACK_RELOCATE (yyvs);
-
+	YYSTACK_RELOCATE (yyss_alloc, yyss);
+	YYSTACK_RELOCATE (yyvs_alloc, yyvs);
 #  undef YYSTACK_RELOCATE
 	if (yyss1 != yyssa)
@@ -3602,5 +3533,4 @@
       yyvsp = yyvs + yysize - 1;
 
-
       YYDPRINTF ((stderr, "Stack size increased to %lu\n",
 		  (unsigned long int) yystacksize));
@@ -3611,4 +3541,7 @@
 
   YYDPRINTF ((stderr, "Entering state %d\n", yystate));
+
+  if (yystate == YYFINAL)
+    YYACCEPT;
 
   goto yybackup;
@@ -3620,14 +3553,14 @@
 
   /* Do appropriate processing given the current state.  Read a
-     look-ahead token if we need one and don't already have one.  */
-
-  /* First try to decide what to do without reference to look-ahead token.  */
+     lookahead token if we need one and don't already have one.  */
+
+  /* First try to decide what to do without reference to lookahead token.  */
   yyn = yypact[yystate];
-  if (yyn == YYPACT_NINF)
+  if (yypact_value_is_default (yyn))
     goto yydefault;
 
-  /* Not known => get a look-ahead token if don't already have one.  */
-
-  /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol.  */
+  /* Not known => get a lookahead token if don't already have one.  */
+
+  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
   if (yychar == YYEMPTY)
     {
@@ -3655,12 +3588,9 @@
   if (yyn <= 0)
     {
-      if (yyn == 0 || yyn == YYTABLE_NINF)
-	goto yyerrlab;
+      if (yytable_value_is_error (yyn))
+        goto yyerrlab;
       yyn = -yyn;
       goto yyreduce;
     }
-
-  if (yyn == YYFINAL)
-    YYACCEPT;
 
   /* Count tokens shifted since error; after three, turn off error
@@ -3669,13 +3599,14 @@
     yyerrstatus--;
 
-  /* Shift the look-ahead token.  */
+  /* Shift the lookahead token.  */
   YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
 
-  /* Discard the shifted token unless it is eof.  */
-  if (yychar != YYEOF)
-    yychar = YYEMPTY;
+  /* Discard the shifted token.  */
+  yychar = YYEMPTY;
 
   yystate = yyn;
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
   *++yyvsp = yylval;
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
 
   goto yynewstate;
@@ -3713,2816 +3644,2480 @@
   switch (yyn)
     {
-        case 8:
-#line 344 "fortran.y"
-    {yyerrok;yyclearin;;}
-    break;
-
-  case 13:
-#line 352 "fortran.y"
+        case 7:
+/* Line 1807 of yacc.c  */
+#line 319 "fortran.y"
+    {yyerrok;yyclearin;}
+    break;
+
+  case 18:
+/* Line 1807 of yacc.c  */
+#line 337 "fortran.y"
     {
-                     if (inmoduledeclare == 0 )
-                     {
-                        pos_end = setposcur();
-                        RemoveWordSET_0(fortranout,pos_curinclude,
-                                              pos_end-pos_curinclude);
-                     }
-                  ;}
-    break;
-
-  case 18:
-#line 368 "fortran.y"
+            if (inmoduledeclare == 0 )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_curinclude,pos_end-pos_curinclude);
+            }
+        }
+    break;
+
+  case 20:
+/* Line 1807 of yacc.c  */
+#line 347 "fortran.y"
+    { pos_cur = setposcur(); }
+    break;
+
+  case 21:
+/* Line 1807 of yacc.c  */
+#line 350 "fortran.y"
+    { isrecursive = 0; }
+    break;
+
+  case 22:
+/* Line 1807 of yacc.c  */
+#line 351 "fortran.y"
+    { isrecursive = 1; }
+    break;
+
+  case 23:
+/* Line 1807 of yacc.c  */
+#line 354 "fortran.y"
+    { is_result_present = 0; }
+    break;
+
+  case 24:
+/* Line 1807 of yacc.c  */
+#line 355 "fortran.y"
+    { is_result_present = 1; }
+    break;
+
+  case 25:
+/* Line 1807 of yacc.c  */
+#line 359 "fortran.y"
     {
-            /* we should ignore the declaration until the keyword             */
-            /*    TOK_ENDDONOTTREAT                                           */
-            couldaddvariable = 0 ;
-            RemoveWordCUR_0(fortranout,-20,20);
-         ;}
-    break;
-
-  case 19:
-#line 375 "fortran.y"
+            insubroutinedeclare = 1;
+            if ( firstpass )
+                Add_SubroutineArgument_Var_1((yyvsp[(4) - (4)].l));
+            else
+                WriteBeginof_SubLoop();
+        }
+    break;
+
+  case 26:
+/* Line 1807 of yacc.c  */
+#line 367 "fortran.y"
     {
-             couldaddvariable = 1 ;
-             RemoveWordCUR_0(fortranout,-24,24);
-          ;}
-    break;
-
-  case 22:
-#line 382 "fortran.y"
-    {pos_cur = setposcur();;}
+            insubroutinedeclare = 1;
+            inprogramdeclare = 1;
+            /* in the second step we should write the head of       */
+            /*    the subroutine sub_loop_<subroutinename>          */
+            if ( ! firstpass )
+                WriteBeginof_SubLoop();
+        }
     break;
 
   case 27:
-#line 394 "fortran.y"
-    {if (incom !=1) {strcpy(curbuf,"");incom=0;};}
+/* Line 1807 of yacc.c  */
+#line 376 "fortran.y"
+    {
+            insubroutinedeclare = 1;
+            strcpy(DeclType, "");
+            /* we should to list of the subroutine argument the  */
+            /*    name of the function which has to be defined   */
+            if ( firstpass )
+            {
+                Add_SubroutineArgument_Var_1((yyvsp[(4) - (5)].l));
+                if ( ! is_result_present )
+                    Add_FunctionType_Var_1((yyvsp[(3) - (5)].na));
+            }
+            else
+            /* in the second step we should write the head of    */
+            /*    the subroutine sub_loop_<subroutinename>       */
+                WriteBeginof_SubLoop();
+        }
     break;
 
   case 28:
-#line 397 "fortran.y"
-    {isrecursive = 0;;}
-    break;
-
-  case 29:
-#line 399 "fortran.y"
-    {isrecursive = 1;;}
+/* Line 1807 of yacc.c  */
+#line 393 "fortran.y"
+    {
+            GlobalDeclaration = 0;
+            strcpy(curmodulename,(yyvsp[(2) - (2)].na));
+            strcpy(subroutinename,"");
+            Add_NameOfModule_1((yyvsp[(2) - (2)].na));
+            if ( inmoduledeclare == 0 )
+            {
+                /* To know if there are in the module declaration    */
+                inmoduledeclare = 1;
+                /* to know if a module has been met                  */
+                inmodulemeet = 1;
+                /* to know if we are after the keyword contains      */
+                aftercontainsdeclare = 0 ;
+            }
+        }
     break;
 
   case 31:
-#line 403 "fortran.y"
+/* Line 1807 of yacc.c  */
+#line 415 "fortran.y"
+    { strcpy((yyval.na), (yyvsp[(1) - (1)].na)); strcpy(subroutinename, (yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 32:
+/* Line 1807 of yacc.c  */
+#line 417 "fortran.y"
+    { Add_Include_1((yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 33:
+/* Line 1807 of yacc.c  */
+#line 419 "fortran.y"
+    { if ( firstpass ) (yyval.l)=NULL; }
+    break;
+
+  case 34:
+/* Line 1807 of yacc.c  */
+#line 420 "fortran.y"
+    { if ( firstpass ) (yyval.l)=NULL; }
+    break;
+
+  case 35:
+/* Line 1807 of yacc.c  */
+#line 421 "fortran.y"
+    { if ( firstpass ) (yyval.l)=(yyvsp[(2) - (3)].l); }
+    break;
+
+  case 38:
+/* Line 1807 of yacc.c  */
+#line 425 "fortran.y"
+    { if ( firstpass ) Add_SubroutineArgument_Var_1((yyvsp[(2) - (3)].l)); }
+    break;
+
+  case 39:
+/* Line 1807 of yacc.c  */
+#line 428 "fortran.y"
     {
-                      if ( couldaddvariable == 1)
-                      {
-                      /* open param file                                      */
-                      if ( firstpass == 0 )
-                      {
-                         sprintf(ligne,"%s/ParamFile%s.h",nomdir,(yyvsp[(3) - (4)].nac));
-                         paramout=fopen(ligne,"w");
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-
-                      }
-                      Add_SubroutineArgument_Var_1((yyvsp[(4) - (4)].l));
-                      if ( inmodulemeet == 1 )
-                      {
-                         insubroutinedeclare = 1;
-                         /* in the second step we should write the head of    */
-                         /*    the subroutine sub_loop_<subroutinename>       */
-                         writeheadnewsub_0(1);
-                      }
-                      else
-                      {
-                            insubroutinedeclare = 1;
-                            writeheadnewsub_0(1);
-                      }
-                      }
-                   ;}
-    break;
-
-  case 32:
-#line 431 "fortran.y"
+            if ( firstpass == 1 )
+            {
+                strcpy(nameinttypenameback,nameinttypename);
+                strcpy(nameinttypename,"");
+                curvar = createvar((yyvsp[(1) - (1)].na),NULL);
+                strcpy(nameinttypename,nameinttypenameback);
+                curlistvar = insertvar(NULL,curvar);
+                (yyval.l) = settype("",curlistvar);
+            }
+        }
+    break;
+
+  case 40:
+/* Line 1807 of yacc.c  */
+#line 440 "fortran.y"
     {
-                      /* open param file                                      */
-                      if ( firstpass == 0 )
-                      {
-                         sprintf(ligne,"%s/ParamFile%s.h",nomdir,(yyvsp[(2) - (2)].nac));
-                         paramout=fopen(ligne,"w");
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-
-                      }
-                      strcpy(subroutinename,(yyvsp[(2) - (2)].nac));
-                      /* Common case                                          */
-                      insubroutinedeclare = 1;
-                      /* in the second step we should write the head of       */
-                      /*    the subroutine sub_loop_<subroutinename>          */
-                      writeheadnewsub_0(1);
-                   ;}
-    break;
-
-  case 33:
-#line 449 "fortran.y"
+            if ( firstpass == 1 )
+            {
+                strcpy(nameinttypenameback,nameinttypename);
+                strcpy(nameinttypename,"");
+                curvar = createvar((yyvsp[(3) - (3)].na),NULL);
+                strcpy(nameinttypename,nameinttypenameback);
+                (yyval.l) = insertvar((yyvsp[(1) - (3)].l),curvar);
+            }
+        }
+    break;
+
+  case 41:
+/* Line 1807 of yacc.c  */
+#line 451 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));  }
+    break;
+
+  case 42:
+/* Line 1807 of yacc.c  */
+#line 452 "fortran.y"
+    { strcpy((yyval.na),"*"); }
+    break;
+
+  case 44:
+/* Line 1807 of yacc.c  */
+#line 455 "fortran.y"
+    { inside_type_declare = 1; }
+    break;
+
+  case 45:
+/* Line 1807 of yacc.c  */
+#line 456 "fortran.y"
+    { inside_type_declare = 0; }
+    break;
+
+  case 47:
+/* Line 1807 of yacc.c  */
+#line 459 "fortran.y"
     {
-                      /* open param file                                      */
-                      if ( firstpass == 0 )
-                      {
-                         sprintf(ligne,"%s/ParamFile%s.h",nomdir,(yyvsp[(3) - (6)].nac));
-                         paramout=fopen(ligne,"w");
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-                      }
-                      strcpy(subroutinename,(yyvsp[(3) - (6)].nac));
-                      if ( inmodulemeet == 1 )
-                      {
-                         insubroutinedeclare = 1;
-                         /* we should to list of the subroutine argument the  */
-                         /*    name of the function which has to be defined   */
-                         Add_SubroutineArgument_Var_1((yyvsp[(4) - (6)].l));
-                         strcpy(DeclType,"");
-                         /* in the second step we should write the head of    */
-                         /*    the subroutine sub_loop_<subroutinename>       */
-                         writeheadnewsub_0(2);
-                      }
-                      else
-                      {
-                            insubroutinedeclare = 1;
-                            /* we should to list of the subroutine argument   */
-                            /* name of the function which has to be defined   */
-                            Add_SubroutineArgument_Var_1((yyvsp[(4) - (6)].l));
-                            strcpy(DeclType,"");
-                            Add_FunctionType_Var_1((yyvsp[(3) - (6)].nac));
-                            writeheadnewsub_0(2);
-                      }
-                   ;}
-    break;
-
-  case 34:
-#line 482 "fortran.y"
+            if ( ! inside_type_declare )
+            {
+                if ( firstpass )
+                {
+                    if ( insubroutinedeclare )  Add_Parameter_Var_1((yyvsp[(3) - (4)].l));
+                    else                        Add_GlobalParameter_Var_1((yyvsp[(3) - (4)].l));
+                }
+                else
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out, pos_cur_decl, pos_end-pos_cur_decl);
+                }
+            }
+            VariableIsParameter =  0 ;
+        }
+    break;
+
+  case 48:
+/* Line 1807 of yacc.c  */
+#line 476 "fortran.y"
     {
-                      /* open param file                                      */
-                      if ( firstpass == 0 )
-                      {
-                         sprintf(ligne,"%s/ParamFile%s.h",nomdir,(yyvsp[(3) - (4)].nac));
-                         paramout=fopen(ligne,"w");
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-                      }
-                      strcpy(subroutinename,(yyvsp[(3) - (4)].nac));
-                      if ( inmodulemeet == 1 )
-                      {
-                         insubroutinedeclare = 1;
-                         /* we should to list of the subroutine argument the  */
-                         /*    name of the function which has to be defined   */
-                         Add_SubroutineArgument_Var_1((yyvsp[(4) - (4)].l));
-                         strcpy(DeclType,"");
-                         Add_FunctionType_Var_1((yyvsp[(3) - (4)].nac));
-                         /* in the second step we should write the head of    */
-                         /*    the subroutine sub_loop_<subroutinename>       */
-                         writeheadnewsub_0(2);
-                      }
-                      else
-                      {
-                            insubroutinedeclare = 1;
-                            /* we should to list of the subroutine argument   */
-                            /* name of the function which has to be defined   */
-                            Add_SubroutineArgument_Var_1((yyvsp[(4) - (4)].l));
-                            strcpy(DeclType,"");
-                            Add_FunctionType_Var_1((yyvsp[(3) - (4)].nac));
-                            writeheadnewsub_0(2);
-                      }
-                   ;}
-    break;
-
-  case 35:
-#line 516 "fortran.y"
+            if ( ! inside_type_declare )
+            {
+                if ( firstpass )
+                {
+                    if ( insubroutinedeclare )  Add_Parameter_Var_1((yyvsp[(2) - (2)].l));
+                    else                        Add_GlobalParameter_Var_1((yyvsp[(2) - (2)].l));
+                }
+                else
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_cur_decl,pos_end-pos_cur_decl);
+                }
+            }
+            VariableIsParameter =  0 ;
+        }
+    break;
+
+  case 50:
+/* Line 1807 of yacc.c  */
+#line 494 "fortran.y"
     {
-                      GlobalDeclaration = 0;
-                      strcpy(curmodulename,(yyvsp[(2) - (2)].nac));
-                      strcpy(subroutinename,"");
-                      Add_NameOfModule_1((yyvsp[(2) - (2)].nac));
-                      if ( inmoduledeclare == 0 )
-                      {
-                         /* To know if there are in the module declaration    */
-                         inmoduledeclare = 1;
-                         /* to know if a module has been met                  */
-                         inmodulemeet = 1;
-                         /* to know if we are after the keyword contains      */
-                         aftercontainsdeclare = 0 ;
-                      }
-                   ;}
-    break;
-
-  case 36:
-#line 533 "fortran.y"
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_cursave,pos_end-pos_cursave);
+        }
+    break;
+
+  case 52:
+/* Line 1807 of yacc.c  */
+#line 500 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));strcpy(subroutinename,(yyvsp[(1) - (1)].nac));
-                      }
-                   ;}
-    break;
-
-  case 38:
-#line 542 "fortran.y"
+            /* if the variable is a parameter we can suppose that is   */
+            /*    value is the same on each grid. It is not useless to */
+            /*    create a copy of it on each grid                     */
+            if ( ! inside_type_declare )
+            {
+                if ( firstpass )
+                {
+                    Add_Globliste_1((yyvsp[(1) - (1)].l));
+                    /* if variableparamlists has been declared in a subroutine   */
+                    if ( insubroutinedeclare )     Add_Dimension_Var_1((yyvsp[(1) - (1)].l));
+                }
+                else
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curdimension,pos_end-pos_curdimension);
+                }
+            }
+            PublicDeclare = 0;
+            PrivateDeclare = 0;
+            ExternalDeclare = 0;
+            strcpy(NamePrecision,"");
+            c_star = 0;
+            InitialValueGiven = 0 ;
+            strcpy(IntentSpec,"");
+            VariableIsParameter =  0 ;
+            Allocatabledeclare = 0 ;
+            Targetdeclare = 0 ;
+            SaveDeclare = 0;
+            pointerdeclare = 0;
+            optionaldeclare = 0 ;
+            dimsgiven=0;
+            c_selectorgiven=0;
+            strcpy(nameinttypename,"");
+            strcpy(c_selectorname,"");
+        }
+    break;
+
+  case 53:
+/* Line 1807 of yacc.c  */
+#line 537 "fortran.y"
     {
-                      pos_curinclude = setposcur()-9;
-                   ;}
-    break;
-
-  case 39:
-#line 546 "fortran.y"
+            if (firstpass == 0)
+            {
+                if ((yyvsp[(1) - (1)].lnn))
+                {
+                    removeglobfromlist(&((yyvsp[(1) - (1)].lnn)));
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_cur,pos_end-pos_cur);
+                    writelistpublic((yyvsp[(1) - (1)].lnn));
+                }
+            }
+        }
+    break;
+
+  case 62:
+/* Line 1807 of yacc.c  */
+#line 558 "fortran.y"
     {
-                      if ( couldaddvariable == 1 ) Add_Include_1((yyvsp[(1) - (1)].nac));
-                   ;}
-    break;
-
-  case 40:
-#line 550 "fortran.y"
+            /* we should remove the data declaration                */
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curdata,pos_end-pos_curdata);
+
+            if ( aftercontainsdeclare == 1  && firstpass == 0 )
+            {
+                ReWriteDataStatement_0(fortran_out);
+                pos_end = setposcur();
+            }
+        }
+    break;
+
+  case 64:
+/* Line 1807 of yacc.c  */
+#line 572 "fortran.y"
     {
-                      if ( firstpass == 1 && couldaddvariable == 1) (yyval.l)=NULL;
-                   ;}
-    break;
-
-  case 41:
-#line 553 "fortran.y"
+            PublicDeclare = 0 ;
+            PrivateDeclare = 0 ;
+        }
+    break;
+
+  case 102:
+/* Line 1807 of yacc.c  */
+#line 630 "fortran.y"
     {
-                      if ( firstpass == 1 && couldaddvariable == 1 ) (yyval.l)=NULL;
-                   ;}
-    break;
-
-  case 42:
-#line 557 "fortran.y"
+            /* if the variable is a parameter we can suppose that is*/
+            /*    value is the same on each grid. It is not useless */
+            /*    to create a copy of it on each grid               */
+            if ( ! inside_type_declare )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_cur_decl,pos_end-pos_cur_decl);
+                ReWriteDeclarationAndAddTosubroutine_01((yyvsp[(1) - (2)].l));
+                pos_cur_decl = setposcur();
+                if ( firstpass == 0 && GlobalDeclaration == 0
+                                    && insubroutinedeclare == 0 )
+                {
+                    fprintf(fortran_out,"\n#include \"Module_Declar_%s.h\"\n", curmodulename);
+                    sprintf(ligne, "Module_Declar_%s.h", curmodulename);
+                    module_declar = open_for_write(ligne);
+                    GlobalDeclaration = 1 ;
+                    pos_cur_decl = setposcur();
+                }
+                (yyval.l) = (yyvsp[(1) - (2)].l);
+
+                if ( firstpass )
+                {
+                    Add_Globliste_1((yyvsp[(1) - (2)].l));
+                    if ( insubroutinedeclare )
+                    {
+                        if ( pointerdeclare ) Add_Pointer_Var_From_List_1((yyvsp[(1) - (2)].l));
+                        Add_Parameter_Var_1((yyvsp[(1) - (2)].l));
+                    }
+                    else
+                        Add_GlobalParameter_Var_1((yyvsp[(1) - (2)].l));
+
+                    /* If there's a SAVE declaration in module's subroutines we should    */
+                    /*    remove it from the subroutines declaration and add it in the    */
+                    /*    global declarations                                             */
+                    if ( aftercontainsdeclare && SaveDeclare )
+                    {
+                        if ( inmodulemeet ) Add_SubroutineDeclarationSave_Var_1((yyvsp[(1) - (2)].l));
+                        else                Add_Save_Var_dcl_1((yyvsp[(1) - (2)].l));
+                    }
+                }
+            }
+            else
+            {
+                (yyval.l) = (listvar *) NULL;
+            }
+            PublicDeclare = 0;
+            PrivateDeclare = 0;
+            ExternalDeclare = 0;
+            strcpy(NamePrecision,"");
+            c_star = 0;
+            InitialValueGiven = 0 ;
+            strcpy(IntentSpec,"");
+            VariableIsParameter =  0 ;
+            Allocatabledeclare = 0 ;
+            Targetdeclare = 0 ;
+            SaveDeclare = 0;
+            pointerdeclare = 0;
+            optionaldeclare = 0 ;
+            dimsgiven=0;
+            c_selectorgiven=0;
+            strcpy(nameinttypename,"");
+            strcpy(c_selectorname,"");
+            GlobalDeclarationType = 0;
+        }
+    break;
+
+  case 103:
+/* Line 1807 of yacc.c  */
+#line 696 "fortran.y"
     {
-                       if ( firstpass == 1 && couldaddvariable == 1 ) (yyval.l)=(yyvsp[(2) - (3)].l);
-                   ;}
-    break;
-
-  case 45:
-#line 564 "fortran.y"
+            insubroutinedeclare = 1;
+
+            if ( firstpass )
+            {
+                Add_SubroutineArgument_Var_1((yyvsp[(3) - (3)].l));
+                Add_FunctionType_Var_1((yyvsp[(2) - (3)].na));
+            }
+            else
+                WriteBeginof_SubLoop();
+
+            strcpy(nameinttypename,"");
+        }
+    break;
+
+  case 104:
+/* Line 1807 of yacc.c  */
+#line 710 "fortran.y"
+    { functiondeclarationisdone = 1; }
+    break;
+
+  case 105:
+/* Line 1807 of yacc.c  */
+#line 712 "fortran.y"
+    { VariableIsParameter = 1; pos_curparameter = setposcur()-9; }
+    break;
+
+  case 109:
+/* Line 1807 of yacc.c  */
+#line 724 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         Add_SubroutineArgument_Var_1((yyvsp[(2) - (3)].l));
-                      }
-                   ;}
-    break;
-
-  case 46:
-#line 571 "fortran.y"
+            createstringfromlistname(ligne,(yyvsp[(3) - (4)].lnn));
+            if (firstpass == 1) Add_Data_Var_1(&List_Data_Var,(yyvsp[(1) - (4)].na),ligne);
+            else                Add_Data_Var_1(&List_Data_Var_Cur,(yyvsp[(1) - (4)].na),ligne);
+        }
+    break;
+
+  case 110:
+/* Line 1807 of yacc.c  */
+#line 730 "fortran.y"
     {
-                      if ( firstpass == 1  && couldaddvariable == 1)
-                      {
-                         strcpy(nameinttypenameback,nameinttypename);
-                         strcpy(nameinttypename,"");
-                         curvar=createvar((yyvsp[(1) - (1)].na),NULL);
-                        strcpy(nameinttypename,nameinttypenameback);
-                         curlistvar=insertvar(NULL,curvar);
-                         (yyval.l)=settype("",curlistvar);
-                      }
-                   ;}
-    break;
-
-  case 47:
-#line 583 "fortran.y"
+            if (firstpass == 1)  Add_Data_Var_Names_01(&List_Data_Var,(yyvsp[(1) - (4)].lnn),(yyvsp[(3) - (4)].lnn));
+            else                 Add_Data_Var_Names_01(&List_Data_Var_Cur,(yyvsp[(1) - (4)].lnn),(yyvsp[(3) - (4)].lnn));
+        }
+    break;
+
+  case 111:
+/* Line 1807 of yacc.c  */
+#line 735 "fortran.y"
     {
-                      if ( firstpass == 1  && couldaddvariable == 1)
-                      {
-                         strcpy(nameinttypenameback,nameinttypename);
-                         strcpy(nameinttypename,"");                      
-                         curvar=createvar((yyvsp[(3) - (3)].na),NULL);
-                         strcpy(nameinttypename,nameinttypenameback);                         
-                         (yyval.l)=insertvar((yyvsp[(1) - (3)].l),curvar);
-                      }
-                   ;}
-    break;
-
-  case 48:
-#line 594 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 49:
-#line 595 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),"*");;}
-    break;
-
-  case 50:
-#line 598 "fortran.y"
+            createstringfromlistname(ligne,(yyvsp[(7) - (8)].lnn));
+            printf("###################################################################################################################\n");
+            printf("## CONV Error : data_implied_do statements (R537) are not yet supported. Please complain to the proper authorities.\n");
+            printf("l.%4d -- data_stmt_set : ( lhs , dospec ) /data_stmt_value_list/ -- lhs=|%s| dospec=|%s| data_stmt_value_list=|%s|\n",
+                line_num_input,(yyvsp[(2) - (8)].na),(yyvsp[(4) - (8)].na),ligne);
+            printf("## But, are you SURE you NEED a DATA construct ?\n");
+            printf("###################################################################################################################\n");
+            exit(1);
+        }
+    break;
+
+  case 112:
+/* Line 1807 of yacc.c  */
+#line 748 "fortran.y"
+    { (yyval.lnn) = Insertname(NULL,(yyvsp[(1) - (1)].na),0); }
+    break;
+
+  case 113:
+/* Line 1807 of yacc.c  */
+#line 749 "fortran.y"
+    { (yyval.lnn) = Insertname((yyvsp[(3) - (3)].lnn),(yyvsp[(1) - (3)].na),1);   }
+    break;
+
+  case 118:
+/* Line 1807 of yacc.c  */
+#line 758 "fortran.y"
+    { pos_cursave = setposcur()-4; }
+    break;
+
+  case 120:
+/* Line 1807 of yacc.c  */
+#line 761 "fortran.y"
+    { if ( ! inside_type_declare ) Add_Save_Var_1((yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].d)); }
+    break;
+
+  case 121:
+/* Line 1807 of yacc.c  */
+#line 764 "fortran.y"
+    { (yyval.lnn) = Insertname(NULL,(yyvsp[(1) - (1)].na),0); }
+    break;
+
+  case 122:
+/* Line 1807 of yacc.c  */
+#line 765 "fortran.y"
+    { printf("l.%4d -- INSTRUCTION NON TRAITEE : INITIALISATION DE DATA AVEC EXPRESSION\n",line_num_input); exit(0); }
+    break;
+
+  case 123:
+/* Line 1807 of yacc.c  */
+#line 766 "fortran.y"
+    { (yyval.lnn) = concat_listname((yyvsp[(1) - (3)].lnn),(yyvsp[(3) - (3)].lnn)); }
+    break;
+
+  case 124:
+/* Line 1807 of yacc.c  */
+#line 769 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na));  }
+    break;
+
+  case 125:
+/* Line 1807 of yacc.c  */
+#line 770 "fortran.y"
+    { sprintf((yyval.na),"%s+%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 126:
+/* Line 1807 of yacc.c  */
+#line 771 "fortran.y"
+    { sprintf((yyval.na),"%s-%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 127:
+/* Line 1807 of yacc.c  */
+#line 772 "fortran.y"
+    { sprintf((yyval.na),"%s*%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 128:
+/* Line 1807 of yacc.c  */
+#line 773 "fortran.y"
+    { sprintf((yyval.na),"%s/%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 129:
+/* Line 1807 of yacc.c  */
+#line 775 "fortran.y"
+    { strcpy((yyval.na),""); }
+    break;
+
+  case 130:
+/* Line 1807 of yacc.c  */
+#line 776 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 135:
+/* Line 1807 of yacc.c  */
+#line 786 "fortran.y"
     {
-                      if ( VarTypepar == 1 )
-                      {
-                         couldaddvariable = 1 ;
-                         VarTypepar = 0;
-                      }
-                   ;}
-    break;
-
-  case 51:
-#line 606 "fortran.y"
+            positioninblock = 0;
+            pos_curdimension = setposcur()-9;
+        }
+    break;
+
+  case 136:
+/* Line 1807 of yacc.c  */
+#line 793 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         VarType = 1;
-                         couldaddvariable = 0 ;
-                      }
-                   ;}
-    break;
-
-  case 52:
-#line 614 "fortran.y"
+            printf("l.%4d -- dimension : before_dimension opt_comma TOK_NAME = |%s| -- MHCHECK\n",line_num_input,(yyvsp[(3) - (5)].na));
+            if ( inside_type_declare ) break;
+            curvar = createvar((yyvsp[(3) - (5)].na),(yyvsp[(4) - (5)].d));
+            CreateAndFillin_Curvar("", curvar);
+            curlistvar=insertvar(NULL, curvar);
+            (yyval.l) = settype("",curlistvar);
+            strcpy(vallengspec,"");
+        }
+    break;
+
+  case 137:
+/* Line 1807 of yacc.c  */
+#line 803 "fortran.y"
     {
-                      if ( VarType == 1 ) couldaddvariable = 1 ;
-                      VarType = 0;
-                      VarTypepar = 0;
-                   ;}
-    break;
-
-  case 54:
-#line 621 "fortran.y"
+            printf("l.%4d -- dimension : dimension ',' TOK_NAME dims lengspec = |%s| -- MHCHECK\n",line_num_input,(yyvsp[(3) - (5)].na));
+            if ( inside_type_declare ) break;
+            curvar = createvar((yyvsp[(3) - (5)].na),(yyvsp[(4) - (5)].d));
+            CreateAndFillin_Curvar("", curvar);
+            curlistvar = insertvar((yyvsp[(1) - (5)].l), curvar);
+            (yyval.l) = curlistvar;
+            strcpy(vallengspec,"");
+        }
+    break;
+
+  case 140:
+/* Line 1807 of yacc.c  */
+#line 818 "fortran.y"
+    { (yyval.lnn) = (listname *) NULL; }
+    break;
+
+  case 141:
+/* Line 1807 of yacc.c  */
+#line 819 "fortran.y"
+    { (yyval.lnn) = (yyvsp[(3) - (3)].lnn); }
+    break;
+
+  case 142:
+/* Line 1807 of yacc.c  */
+#line 822 "fortran.y"
+    { (yyval.lnn) = Insertname(NULL,(yyvsp[(1) - (1)].na),0); }
+    break;
+
+  case 143:
+/* Line 1807 of yacc.c  */
+#line 823 "fortran.y"
+    { (yyval.lnn) = Insertname(NULL,(yyvsp[(1) - (1)].na),0); }
+    break;
+
+  case 144:
+/* Line 1807 of yacc.c  */
+#line 824 "fortran.y"
+    { (yyval.lnn) = Insertname((yyvsp[(1) - (3)].lnn),(yyvsp[(3) - (3)].na),0);   }
+    break;
+
+  case 145:
+/* Line 1807 of yacc.c  */
+#line 825 "fortran.y"
+    { (yyval.lnn) = Insertname((yyvsp[(1) - (3)].lnn),(yyvsp[(3) - (3)].na),0);   }
+    break;
+
+  case 146:
+/* Line 1807 of yacc.c  */
+#line 829 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         if ( insubroutinedeclare == 0 )
-                         {
-                                                  Add_GlobalParameter_Var_1((yyvsp[(3) - (4)].l));
-                                                  }
-                         else Add_Parameter_Var_1((yyvsp[(3) - (4)].l));
-                         pos_end = setposcur();
-                        RemoveWordSET_0(fortranout,pos_cur_decl,
-                                                    pos_end-pos_cur_decl);
-                      }
-                      VariableIsParameter =  0 ;
-                   ;}
-    break;
-
-  case 55:
-#line 636 "fortran.y"
+            if ( inside_type_declare ) break;
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curcommon,pos_end-pos_curcommon);
+        }
+    break;
+
+  case 147:
+/* Line 1807 of yacc.c  */
+#line 835 "fortran.y"
     {
-                     if ( couldaddvariable == 1 )
-                     {
-                        if ( insubroutinedeclare == 0 )
-                                                  Add_GlobalParameter_Var_1((yyvsp[(2) - (2)].l));
-                         else Add_Parameter_Var_1((yyvsp[(2) - (2)].l));
-                         pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_cur_decl,
-                                                    pos_end-pos_cur_decl);
-                      }
-                      VariableIsParameter =  0 ;
-                   ;}
-    break;
-
-  case 57:
-#line 650 "fortran.y"
+            if ( inside_type_declare ) break;
+            sprintf(charusemodule,"%s",(yyvsp[(2) - (3)].na));
+            Add_NameOfCommon_1((yyvsp[(2) - (3)].na),subroutinename);
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curcommon,pos_end-pos_curcommon);
+        }
+    break;
+
+  case 148:
+/* Line 1807 of yacc.c  */
+#line 843 "fortran.y"
     {
-                     pos_end = setposcur();
-                     RemoveWordSET_0(fortranout,pos_cursave,
-                                                pos_end-pos_cursave);
-                  ;}
-    break;
-
-  case 59:
-#line 657 "fortran.y"
+            if ( inside_type_declare ) break;
+            sprintf(charusemodule,"%s",(yyvsp[(3) - (5)].na));
+            Add_NameOfCommon_1((yyvsp[(3) - (5)].na),subroutinename);
+            pos_end = setposcur();
+            RemoveWordSET_0(fortran_out,pos_curcommon,pos_end-pos_curcommon);
+        }
+    break;
+
+  case 149:
+/* Line 1807 of yacc.c  */
+#line 852 "fortran.y"
+    { positioninblock = 0; pos_curcommon = setposcur()-6;   }
+    break;
+
+  case 150:
+/* Line 1807 of yacc.c  */
+#line 853 "fortran.y"
+    { positioninblock = 0; pos_curcommon = setposcur()-6-7; }
+    break;
+
+  case 151:
+/* Line 1807 of yacc.c  */
+#line 856 "fortran.y"
+    { if ( ! inside_type_declare ) Add_Common_var_1(); }
+    break;
+
+  case 152:
+/* Line 1807 of yacc.c  */
+#line 857 "fortran.y"
+    { if ( ! inside_type_declare ) Add_Common_var_1(); }
+    break;
+
+  case 153:
+/* Line 1807 of yacc.c  */
+#line 861 "fortran.y"
     {
-                   /* if the variable is a parameter we can suppose that is   */
-                   /*    value is the same on each grid. It is not useless to */
-                   /*    create a copy of it on each grid                     */
-                      if ( couldaddvariable == 1 )
-                      {
-                         Add_Globliste_1((yyvsp[(1) - (1)].l));
-                         /* if variableparamlists has been declared in a      */
-                         /*    subroutine                                     */
-                         if ( insubroutinedeclare == 1 )
-                         {
-                            Add_Dimension_Var_1((yyvsp[(1) - (1)].l));
-                         }
-                         pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_curdimension,
-                                                pos_end-pos_curdimension);
-                      }
-                      /*                                                      */
-                      PublicDeclare = 0;
-                      PrivateDeclare = 0;
-                      ExternalDeclare = 0;
-                      strcpy(NamePrecision,"");
-                      c_star = 0;
-                      strcpy(InitialValueGiven," ");
-                      strcpy(IntentSpec,"");
-                      VariableIsParameter =  0 ;
-                      Allocatabledeclare = 0 ;
-                      Targetdeclare = 0 ;
-                      SaveDeclare = 0;
-                      pointerdeclare = 0;
-                      optionaldeclare = 0 ;
-                      dimsgiven=0;
-                      c_selectorgiven=0;
-                      strcpy(nameinttypename,"");
-                      strcpy(c_selectorname,"");
-                   ;}
-    break;
-
-  case 60:
-#line 694 "fortran.y"
+            positioninblock = positioninblock + 1 ;
+            strcpy(commonvar,(yyvsp[(1) - (2)].na));
+            commondim = (yyvsp[(2) - (2)].d);
+        }
+    break;
+
+  case 154:
+/* Line 1807 of yacc.c  */
+#line 869 "fortran.y"
     {
-      if (firstpass == 0)
-      {
-      if ((yyvsp[(1) - (1)].lnn))
-      {
-      removeglobfromlist(&((yyvsp[(1) - (1)].lnn)));
-      pos_end = setposcur();
-           RemoveWordSET_0(fortranout,pos_cur,pos_end-pos_cur);
-      writelistpublic((yyvsp[(1) - (1)].lnn));
-      }
-      }
-      ;}
-    break;
-
-  case 70:
-#line 716 "fortran.y"
+            strcpy((yyval.na),"");
+            positioninblock=0;
+            strcpy(commonblockname,"");
+        }
+    break;
+
+  case 155:
+/* Line 1807 of yacc.c  */
+#line 875 "fortran.y"
     {
-                      /* we should remove the data declaration                */
-                      if ( couldaddvariable == 1 && aftercontainsdeclare != 2 )
-                      {
-                        pos_end = setposcur();
-                        RemoveWordSET_0(fortranout,pos_curdata,
-                                              pos_end-pos_curdata);
-                      }
-                      if ( couldaddvariable == 1 && aftercontainsdeclare == 1 )
-                      {
-                      if (firstpass == 0)
-                      {
-                        ReWriteDataStatement_0(fortranout);
-                        pos_end = setposcur();
-                  }
-                      }
-                  ;}
-    break;
-
-  case 72:
-#line 736 "fortran.y"
+            strcpy((yyval.na),(yyvsp[(2) - (3)].na));
+            positioninblock=0;
+            strcpy(commonblockname,(yyvsp[(2) - (3)].na));
+        }
+    break;
+
+  case 158:
+/* Line 1807 of yacc.c  */
+#line 885 "fortran.y"
+    { (yyval.l)=insertvar(NULL,(yyvsp[(1) - (1)].v)); }
+    break;
+
+  case 159:
+/* Line 1807 of yacc.c  */
+#line 886 "fortran.y"
+    { (yyval.l)=insertvar((yyvsp[(1) - (3)].l),(yyvsp[(3) - (3)].v));   }
+    break;
+
+  case 160:
+/* Line 1807 of yacc.c  */
+#line 890 "fortran.y"
     {
-         PublicDeclare = 0 ;
-         PrivateDeclare = 0 ;
-      ;}
-    break;
-
-  case 110:
-#line 787 "fortran.y"
+            if ( inside_type_declare ) break;
+            curvar=(variable *) calloc(1,sizeof(variable));
+            Init_Variable(curvar);
+            curvar->v_VariableIsParameter = 1;
+            strcpy(curvar->v_nomvar,(yyvsp[(1) - (3)].na));
+            strcpy(curvar->v_subroutinename,subroutinename);
+            strcpy(curvar->v_modulename,curmodulename);
+            strcpy(curvar->v_initialvalue,(yyvsp[(3) - (3)].na));
+            strcpy(curvar->v_commoninfile,cur_filename);
+            Save_Length((yyvsp[(3) - (3)].na),14);
+            (yyval.v) = curvar;
+        }
+    break;
+
+  case 164:
+/* Line 1807 of yacc.c  */
+#line 913 "fortran.y"
     {
-                      /* if the variable is a parameter we can suppose that is*/
-                      /*    value is the same on each grid. It is not useless */
-                      /*    to create a copy of it on each grid               */
-                      if ( couldaddvariable == 1 )
-                      {
-                      pos_end = setposcur();
-                      /*if (insubroutinedeclare == 0)
-                        {   */
-                         RemoveWordSET_0(fortranout,pos_cur_decl,
-                                                 pos_end-pos_cur_decl);
-                                         
-                       /* }
-                      else
-                       {*/
-                        ReWriteDeclarationAndAddTosubroutine_01((yyvsp[(1) - (2)].l));
-                        pos_cur_decl = setposcur();
-                        
-                       /*}*/
-                      if ( firstpass == 0 &&
-                           GlobalDeclaration == 0 &&
-                           insubroutinedeclare == 0 )
-                      {
-
-                         sprintf(ligne,"\n#include \"Module_Declar_%s.h\"\n"
-                                                                ,curmodulename);
-                         tofich(fortranout,ligne,1);
-                         sprintf (ligne, "Module_Declar_%s.h",curmodulename);
-                         module_declar = associate(ligne);
-                         sprintf (ligne, " ");
-                         tofich (module_declar, ligne,1);
-                         GlobalDeclaration = 1 ;
-                         pos_cur_decl = setposcur();
-
-                      }
-                         (yyval.l) = (yyvsp[(1) - (2)].l);
-                         Add_Globliste_1((yyvsp[(1) - (2)].l));
-                                                  
-                         if ( insubroutinedeclare == 0 )
-                                                  Add_GlobalParameter_Var_1((yyvsp[(1) - (2)].l));
-                         else
-                         {
-                            if ( pointerdeclare == 1 )
-                                                Add_Pointer_Var_From_List_1((yyvsp[(1) - (2)].l));
-                            Add_Parameter_Var_1((yyvsp[(1) - (2)].l));
-                         }
-
-                         /* if variables has been declared in a subroutine    */
-                         if ( insubroutinedeclare == 1 )
-                         { 
-                       /*    Add_SubroutineDeclaration_Var_1($1);*/
-                         }
-                         /* If there are a SAVE declarations in module's      */
-                         /*    subroutines we should remove it from the       */
-                         /*    subroutines declaration and add it in the      */
-                         /*    global declarations                            */
-                         if ( aftercontainsdeclare == 1 &&
-                              SaveDeclare == 1 && firstpass == 1 )
-                         {
-                              if ( inmodulemeet == 0 ) Add_Save_Var_dcl_1((yyvsp[(1) - (2)].l));
-                              else  Add_SubroutineDeclarationSave_Var_1((yyvsp[(1) - (2)].l));
-                         }
-                      }
-                      /*                                                      */
-                      PublicDeclare = 0;
-                      PrivateDeclare = 0;
-                      ExternalDeclare = 0;
-                      strcpy(NamePrecision,"");
-                      c_star = 0;
-                      strcpy(InitialValueGiven," ");
-                      strcpy(IntentSpec,"");
-                      VariableIsParameter =  0 ;
-                      Allocatabledeclare = 0 ;
-                      Targetdeclare = 0 ;
-                      SaveDeclare = 0;
-                      pointerdeclare = 0;
-                      optionaldeclare = 0 ;
-                      dimsgiven=0;
-                      c_selectorgiven=0;
-                      strcpy(nameinttypename,"");
-                      strcpy(c_selectorname,"");
-                      GlobalDeclarationType = 0; 
-                   ;}
-    break;
-
-  case 111:
-#line 871 "fortran.y"
-    {
-                      /* open param file                                      */
-                      if ( firstpass == 0 )
-                      {
-                         sprintf(ligne,"%s/ParamFile%s.h",nomdir,(yyvsp[(2) - (3)].nac));
-                         paramout=fopen(ligne,"w");
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-                      }
-                      strcpy(subroutinename,(yyvsp[(2) - (3)].nac));
-                      if ( inmodulemeet == 1 )
-                      {
-                         insubroutinedeclare = 1;
-                         /* we should to list of the subroutine argument the  */
-                         /*    name of the function which has to be defined   */
-                         Add_SubroutineArgument_Var_1((yyvsp[(3) - (3)].l));
-                         Add_FunctionType_Var_1((yyvsp[(2) - (3)].nac));
-                         /* in the second step we should write the head of    */
-                         /*    the subroutine sub_loop_<subroutinename>       */
-                         writeheadnewsub_0(2);
-                      }
-                      else
-                      {
-                         insubroutinedeclare = 1;
-                         /* we should to list of the subroutine argument the  */
-                         /*    name of the function which has to be defined   */
-                         Add_SubroutineArgument_Var_1((yyvsp[(3) - (3)].l));
-                         Add_FunctionType_Var_1((yyvsp[(2) - (3)].nac));
-                         /* in the second step we should write the head of    */
-                         /*    the subroutine sub_loop_<subroutinename>       */
-                         writeheadnewsub_0(2);
-                      }
-                      strcpy(nameinttypename,"");
-
-                   ;}
-    break;
-
-  case 112:
-#line 908 "fortran.y"
-    {
-                       functiondeclarationisdone = 1;
-                   ;}
-    break;
-
-  case 113:
-#line 914 "fortran.y"
-    {
-                      VariableIsParameter = 1;
-                      pos_curparameter = setposcur()-9;
-                   ;}
-    break;
-
-  case 114:
-#line 919 "fortran.y"
-    {
-                      pos_curdata = setposcur()-strlen((yyvsp[(1) - (1)].nac));
-                      Init_List_Data_Var();
-                   ;}
-    break;
-
-  case 115:
+            if ( insubroutinedeclare == 1 )
+            {
+                Add_ImplicitNoneSubroutine_1();
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_end-13,13);
+            }
+        }
+    break;
+
+  case 166:
+/* Line 1807 of yacc.c  */
 #line 924 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-/*                      if ( aftercontainsdeclare == 1 ) strcpy(ligne,"");
-                      else */
-/*                      sprintf(ligne,"%s",$3);*/
-                      createstringfromlistname(ligne,(yyvsp[(3) - (4)].lnn));
-                      if (firstpass == 1)
-                      Add_Data_Var_1(&List_Data_Var,(yyvsp[(1) - (4)].nac),ligne);
-                      else
-                      Add_Data_Var_1(&List_Data_Var_Cur,(yyvsp[(1) - (4)].nac),ligne);
-                      }
-                   ;}
-    break;
-
-  case 116:
-#line 938 "fortran.y"
+            if ( ! inside_type_declare )
+            {
+                if (dimsgiven == 1) curvar = createvar((yyvsp[(2) - (5)].na),curdim);
+                else                curvar = createvar((yyvsp[(2) - (5)].na),(yyvsp[(3) - (5)].d));
+                CreateAndFillin_Curvar(DeclType, curvar);
+                curlistvar = insertvar(NULL, curvar);
+                if (!strcasecmp(DeclType,"character"))
+                {
+                    if (c_selectorgiven == 1)
+                    {
+                        strcpy(c_selectordim.first,"1");
+                        strcpy(c_selectordim.last,c_selectorname);
+                        Save_Length(c_selectorname,1);
+                        change_dim_char(insertdim(NULL,c_selectordim),curlistvar);
+                    }
+                }
+                (yyval.l)=settype(DeclType,curlistvar);
+            }
+            strcpy(vallengspec,"");
+        }
+    break;
+
+  case 167:
+/* Line 1807 of yacc.c  */
+#line 946 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                      /*if ( aftercontainsdeclare == 1 ) strcpy(ligne,"");
-                      else */
-                      /*sprintf(ligne,"%s",$5);   */
-                      createstringfromlistname(ligne,(yyvsp[(5) - (6)].lnn));                      
-                      if (firstpass == 1)                      
-                      Add_Data_Var_1(&List_Data_Var,(yyvsp[(3) - (6)].nac),ligne);
-                      else
-                      Add_Data_Var_1(&List_Data_Var_Cur,(yyvsp[(3) - (6)].nac),ligne);                      
-                      }
-                   ;}
-    break;
-
-  case 117:
-#line 952 "fortran.y"
+            if ( ! inside_type_declare )
+            {
+                if (dimsgiven == 1) curvar = createvar((yyvsp[(3) - (6)].na), curdim);
+                else                curvar = createvar((yyvsp[(3) - (6)].na), (yyvsp[(4) - (6)].d));
+                CreateAndFillin_Curvar((yyvsp[(1) - (6)].l)->var->v_typevar,curvar);
+                strcpy(curvar->v_typevar, (yyvsp[(1) - (6)].l)->var->v_typevar);
+                curvar->v_catvar = get_cat_var(curvar);
+                curlistvar = insertvar((yyvsp[(1) - (6)].l), curvar);
+                if (!strcasecmp(DeclType,"character"))
+                {
+                    if (c_selectorgiven == 1)
+                    {
+                        strcpy(c_selectordim.first,"1");
+                        strcpy(c_selectordim.last,c_selectorname);
+                        Save_Length(c_selectorname,1);
+                        change_dim_char(insertdim(NULL,c_selectordim),curlistvar);
+                    }
+                }
+                (yyval.l)=curlistvar;
+            }
+            strcpy(vallengspec,"");
+        }
+    break;
+
+  case 168:
+/* Line 1807 of yacc.c  */
+#line 970 "fortran.y"
+    { dimsgiven = 0; }
+    break;
+
+  case 169:
+/* Line 1807 of yacc.c  */
+#line 972 "fortran.y"
+    { strcpy(DeclType,(yyvsp[(1) - (2)].na));  }
+    break;
+
+  case 170:
+/* Line 1807 of yacc.c  */
+#line 973 "fortran.y"
+    { strcpy(DeclType,"character");  }
+    break;
+
+  case 171:
+/* Line 1807 of yacc.c  */
+#line 974 "fortran.y"
+    { strcpy(DeclType,(yyvsp[(1) - (3)].na)); strcpy(nameinttypename,(yyvsp[(3) - (3)].na));  }
+    break;
+
+  case 172:
+/* Line 1807 of yacc.c  */
+#line 975 "fortran.y"
+    { strcpy(DeclType,"type"); GlobalDeclarationType = 1;  }
+    break;
+
+  case 174:
+/* Line 1807 of yacc.c  */
+#line 978 "fortran.y"
+    { c_selectorgiven = 1; strcpy(c_selectorname,(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 175:
+/* Line 1807 of yacc.c  */
+#line 979 "fortran.y"
+    { c_star = 1;}
+    break;
+
+  case 180:
+/* Line 1807 of yacc.c  */
+#line 987 "fortran.y"
+    { pos_cur_decl = setposcur()-9; }
+    break;
+
+  case 181:
+/* Line 1807 of yacc.c  */
+#line 990 "fortran.y"
+    { strcpy((yyval.na),"integer"); pos_cur_decl = setposcur()-7; }
+    break;
+
+  case 182:
+/* Line 1807 of yacc.c  */
+#line 991 "fortran.y"
+    { strcpy((yyval.na),"logical"); pos_cur_decl = setposcur()-7; }
+    break;
+
+  case 183:
+/* Line 1807 of yacc.c  */
+#line 992 "fortran.y"
+    { strcpy((yyval.na),"real");    pos_cur_decl = setposcur()-4; }
+    break;
+
+  case 184:
+/* Line 1807 of yacc.c  */
+#line 993 "fortran.y"
+    { strcpy((yyval.na),"complex"); pos_cur_decl = setposcur()-7; }
+    break;
+
+  case 185:
+/* Line 1807 of yacc.c  */
+#line 994 "fortran.y"
+    { strcpy((yyval.na),"double complex"); pos_cur_decl = setposcur()-14; }
+    break;
+
+  case 186:
+/* Line 1807 of yacc.c  */
+#line 995 "fortran.y"
+    { pos_cur_decl = setposcur()-16; strcpy((yyval.na),"real"); strcpy(nameinttypename,"8"); }
+    break;
+
+  case 188:
+/* Line 1807 of yacc.c  */
+#line 998 "fortran.y"
+    {strcpy(vallengspec,(yyvsp[(2) - (2)].na));}
+    break;
+
+  case 189:
+/* Line 1807 of yacc.c  */
+#line 1001 "fortran.y"
+    { sprintf((yyval.na),"*%s",(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 190:
+/* Line 1807 of yacc.c  */
+#line 1002 "fortran.y"
+    { strcpy((yyval.na),"*(*)"); }
+    break;
+
+  case 197:
+/* Line 1807 of yacc.c  */
+#line 1014 "fortran.y"
     {
-                       /*******************************************************/
-                       /*******************************************************/
-                       /*******************************************************/
-                       /*******************************************************/
-                       /*******************************************************/
-                       /*******************************************************/
-                       /*******************************************************/
-                       if (firstpass == 1)
-                       Add_Data_Var_Names_01(&List_Data_Var,(yyvsp[(1) - (4)].lnn),(yyvsp[(3) - (4)].lnn));
-                       else
-                       Add_Data_Var_Names_01(&List_Data_Var_Cur,(yyvsp[(1) - (4)].lnn),(yyvsp[(3) - (4)].lnn));
-                   ;}
-    break;
-
-  case 118:
-#line 967 "fortran.y"
+            if ( strstr((yyvsp[(3) - (3)].na),"0.d0") )
+            {
+                strcpy(nameinttypename,"8");
+                strcpy(NamePrecision,"");
+            }
+            else
+                sprintf(NamePrecision,"%s = %s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));
+        }
+    break;
+
+  case 198:
+/* Line 1807 of yacc.c  */
+#line 1023 "fortran.y"
+    { strcpy(NamePrecision,(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 199:
+/* Line 1807 of yacc.c  */
+#line 1024 "fortran.y"
+    { strcpy(NamePrecision,(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 200:
+/* Line 1807 of yacc.c  */
+#line 1025 "fortran.y"
+    { strcpy(NamePrecision,(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 201:
+/* Line 1807 of yacc.c  */
+#line 1028 "fortran.y"
+    { strcpy(CharacterSize,(yyvsp[(1) - (1)].na));  strcpy((yyval.na),(yyvsp[(1) - (1)].na));  }
+    break;
+
+  case 202:
+/* Line 1807 of yacc.c  */
+#line 1029 "fortran.y"
+    { strcpy(CharacterSize,"*"); strcpy((yyval.na),"*"); }
+    break;
+
+  case 210:
+/* Line 1807 of yacc.c  */
+#line 1042 "fortran.y"
+    { VariableIsParameter = 1; }
+    break;
+
+  case 212:
+/* Line 1807 of yacc.c  */
+#line 1044 "fortran.y"
+    { Allocatabledeclare = 1; }
+    break;
+
+  case 213:
+/* Line 1807 of yacc.c  */
+#line 1045 "fortran.y"
+    { dimsgiven = 1; curdim = (yyvsp[(2) - (2)].d); }
+    break;
+
+  case 214:
+/* Line 1807 of yacc.c  */
+#line 1046 "fortran.y"
+    { ExternalDeclare = 1; }
+    break;
+
+  case 215:
+/* Line 1807 of yacc.c  */
+#line 1048 "fortran.y"
+    { strcpy(IntentSpec,(yyvsp[(3) - (4)].na)); }
+    break;
+
+  case 217:
+/* Line 1807 of yacc.c  */
+#line 1050 "fortran.y"
+    { optionaldeclare = 1 ; }
+    break;
+
+  case 218:
+/* Line 1807 of yacc.c  */
+#line 1051 "fortran.y"
+    { pointerdeclare = 1 ; }
+    break;
+
+  case 219:
+/* Line 1807 of yacc.c  */
+#line 1052 "fortran.y"
+    { SaveDeclare = 1 ; }
+    break;
+
+  case 220:
+/* Line 1807 of yacc.c  */
+#line 1053 "fortran.y"
+    { Targetdeclare = 1; }
+    break;
+
+  case 221:
+/* Line 1807 of yacc.c  */
+#line 1056 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 222:
+/* Line 1807 of yacc.c  */
+#line 1057 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 223:
+/* Line 1807 of yacc.c  */
+#line 1058 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 224:
+/* Line 1807 of yacc.c  */
+#line 1061 "fortran.y"
+    { PublicDeclare = 1;  }
+    break;
+
+  case 225:
+/* Line 1807 of yacc.c  */
+#line 1062 "fortran.y"
+    { PrivateDeclare = 1; }
+    break;
+
+  case 226:
+/* Line 1807 of yacc.c  */
+#line 1064 "fortran.y"
+    { (yyval.d) = (listdim*) NULL; }
+    break;
+
+  case 227:
+/* Line 1807 of yacc.c  */
+#line 1066 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         (yyval.lnn) = Insertname(NULL,(yyvsp[(1) - (1)].na),0);
-                      }
-                   ;}
-    break;
-
-  case 119:
-#line 974 "fortran.y"
+            (yyval.d) = (listdim*) NULL;
+            if ( inside_type_declare ) break;
+            if ( created_dimensionlist == 1 || agrif_parentcall == 1 )  (yyval.d)=(yyvsp[(2) - (3)].d);
+        }
+    break;
+
+  case 228:
+/* Line 1807 of yacc.c  */
+#line 1074 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         (yyval.lnn) = Insertname((yyvsp[(3) - (3)].lnn),(yyvsp[(1) - (3)].na),1);
-                      }
-                   ;}
-    break;
-
-  case 124:
-#line 988 "fortran.y"
+            (yyval.d) = (listdim*) NULL;
+            if ( inside_type_declare ) break;
+            if ( created_dimensionlist == 1 || agrif_parentcall == 1 )  (yyval.d)=insertdim(NULL,(yyvsp[(1) - (1)].dim1));
+        }
+    break;
+
+  case 229:
+/* Line 1807 of yacc.c  */
+#line 1080 "fortran.y"
     {
-                     pos_cursave = setposcur()-4;
-                  ;}
-    break;
-
-  case 126:
-#line 994 "fortran.y"
+            (yyval.d) = (listdim*) NULL;
+            if ( inside_type_declare ) break;
+            if ( (!inside_type_declare) && created_dimensionlist == 1 ) (yyval.d)=insertdim((yyvsp[(1) - (3)].d),(yyvsp[(3) - (3)].dim1));
+        }
+    break;
+
+  case 230:
+/* Line 1807 of yacc.c  */
+#line 1086 "fortran.y"
+    { strcpy((yyval.dim1).first,"1"); strcpy((yyval.dim1).last,(yyvsp[(1) - (1)].na)); Save_Length((yyvsp[(1) - (1)].na),1); }
+    break;
+
+  case 231:
+/* Line 1807 of yacc.c  */
+#line 1087 "fortran.y"
+    { strcpy((yyval.dim1).first,"");  strcpy((yyval.dim1).last,"");                    }
+    break;
+
+  case 232:
+/* Line 1807 of yacc.c  */
+#line 1088 "fortran.y"
+    { strcpy((yyval.dim1).first,(yyvsp[(1) - (2)].na));  Save_Length((yyvsp[(1) - (2)].na),2); strcpy((yyval.dim1).last,""); }
+    break;
+
+  case 233:
+/* Line 1807 of yacc.c  */
+#line 1089 "fortran.y"
+    { strcpy((yyval.dim1).first,"");  strcpy((yyval.dim1).last,(yyvsp[(2) - (2)].na)); Save_Length((yyvsp[(2) - (2)].na),1); }
+    break;
+
+  case 234:
+/* Line 1807 of yacc.c  */
+#line 1090 "fortran.y"
+    { strcpy((yyval.dim1).first,(yyvsp[(1) - (3)].na));  Save_Length((yyvsp[(1) - (3)].na),2); strcpy((yyval.dim1).last,(yyvsp[(3) - (3)].na)); Save_Length((yyvsp[(3) - (3)].na),1); }
+    break;
+
+  case 235:
+/* Line 1807 of yacc.c  */
+#line 1093 "fortran.y"
+    { strcpy((yyval.na),"*"); }
+    break;
+
+  case 236:
+/* Line 1807 of yacc.c  */
+#line 1094 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));  }
+    break;
+
+  case 237:
+/* Line 1807 of yacc.c  */
+#line 1096 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 238:
+/* Line 1807 of yacc.c  */
+#line 1097 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 239:
+/* Line 1807 of yacc.c  */
+#line 1098 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 240:
+/* Line 1807 of yacc.c  */
+#line 1099 "fortran.y"
+    { sprintf((yyval.na),"(%s)",(yyvsp[(2) - (3)].na)); }
+    break;
+
+  case 241:
+/* Line 1807 of yacc.c  */
+#line 1103 "fortran.y"
+    { sprintf((yyval.na),"SUM(%s)",(yyvsp[(2) - (3)].na));}
+    break;
+
+  case 242:
+/* Line 1807 of yacc.c  */
+#line 1104 "fortran.y"
+    { sprintf((yyval.na),"MAX(%s)",(yyvsp[(2) - (3)].na));}
+    break;
+
+  case 243:
+/* Line 1807 of yacc.c  */
+#line 1105 "fortran.y"
+    { sprintf((yyval.na),"TANH(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 244:
+/* Line 1807 of yacc.c  */
+#line 1106 "fortran.y"
+    { sprintf((yyval.na),"MAXVAL(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 245:
+/* Line 1807 of yacc.c  */
+#line 1107 "fortran.y"
+    { sprintf((yyval.na),"MIN(%s)",(yyvsp[(2) - (3)].na));}
+    break;
+
+  case 246:
+/* Line 1807 of yacc.c  */
+#line 1108 "fortran.y"
+    { sprintf((yyval.na),"MINVAL(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 247:
+/* Line 1807 of yacc.c  */
+#line 1109 "fortran.y"
+    { sprintf((yyval.na),"TRIM(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 248:
+/* Line 1807 of yacc.c  */
+#line 1110 "fortran.y"
+    { sprintf((yyval.na),"SQRT(%s)",(yyvsp[(2) - (3)].na));}
+    break;
+
+  case 249:
+/* Line 1807 of yacc.c  */
+#line 1111 "fortran.y"
+    { sprintf((yyval.na),"REAL(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 250:
+/* Line 1807 of yacc.c  */
+#line 1112 "fortran.y"
+    { sprintf((yyval.na),"NINT(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 251:
+/* Line 1807 of yacc.c  */
+#line 1113 "fortran.y"
+    { sprintf((yyval.na),"FLOAT(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 252:
+/* Line 1807 of yacc.c  */
+#line 1114 "fortran.y"
+    { sprintf((yyval.na),"EXP(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 253:
+/* Line 1807 of yacc.c  */
+#line 1115 "fortran.y"
+    { sprintf((yyval.na),"COS(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 254:
+/* Line 1807 of yacc.c  */
+#line 1116 "fortran.y"
+    { sprintf((yyval.na),"COSH(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 255:
+/* Line 1807 of yacc.c  */
+#line 1117 "fortran.y"
+    { sprintf((yyval.na),"ACOS(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 256:
+/* Line 1807 of yacc.c  */
+#line 1118 "fortran.y"
+    { sprintf((yyval.na),"SIN(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 257:
+/* Line 1807 of yacc.c  */
+#line 1119 "fortran.y"
+    { sprintf((yyval.na),"SINH(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 258:
+/* Line 1807 of yacc.c  */
+#line 1120 "fortran.y"
+    { sprintf((yyval.na),"ASIN(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 259:
+/* Line 1807 of yacc.c  */
+#line 1121 "fortran.y"
+    { sprintf((yyval.na),"LOG(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 260:
+/* Line 1807 of yacc.c  */
+#line 1122 "fortran.y"
+    { sprintf((yyval.na),"TAN(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 261:
+/* Line 1807 of yacc.c  */
+#line 1123 "fortran.y"
+    { sprintf((yyval.na),"ATAN(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 262:
+/* Line 1807 of yacc.c  */
+#line 1124 "fortran.y"
+    { sprintf((yyval.na),"ABS(%s)",(yyvsp[(2) - (3)].na));}
+    break;
+
+  case 263:
+/* Line 1807 of yacc.c  */
+#line 1125 "fortran.y"
+    { sprintf((yyval.na),"MOD(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 264:
+/* Line 1807 of yacc.c  */
+#line 1126 "fortran.y"
+    { sprintf((yyval.na),"SIGN(%s)",(yyvsp[(2) - (3)].na));}
+    break;
+
+  case 265:
+/* Line 1807 of yacc.c  */
+#line 1127 "fortran.y"
+    { sprintf((yyval.na),"MINLOC(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 266:
+/* Line 1807 of yacc.c  */
+#line 1128 "fortran.y"
+    { sprintf((yyval.na),"MAXLOC(%s)",(yyvsp[(3) - (4)].na));}
+    break;
+
+  case 267:
+/* Line 1807 of yacc.c  */
+#line 1130 "fortran.y"
+    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 268:
+/* Line 1807 of yacc.c  */
+#line 1131 "fortran.y"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 269:
+/* Line 1807 of yacc.c  */
+#line 1133 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 270:
+/* Line 1807 of yacc.c  */
+#line 1134 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 271:
+/* Line 1807 of yacc.c  */
+#line 1135 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 272:
+/* Line 1807 of yacc.c  */
+#line 1136 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 273:
+/* Line 1807 of yacc.c  */
+#line 1137 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 274:
+/* Line 1807 of yacc.c  */
+#line 1138 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 275:
+/* Line 1807 of yacc.c  */
+#line 1140 "fortran.y"
+    { strcpy((yyval.na),"+"); }
+    break;
+
+  case 276:
+/* Line 1807 of yacc.c  */
+#line 1141 "fortran.y"
+    { strcpy((yyval.na),"-"); }
+    break;
+
+  case 277:
+/* Line 1807 of yacc.c  */
+#line 1145 "fortran.y"
+    { sprintf((yyval.na),"+%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 278:
+/* Line 1807 of yacc.c  */
+#line 1146 "fortran.y"
+    { sprintf((yyval.na),"-%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 279:
+/* Line 1807 of yacc.c  */
+#line 1147 "fortran.y"
+    { sprintf((yyval.na),"*%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 280:
+/* Line 1807 of yacc.c  */
+#line 1148 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 281:
+/* Line 1807 of yacc.c  */
+#line 1149 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 282:
+/* Line 1807 of yacc.c  */
+#line 1150 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 283:
+/* Line 1807 of yacc.c  */
+#line 1151 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 284:
+/* Line 1807 of yacc.c  */
+#line 1152 "fortran.y"
+    { sprintf((yyval.na)," > %s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 285:
+/* Line 1807 of yacc.c  */
+#line 1153 "fortran.y"
+    { sprintf((yyval.na)," < %s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 286:
+/* Line 1807 of yacc.c  */
+#line 1154 "fortran.y"
+    { sprintf((yyval.na)," >= %s",(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 287:
+/* Line 1807 of yacc.c  */
+#line 1155 "fortran.y"
+    { sprintf((yyval.na)," <= %s",(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 288:
+/* Line 1807 of yacc.c  */
+#line 1156 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 289:
+/* Line 1807 of yacc.c  */
+#line 1157 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 290:
+/* Line 1807 of yacc.c  */
+#line 1158 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 291:
+/* Line 1807 of yacc.c  */
+#line 1159 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 292:
+/* Line 1807 of yacc.c  */
+#line 1160 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 293:
+/* Line 1807 of yacc.c  */
+#line 1161 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 294:
+/* Line 1807 of yacc.c  */
+#line 1162 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 295:
+/* Line 1807 of yacc.c  */
+#line 1163 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 296:
+/* Line 1807 of yacc.c  */
+#line 1164 "fortran.y"
+    { sprintf((yyval.na),"%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 297:
+/* Line 1807 of yacc.c  */
+#line 1165 "fortran.y"
+    { sprintf((yyval.na),"%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 298:
+/* Line 1807 of yacc.c  */
+#line 1167 "fortran.y"
+    { strcpy((yyval.na),""); }
+    break;
+
+  case 299:
+/* Line 1807 of yacc.c  */
+#line 1168 "fortran.y"
+    { sprintf((yyval.na),"/%s",(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 300:
+/* Line 1807 of yacc.c  */
+#line 1169 "fortran.y"
+    { sprintf((yyval.na),"/= %s",(yyvsp[(2) - (2)].na));}
+    break;
+
+  case 301:
+/* Line 1807 of yacc.c  */
+#line 1170 "fortran.y"
+    { sprintf((yyval.na),"//%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 302:
+/* Line 1807 of yacc.c  */
+#line 1173 "fortran.y"
+    { sprintf((yyval.na),"==%s",(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 303:
+/* Line 1807 of yacc.c  */
+#line 1174 "fortran.y"
+    { sprintf((yyval.na),"= %s",(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 304:
+/* Line 1807 of yacc.c  */
+#line 1177 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 305:
+/* Line 1807 of yacc.c  */
+#line 1178 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 306:
+/* Line 1807 of yacc.c  */
+#line 1179 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 307:
+/* Line 1807 of yacc.c  */
+#line 1183 "fortran.y"
     {
-                     if ( couldaddvariable == 1 ) Add_Save_Var_1((yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].d));
-                  ;}
-    break;
-
-  case 127:
-#line 999 "fortran.y"
+            agrif_parentcall = 0;
+            if ( !strcasecmp(identcopy, "Agrif_Parent") )   agrif_parentcall = 1;
+            if ( Agrif_in_Tok_NAME(identcopy) )
+            {
+                inagrifcallargument = 1;
+                Add_SubroutineWhereAgrifUsed_1(subroutinename, curmodulename);
+            }
+        }
+    break;
+
+  case 308:
+/* Line 1807 of yacc.c  */
+#line 1194 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); if ( incalldeclare == 0 ) inagrifcallargument = 0;   }
+    break;
+
+  case 309:
+/* Line 1807 of yacc.c  */
+#line 1195 "fortran.y"
+    { sprintf((yyval.na)," %s %s ",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 310:
+/* Line 1807 of yacc.c  */
+#line 1196 "fortran.y"
+    { sprintf((yyval.na)," %s ( %s )",(yyvsp[(1) - (4)].na),(yyvsp[(3) - (4)].na)); }
+    break;
+
+  case 311:
+/* Line 1807 of yacc.c  */
+#line 1197 "fortran.y"
+    { sprintf((yyval.na)," %s ( %s ) %s ",(yyvsp[(1) - (5)].na),(yyvsp[(3) - (5)].na),(yyvsp[(5) - (5)].na)); }
+    break;
+
+  case 312:
+/* Line 1807 of yacc.c  */
+#line 1201 "fortran.y"
     {
-		(yyval.lnn)=Insertname(NULL,(yyvsp[(1) - (1)].nac),0);
-		;}
-    break;
-
-  case 128:
-#line 1003 "fortran.y"
+            if ( inside_type_declare ) break;
+            sprintf((yyval.na)," %s ( %s )",(yyvsp[(1) - (4)].na),(yyvsp[(3) - (4)].na));
+            ModifyTheAgrifFunction_0((yyvsp[(3) - (4)].na));
+            agrif_parentcall = 0;
+        }
+    break;
+
+  case 313:
+/* Line 1807 of yacc.c  */
+#line 1210 "fortran.y"
     {
-      printf("INSTRUCTION NON TRAITEE : INITIALISATION DE DATA AVEC EXPRESSION\n");
-      exit(0);
-      ;}
-    break;
-
-  case 129:
-#line 1008 "fortran.y"
-    {
-      (yyval.lnn) = concat_listname((yyvsp[(1) - (3)].lnn),(yyvsp[(3) - (3)].lnn));
-      ;}
-    break;
-
-  case 130:
-#line 1013 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].nac));;}
-    break;
-
-  case 131:
-#line 1015 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s+%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 132:
-#line 1017 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s-%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 133:
-#line 1019 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s*%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 134:
-#line 1021 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s/%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 135:
-#line 1024 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),"");;}
-    break;
-
-  case 136:
-#line 1026 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 143:
-#line 1038 "fortran.y"
-    {
-	ininterfacedeclare = 1 ;
-	printf("INTEFACE entree\n");
-	;}
-    break;
-
-  case 144:
-#line 1043 "fortran.y"
-    {
-      ininterfacedeclare = 0;
-      ;}
-    break;
-
-  case 145:
-#line 1048 "fortran.y"
-    {
-                      positioninblock=0;
-                      pos_curdimension = setposcur()-9;
-                   ;}
-    break;
-
-  case 146:
-#line 1054 "fortran.y"
-    {
-         if ( couldaddvariable == 1 )
-         {
-            /*                                                                */
-            curvar=createvar((yyvsp[(3) - (5)].nac),(yyvsp[(4) - (5)].d));
-            /*                                                                */
-            CreateAndFillin_Curvar("",curvar);
-            /*                                                                */
-            curlistvar=insertvar(NULL,curvar);
-            /*                                                                */
-            (yyval.l)=settype("",curlistvar);
-            /*                                                                */
-            strcpy(vallengspec,"");
-         }
-      ;}
-    break;
-
-  case 147:
-#line 1070 "fortran.y"
-    {
-         if ( couldaddvariable == 1 )
-         {
-            /*                                                                */
-            curvar=createvar((yyvsp[(3) - (5)].nac),(yyvsp[(4) - (5)].d));
-            /*                                                                */
-            CreateAndFillin_Curvar("",curvar);
-            /*                                                                */
-            curlistvar=insertvar((yyvsp[(1) - (5)].l),curvar);
-            /*                                                                */
-            (yyval.l)=curlistvar;
-            /*                                                                */
-            strcpy(vallengspec,"");
-         }
-      ;}
-    break;
-
-  case 150:
-#line 1090 "fortran.y"
-    {
-        (yyval.lnn)=(listname *)NULL;
-        ;}
-    break;
-
-  case 151:
-#line 1094 "fortran.y"
-    {
-          (yyval.lnn)=(yyvsp[(3) - (3)].lnn);
-         ;}
-    break;
-
-  case 152:
-#line 1099 "fortran.y"
-    {
-           (yyval.lnn) = Insertname(NULL,(yyvsp[(1) - (1)].nac),0);
-           ;}
-    break;
-
-  case 153:
-#line 1103 "fortran.y"
-    {
-          (yyval.lnn) = Insertname((yyvsp[(1) - (3)].lnn),(yyvsp[(3) - (3)].nac),0);
-          ;}
-    break;
-
-  case 154:
-#line 1108 "fortran.y"
-    {
-                         pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_curcommon,
-                                                  pos_end-pos_curcommon);
-                   ;}
-    break;
-
-  case 155:
-#line 1114 "fortran.y"
-    {
-                         if ( couldaddvariable == 1 )
-                         {
-                            sprintf(charusemodule,"%s",(yyvsp[(2) - (3)].nac));
-                            Add_NameOfCommon_1((yyvsp[(2) - (3)].nac),subroutinename);
-                            pos_end = setposcur();
-                            RemoveWordSET_0(fortranout,pos_curcommon,
-                                                       pos_end-pos_curcommon);
-                         }
-                   ;}
-    break;
-
-  case 156:
-#line 1125 "fortran.y"
-    {
-                         if ( couldaddvariable == 1 )
-                         {
-                            sprintf(charusemodule,"%s",(yyvsp[(3) - (5)].nac));
-                            Add_NameOfCommon_1((yyvsp[(3) - (5)].nac),subroutinename);
-                            pos_end = setposcur();
-                            RemoveWordSET_0(fortranout,pos_curcommon,
-                                                       pos_end-pos_curcommon);
-                         }
-                   ;}
-    break;
-
-  case 157:
-#line 1137 "fortran.y"
-    {
-                      positioninblock=0;
-                      pos_curcommon = setposcur()-6;
-                   ;}
-    break;
-
-  case 158:
-#line 1142 "fortran.y"
-    {
-                      positioninblock=0;
-                      pos_curcommon = setposcur()-6-7;
-                   ;}
-    break;
-
-  case 159:
-#line 1148 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 ) Add_Common_var_1();
-                   ;}
-    break;
-
-  case 160:
-#line 1153 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 ) Add_Common_var_1();
-                   ;}
-    break;
-
-  case 161:
-#line 1157 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                         positioninblock = positioninblock + 1 ;
-                         strcpy(commonvar,(yyvsp[(1) - (2)].nac));
-                         commondim = (yyvsp[(2) - (2)].d);
-                      }
-                   ;}
-    break;
-
-  case 162:
-#line 1167 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                         strcpy((yyval.nac),"");
-                         positioninblock=0;
-                         strcpy(commonblockname,"");
-                      }
-                   ;}
-    break;
-
-  case 163:
-#line 1176 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                         strcpy((yyval.nac),(yyvsp[(2) - (3)].nac));
-                         positioninblock=0;
-                         strcpy(commonblockname,(yyvsp[(2) - (3)].nac));
-                      }
-                   ;}
-    break;
-
-  case 166:
-#line 1189 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 ) (yyval.l)=insertvar(NULL,(yyvsp[(1) - (1)].v));
-                   ;}
-    break;
-
-  case 167:
-#line 1193 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 ) (yyval.l)=insertvar((yyvsp[(1) - (3)].l),(yyvsp[(3) - (3)].v));
-                   ;}
-    break;
-
-  case 168:
-#line 1198 "fortran.y"
-    {
-                     if ( couldaddvariable == 1 )
-                     {
-                         curvar=(variable *) malloc(sizeof(variable));
-                         /*                                                   */
-                         Init_Variable(curvar);
-                         /*                                                   */
-                         curvar->v_VariableIsParameter=1;
-                         strcpy(curvar->v_nomvar,(yyvsp[(1) - (3)].nac));
-                         Save_Length((yyvsp[(1) - (3)].nac),4);
-                         strcpy(curvar->v_subroutinename,subroutinename);
-                         Save_Length(subroutinename,11);
-                         strcpy(curvar->v_modulename,curmodulename);
-                         Save_Length(curmodulename,6);
-                         strcpy(curvar->v_initialvalue,(yyvsp[(3) - (3)].na));
-                         Save_Length((yyvsp[(3) - (3)].na),14);
-                         strcpy(curvar->v_commoninfile,mainfile);
-                         Save_Length(mainfile,10);
-                         (yyval.v)=curvar;
-                      }
-                   ;}
-    break;
-
-  case 172:
-#line 1226 "fortran.y"
-    {
-                       if ( insubroutinedeclare == 1 )
-                       {
-                          Add_ImplicitNoneSubroutine_1();
-                          pos_end = setposcur();
-                          RemoveWordSET_0(fortranout,pos_end-13,
-                                                             13);
-                       }
-                    ;}
-    break;
-
-  case 175:
+            sprintf((yyval.na)," %s %% %s ",(yyvsp[(1) - (4)].na),(yyvsp[(4) - (4)].na));
+            if ( incalldeclare == 0 ) inagrifcallargument = 0;
+        }
+    break;
+
+  case 314:
+/* Line 1807 of yacc.c  */
+#line 1216 "fortran.y"
+    { sprintf((yyval.na),"(/%s/)",(yyvsp[(2) - (3)].na)); }
+    break;
+
+  case 315:
+/* Line 1807 of yacc.c  */
+#line 1219 "fortran.y"
+    { strcpy((yyval.na)," "); }
+    break;
+
+  case 316:
+/* Line 1807 of yacc.c  */
+#line 1220 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 317:
+/* Line 1807 of yacc.c  */
+#line 1223 "fortran.y"
+    {  strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 318:
+/* Line 1807 of yacc.c  */
+#line 1224 "fortran.y"
+    {  sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 319:
+/* Line 1807 of yacc.c  */
+#line 1227 "fortran.y"
+    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 320:
+/* Line 1807 of yacc.c  */
+#line 1228 "fortran.y"
+    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 321:
+/* Line 1807 of yacc.c  */
+#line 1231 "fortran.y"
+    {  sprintf((yyval.na),"%s :%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));}
+    break;
+
+  case 322:
+/* Line 1807 of yacc.c  */
+#line 1232 "fortran.y"
+    {  sprintf((yyval.na),"%s :%s :%s",(yyvsp[(1) - (5)].na),(yyvsp[(3) - (5)].na),(yyvsp[(5) - (5)].na));}
+    break;
+
+  case 323:
+/* Line 1807 of yacc.c  */
+#line 1233 "fortran.y"
+    {  sprintf((yyval.na),":%s :%s",(yyvsp[(2) - (4)].na),(yyvsp[(4) - (4)].na));}
+    break;
+
+  case 324:
+/* Line 1807 of yacc.c  */
+#line 1234 "fortran.y"
+    {  sprintf((yyval.na),": : %s",(yyvsp[(3) - (3)].na));}
+    break;
+
+  case 325:
+/* Line 1807 of yacc.c  */
+#line 1235 "fortran.y"
+    {  sprintf((yyval.na),":%s",(yyvsp[(2) - (2)].na));}
+    break;
+
+  case 326:
+/* Line 1807 of yacc.c  */
+#line 1236 "fortran.y"
+    {  sprintf((yyval.na),"%s :",(yyvsp[(1) - (2)].na));}
+    break;
+
+  case 327:
+/* Line 1807 of yacc.c  */
+#line 1237 "fortran.y"
+    {  sprintf((yyval.na),":");}
+    break;
+
+  case 328:
+/* Line 1807 of yacc.c  */
 #line 1240 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         /*                                                   */
-                         if (dimsgiven == 1)
-                         {
-                            curvar=createvar((yyvsp[(3) - (6)].nac),curdim);
-                            GlobalDeclarationType == 0;
-                         }
-                         else
-                         {
-                            curvar=createvar((yyvsp[(3) - (6)].nac),(yyvsp[(4) - (6)].d));
-                         }
-                         /*                                                   */
-                         CreateAndFillin_Curvar(DeclType,curvar);
-                         /*                                                   */
-                         curlistvar=insertvar(NULL,curvar);
-                         if (!strcasecmp(DeclType,"character"))
-                         {
-                            if (c_selectorgiven == 1)
+            if ( afterpercent == 0 )
+            {
+                if ( Agrif_in_Tok_NAME((yyvsp[(1) - (1)].na)) ) Add_SubroutineWhereAgrifUsed_1(subroutinename, curmodulename);
+                if ( !strcasecmp((yyvsp[(1) - (1)].na),"Agrif_Parent") )   agrif_parentcall = 1;
+                if ( VariableIsFunction((yyvsp[(1) - (1)].na)) )
+                {
+                    if ( inagrifcallargument == 1 )
+                    {
+                        if ( !strcasecmp((yyvsp[(1) - (1)].na),identcopy) )
+                        {
+                            strcpy(sameagrifname,identcopy);
+                            sameagrifargument = 1;
+                        }
+                    }
+                    strcpy(identcopy,(yyvsp[(1) - (1)].na));
+                    pointedvar = 0;
+
+                    if (variscoupled_0((yyvsp[(1) - (1)].na))) strcpy(truename, getcoupledname_0((yyvsp[(1) - (1)].na)));
+                    else                    strcpy(truename, (yyvsp[(1) - (1)].na));
+
+                    if ( VarIsNonGridDepend(truename) == 0 && (! Variableshouldberemoved(truename)) )
+                    {
+                        if ( inagrifcallargument == 1 || varispointer_0(truename) == 1 )
+                        {
+                            if ( (IsinListe(List_UsedInSubroutine_Var,(yyvsp[(1) - (1)].na)) == 1) || (inagrifcallargument == 1) )
                             {
-                               strcpy(c_selectordim.first,"1");
-                               strcpy(c_selectordim.last,c_selectorname);
-                               Save_Length(c_selectorname,1);
-                               change_dim_char
-                                     (insertdim(NULL,c_selectordim),curlistvar);
+                                if (varistyped_0(truename) == 0)    ModifyTheVariableName_0(truename,strlen((yyvsp[(1) - (1)].na)));
                             }
-                         }
-                         (yyval.l)=settype(DeclType,curlistvar);
-                      }
-                      strcpy(vallengspec,"");
-                   ;}
-    break;
-
-  case 176:
-#line 1273 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                         if (dimsgiven == 1)
-                         {
-                            curvar=createvar((yyvsp[(4) - (7)].nac),curdim);
-                         }
-                         else
-                         {
-                            curvar=createvar((yyvsp[(4) - (7)].nac),(yyvsp[(5) - (7)].d));
-                         }
-                         /*                                                   */
-                         CreateAndFillin_Curvar((yyvsp[(1) - (7)].l)->var->v_typevar,curvar);
-                         /*                                                   */
-                         strcpy(curvar->v_typevar,((yyvsp[(1) - (7)].l)->var->v_typevar));
-                         Save_Length((yyvsp[(1) - (7)].l)->var->v_typevar,3);
-                         /*                                                   */
-                         curlistvar=insertvar((yyvsp[(1) - (7)].l),curvar);
-                         if (!strcasecmp(DeclType,"character"))
-                         {
-                            if (c_selectorgiven == 1)
-                            {
-                               strcpy(c_selectordim.first,"1");
-                               strcpy(c_selectordim.last,c_selectorname);
-                               Save_Length(c_selectorname,1);
-                               change_dim_char
-                                     (insertdim(NULL,c_selectordim),curlistvar);
-                            }
-                         }
-                         (yyval.l)=curlistvar;
-                      }
-                      strcpy(vallengspec,"");
-                   ;}
-    break;
-
-  case 177:
+                        }
+                        if ( inagrifcallargument != 1 || sameagrifargument ==1 )
+                        {
+                            Add_UsedInSubroutine_Var_1(truename);
+                        }
+                    }
+                    NotifyAgrifFunction_0(truename);
+                }
+            }
+            else
+            {
+                afterpercent = 0;
+            }
+        }
+    break;
+
+  case 329:
+/* Line 1807 of yacc.c  */
+#line 1285 "fortran.y"
+    { strcpy((yyval.na),".TRUE.");}
+    break;
+
+  case 330:
+/* Line 1807 of yacc.c  */
+#line 1286 "fortran.y"
+    { strcpy((yyval.na),".FALSE.");}
+    break;
+
+  case 331:
+/* Line 1807 of yacc.c  */
+#line 1287 "fortran.y"
+    { strcpy((yyval.na),"NULL()"); }
+    break;
+
+  case 332:
+/* Line 1807 of yacc.c  */
+#line 1288 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 333:
+/* Line 1807 of yacc.c  */
+#line 1289 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 334:
+/* Line 1807 of yacc.c  */
+#line 1290 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 335:
+/* Line 1807 of yacc.c  */
+#line 1292 "fortran.y"
+    { sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na)); }
+    break;
+
+  case 337:
+/* Line 1807 of yacc.c  */
+#line 1296 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 339:
+/* Line 1807 of yacc.c  */
+#line 1298 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 340:
+/* Line 1807 of yacc.c  */
+#line 1299 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 341:
+/* Line 1807 of yacc.c  */
+#line 1301 "fortran.y"
+    { strcpy((yyval.na)," ");}
+    break;
+
+  case 342:
+/* Line 1807 of yacc.c  */
+#line 1302 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 343:
+/* Line 1807 of yacc.c  */
+#line 1305 "fortran.y"
+    { sprintf((yyval.na),"(%s :%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na));}
+    break;
+
+  case 344:
+/* Line 1807 of yacc.c  */
 #line 1307 "fortran.y"
-    {dimsgiven=0;;}
-    break;
-
-  case 178:
-#line 1310 "fortran.y"
-    {strcpy(DeclType,(yyvsp[(1) - (2)].nac));;}
-    break;
-
-  case 179:
+    { strcpy((yyval.na)," ");}
+    break;
+
+  case 345:
+/* Line 1807 of yacc.c  */
+#line 1308 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 346:
+/* Line 1807 of yacc.c  */
+#line 1311 "fortran.y"
+    { strcpy((yyval.na)," ");}
+    break;
+
+  case 347:
+/* Line 1807 of yacc.c  */
 #line 1312 "fortran.y"
-    {
-                      strcpy(DeclType,"CHARACTER");
-                   ;}
-    break;
-
-  case 180:
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 348:
+/* Line 1807 of yacc.c  */
+#line 1314 "fortran.y"
+    { InitialValueGiven = 0; }
+    break;
+
+  case 349:
+/* Line 1807 of yacc.c  */
 #line 1316 "fortran.y"
     {
-                      strcpy(DeclType,(yyvsp[(1) - (3)].nac));
-                      strcpy(nameinttypename,(yyvsp[(3) - (3)].nac));
-                   ;}
-    break;
-
-  case 181:
-#line 1321 "fortran.y"
+            if ( inside_type_declare ) break;
+            strcpy(InitValue,(yyvsp[(2) - (2)].na));
+            InitialValueGiven = 1;
+        }
+    break;
+
+  case 350:
+/* Line 1807 of yacc.c  */
+#line 1322 "fortran.y"
     {
-                      strcpy(DeclType,"TYPE");
-                      GlobalDeclarationType = 1
-                   ;}
-    break;
-
-  case 182:
-#line 1327 "fortran.y"
+            if ( inside_type_declare ) break;
+            strcpy(InitValue,(yyvsp[(2) - (2)].na));
+            InitialValueGiven = 2;
+        }
+    break;
+
+  case 351:
+/* Line 1807 of yacc.c  */
+#line 1329 "fortran.y"
+    {sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na)); }
+    break;
+
+  case 352:
+/* Line 1807 of yacc.c  */
+#line 1333 "fortran.y"
     {
-                 /*     if ( couldaddvariable == 1 ) VarTypepar = 1 ;
-                      couldaddvariable = 0 ;
-                      pos_cur_decl = setposcur()-5;*/
-                   pos_cur_decl = setposcur()-5;
-                   ;}
-    break;
-
-  case 184:
-#line 1336 "fortran.y"
-    {c_selectorgiven=1;strcpy(c_selectorname,(yyvsp[(2) - (2)].nac));;}
-    break;
-
-  case 185:
-#line 1337 "fortran.y"
-    {c_star = 1;;}
-    break;
-
-  case 190:
-#line 1345 "fortran.y"
+            /* if variables has been declared in a subroutine       */
+            sprintf(charusemodule, "%s", (yyvsp[(2) - (2)].na));
+            if ( firstpass )
+            {
+                Add_NameOfModuleUsed_1((yyvsp[(2) - (2)].na));
+            }
+            else
+            {
+                if ( insubroutinedeclare )
+                    copyuse_0((yyvsp[(2) - (2)].na));
+
+                if ( inmoduledeclare == 0 )
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+                }
+            }
+        }
+    break;
+
+  case 353:
+/* Line 1807 of yacc.c  */
+#line 1353 "fortran.y"
     {
-                      pos_cur_decl = setposcur()-9;
-                   ;}
-    break;
-
-  case 191:
-#line 1349 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 192:
-#line 1352 "fortran.y"
+            if ( firstpass )
+            {
+                if ( insubroutinedeclare )
+                {
+                    Add_CouplePointed_Var_1((yyvsp[(2) - (4)].na),(yyvsp[(4) - (4)].lc));
+                    coupletmp = (yyvsp[(4) - (4)].lc);
+                    strcpy(ligne,"");
+                    while ( coupletmp )
+                    {
+                        strcat(ligne, coupletmp->c_namevar);
+                        strcat(ligne, " => ");
+                        strcat(ligne, coupletmp->c_namepointedvar);
+                        coupletmp = coupletmp->suiv;
+                        if ( coupletmp ) strcat(ligne,",");
+                    }
+                    sprintf(charusemodule,"%s",(yyvsp[(2) - (4)].na));
+                }
+                Add_NameOfModuleUsed_1((yyvsp[(2) - (4)].na));
+            }
+            if ( inmoduledeclare == 0 )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+            }
+        }
+    break;
+
+  case 354:
+/* Line 1807 of yacc.c  */
+#line 1380 "fortran.y"
     {
-                      strcpy((yyval.nac),"INTEGER");
-                      pos_cur_decl = setposcur()-7;
-                   ;}
-    break;
-
-  case 193:
-#line 1356 "fortran.y"
+            /* if variables has been declared in a subroutine       */
+            sprintf(charusemodule,"%s",(yyvsp[(2) - (6)].na));
+            if ( firstpass )
+            {
+                Add_NameOfModuleUsed_1((yyvsp[(2) - (6)].na));
+            }
+            else
+            {
+                if ( insubroutinedeclare )
+                    copyuseonly_0((yyvsp[(2) - (6)].na));
+
+                if ( inmoduledeclare == 0 )
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+                }
+            }
+        }
+    break;
+
+  case 355:
+/* Line 1807 of yacc.c  */
+#line 1400 "fortran.y"
     {
-                      strcpy((yyval.nac),"REAL");
-                      pos_cur_decl = setposcur()-4;
-                   ;}
-    break;
-
-  case 194:
-#line 1361 "fortran.y"
-    {strcpy((yyval.nac),"COMPLEX");
-                   pos_cur_decl = setposcur()-7;;}
-    break;
-
-  case 195:
-#line 1364 "fortran.y"
+            /* if variables has been declared in a subroutine      */
+            if ( firstpass )
+            {
+                if ( insubroutinedeclare )
+                {
+                    Add_CouplePointed_Var_1((yyvsp[(2) - (6)].na),(yyvsp[(6) - (6)].lc));
+                    coupletmp = (yyvsp[(6) - (6)].lc);
+                    strcpy(ligne,"");
+                    while ( coupletmp )
+                    {
+                        strcat(ligne,coupletmp->c_namevar);
+                        if ( strcasecmp(coupletmp->c_namepointedvar,"") )   strcat(ligne," => ");
+                        strcat(ligne,coupletmp->c_namepointedvar);
+                        coupletmp = coupletmp->suiv;
+                        if ( coupletmp ) strcat(ligne,",");
+                    }
+                    sprintf(charusemodule,"%s",(yyvsp[(2) - (6)].na));
+                }
+                Add_NameOfModuleUsed_1((yyvsp[(2) - (6)].na));
+            }
+            else /* if ( firstpass == 0 ) */
+            {
+                if ( inmoduledeclare == 0 )
+                {
+                    pos_end = setposcur();
+                    RemoveWordSET_0(fortran_out,pos_curuse,pos_end-pos_curuse);
+                    if (oldfortran_out)  variableisglobalinmodule((yyvsp[(6) - (6)].lc),(yyvsp[(2) - (6)].na),oldfortran_out,pos_curuseold);
+                }
+                else
+                {
+                    /* if we are in the module declare and if the    */
+                    /* onlylist is a list of global variable         */
+                    variableisglobalinmodule((yyvsp[(6) - (6)].lc), (yyvsp[(2) - (6)].na), fortran_out,pos_curuse);
+                }
+            }
+        }
+    break;
+
+  case 356:
+/* Line 1807 of yacc.c  */
+#line 1440 "fortran.y"
     {
-                      pos_cur_decl = setposcur()-16;
-                      strcpy((yyval.nac),"REAL");
-                      strcpy(nameinttypename,"8");
-                   ;}
-    break;
-
-  case 196:
-#line 1370 "fortran.y"
-    {strcpy((yyval.nac),"DOUBLE COMPLEX");;}
-    break;
-
-  case 197:
-#line 1372 "fortran.y"
+            pos_curuse = setposcur()-strlen((yyvsp[(1) - (1)].na));
+            if (firstpass == 0 && oldfortran_out) pos_curuseold = setposcurname(oldfortran_out);
+        }
+    break;
+
+  case 357:
+/* Line 1807 of yacc.c  */
+#line 1447 "fortran.y"
     {
-                      strcpy((yyval.nac),"LOGICAL");
-                      pos_cur_decl = setposcur()-7;
-                   ;}
-    break;
-
-  case 199:
-#line 1378 "fortran.y"
-    {strcpy(vallengspec,(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 200:
-#line 1380 "fortran.y"
-    {sprintf((yyval.na),"*%s",(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 201:
-#line 1381 "fortran.y"
-    {strcpy((yyval.na),"*(*)");;}
-    break;
-
-  case 208:
-#line 1392 "fortran.y"
+            (yyval.lc) = (yyvsp[(1) - (1)].lc);
+        }
+    break;
+
+  case 358:
+/* Line 1807 of yacc.c  */
+#line 1451 "fortran.y"
     {
-                      if ( strstr((yyvsp[(3) - (3)].na),"0.d0") )
-                      {
-                         strcpy(nameinttypename,"8");
-                         sprintf(NamePrecision,"");
-                      }
-                      else sprintf(NamePrecision,"%s = %s",(yyvsp[(1) - (3)].nac),(yyvsp[(3) - (3)].na));
-                   ;}
-    break;
-
-  case 209:
-#line 1401 "fortran.y"
+            /* insert the variable in the list $1                 */
+            (yyvsp[(3) - (3)].lc)->suiv = (yyvsp[(1) - (3)].lc);
+            (yyval.lc) = (yyvsp[(3) - (3)].lc);
+        }
+    break;
+
+  case 359:
+/* Line 1807 of yacc.c  */
+#line 1458 "fortran.y"
     {
-                      strcpy(NamePrecision,(yyvsp[(1) - (1)].nac));
-                   ;}
-    break;
-
-  case 210:
-#line 1405 "fortran.y"
+            coupletmp = (listcouple *) calloc(1,sizeof(listcouple));
+            strcpy(coupletmp->c_namevar,(yyvsp[(1) - (3)].na));
+            strcpy(coupletmp->c_namepointedvar,(yyvsp[(3) - (3)].na));
+            coupletmp->suiv = NULL;
+            (yyval.lc) = coupletmp;
+        }
+    break;
+
+  case 360:
+/* Line 1807 of yacc.c  */
+#line 1467 "fortran.y"
+    {  (yyval.lc) = (yyvsp[(1) - (1)].lc); }
+    break;
+
+  case 361:
+/* Line 1807 of yacc.c  */
+#line 1469 "fortran.y"
     {
-                      strcpy(NamePrecision,(yyvsp[(1) - (1)].nac));
-                   ;}
-    break;
-
-  case 211:
-#line 1409 "fortran.y"
-    {strcpy(CharacterSize,(yyvsp[(1) - (1)].na));
-                    strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 212:
-#line 1411 "fortran.y"
-    {strcpy(CharacterSize,"*");
-                    strcpy((yyval.na),"*");;}
-    break;
-
-  case 220:
-#line 1425 "fortran.y"
+            /* insert the variable in the list $1                 */
+            (yyvsp[(3) - (3)].lc)->suiv = (yyvsp[(1) - (3)].lc);
+            (yyval.lc) = (yyvsp[(3) - (3)].lc);
+        }
+    break;
+
+  case 362:
+/* Line 1807 of yacc.c  */
+#line 1477 "fortran.y"
     {
-                      VariableIsParameter = 1;
-                   ;}
-    break;
-
-  case 222:
-#line 1430 "fortran.y"
-    {Allocatabledeclare = 1;;}
-    break;
-
-  case 223:
-#line 1432 "fortran.y"
+            coupletmp = (listcouple *)calloc(1,sizeof(listcouple));
+            strcpy(coupletmp->c_namevar,(yyvsp[(1) - (3)].na));
+            strcpy(coupletmp->c_namepointedvar,(yyvsp[(3) - (3)].na));
+            coupletmp->suiv = NULL;
+            (yyval.lc) = coupletmp;
+            pointedvar = 1;
+            Add_UsedInSubroutine_Var_1((yyvsp[(1) - (3)].na));
+        }
+    break;
+
+  case 363:
+/* Line 1807 of yacc.c  */
+#line 1487 "fortran.y"
     {
-                      dimsgiven=1;
-                      curdim=(yyvsp[(2) - (2)].d);
-                   ;}
-    break;
-
-  case 224:
-#line 1437 "fortran.y"
-    {ExternalDeclare = 1;;}
-    break;
-
-  case 225:
-#line 1439 "fortran.y"
-    {strcpy(IntentSpec,(yyvsp[(3) - (4)].nac));;}
-    break;
-
-  case 227:
-#line 1441 "fortran.y"
-    {optionaldeclare = 1 ;;}
-    break;
-
-  case 228:
-#line 1442 "fortran.y"
-    {pointerdeclare = 1 ;;}
-    break;
-
-  case 229:
-#line 1443 "fortran.y"
+            coupletmp = (listcouple *)calloc(1,sizeof(listcouple));
+            strcpy(coupletmp->c_namevar,(yyvsp[(1) - (1)].na));
+            strcpy(coupletmp->c_namepointedvar,"");
+            coupletmp->suiv = NULL;
+            (yyval.lc) = coupletmp;
+        }
+    break;
+
+  case 380:
+/* Line 1807 of yacc.c  */
+#line 1522 "fortran.y"
+    { inallocate = 0; }
+    break;
+
+  case 381:
+/* Line 1807 of yacc.c  */
+#line 1523 "fortran.y"
+    { inallocate = 0; }
+    break;
+
+  case 388:
+/* Line 1807 of yacc.c  */
+#line 1531 "fortran.y"
     {
-/*                       if ( inmodulemeet == 1 )
-                       {*/
-                          SaveDeclare = 1 ;
-                     /*  }*/
-                    ;}
-    break;
-
-  case 230:
-#line 1450 "fortran.y"
-    {Targetdeclare = 1;;}
-    break;
-
-  case 231:
-#line 1452 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 232:
-#line 1453 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 233:
-#line 1454 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac)); ;}
-    break;
-
-  case 234:
-#line 1457 "fortran.y"
-    {PublicDeclare = 1;;}
-    break;
-
-  case 235:
-#line 1459 "fortran.y"
-    {PrivateDeclare = 1;;}
-    break;
-
-  case 236:
-#line 1461 "fortran.y"
-    {if ( created_dimensionlist == 1 )
-                       {
-                           (yyval.d)=(listdim *)NULL;
-                       }
-                   ;}
-    break;
-
-  case 237:
-#line 1467 "fortran.y"
-    {if ( created_dimensionlist == 1 ||
-                         agrif_parentcall      == 1 ) (yyval.d)=(yyvsp[(2) - (3)].d);;}
-    break;
-
-  case 238:
-#line 1470 "fortran.y"
-    {if ( created_dimensionlist == 1 ||
-                         agrif_parentcall      == 1 ) (yyval.d)=insertdim(NULL,(yyvsp[(1) - (1)].dim1));;}
-    break;
-
-  case 239:
-#line 1473 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                         if ( created_dimensionlist == 1 ) (yyval.d)=insertdim((yyvsp[(1) - (3)].d),(yyvsp[(3) - (3)].dim1));;}
-    break;
-
-  case 240:
-#line 1476 "fortran.y"
+            GlobalDeclaration = 0 ;
+            if ( firstpass == 0 && strcasecmp(subroutinename,"") )
+            {
+                if ( module_declar && insubroutinedeclare == 0 )    fclose(module_declar);
+            }
+            if ( strcasecmp(subroutinename,"") )
+            {
+                if ( inmodulemeet == 1 )
+                {
+                    /* we are in a module                                */
+                    if ( insubroutinedeclare == 1 )
+                    {
+                        /* it is like an end subroutine <name>            */
+                        insubroutinedeclare = 0 ;
+                        pos_cur = setposcur();
+                        closeandcallsubloopandincludeit_0(1);
+                        functiondeclarationisdone = 0;
+                    }
+                    else
+                    {
+                        /* it is like an end module <name>                */
+                        inmoduledeclare = 0 ;
+                        inmodulemeet = 0 ;
+                    }
+                }
+                else
+                {
+                    insubroutinedeclare = 0;
+                    pos_cur = setposcur();
+                    closeandcallsubloopandincludeit_0(2);
+                    functiondeclarationisdone = 0;
+                }
+            }
+            strcpy(subroutinename,"");
+        }
+    break;
+
+  case 389:
+/* Line 1807 of yacc.c  */
+#line 1568 "fortran.y"
     {
-                      strcpy((yyval.dim1).first,"1");
-                      strcpy((yyval.dim1).last,(yyvsp[(1) - (1)].na));
-                      Save_Length((yyvsp[(1) - (1)].na),1);
-                   ;}
-    break;
-
-  case 241:
-#line 1481 "fortran.y"
+            insubroutinedeclare = 0;
+            inprogramdeclare = 0;
+            pos_cur = setposcur();
+            closeandcallsubloopandincludeit_0(3);
+            functiondeclarationisdone = 0;
+            strcpy(subroutinename,"");
+        }
+    break;
+
+  case 390:
+/* Line 1807 of yacc.c  */
+#line 1577 "fortran.y"
     {
-                      strcpy((yyval.dim1).first,"");
-                      strcpy((yyval.dim1).last,"");
-                   ;}
-    break;
-
-  case 242:
-#line 1485 "fortran.y"
+            if ( strcasecmp(subroutinename,"") )
+            {
+                insubroutinedeclare = 0;
+                pos_cur = setposcur();
+                closeandcallsubloopandincludeit_0(1);
+                functiondeclarationisdone = 0;
+                strcpy(subroutinename,"");
+            }
+        }
+    break;
+
+  case 391:
+/* Line 1807 of yacc.c  */
+#line 1588 "fortran.y"
     {
-                      strcpy((yyval.dim1).first,(yyvsp[(1) - (2)].na));
-                      Save_Length((yyvsp[(1) - (2)].na),2);
-                      strcpy((yyval.dim1).last,"");
-                   ;}
-    break;
-
-  case 243:
-#line 1490 "fortran.y"
+            insubroutinedeclare = 0;
+            pos_cur = setposcur();
+            closeandcallsubloopandincludeit_0(0);
+            functiondeclarationisdone = 0;
+            strcpy(subroutinename,"");
+        }
+    break;
+
+  case 392:
+/* Line 1807 of yacc.c  */
+#line 1596 "fortran.y"
     {
-                      strcpy((yyval.dim1).first,"");
-                      strcpy((yyval.dim1).last,(yyvsp[(2) - (2)].na));
-                      Save_Length((yyvsp[(2) - (2)].na),1);
-                   ;}
-    break;
-
-  case 244:
-#line 1496 "fortran.y"
+            /* if we never meet the contains keyword               */
+            if ( firstpass == 0 )
+            {
+                RemoveWordCUR_0(fortran_out, strlen((yyvsp[(2) - (2)].na))+11);    // Remove word "end module"
+                if ( inmoduledeclare && ! aftercontainsdeclare )
+                {
+                    Write_Closing_Module(1);
+                }
+                fprintf(fortran_out,"\n      end module %s\n", curmodulename);
+                if ( module_declar && insubroutinedeclare == 0 )
+                {
+                    fclose(module_declar);
+                }
+            }
+            inmoduledeclare = 0 ;
+            inmodulemeet = 0 ;
+            aftercontainsdeclare = 1;
+            strcpy(curmodulename, "");
+            GlobalDeclaration = 0 ;
+        }
+    break;
+
+  case 395:
+/* Line 1807 of yacc.c  */
+#line 1620 "fortran.y"
     {
-                      strcpy((yyval.dim1).first,(yyvsp[(1) - (3)].na));
-                      Save_Length((yyvsp[(1) - (3)].na),2);
-                      strcpy((yyval.dim1).last,(yyvsp[(3) - (3)].na));
-                      Save_Length((yyvsp[(3) - (3)].na),1);
-                   ;}
-    break;
-
-  case 245:
-#line 1503 "fortran.y"
-    {strcpy((yyval.na),"*");;}
-    break;
-
-  case 246:
-#line 1504 "fortran.y"
-    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 247:
-#line 1506 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 248:
-#line 1508 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"(%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 249:
-#line 1510 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 250:
-#line 1512 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 251:
-#line 1516 "fortran.y"
-    {sprintf((yyval.na),"SUM(%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 252:
-#line 1518 "fortran.y"
-    {sprintf((yyval.na),"MAX(%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 253:
-#line 1520 "fortran.y"
-    {sprintf((yyval.na),"TANH(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 254:
-#line 1522 "fortran.y"
-    {sprintf((yyval.na),"MAXVAL(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 255:
-#line 1524 "fortran.y"
-    {sprintf((yyval.na),"MIN(%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 256:
-#line 1526 "fortran.y"
-    {sprintf((yyval.na),"MINVAL(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 257:
-#line 1528 "fortran.y"
-    {sprintf((yyval.na),"TRIM(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 258:
-#line 1530 "fortran.y"
-    {sprintf((yyval.na),"SQRT(%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 259:
-#line 1532 "fortran.y"
-    {sprintf((yyval.na),"REAL(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 260:
-#line 1534 "fortran.y"
-    {sprintf((yyval.na),"NINT(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 261:
-#line 1536 "fortran.y"
-    {sprintf((yyval.na),"FLOAT(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 262:
-#line 1538 "fortran.y"
-    {sprintf((yyval.na),"EXP(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 263:
-#line 1540 "fortran.y"
-    {sprintf((yyval.na),"COS(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 264:
-#line 1542 "fortran.y"
-    {sprintf((yyval.na),"COSH(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 265:
-#line 1544 "fortran.y"
-    {sprintf((yyval.na),"ACOS(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 266:
-#line 1546 "fortran.y"
-    {sprintf((yyval.na),"SIN(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 267:
-#line 1548 "fortran.y"
-    {sprintf((yyval.na),"SINH(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 268:
-#line 1550 "fortran.y"
-    {sprintf((yyval.na),"ASIN(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 269:
-#line 1552 "fortran.y"
-    {sprintf((yyval.na),"LOG(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 270:
-#line 1554 "fortran.y"
-    {sprintf((yyval.na),"TAN(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 271:
-#line 1556 "fortran.y"
-    {sprintf((yyval.na),"ATAN(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 272:
-#line 1558 "fortran.y"
-    {sprintf((yyval.na),"ABS(%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 273:
-#line 1560 "fortran.y"
-    {sprintf((yyval.na),"MOD(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 274:
-#line 1562 "fortran.y"
-    {sprintf((yyval.na),"SIGN(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 275:
-#line 1564 "fortran.y"
-    {sprintf((yyval.na),"MINLOC(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 276:
-#line 1566 "fortran.y"
-    {sprintf((yyval.na),"MAXLOC(%s)",(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 277:
-#line 1568 "fortran.y"
-    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 278:
-#line 1570 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                   { strcpy((yyval.na),(yyvsp[(1) - (3)].na));strcat((yyval.na),",");strcat((yyval.na),(yyvsp[(3) - (3)].na));};}
-    break;
-
-  case 279:
-#line 1573 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 280:
-#line 1575 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 281:
-#line 1577 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 282:
-#line 1579 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 283:
-#line 1581 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 284:
-#line 1583 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 285:
-#line 1585 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),"+");;}
-    break;
-
-  case 286:
-#line 1586 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),"-");;}
-    break;
-
-  case 287:
-#line 1589 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"+%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 288:
-#line 1591 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"-%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 289:
-#line 1593 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"*%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 290:
-#line 1595 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 291:
-#line 1597 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 292:
-#line 1599 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 293:
-#line 1601 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 294:
-#line 1603 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na)," > %s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 295:
-#line 1605 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 296:
-#line 1607 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na)," < %s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 297:
-#line 1609 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 298:
-#line 1611 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na)," >= %s",(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 299:
-#line 1613 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 300:
-#line 1615 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na)," <= %s",(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 301:
-#line 1617 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 302:
-#line 1619 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 303:
-#line 1621 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 304:
-#line 1623 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 305:
-#line 1625 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 306:
-#line 1627 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 307:
-#line 1629 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 308:
-#line 1631 "fortran.y"
-    {strcpy((yyval.na),"");;}
-    break;
-
-  case 309:
-#line 1633 "fortran.y"
-    {sprintf((yyval.na),"/%s",(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 310:
-#line 1635 "fortran.y"
-    {sprintf((yyval.na),"/= %s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 311:
-#line 1637 "fortran.y"
-    {sprintf((yyval.na),"//%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 312:
-#line 1640 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"==%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 313:
-#line 1642 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"= %s",(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 314:
-#line 1645 "fortran.y"
-    {if ( couldaddvariable == 1 )
-						{
-						printf("ident = %s\n",(yyvsp[(1) - (1)].nac));
-						strcpy((yyval.na),(yyvsp[(1) - (1)].nac));}
-						;}
-    break;
-
-  case 315:
-#line 1651 "fortran.y"
-    {if ( couldaddvariable == 1 ) {
-                   printf("struct = %s\n",(yyvsp[(1) - (1)].na));
-                   strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
-                   ;}
-    break;
-
-  case 316:
-#line 1656 "fortran.y"
-    {if ( couldaddvariable == 1 ) {
-                   printf("arrayref = %s\n",(yyvsp[(1) - (1)].na));
-                   strcpy((yyval.na),(yyvsp[(1) - (1)].na));
-                   };}
-    break;
-
-  case 317:
-#line 1661 "fortran.y"
+            if ( inside_type_declare ) break;
+            if ( inmoduledeclare )
+            {
+                if ( firstpass == 0 )
+                {
+                    RemoveWordCUR_0(fortran_out,9);   // Remove word 'contains'
+                    Write_Closing_Module(0);
+                }
+                inmoduledeclare = 0 ;
+                aftercontainsdeclare = 1;
+            }
+            else if ( insubroutinedeclare )
+            {
+                incontainssubroutine = 1;
+                insubroutinedeclare  = 0;
+                incontainssubroutine = 0;
+                functiondeclarationisdone = 0;
+
+                if ( firstpass )
+                    List_ContainsSubroutine = Addtolistnom(subroutinename, List_ContainsSubroutine, 0);
+                else
+                    closeandcallsubloop_contains_0();
+
+                strcpy(subroutinename, "");
+            }
+            else printf("l.%4d -- TOK_CONTAINS -- MHCHECK\n",line_num_input);
+        }
+    break;
+
+  case 483:
+/* Line 1807 of yacc.c  */
+#line 1898 "fortran.y"
     {
-                      agrif_parentcall =0;
-                      if (!strcasecmp(identcopy,"Agrif_Parent") )
-                                                            agrif_parentcall =1;
-                      if ( Agrif_in_Tok_NAME(identcopy) == 1 )
-                      {
-                         inagrifcallargument = 1;
-                         Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                      }
-                   ;}
-    break;
-
-  case 318:
-#line 1674 "fortran.y"
+            strcpy((yyval.na),(yyvsp[(1) - (1)].na));
+            pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].na));
+            functiondeclarationisdone = 0;
+        }
+    break;
+
+  case 484:
+/* Line 1807 of yacc.c  */
+#line 1906 "fortran.y"
     {
-                     strcpy((yyval.na),(yyvsp[(1) - (1)].na));
-                     if ( incalldeclare == 0 ) inagrifcallargument = 0;
-                   ;}
-    break;
-
-  case 319:
-#line 1679 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na)," %s %s ",(yyvsp[(1) - (2)].na),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 320:
-#line 1681 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                                                sprintf((yyval.na)," %s ( %s )",(yyvsp[(1) - (4)].na),(yyvsp[(3) - (4)].na));;}
-    break;
-
-  case 321:
-#line 1684 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                                         sprintf((yyval.na)," %s ( %s ) %s ",(yyvsp[(1) - (5)].na),(yyvsp[(3) - (5)].na),(yyvsp[(5) - (5)].na));;}
-    break;
-
-  case 322:
-#line 1688 "fortran.y"
+            strcpy((yyval.na),(yyvsp[(1) - (1)].na));
+            pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].na));
+        }
+    break;
+
+  case 485:
+/* Line 1807 of yacc.c  */
+#line 1913 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                         sprintf((yyval.na)," %s ( %s )",(yyvsp[(1) - (4)].nac),(yyvsp[(3) - (4)].na));
-                         ModifyTheAgrifFunction_0((yyvsp[(3) - (4)].na));
-                         agrif_parentcall =0;
-                      }
-                   ;}
-    break;
-
-  case 323:
-#line 1698 "fortran.y"
+            strcpy((yyval.na),(yyvsp[(1) - (1)].na));
+            pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].na));
+        }
+    break;
+
+  case 486:
+/* Line 1807 of yacc.c  */
+#line 1920 "fortran.y"
     {
-                      sprintf((yyval.na)," %s %% %s ",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));
-                      if ( incalldeclare == 0 ) inagrifcallargument = 0;
-                   ;}
-    break;
-
-  case 324:
-#line 1704 "fortran.y"
-    {sprintf((yyval.na),"(/%s/)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 325:
-#line 1706 "fortran.y"
-    {strcpy((yyval.na)," ");;}
-    break;
-
-  case 326:
-#line 1708 "fortran.y"
-    {strcpy((yyval.na),(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 327:
-#line 1710 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 328:
-#line 1712 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 329:
-#line 1714 "fortran.y"
-    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 330:
-#line 1715 "fortran.y"
-    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 331:
-#line 1718 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s :%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 332:
-#line 1720 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                                               sprintf((yyval.na),"%s :%s :%s",(yyvsp[(1) - (5)].na),(yyvsp[(3) - (5)].na),(yyvsp[(5) - (5)].na));;}
-    break;
-
-  case 333:
-#line 1723 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),":%s :%s",(yyvsp[(2) - (4)].na),(yyvsp[(4) - (4)].na));;}
-    break;
-
-  case 334:
-#line 1724 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),": : %s",(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 335:
-#line 1725 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),":%s",(yyvsp[(2) - (2)].na));;}
-    break;
-
-  case 336:
-#line 1726 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s :",(yyvsp[(1) - (2)].na));;}
-    break;
-
-  case 337:
-#line 1727 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),":");;}
-    break;
-
-  case 338:
-#line 1729 "fortran.y"
+            strcpy((yyval.na),(yyvsp[(1) - (1)].na));
+            pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].na));
+        }
+    break;
+
+  case 487:
+/* Line 1807 of yacc.c  */
+#line 1926 "fortran.y"
+    {strcpy((yyval.na),"");}
+    break;
+
+  case 488:
+/* Line 1807 of yacc.c  */
+#line 1927 "fortran.y"
+    {strcpy((yyval.na),(yyvsp[(1) - (1)].na));}
+    break;
+
+  case 489:
+/* Line 1807 of yacc.c  */
+#line 1930 "fortran.y"
+    { created_dimensionlist = 0; }
+    break;
+
+  case 490:
+/* Line 1807 of yacc.c  */
+#line 1934 "fortran.y"
     {
-                       if ( couldaddvariable == 1 && afterpercent == 0)
-                       {
-                       if ( Vartonumber((yyvsp[(1) - (1)].nac)) == 1 )
-                       {
-                          Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                       }
-                       if (!strcasecmp((yyvsp[(1) - (1)].nac),"Agrif_Parent") )
-                                                            agrif_parentcall =1;
-                       if ( VariableIsNotFunction((yyvsp[(1) - (1)].nac)) == 0 )
-                       {
-                       printf("var = %s\n",(yyvsp[(1) - (1)].nac));
-                          if ( inagrifcallargument == 1 )
-                          {
-                             if ( !strcasecmp((yyvsp[(1) - (1)].nac),identcopy) )
-                             {
-                                strcpy(sameagrifname,identcopy);
-                                sameagrifargument = 1;
-                             }
-                          }
-                          strcpy(identcopy,(yyvsp[(1) - (1)].nac));
-                          pointedvar=0;
-                          strcpy(truename,(yyvsp[(1) - (1)].nac));
-                          if (variscoupled_0((yyvsp[(1) - (1)].nac))) strcpy(truename,getcoupledname_0((yyvsp[(1) - (1)].nac)));
-
-                          if ( VarIsNonGridDepend(truename) == 0 &&
-                               Variableshouldberemove(truename) == 0 )
-                          {                      
-                             if ( inagrifcallargument == 1 ||
-                                  varispointer_0(truename) == 1 )
-                             {
-                             printf("var2 = %s\n",(yyvsp[(1) - (1)].nac));
-                            if ((IsinListe(List_UsedInSubroutine_Var,(yyvsp[(1) - (1)].nac)) == 1) || (inagrifcallargument == 1))
-                             {
-                              if (varistyped_0(truename) == 0)
-                                 {
-                                 ModifyTheVariableName_0(truename,strlen((yyvsp[(1) - (1)].nac)));
-                                 }
-                                 }
-                             }
-                             printf("ici3\n");
-                             if ( inagrifcallargument != 1 ||
-                                  sameagrifargument ==1 )
-                                  {
-                                  printf("ici5 %s\n",truename);
-                                  Add_UsedInSubroutine_Var_1(truename);
-                          }
-                          }
-                          NotifyAgrifFunction_0(truename);
-                       }
-                       }
-                       else
-                       {
-                       afterpercent = 0;
-                    }
-                    ;}
-    break;
-
-  case 339:
-#line 1788 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),".TRUE.");;}
-    break;
-
-  case 340:
-#line 1789 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),".FALSE.");;}
-    break;
-
-  case 341:
-#line 1790 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 342:
-#line 1791 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 343:
-#line 1792 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 344:
-#line 1793 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 345:
-#line 1795 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.nac),"%s%s",(yyvsp[(1) - (2)].nac),(yyvsp[(2) - (2)].nac));;}
-    break;
-
-  case 347:
-#line 1799 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 349:
-#line 1802 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 350:
-#line 1804 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 351:
-#line 1806 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na)," ");;}
-    break;
-
-  case 352:
-#line 1807 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 353:
-#line 1810 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"(%s :%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na));;}
-    break;
-
-  case 354:
-#line 1812 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na)," ");;}
-    break;
-
-  case 355:
-#line 1813 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 356:
-#line 1815 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na)," ");;}
-    break;
-
-  case 357:
-#line 1816 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 358:
-#line 1818 "fortran.y"
-    {   strcpy(InitialValueGiven," ");;}
-    break;
-
-  case 359:
-#line 1820 "fortran.y"
+            created_dimensionlist = 1;
+            if ( ((yyvsp[(3) - (4)].d) == NULL) || ((yyvsp[(4) - (4)].d) == NULL) ) break;
+            if  ( agrif_parentcall == 1 )
+            {
+                ModifyTheAgrifFunction_0((yyvsp[(3) - (4)].d)->dim.last);
+                agrif_parentcall = 0;
+                fprintf(fortran_out," = ");
+            }
+        }
+    break;
+
+  case 491:
+/* Line 1807 of yacc.c  */
+#line 1945 "fortran.y"
     {
-                       if ( couldaddvariable == 1 )
-                       {
-                          strcpy(InitValue,(yyvsp[(3) - (3)].na));
-                          strcpy(InitialValueGiven,"=");
-                       }
-                    ;}
-    break;
-
-  case 360:
-#line 1828 "fortran.y"
+            created_dimensionlist = 1;
+        }
+    break;
+
+  case 496:
+/* Line 1807 of yacc.c  */
+#line 1958 "fortran.y"
     {
-                       if ( couldaddvariable == 1 )
-                       {
-                          strcpy(InitValue,(yyvsp[(3) - (3)].na));
-                          strcpy(InitialValueGiven,"=>");
-                       }
-                    ;}
-    break;
-
-  case 361:
-#line 1836 "fortran.y"
-    {pos_curinit = setposcur();;}
-    break;
-
-  case 362:
-#line 1839 "fortran.y"
-    {sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na));;}
-    break;
-
-  case 363:
-#line 1842 "fortran.y"
+            inagrifcallargument = 0 ;
+            incalldeclare=0;
+            if ( oldfortran_out && (callagrifinitgrids == 1) && (firstpass == 0) )
+            {
+                pos_end = setposcur();
+                RemoveWordSET_0(fortran_out,pos_curcall,pos_end-pos_curcall);
+                strcpy(subofagrifinitgrids,subroutinename);
+            }
+            Instanciation_0(sameagrifname);
+        }
+    break;
+
+  case 502:
+/* Line 1807 of yacc.c  */
+#line 1979 "fortran.y"
     {
-                      if ( couldaddvariable == 1 )
-                      {
-                      /* if variables has been declared in a subroutine       */
-                      if (insubroutinedeclare == 1)
-                      {
-                         copyuse_0((yyvsp[(2) - (2)].nac));
-                      }
-                      sprintf(charusemodule,"%s",(yyvsp[(2) - (2)].nac));
-                      Add_NameOfModuleUsed_1((yyvsp[(2) - (2)].nac));
-
-                      if ( inmoduledeclare == 0 )
-                      {
-                         pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_curuse,
-                                               pos_end-pos_curuse);
-                      }
-                      }
-                    ;}
-    break;
-
-  case 364:
-#line 1862 "fortran.y"
+            if (!strcasecmp((yyvsp[(2) - (2)].na),"MPI_Init") )    callmpiinit = 1;
+            else                                callmpiinit = 0;
+
+            if (!strcasecmp((yyvsp[(2) - (2)].na),"Agrif_Init_Grids") )
+            {
+                callagrifinitgrids = 1;
+                strcpy(meetagrifinitgrids,subroutinename);
+            }
+            else
+            {
+                callagrifinitgrids = 0;
+            }
+            if ( Vartonumber((yyvsp[(2) - (2)].na)) == 1 )
+            {
+                incalldeclare = 1;
+                inagrifcallargument = 1 ;
+                Add_SubroutineWhereAgrifUsed_1(subroutinename, curmodulename);
+            }
+        }
+    break;
+
+  case 503:
+/* Line 1807 of yacc.c  */
+#line 2000 "fortran.y"
+    { pos_curcall=setposcur()-4; }
+    break;
+
+  case 506:
+/* Line 1807 of yacc.c  */
+#line 2008 "fortran.y"
     {
-                       if ( couldaddvariable == 1 )
-                       {
-                      if (insubroutinedeclare == 1)
-                      {
-                         Add_CouplePointed_Var_1((yyvsp[(2) - (4)].nac),(yyvsp[(4) - (4)].lc));
-                      }
-                      if ( firstpass == 1 )
-                      {
-                         if ( insubroutinedeclare == 1 )
-                         {
-                            coupletmp = (yyvsp[(4) - (4)].lc);
-                            strcpy(ligne,"");
-                            while ( coupletmp )
-                            {
-                               strcat(ligne,coupletmp->c_namevar);
-                               strcat(ligne," => ");
-                               strcat(ligne,coupletmp->c_namepointedvar);
-                               coupletmp = coupletmp->suiv;
-                               if ( coupletmp ) strcat(ligne,",");
-                            }
-                            sprintf(charusemodule,"%s",(yyvsp[(2) - (4)].nac));
-                         }
-                         Add_NameOfModuleUsed_1((yyvsp[(2) - (4)].nac));
-                      }
-                      if ( inmoduledeclare == 0 )
-                      {
-                         pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_curuse,
-                                               pos_end-pos_curuse);
-                      }
-                      }
-                    ;}
-    break;
-
-  case 365:
-#line 1896 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 )
-                       {
-                      /* if variables has been declared in a subroutine       */
-                      if (insubroutinedeclare == 1)
-                      {
-                         copyuseonly_0((yyvsp[(2) - (6)].nac));
-                      }
-                      sprintf(charusemodule,"%s",(yyvsp[(2) - (6)].nac));
-                      Add_NameOfModuleUsed_1((yyvsp[(2) - (6)].nac));
-
-                       if ( inmoduledeclare == 0 )
-                       {
-                          pos_end = setposcur();
-                          RemoveWordSET_0(fortranout,pos_curuse,
-                                                pos_end-pos_curuse);
-                       }
-                       }
-                    ;}
-    break;
-
-  case 366:
-#line 1916 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 )
-                       {
-                       /* if variables has been declared in a subroutine      */
-                       if (insubroutinedeclare == 1)
-                       {
-                          Add_CouplePointed_Var_1((yyvsp[(2) - (6)].nac),(yyvsp[(6) - (6)].lc));
-                       }
-                       if ( firstpass == 1 )
-                       {
-                         if ( insubroutinedeclare == 1 )
-                         {
-                             coupletmp = (yyvsp[(6) - (6)].lc);
-                             strcpy(ligne,"");
-                             while ( coupletmp )
-                             {
-                                strcat(ligne,coupletmp->c_namevar);
-                               if ( strcasecmp(coupletmp->c_namepointedvar,"") )
-                                                           strcat(ligne," => ");
-                                strcat(ligne,coupletmp->c_namepointedvar);
-                                coupletmp = coupletmp->suiv;
-                                if ( coupletmp ) strcat(ligne,",");
-                             }
-                             sprintf(charusemodule,"%s",(yyvsp[(2) - (6)].nac));
-                          }
-                          Add_NameOfModuleUsed_1((yyvsp[(2) - (6)].nac));
-                       }
-                       if ( firstpass == 0 )
-                       {
-                          if ( inmoduledeclare == 0 )
-                          {
-
-                            pos_end = setposcur();
-                             RemoveWordSET_0(fortranout,pos_curuse,
-                                                   pos_end-pos_curuse);
-                       if (oldfortranout) 
-                         variableisglobalinmodule((yyvsp[(6) - (6)].lc),(yyvsp[(2) - (6)].nac),oldfortranout,pos_curuseold);
-                        
-                          }
-                          else
-                          {
-
-                             /* if we are in the module declare and if the    */
-                             /* onlylist is a list of global variable         */
-                             variableisglobalinmodule((yyvsp[(6) - (6)].lc), (yyvsp[(2) - (6)].nac), fortranout,pos_curuse);
-                          }
-                       }
-                       }
-                    ;}
-    break;
-
-  case 367:
-#line 1967 "fortran.y"
-    {
-                      pos_curuse = setposcur()-strlen((yyvsp[(1) - (1)].nac));
-                     if (firstpass == 0 && oldfortranout) {
-                     pos_curuseold = setposcurname(oldfortranout);
-                     }
-                   ;}
-    break;
-
-  case 368:
-#line 1975 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 369:
-#line 1978 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 ) (yyval.lc) = (yyvsp[(1) - (1)].lc);
-                    ;}
-    break;
-
-  case 370:
-#line 1982 "fortran.y"
-    {
-                        if ( couldaddvariable == 1 )
-                        {
-                        /* insert the variable in the list $1                 */
-                        (yyvsp[(3) - (3)].lc)->suiv = (yyvsp[(1) - (3)].lc);
-                        (yyval.lc) = (yyvsp[(3) - (3)].lc);
-                        }
-                    ;}
-    break;
-
-  case 371:
-#line 1992 "fortran.y"
-    {
-                       coupletmp =(listcouple *)malloc(sizeof(listcouple));
-                       strcpy(coupletmp->c_namevar,(yyvsp[(1) - (3)].nac));
-                       Save_Length((yyvsp[(1) - (3)].nac),21);
-                       strcpy(coupletmp->c_namepointedvar,(yyvsp[(3) - (3)].nac));
-                       Save_Length((yyvsp[(3) - (3)].nac),22);
-                       coupletmp->suiv = NULL;
-                       (yyval.lc) = coupletmp;
-                     ;}
-    break;
-
-  case 372:
-#line 2003 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 ) (yyval.lc) = (yyvsp[(1) - (1)].lc);
-                    ;}
-    break;
-
-  case 373:
-#line 2007 "fortran.y"
-    {
-                        if ( couldaddvariable == 1 )
-                        {
-                        /* insert the variable in the list $1                 */
-                        (yyvsp[(3) - (3)].lc)->suiv = (yyvsp[(1) - (3)].lc);
-                        (yyval.lc) = (yyvsp[(3) - (3)].lc);
-                        }
-                    ;}
-    break;
-
-  case 374:
-#line 2017 "fortran.y"
-    {
-                       coupletmp =(listcouple *)malloc(sizeof(listcouple));
-                       strcpy(coupletmp->c_namevar,(yyvsp[(1) - (3)].nac));
-                       Save_Length((yyvsp[(1) - (3)].nac),21);
-                       strcpy(coupletmp->c_namepointedvar,(yyvsp[(3) - (3)].nac));
-                       Save_Length((yyvsp[(3) - (3)].nac),22);
-                       coupletmp->suiv = NULL;
-                       (yyval.lc) = coupletmp;
-                       pointedvar=1;
-                       Add_UsedInSubroutine_Var_1((yyvsp[(1) - (3)].nac));
-                    ;}
-    break;
-
-  case 375:
-#line 2028 "fortran.y"
-    {
-                       coupletmp =(listcouple *)malloc(sizeof(listcouple));
-                       strcpy(coupletmp->c_namevar,(yyvsp[(1) - (1)].nac));
-                       Save_Length((yyvsp[(1) - (1)].nac),21);
-                       strcpy(coupletmp->c_namepointedvar,"");
-                       coupletmp->suiv = NULL;
-                       (yyval.lc) = coupletmp;
-                     ;}
-    break;
-
-  case 377:
-#line 2039 "fortran.y"
-    {
-                         Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                                                        inallocate = 0;
-                     ;}
-    break;
-
-  case 378:
-#line 2045 "fortran.y"
-    {
-                          Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                         curmodulename);
-                                                         inallocate = 0;
-                     ;}
-    break;
-
-  case 380:
-#line 2052 "fortran.y"
-    {
-                       GlobalDeclaration = 0 ;
-                       if ( firstpass == 0 &&
-                            strcasecmp(subroutinename,"") )
-                       {
-                          if ( module_declar && insubroutinedeclare == 0 )
-                          {
-                              fclose(module_declar);
-                          }
-                       }
-                       if ( couldaddvariable == 1 &&
-                            strcasecmp(subroutinename,"") )
-                       {
-                       if ( inmodulemeet == 1 )
-                       {
-                         /* we are in a module                                */
-                         if ( insubroutinedeclare == 1 )
-                         {
-                            /* it is like an end subroutine <name>            */
-                            insubroutinedeclare = 0 ;
-                            /*                                                */
-                            pos_cur = setposcur();
-                            closeandcallsubloopandincludeit_0(1);
-                            functiondeclarationisdone = 0;
-                         }
-                         else
-                         {
-                            /* it is like an end module <name>                */
-                            inmoduledeclare = 0 ;
-                            inmodulemeet = 0 ;
-                         }
-                       }
-                       else
-                       {
-                          insubroutinedeclare = 0;
-                          /*                                                  */
-                          pos_cur = setposcur();                        
-                          closeandcallsubloopandincludeit_0(2);
-                            functiondeclarationisdone = 0;
-                          if ( firstpass == 0 )
-                          {
-                             if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                             else fprintf(paramout,"C\n");
-                             fclose(paramout);
-                           }
-                        }
-                      }
-                      strcpy(subroutinename,"");
-                    ;}
-    break;
-
-  case 381:
-#line 2102 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 )
-                       {
-                       insubroutinedeclare = 0;
-                       /*                                                     */
-                       pos_cur = setposcur();                      
-                       closeandcallsubloopandincludeit_0(3);
-                            functiondeclarationisdone = 0;
-                      if ( firstpass == 0 )
-                      {
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-                         fclose(paramout);
-                      }
-                      strcpy(subroutinename,"");
-                      }
-                    ;}
-    break;
-
-  case 382:
+            if ( callmpiinit == 1 )
+            {
+                strcpy(mpiinitvar,(yyvsp[(1) - (1)].na));
+                if ( firstpass == 1 )  Add_UsedInSubroutine_Var_1 (mpiinitvar);
+            }
+        }
+    break;
+
+  case 532:
+/* Line 1807 of yacc.c  */
+#line 2056 "fortran.y"
+    { afterpercent = 1; }
+    break;
+
+  case 572:
+/* Line 1807 of yacc.c  */
+#line 2115 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 573:
+/* Line 1807 of yacc.c  */
+#line 2116 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 574:
+/* Line 1807 of yacc.c  */
+#line 2117 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 575:
+/* Line 1807 of yacc.c  */
+#line 2118 "fortran.y"
+    { strcpy((yyval.na),(yyvsp[(1) - (1)].na)); }
+    break;
+
+  case 576:
+/* Line 1807 of yacc.c  */
+#line 2119 "fortran.y"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 577:
+/* Line 1807 of yacc.c  */
 #line 2120 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 &&
-                            strcasecmp(subroutinename,"") )
-                       {
-                       insubroutinedeclare = 0;
-                       /*                                                     */
-                       pos_cur = setposcur();
-                                             
-                       closeandcallsubloopandincludeit_0(1);
-                            functiondeclarationisdone = 0;
-                      if ( firstpass == 0 )
-                      {
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-                         fclose(paramout);
-                      }
-                      strcpy(subroutinename,"");
-                      }
-                    ;}
-    break;
-
-  case 383:
-#line 2140 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 )
-                       {
-                       insubroutinedeclare = 0;
-                       /*                                                     */
-                       pos_cur = setposcur();
-
-                       closeandcallsubloopandincludeit_0(0);
-                            functiondeclarationisdone = 0;
-                      if ( firstpass == 0 )
-                      {
-                         if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                         else fprintf(paramout,"C\n");
-                         fclose(paramout);
-                      }
-                      strcpy(subroutinename,"");
-                      }
-                    ;}
-    break;
-
-  case 384:
-#line 2159 "fortran.y"
-    {
-                       if ( couldaddvariable == 1 )
-                       {
-                       /* if we never meet the contains keyword               */
-                      Remove_Word_end_module_0(strlen((yyvsp[(2) - (2)].nac)));
-                       if ( inmoduledeclare == 1 )
-                       {
-                          if ( aftercontainsdeclare == 0 )
-                          {
-                             Write_GlobalParameter_Declaration_0();
-                             Write_NotGridDepend_Declaration_0();
-                             Write_GlobalType_Declaration_0();
-                             if ( module_declar_type )
-                             {
-                             strcpy (ligne, "\n#include \"Module_DeclarType_");
-                             strcat (ligne, curmodulename);
-                             strcat (ligne, ".h\"\n");
-                             tofich(fortranout,ligne,1); 
-                             }
-                             Write_Alloc_Subroutine_For_End_0();
-                          }
-                       }
-                                           
-                       inmoduledeclare = 0 ;
-                       inmodulemeet = 0 ;
-
-                      Write_Word_end_module_0();
-                      strcpy(curmodulename,"");
-                      aftercontainsdeclare = 1;
-                      if ( firstpass == 0 )
-                      {
-                         if ( module_declar && insubroutinedeclare == 0)
-                         {
-                           fclose(module_declar);
-                         }
-                         if ( module_declar_type && insubroutinedeclare == 0)
-                         {
-                          fclose(module_declar_type);
-                          module_declar_type = 0;
-                         }
-                      }
-                      GlobalDeclaration = 0 ;
-                      }
-                  ;}
-    break;
-
-  case 398:
-#line 2217 "fortran.y"
-    {
-                      if (inmoduledeclare == 1 )
-                      {
-                         Remove_Word_Contains_0();
-                         Write_GlobalParameter_Declaration_0();
-                         Write_GlobalType_Declaration_0();
-                             if ( module_declar_type)
-                             {                         
-                             strcpy (ligne, "\n#include \"Module_DeclarType_");
-                             strcat (ligne, curmodulename);
-                             strcat (ligne, ".h\"\n");
-                             tofich(fortranout,ligne,1); 
-                             }
-                         Write_NotGridDepend_Declaration_0();
-                         Write_Alloc_Subroutine_0();
-                         inmoduledeclare = 0 ;
-                         aftercontainsdeclare = 1;
-                      }
-                      else
-                      {
-                      incontainssubroutine = 1;
-                      strcpy(previoussubroutinename,subroutinename);
-                       if ( couldaddvariable == 1 )
-                       {
-                          if ( firstpass == 1 ) List_ContainsSubroutine =
-                                                Addtolistnom(subroutinename,
-                                                     List_ContainsSubroutine,0);
-                          insubroutinedeclare = 0;
-                          /*                                                  */
-
-                          closeandcallsubloop_contains_0();
-                            functiondeclarationisdone = 0;
-                         if ( firstpass == 0 )
-                         {
-                            if ( retour77 == 0 ) fprintf(paramout,"!\n");
-                            else fprintf(paramout,"C\n");
-                            fclose(paramout);
-                         }
-                         }
-                         strcpy(subroutinename,"");
-                      }
-                   ;}
-    break;
-
-  case 399:
-#line 2261 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                       strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));
-                       pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].nac));
-                       functiondeclarationisdone = 0;
-                       }
-                    ;}
-    break;
-
-  case 400:
-#line 2271 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                       strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));
-                       pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].nac));
-                       }
-                    ;}
-    break;
-
-  case 401:
-#line 2280 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                       strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));
-                       pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].nac));
-                       }
-                    ;}
-    break;
-
-  case 402:
-#line 2289 "fortran.y"
-    {
-                      if ( couldaddvariable == 1 )
-                      {
-                       strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));
-                       pos_endsubroutine = setposcur()-strlen((yyvsp[(1) - (1)].nac));
-                       }
-                    ;}
-    break;
-
-  case 414:
-#line 2311 "fortran.y"
-    {strcpy((yyval.nac),"");;}
-    break;
-
-  case 415:
-#line 2312 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-  case 425:
-#line 2332 "fortran.y"
-    {
-                          Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                                                        inallocate = 0;
-                     ;}
-    break;
-
-  case 426:
-#line 2338 "fortran.y"
-    {
-                          Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                                                        inallocate = 0;
-                     ;}
-    break;
-
-  case 432:
-#line 2349 "fortran.y"
-    {if ( couldaddvariable == 1 ) created_dimensionlist = 0;;}
-    break;
-
-  case 433:
-#line 2351 "fortran.y"
-    {
-                  created_dimensionlist = 1;
-                  if  ( agrif_parentcall == 1 )
-                  {
-                      ModifyTheAgrifFunction_0((yyvsp[(3) - (4)].d)->dim.last);
-                      agrif_parentcall =0;
-                      fprintf(fortranout," = ");
-                  }
-              ;}
-    break;
-
-  case 434:
-#line 2361 "fortran.y"
-    {created_dimensionlist = 1;;}
-    break;
-
-  case 439:
-#line 2369 "fortran.y"
-    {
-                      inagrifcallargument = 0 ;
-                      incalldeclare=0;
-                      if ( oldfortranout &&
-                           !strcasecmp(meetagrifinitgrids,subroutinename) &&
-                           firstpass == 0 &&
-                           callmpiinit == 1)
-                      {
-                      /*   pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_curcall,
-                                               pos_end-pos_curcall);
-                         fprintf(oldfortranout,"      Call MPI_Init (%s) \n"
-                                                                   ,mpiinitvar);*/
-                      }
-                      if ( oldfortranout           &&
-                           callagrifinitgrids == 1 &&
-                           firstpass == 0 )
-                      {
-                         pos_end = setposcur();
-                         RemoveWordSET_0(fortranout,pos_curcall,
-                                               pos_end-pos_curcall);
-
-                         strcpy(subofagrifinitgrids,subroutinename);
-                      }
-                      Instanciation_0(sameagrifname);
-                   ;}
-    break;
-
-  case 444:
-#line 2403 "fortran.y"
-    {
-                       if (!strcasecmp((yyvsp[(2) - (2)].nac),"MPI_Init") )
-                       {
-                          callmpiinit = 1;
-                       }
-                       else
-                       {
-                          callmpiinit = 0;
-                       }
-                       if (!strcasecmp((yyvsp[(2) - (2)].nac),"Agrif_Init_Grids") )
-                       {
-                          callagrifinitgrids = 1;
-                          strcpy(meetagrifinitgrids,subroutinename);
-                       }
-                       else callagrifinitgrids = 0;
-                       if ( !strcasecmp((yyvsp[(2) - (2)].nac),"Agrif_Open_File") )
-                       {
-                          Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                       }
-                       if ( Vartonumber((yyvsp[(2) - (2)].nac)) == 1 )
-                       {
-                          incalldeclare=1;
-                          inagrifcallargument = 1 ;
-                          Add_SubroutineWhereAgrifUsed_1(subroutinename,
-                                                        curmodulename);
-                       }
-                    ;}
-    break;
-
-  case 445:
-#line 2433 "fortran.y"
-    {pos_curcall=setposcur()-4;;}
-    break;
-
-  case 448:
-#line 2438 "fortran.y"
-    {
-                  if ( callmpiinit == 1 )
-                  {
-                     strcpy(mpiinitvar,(yyvsp[(1) - (1)].na));
-                     if ( firstpass == 1 )
-                     {
-                        Add_UsedInSubroutine_Var_1 (mpiinitvar);
-/*                        curvar=createvar($1,NULL);
-                        curlistvar=insertvar(NULL,curvar);
-                        List_Subr outineArgument_Var = AddListvarToListvar
-                         (curlistvar,List_SubroutineAr gument_Var,1);*/
-                     }
-                  }
-               ;}
-    break;
-
-  case 520:
-#line 2562 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 521:
-#line 2563 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 522:
-#line 2564 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 523:
-#line 2567 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 524:
-#line 2569 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 525:
-#line 2571 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 526:
-#line 2573 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 527:
-#line 2575 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 528:
-#line 2577 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na));;}
-    break;
-
-  case 529:
-#line 2578 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 530:
-#line 2579 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 531:
-#line 2582 "fortran.y"
-    {if ( couldaddvariable == 1 ) strcpy((yyval.na),(yyvsp[(1) - (1)].na));;}
-    break;
-
-  case 532:
-#line 2584 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na)," (%s)",(yyvsp[(2) - (3)].na));;}
-    break;
-
-  case 533:
-#line 2586 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na));;}
-    break;
-
-  case 534:
-#line 2588 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na));;}
-    break;
-
-  case 535:
-#line 2590 "fortran.y"
-    {if ( couldaddvariable == 1 ) sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na));;}
-    break;
-
-  case 536:
-#line 2594 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                                              sprintf((yyval.na),"%s=%s,%s)",(yyvsp[(1) - (5)].nac),(yyvsp[(3) - (5)].na),(yyvsp[(5) - (5)].na));;}
-    break;
-
-  case 537:
-#line 2597 "fortran.y"
-    {if ( couldaddvariable == 1 )
-                                        sprintf((yyval.na),"%s=%s,%s,%s)",(yyvsp[(1) - (7)].nac),(yyvsp[(3) - (7)].na),(yyvsp[(5) - (7)].na),(yyvsp[(7) - (7)].na));;}
-    break;
-
-  case 544:
-#line 2613 "fortran.y"
-    {Add_Allocate_Var_1((yyvsp[(1) - (1)].nac),curmodulename);;}
-    break;
-
-  case 547:
-#line 2618 "fortran.y"
-    {Add_Allocate_Var_1((yyvsp[(1) - (4)].nac),curmodulename);;}
-    break;
-
-  case 555:
-#line 2641 "fortran.y"
-    {strcpy((yyval.nac),(yyvsp[(1) - (1)].nac));;}
-    break;
-
-
-/* Line 1267 of yacc.c.  */
-#line 6522 "fortran.tab.c"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 578:
+/* Line 1807 of yacc.c  */
+#line 2121 "fortran.y"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 579:
+/* Line 1807 of yacc.c  */
+#line 2122 "fortran.y"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 580:
+/* Line 1807 of yacc.c  */
+#line 2123 "fortran.y"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 581:
+/* Line 1807 of yacc.c  */
+#line 2124 "fortran.y"
+    { sprintf((yyval.na),"%s,%s",(yyvsp[(1) - (3)].na),(yyvsp[(3) - (3)].na)); }
+    break;
+
+  case 582:
+/* Line 1807 of yacc.c  */
+#line 2127 "fortran.y"
+    { sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na)); }
+    break;
+
+  case 583:
+/* Line 1807 of yacc.c  */
+#line 2128 "fortran.y"
+    { sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na)); }
+    break;
+
+  case 584:
+/* Line 1807 of yacc.c  */
+#line 2129 "fortran.y"
+    { sprintf((yyval.na),"(%s,%s)",(yyvsp[(2) - (5)].na),(yyvsp[(4) - (5)].na)); }
+    break;
+
+  case 585:
+/* Line 1807 of yacc.c  */
+#line 2131 "fortran.y"
+    { sprintf((yyval.na),"%s=%s,%s)",(yyvsp[(1) - (5)].na),(yyvsp[(3) - (5)].na),(yyvsp[(5) - (5)].na));}
+    break;
+
+  case 586:
+/* Line 1807 of yacc.c  */
+#line 2132 "fortran.y"
+    { sprintf((yyval.na),"%s=%s,%s,%s)",(yyvsp[(1) - (7)].na),(yyvsp[(3) - (7)].na),(yyvsp[(5) - (7)].na),(yyvsp[(7) - (7)].na));}
+    break;
+
+  case 591:
+/* Line 1807 of yacc.c  */
+#line 2142 "fortran.y"
+    { Add_Allocate_Var_1((yyvsp[(1) - (1)].na),curmodulename); }
+    break;
+
+
+/* Line 1807 of yacc.c  */
+#line 6110 "fortran.tab.c"
       default: break;
     }
+  /* User semantic actions sometimes alter yychar, and that requires
+     that yytoken be updated with the new translation.  We take the
+     approach of translating immediately before every use of yytoken.
+     One alternative is translating here after every semantic action,
+     but that translation would be missed if the semantic action invokes
+     YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
+     if it invokes YYBACKUP.  In the case of YYABORT or YYACCEPT, an
+     incorrect destructor might then be invoked immediately.  In the
+     case of YYERROR or YYBACKUP, subsequent parser actions might lead
+     to an incorrect destructor call or verbose syntax error message
+     before the lookahead is translated.  */
   YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
 
@@ -6532,5 +6127,4 @@
 
   *++yyvsp = yyval;
-
 
   /* Now `shift' the result of the reduction.  Determine what state
@@ -6553,4 +6147,8 @@
 `------------------------------------*/
 yyerrlab:
+  /* Make sure we have latest lookahead translation.  See comments at
+     user semantic actions for why this is necessary.  */
+  yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
+
   /* If not already recovering from an error, report this error.  */
   if (!yyerrstatus)
@@ -6560,35 +6158,34 @@
       yyerror (YY_("syntax error"));
 #else
+# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
+                                        yyssp, yytoken)
       {
-	YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
-	if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
-	  {
-	    YYSIZE_T yyalloc = 2 * yysize;
-	    if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
-	      yyalloc = YYSTACK_ALLOC_MAXIMUM;
-	    if (yymsg != yymsgbuf)
-	      YYSTACK_FREE (yymsg);
-	    yymsg = (char *) YYSTACK_ALLOC (yyalloc);
-	    if (yymsg)
-	      yymsg_alloc = yyalloc;
-	    else
-	      {
-		yymsg = yymsgbuf;
-		yymsg_alloc = sizeof yymsgbuf;
-	      }
-	  }
-
-	if (0 < yysize && yysize <= yymsg_alloc)
-	  {
-	    (void) yysyntax_error (yymsg, yystate, yychar);
-	    yyerror (yymsg);
-	  }
-	else
-	  {
-	    yyerror (YY_("syntax error"));
-	    if (yysize != 0)
-	      goto yyexhaustedlab;
-	  }
+        char const *yymsgp = YY_("syntax error");
+        int yysyntax_error_status;
+        yysyntax_error_status = YYSYNTAX_ERROR;
+        if (yysyntax_error_status == 0)
+          yymsgp = yymsg;
+        else if (yysyntax_error_status == 1)
+          {
+            if (yymsg != yymsgbuf)
+              YYSTACK_FREE (yymsg);
+            yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
+            if (!yymsg)
+              {
+                yymsg = yymsgbuf;
+                yymsg_alloc = sizeof yymsgbuf;
+                yysyntax_error_status = 2;
+              }
+            else
+              {
+                yysyntax_error_status = YYSYNTAX_ERROR;
+                yymsgp = yymsg;
+              }
+          }
+        yyerror (yymsgp);
+        if (yysyntax_error_status == 2)
+          goto yyexhaustedlab;
       }
+# undef YYSYNTAX_ERROR
 #endif
     }
@@ -6598,5 +6195,5 @@
   if (yyerrstatus == 3)
     {
-      /* If just tried and failed to reuse look-ahead token after an
+      /* If just tried and failed to reuse lookahead token after an
 	 error, discard it.  */
 
@@ -6615,5 +6212,5 @@
     }
 
-  /* Else will try to reuse look-ahead token after shifting the error
+  /* Else will try to reuse lookahead token after shifting the error
      token.  */
   goto yyerrlab1;
@@ -6649,5 +6246,5 @@
     {
       yyn = yypact[yystate];
-      if (yyn != YYPACT_NINF)
+      if (!yypact_value_is_default (yyn))
 	{
 	  yyn += YYTERROR;
@@ -6672,8 +6269,7 @@
     }
 
-  if (yyn == YYFINAL)
-    YYACCEPT;
-
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
   *++yyvsp = yylval;
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
 
 
@@ -6699,5 +6295,5 @@
   goto yyreturn;
 
-#ifndef yyoverflow
+#if !defined yyoverflow || YYERROR_VERBOSE
 /*-------------------------------------------------.
 | yyexhaustedlab -- memory exhaustion comes here.  |
@@ -6710,7 +6306,12 @@
 
 yyreturn:
-  if (yychar != YYEOF && yychar != YYEMPTY)
-     yydestruct ("Cleanup: discarding lookahead",
-		 yytoken, &yylval);
+  if (yychar != YYEMPTY)
+    {
+      /* Make sure we have latest lookahead translation.  See comments at
+         user semantic actions for why this is necessary.  */
+      yytoken = YYTRANSLATE (yychar);
+      yydestruct ("Cleanup: discarding lookahead",
+                  yytoken, &yylval);
+    }
   /* Do not reclaim the symbols of the rule which action triggered
      this YYABORT or YYACCEPT.  */
@@ -6736,62 +6337,32 @@
 
 
-#line 2643 "fortran.y"
-
-
-void processfortran(char *fichier_entree)
+/* Line 2055 of yacc.c  */
+#line 2156 "fortran.y"
+
+
+void process_fortran(const char *input_file)
 {
-   extern FILE *fortranin;
-   extern FILE *fortranout;
-   char nomfile[LONG_C];
-   int c;
-   int confirmyes;
-
-/*   fortrandebug = 1;*/
-   if ( mark == 1 ) printf("Firstpass == %d \n",firstpass);
+    extern FILE *fortran_in;
+    extern FILE *fortran_out;
+
+    char output_file[LONG_FNAME];
+    char input_fullpath[LONG_FNAME];
+
+    if ( todebug == 1 ) printf("Firstpass == %d \n", firstpass);
+
+     yydebug=0;
 /******************************************************************************/
-/*  1-  Open input and output files                                           */
+/*  1-  Open input file                                                       */
 /******************************************************************************/
-   strcpy(nomfile,commondirin);
-   strcat(nomfile,"/");
-   strcat(nomfile,fichier_entree);
-   fortranin=fopen( nomfile,"r");
-   if (! fortranin)
-   {
-      printf("Error : File %s does not exist\n",nomfile);
-      exit(1);
-   }
-
-   strcpy(curfile,nomfile);
-   strcpy(nomfile,commondirout);
-   strcat(nomfile,"/");
-   strcat(nomfile,fichier_entree);
-   strcpy(nomfileoutput,nomfile);
-   Save_Length(nomfileoutput,31);
-   if (firstpass == 1)
-   {
-      if (checkexistcommon == 1)
-      {
-         if (fopen(nomfile,"r"))
-         {
-            printf("Warning : file %s already exist\n",nomfile);
-            confirmyes = 0;
-            while (confirmyes==0)
-            {
-               printf("Override file %s ? [Y/N]\n",nomfile);
-               c=getchar();
-               getchar();
-               if (c==79 || c==110)
-               {
-                  printf("We stop\n");
-                  exit(1);
-               }
-               if (c==89 || c==121)
-               {
-                  confirmyes=1;
-               }
-            }
-         }
-      }
-   }
+
+    strcpy(cur_filename, input_file);
+    sprintf(input_fullpath, "%s/%s", input_dir, input_file);
+
+    fortran_in = fopen(input_fullpath, "r");
+    if (! fortran_in)
+    {
+        printf("Error : File %s does not exist\n", input_fullpath);
+        exit(1);
+    }
 
 /******************************************************************************/
@@ -6799,67 +6370,43 @@
 /******************************************************************************/
 
-   line_num_fortran_common=1;
-   line_num_fortran=1;
-   PublicDeclare = 0;
-   PrivateDeclare = 0;
-   ExternalDeclare = 0;
-   SaveDeclare = 0;
-   pointerdeclare = 0;
-   optionaldeclare = 0;
-   incalldeclare = 0;
-   VarType = 0;
-   VarTypepar = 0;
-   Allocatabledeclare = 0 ;
-   Targetdeclare = 0 ;
-   strcpy(NamePrecision," ");
-   VariableIsParameter =  0 ;
-   strcpy(NamePrecision,"");
-   c_star = 0 ;
-   functiondeclarationisdone = 0;
-   insubroutinedeclare = 0 ;
-   ininterfacedeclare = 0 ;   
-   strcpy(subroutinename," ");
-   isrecursive = 0;
-   strcpy(InitialValueGiven," ");
-   strcpy(EmptyChar," ");
-   inmoduledeclare = 0;
-   incontainssubroutine = 0;
-   module_declar_type = 0;
-   GlobalDeclarationType = 0;
-   colnum=0;
-   incom=0;
-   couldaddvariable=1;
-   afterpercent = 0;
-   aftercontainsdeclare = 1;
-   strcpy(nameinttypename,"");
-   /* Name of the file without format                                         */
-   tmp = strchr(fichier_entree, '.');
-   strncpy(curfilename,fichier_entree,strlen(fichier_entree)-strlen(tmp));
-   Save_Length(curfilename,30);
+    line_num_input = 1;
+    PublicDeclare = 0;
+    PrivateDeclare = 0;
+    ExternalDeclare = 0;
+    SaveDeclare = 0;
+    pointerdeclare = 0;
+    optionaldeclare = 0;
+    incalldeclare = 0;
+    inside_type_declare = 0;
+    Allocatabledeclare = 0 ;
+    Targetdeclare = 0 ;
+    VariableIsParameter =  0 ;
+    strcpy(NamePrecision,"");
+    c_star = 0 ;
+    functiondeclarationisdone = 0;
+    insubroutinedeclare = 0 ;
+    strcpy(subroutinename," ");
+    isrecursive = 0;
+    InitialValueGiven = 0 ;
+    GlobalDeclarationType = 0;
+    inmoduledeclare = 0;
+    incontainssubroutine = 0;
+    afterpercent = 0;
+    aftercontainsdeclare = 1;
+    strcpy(nameinttypename,"");
+
 /******************************************************************************/
 /*  3-  Parsing of the input file (1 time)                                    */
 /******************************************************************************/
-   if (firstpass == 0 )
-   {
-      fortranout=fopen(nomfileoutput,"w");
-
-/*      NewModule_Creation_0();*/
-   }
-
-   fortranparse();
-
-   if (firstpass == 0 )
-   {
-   NewModule_Creation_0();
-   }
-   
-   strcpy(curfile,mainfile);
-
-   if (firstpass == 0 )
-   {
-   fclose(fortranout);
-   }
+
+    sprintf(output_file, "%s/%s", output_dir, input_file);
+
+    if (firstpass == 0) fortran_out = fopen(output_file,"w");
+
+    fortran_parse();
+
+    if (firstpass == 0) NewModule_Creation_0();
+    if (firstpass == 0) fclose(fortran_out);
 }
-
 #line 2 "fortran.yy.c"
 
@@ -6870,22 +6417,22 @@
 /* A lexical scanner generated by flex */
 
-#define yy_create_buffer fortran_create_buffer
-#define yy_delete_buffer fortran_delete_buffer
-#define yy_flex_debug fortran_flex_debug
-#define yy_init_buffer fortran_init_buffer
-#define yy_flush_buffer fortran_flush_buffer
-#define yy_load_buffer_state fortran_load_buffer_state
-#define yy_switch_to_buffer fortran_switch_to_buffer
-#define yyin fortranin
-#define yyleng fortranleng
-#define yylex fortranlex
-#define yylineno fortranlineno
-#define yyout fortranout
-#define yyrestart fortranrestart
-#define yytext fortrantext
-#define yywrap fortranwrap
-#define yyalloc fortranalloc
-#define yyrealloc fortranrealloc
-#define yyfree fortranfree
+#define yy_create_buffer fortran__create_buffer
+#define yy_delete_buffer fortran__delete_buffer
+#define yy_flex_debug fortran__flex_debug
+#define yy_init_buffer fortran__init_buffer
+#define yy_flush_buffer fortran__flush_buffer
+#define yy_load_buffer_state fortran__load_buffer_state
+#define yy_switch_to_buffer fortran__switch_to_buffer
+#define yyin fortran_in
+#define yyleng fortran_leng
+#define yylex fortran_lex
+#define yylineno fortran_lineno
+#define yyout fortran_out
+#define yyrestart fortran_restart
+#define yytext fortran_text
+#define yywrap fortran_wrap
+#define yyalloc fortran_alloc
+#define yyrealloc fortran_realloc
+#define yyfree fortran_free
 
 #define FLEX_SCANNER
@@ -6930,4 +6477,5 @@
 typedef int32_t flex_int32_t;
 typedef uint32_t flex_uint32_t;
+typedef uint64_t flex_uint64_t;
 #else
 typedef signed char flex_int8_t;
@@ -7018,5 +6566,5 @@
 
 /* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE fortranrestart(fortranin  )
+#define YY_NEW_FILE fortran_restart(fortran_in  )
 
 #define YY_END_OF_BUFFER_CHAR 0
@@ -7041,7 +6589,7 @@
 #endif
 
-extern yy_size_t fortranleng;
-
-extern FILE *fortranin, *fortranout;
+extern yy_size_t fortran_leng;
+
+extern FILE *fortran_in, *fortran_out;
 
 #define EOB_ACT_CONTINUE_SCAN 0
@@ -7055,5 +6603,5 @@
 	do \
 		{ \
-		/* Undo effects of setting up fortrantext. */ \
+		/* Undo effects of setting up fortran_text. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
@@ -7061,5 +6609,5 @@
 		YY_RESTORE_YY_MORE_OFFSET \
 		(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
-		YY_DO_BEFORE_ACTION; /* set up fortrantext again */ \
+		YY_DO_BEFORE_ACTION; /* set up fortran_text again */ \
 		} \
 	while ( 0 )
@@ -7124,6 +6672,6 @@
 	 *
 	 * When we actually see the EOF, we change the status to "new"
-	 * (via fortranrestart()), so that the user can continue scanning by
-	 * just pointing fortranin at a new input file.
+	 * (via fortran_restart()), so that the user can continue scanning by
+	 * just pointing fortran_in at a new input file.
 	 */
 #define YY_BUFFER_EOF_PENDING 2
@@ -7152,8 +6700,8 @@
 #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
 
-/* yy_hold_char holds the character lost when fortrantext is formed. */
+/* yy_hold_char holds the character lost when fortran_text is formed. */
 static char yy_hold_char;
 static yy_size_t yy_n_chars;		/* number of characters read into yy_ch_buf */
-yy_size_t fortranleng;
+yy_size_t fortran_leng;
 
 /* Points to current character in buffer. */
@@ -7162,39 +6710,39 @@
 static int yy_start = 0;	/* start state number */
 
-/* Flag which is used to allow fortranwrap()'s to do buffer switches
- * instead of setting up a fresh fortranin.  A bit of a hack ...
+/* Flag which is used to allow fortran_wrap()'s to do buffer switches
+ * instead of setting up a fresh fortran_in.  A bit of a hack ...
  */
 static int yy_did_buffer_switch_on_eof;
 
-void fortranrestart (FILE *input_file  );
-void fortran_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
-YY_BUFFER_STATE fortran_create_buffer (FILE *file,int size  );
-void fortran_delete_buffer (YY_BUFFER_STATE b  );
-void fortran_flush_buffer (YY_BUFFER_STATE b  );
-void fortranpush_buffer_state (YY_BUFFER_STATE new_buffer  );
-void fortranpop_buffer_state (void );
-
-static void fortranensure_buffer_stack (void );
-static void fortran_load_buffer_state (void );
-static void fortran_init_buffer (YY_BUFFER_STATE b,FILE *file  );
-
-#define YY_FLUSH_BUFFER fortran_flush_buffer(YY_CURRENT_BUFFER )
-
-YY_BUFFER_STATE fortran_scan_buffer (char *base,yy_size_t size  );
-YY_BUFFER_STATE fortran_scan_string (yyconst char *yy_str  );
-YY_BUFFER_STATE fortran_scan_bytes (yyconst char *bytes,yy_size_t len  );
-
-void *fortranalloc (yy_size_t  );
-void *fortranrealloc (void *,yy_size_t  );
-void fortranfree (void *  );
-
-#define yy_new_buffer fortran_create_buffer
+void fortran_restart (FILE *input_file  );
+void fortran__switch_to_buffer (YY_BUFFER_STATE new_buffer  );
+YY_BUFFER_STATE fortran__create_buffer (FILE *file,int size  );
+void fortran__delete_buffer (YY_BUFFER_STATE b  );
+void fortran__flush_buffer (YY_BUFFER_STATE b  );
+void fortran_push_buffer_state (YY_BUFFER_STATE new_buffer  );
+void fortran_pop_buffer_state (void );
+
+static void fortran_ensure_buffer_stack (void );
+static void fortran__load_buffer_state (void );
+static void fortran__init_buffer (YY_BUFFER_STATE b,FILE *file  );
+
+#define YY_FLUSH_BUFFER fortran__flush_buffer(YY_CURRENT_BUFFER )
+
+YY_BUFFER_STATE fortran__scan_buffer (char *base,yy_size_t size  );
+YY_BUFFER_STATE fortran__scan_string (yyconst char *yy_str  );
+YY_BUFFER_STATE fortran__scan_bytes (yyconst char *bytes,yy_size_t len  );
+
+void *fortran_alloc (yy_size_t  );
+void *fortran_realloc (void *,yy_size_t  );
+void fortran_free (void *  );
+
+#define yy_new_buffer fortran__create_buffer
 
 #define yy_set_interactive(is_interactive) \
 	{ \
 	if ( ! YY_CURRENT_BUFFER ){ \
-        fortranensure_buffer_stack (); \
+        fortran_ensure_buffer_stack (); \
 		YY_CURRENT_BUFFER_LVALUE =    \
-            fortran_create_buffer(fortranin,YY_BUF_SIZE ); \
+            fortran__create_buffer(fortran_in,YY_BUF_SIZE ); \
 	} \
 	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
@@ -7204,7 +6752,7 @@
 	{ \
 	if ( ! YY_CURRENT_BUFFER ){\
-        fortranensure_buffer_stack (); \
+        fortran_ensure_buffer_stack (); \
 		YY_CURRENT_BUFFER_LVALUE =    \
-            fortran_create_buffer(fortranin,YY_BUF_SIZE ); \
+            fortran__create_buffer(fortran_in,YY_BUF_SIZE ); \
 	} \
 	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
@@ -7215,16 +6763,19 @@
 /* Begin user sect3 */
 
+#define fortran_wrap(n) 1
+#define YY_SKIP_YYWRAP
+
 typedef unsigned char YY_CHAR;
 
-FILE *fortranin = (FILE *) 0, *fortranout = (FILE *) 0;
+FILE *fortran_in = (FILE *) 0, *fortran_out = (FILE *) 0;
 
 typedef int yy_state_type;
 
-extern int fortranlineno;
-
-int fortranlineno = 1;
-
-extern char *fortrantext;
-#define yytext_ptr fortrantext
+extern int fortran_lineno;
+
+int fortran_lineno = 1;
+
+extern char *fortran_text;
+#define yytext_ptr fortran_text
 
 static yy_state_type yy_get_previous_state (void );
@@ -7234,9 +6785,9 @@
 
 /* Done after the current pattern has been matched and before the
- * corresponding action - sets up fortrantext.
+ * corresponding action - sets up fortran_text.
  */
 #define YY_DO_BEFORE_ACTION \
 	(yytext_ptr) = yy_bp; \
-	fortranleng = (size_t) (yy_cp - yy_bp); \
+	fortran_leng = (yy_size_t) (yy_cp - yy_bp); \
 	(yy_hold_char) = *yy_cp; \
 	*yy_cp = '\0'; \
@@ -7252,133 +6803,130 @@
 	flex_int32_t yy_nxt;
 	};
-static yyconst flex_int16_t yy_accept[1162] =
+static yyconst flex_int16_t yy_accept[1132] =
     {   0,
         0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-        0,    0,  177,  176,  165,  161,  164,  175,  152,  151,
-      155,  167,  152,  154,  154,  154,  157,  153,  137,  150,
-      156,  159,  158,  160,  145,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  165,  161,  164,  175,  150,  145,  145,  145,
-      145,  145,  145,  176,  176,  173,  176,  176,  176,  161,
-      161,  154,  145,    0,    0,  165,    0,  166,    0,  164,
-      175,  175,  175,    0,  141,    0,    0,  167,  167,  167,
-      167,    0,    0,    0,  140,    0,    0,  132,   26,    0,
-
-      146,    0,    0,    0,    0,    0,    0,    0,  133,    0,
-      150,   25,    0,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,  145,  145,  145,  145,  145,
-       43,  145,  145,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,   85,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  165,  163,    0,  163,    0,    0,    0,    0,
-        0,    0,  166,  162,  163,    0,  175,  174,  175,  175,
-      175,  163,  150,    4,  145,  145,  145,  145,   85,  145,
-
-      145,    0,  173,    0,    0,    0,    0,    0,    0,    0,
-      169,   26,    0,    0,    4,    0,  145,  145,  145,  145,
-      145,  145,    0,    0,    0,  175,  175,    0,    0,  167,
-      167,    0,    0,    0,    0,  139,    0,    0,    0,    0,
-        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-        0,  149,  146,    0,    0,    0,  142,    0,  145,  145,
-      145,  145,  145,  145,  145,  145,  145,  145,  145,  145,
-      145,  115,  145,  145,  145,    0,  145,  145,  145,  145,
-      145,   16,  145,  145,  145,  114,  145,  145,  145,  145,
-      145,    0,  145,    0,   96,  145,  145,  145,  145,  145,
-
-      121,  145,  145,  126,  145,  145,  145,  145,  145,  145,
-      145,   89,  145,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,  145,  118,  145,  145,  145,
-      145,  145,  122,  145,  145,  145,  145,  145,  165,  163,
-        0,  166,    0,    0,    0,    0,    0,    0,    0,    0,
-      163,    0,  163,  175,  175,  175,  150,    4,    4,    4,
-        4,  145,  145,  145,  145,  145,  145,  145,    0,    0,
-        0,    0,  170,    0,    0,  169,    0,    0,    4,    4,
-        4,    4,  142,    0,  145,  145,    0,  145,  145,  145,
-      145,    0,    0,    0,  175,  175,    0,    0,  167,  167,
-
-        0,    0,    0,    0,  147,    0,  146,    0,  148,    0,
-       28,    0,   30,   29,   32,   31,   34,    0,    0,   36,
-        0,  146,    0,  147,    0,  146,    0,  148,    0,  142,
-        0,  125,  117,  145,  145,  120,  123,  145,  145,   22,
-      145,  145,  145,  145,  145,  116,  145,  145,  145,    0,
-      145,  145,  145,   94,    0,  108,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,    0,  109,  145,  145,  145,
-      145,  145,  145,  145,    0,   88,  145,  145,  145,  145,
-      145,  145,  145,    0,   98,  145,  145,    0,  111,  145,
-      145,  145,  145,  112,   21,  145,   60,   74,  145,  145,
-
-      145,  145,  145,  145,  145,  145,   79,   44,  145,  145,
-      145,  145,   69,  145,  127,  119,  145,   72,   54,  145,
-        0,   97,   99,  145,   92,  101,  145,  145,  165,  163,
-      166,    0,    0,    0,    0,    0,    0,    0,  163,    0,
-      163,  175,  175,  175,  150,    4,    4,  145,  145,  145,
-      145,  145,  145,   18,    0,    0,    0,    0,    0,  170,
-        0,    0,    4,    4,    0,  142,    0,  145,  145,  145,
-      145,    0,    0,    0,  175,  175,    0,    0,  167,  167,
-        0,    0,   38,   27,    0,   35,   37,    0,  142,    0,
-      142,  145,  145,  145,  145,  145,   49,  145,  145,  145,
-
-      124,  145,  145,    0,  145,  145,  145,    0,  145,  145,
-        0,    0,    0,    0,    0,    0,    0,    0,   42,  145,
-       95,  145,  145,  145,  145,  145,  145,  145,  145,   76,
-       76,   76,   76,  145,    0,  107,  113,  145,  145,   88,
-      145,  145,   90,  145,  145,  145,  145,  145,  145,  145,
-      145,  145,  145,  145,  145,  145,  145,   52,  145,   77,
-      145,  145,  145,    0,  145,  145,  145,  145,  145,  102,
-      145,  145,   55,   81,  165,  163,  166,    0,    0,    0,
-        0,    0,    0,  163,    0,  163,  175,  175,  175,  150,
-        4,    3,    0,  104,  145,  145,   86,  145,  145,   70,
-
-       71,   70,    0,    0,    0,    0,    4,    3,    0,  142,
-        0,  142,  145,   49,  145,  124,    0,   23,    0,  175,
-       23,    0,   23,   23,  167,   23,    0,   23,   23,   23,
-       33,  145,  145,   23,   23,   23,  145,  145,   63,  145,
-      145,  145,  145,    0,  145,  145,  138,    0,    0,   93,
-      145,   42,    0,   95,    0,    0,    0,    0,    0,    0,
-      145,  145,  145,  145,  145,  145,  145,  145,    0,  110,
-      145,  145,  145,  145,  145,  145,  145,   66,  145,  145,
-      129,  100,  128,  130,   39,  145,  145,  145,  145,  145,
-      145,  145,   83,    0,  145,   11,   75,   19,  145,  145,
-
-       82,  165,  163,  166,    0,    0,    0,    0,  163,  175,
-      175,   23,    4,    3,    3,  145,  145,  145,  145,    0,
-        0,    0,   23,    4,    3,    3,  145,   23,   23,   23,
-       24,    0,  168,   24,   24,   24,   24,   24,   24,   24,
-       24,   24,   24,  145,  145,  145,   58,  145,  145,  145,
-        0,    0,  145,  145,   40,   93,    0,  145,    0,    0,
-        0,    0,    0,    0,    0,  145,  145,  145,  145,  145,
-       73,  145,  145,  145,    0,    0,  145,  145,   17,   50,
-       45,  145,   46,    0,  145,  145,    9,  145,  145,   67,
-       84,    7,    0,    0,  145,    0,  145,  145,    0,    0,
-
-        0,    0,  175,   24,    4,  145,  145,   64,  145,    0,
-        0,   24,    4,   24,   24,   24,  145,    8,  145,  145,
-       87,  145,  145,   40,    0,    0,  145,  145,    0,  145,
-        0,    0,    0,    0,    0,   73,    0,  145,  145,  145,
-      145,  145,   56,  145,   65,    0,    0,    0,    0,  134,
-       12,   20,  145,    0,  145,   80,   68,  145,    0,  145,
-        0,  145,  145,    0,    0,    0,  175,    4,  145,   59,
-      145,    0,    0,    4,  145,  131,   47,  145,   51,    0,
-        0,  145,  145,    0,   57,    0,    0,    0,    0,    0,
-       56,  145,   41,  145,  106,  145,  145,    0,    0,    0,
-
-        0,    0,  134,   91,    0,  145,   61,    0,   62,    0,
-      145,  145,    0,   59,    0,  175,    4,    4,  145,  143,
-        0,    0,    4,    4,  145,   10,    0,    0,  145,  145,
-       57,    0,   41,    0,  106,    0,  145,   14,  145,  145,
-        0,    0,    0,  145,    0,    0,  103,    6,    0,  143,
-      175,    4,    4,  145,    0,    0,    4,    4,   48,    0,
-        0,  145,  145,    0,   14,    0,   15,  145,   53,    0,
-        0,    0,  145,    0,  103,    0,  175,    4,    2,  105,
-        0,    0,    4,    2,    0,    0,  145,  145,   15,    0,
-      145,    0,    0,    0,  145,    0,  105,  175,    4,    0,
-
-        0,    4,    0,    0,  136,  145,    0,   13,    0,    0,
-        0,  145,    0,  175,    1,    0,    0,  144,    1,  136,
-        0,  145,   13,    0,    0,    0,    0,  145,    0,  175,
-        0,    0,  135,    0,    0,    0,   78,    5,  175,    0,
-      135,   78,  175,    0,  175,    0,  175,    0,  175,    0,
-      175,    0,  175,  171,    0,    0,    0,    0,    0,  172,
+        0,    0,  177,  176,  166,  164,  175,  176,  155,  158,
+      176,  176,  157,  157,  157,  160,  156,  144,  154,  157,
+      159,  162,  161,  163,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,  166,  164,  166,  175,  154,  151,
+      151,  151,  151,  151,  151,  176,  176,  172,  176,  176,
+      176,  157,  151,    0,    0,  166,    0,    0,  175,  175,
+      175,    0,  148,    0,    0,    0,  168,    0,    0,    0,
+        0,    0,  147,    0,    0,  141,   25,    0,  153,    0,
+
+        0,    0,    0,    0,    0,    0,  142,    0,  154,    0,
+      140,   23,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,  151,  151,  151,  151,   42,  151,
+      151,  151,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  100,  151,   89,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,    0,  166,  166,    0,  167,    0,
+        0,    0,    0,    0,    0,  165,  166,    0,  175,  174,
+      175,  175,  175,  167,  154,    0,  151,  151,  151,  151,
+
+       89,  151,  151,    0,  172,    0,    0,    0,    0,    0,
+        0,  173,   25,    0,    0,    0,  151,  151,  151,  151,
+      151,    0,    0,    0,  175,  175,    0,    0,    0,    0,
+        0,    0,    0,    0,  146,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,  152,  152,
+        0,  153,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,  151,  151,  151,  123,  151,  151,  151,
+      151,  151,  151,  151,   14,  151,  151,  151,  151,  122,
+      151,  151,  151,  151,  151,  151,  151,    0,  151,  151,
+      151,  151,  151,  151,  129,  151,  151,  134,  151,  151,
+
+      151,  151,  151,  151,  151,  151,   93,  151,  151,  151,
+      151,  151,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  126,  151,  151,  151,  151,  151,  130,  151,  151,
+      151,  151,  151,  151,  151,    0,  166,  166,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,  166,    0,  167,
+      175,  175,  175,  154,    0,  151,  151,  151,  151,  151,
+      151,  151,    0,    0,    0,    0,  173,    0,    0,    0,
+      151,  151,  151,  151,  151,    0,    0,    0,  175,  175,
+        0,    0,    0,    0,    0,    0,    0,    0,  153,    0,
+       27,    0,   29,   28,   31,   30,   33,    0,    0,   35,
+
+        0,    0,  133,  125,  151,  151,  128,  151,  131,  151,
+      151,   20,  151,  151,  151,  151,  151,  151,  124,  151,
+      151,  151,  151,  151,  151,   98,    0,  115,  151,  151,
+      151,  151,  151,  151,  151,  151,    0,  116,  151,    0,
+      117,  151,  151,  151,  151,  151,  151,    0,  113,  151,
+      151,    0,   92,  151,  151,  151,  151,  151,  151,  151,
+        0,  102,  151,  151,    0,  119,  151,  151,  151,  151,
+      120,    0,  114,   19,  151,   63,   77,  151,  151,  151,
+      151,  151,  151,  151,  151,   82,   43,  151,  151,  151,
+      151,   72,  151,  151,  127,  151,   76,   57,  151,    0,
+
+      101,  103,  151,   96,  105,  151,  151,  151,  151,   47,
+      166,  166,    0,    0,    0,    0,    0,    0,    0,  166,
+        0,  167,  175,  175,  175,  154,    0,  108,  151,  151,
+      151,  151,  151,   16,    0,    0,    0,    0,    0,    0,
+      151,  151,  151,  151,    0,    0,    0,  175,  175,    0,
+        0,    0,    0,    0,    0,   37,   26,    0,   34,   36,
+      151,  151,  151,  151,  151,  151,   52,  151,  151,  151,
+      151,  132,  151,  151,  151,  151,  151,    0,  151,  151,
+        0,    0,    0,    0,    0,    0,    0,    0,   41,  151,
+       99,  151,  151,  151,  151,  151,  151,  151,  151,   79,
+
+       79,  151,    0,  111,  121,   85,  151,  151,   92,  151,
+      151,   94,  151,  151,  151,  151,  151,  151,  151,  151,
+      151,  151,  151,    0,    0,  151,  151,  151,   55,  151,
+       80,  151,  151,  151,    0,  151,  151,  151,  151,  151,
+        0,  135,  106,  151,  151,    0,  112,   58,   39,   84,
+      166,  166,  108,    0,    0,    0,    0,    0,  166,    0,
+      167,  175,  175,  175,  154,    0,  108,  151,   90,  151,
+      151,   74,   73,   74,    0,    0,    0,    0,    0,  151,
+       52,  151,  132,    0,   21,    0,  175,   21,    0,   21,
+       21,    0,   21,    0,   21,   21,   21,   32,  151,  151,
+
+      151,   21,  151,  151,   66,  151,  151,  151,  151,  151,
+      151,  151,  145,    0,    0,   97,  151,   41,    0,   99,
+        0,    0,    0,    0,    0,    0,  151,  151,  151,  151,
+      151,  151,  151,  151,    0,  118,  151,  151,  151,  151,
+      151,  151,  151,   69,  151,  151,  137,  104,  136,  138,
+       38,  151,    0,    6,  151,  151,  151,  151,  151,  151,
+       87,    0,  151,    8,   78,   17,  151,  151,   86,  166,
+      166,    0,    0,    0,  166,  175,  175,   21,    0,  151,
+      151,  151,    0,    0,    0,   21,    0,  151,   21,   22,
+        0,  169,   22,   22,   22,   22,   22,   22,   22,   22,
+
+      151,  151,  151,  151,   50,  151,  151,  151,  109,  151,
+        0,  151,  151,   97,    0,  151,    0,    0,    0,    0,
+        0,    0,    0,  151,  151,  151,  151,  151,   75,  151,
+      151,  151,    0,    0,  151,  151,   15,   53,   44,  151,
+       45,    0,  151,  151,    5,  151,  151,   70,   88,    3,
+        0,    0,  151,    0,  151,  151,    0,    0,    0,  175,
+       22,    0,  151,   67,  151,    0,    0,   22,    0,   22,
+      151,    4,  151,  151,  151,  151,   91,  151,  151,    0,
+        0,  151,  151,    0,  151,    0,    0,    0,    0,    0,
+       75,    0,  151,  151,  151,  151,  151,   59,  151,   68,
+
+        0,    0,    0,    0,  143,    9,   18,  151,    0,  151,
+       83,   71,  151,    0,  151,    0,  151,  151,    0,    0,
+      175,    0,   62,  151,    0,    0,    0,  151,  151,  139,
+       46,  151,  151,   54,    0,    0,  151,  151,    0,   61,
+        0,    0,    0,    0,    0,   59,  151,   11,  151,  110,
+      151,  151,    0,    0,    0,    0,    0,  143,   95,    0,
+      151,   64,    0,   65,    0,  151,  151,   62,    0,  175,
+        0,  149,    0,    0,    0,  151,  151,   40,    7,    0,
+        0,  151,  151,   61,    0,   60,    0,   11,    0,  110,
+        0,  151,   10,  151,  151,    0,    0,    0,  151,    0,
+
+        0,  107,    2,  149,  175,    0,    0,    0,    0,   51,
+        0,    0,    0,    0,  151,  151,    0,   10,    0,   13,
+      151,   56,    0,    0,    0,  151,    0,  107,  175,    0,
+        0,    0,    0,    0,    0,    0,    0,  151,  151,   13,
+        0,  151,    0,    0,    0,  151,    0,  175,    0,    0,
+        0,    0,    0,   24,    0,    0,   49,  151,    0,   12,
+        0,    0,    0,  151,    0,  175,    0,    0,    0,  150,
+        0,   49,    0,  151,   12,    0,    0,    0,    0,  151,
+        0,  175,    0,    0,    0,    0,   48,    0,    0,    0,
+       81,    1,  175,    0,    0,    0,   48,   81,  175,    0,
+
+        0,    0,  175,    0,    0,    0,  175,    0,    0,    0,
+      175,    0,    0,    0,  175,    0,    0,    0,  175,  170,
+        0,  170,    0,    0,  170,    0,    0,    0,    0,  171,
         0
     } ;
@@ -7399,5 +6947,5 @@
        68,   69,   70,   71,   72,   44,   73,   74,   75,   76,
        77,   78,   79,   80,   81,   82,   83,   84,   85,   86,
-       87,   88,   89,   89,   89,    1,    1,    1,    1,    1,
+       87,   88,    1,   89,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -7418,1313 +6966,736 @@
 static yyconst flex_int32_t yy_meta[90] =
     {   0,
-        1,    2,    3,    2,    1,    4,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    5,    1,    6,
-        6,    6,    6,    6,    6,    6,    6,    6,    6,    1,
-        1,    1,    1,    1,    7,    8,    8,    9,    9,    5,
-       10,   11,    8,    8,    8,   10,   10,   10,    7,    8,
-        9,   10,   10,    5,   10,    8,   12,    8,    8,    8,
-        1,    1,    8,    7,    8,    8,    9,    9,    5,   10,
-       11,    8,    8,   10,   10,   10,    7,    8,    9,   10,
-       10,    5,   10,    8,   12,    8,    8,    8,    4
+        1,    1,    2,    1,    1,    3,    1,    1,    1,    1,
+        1,    4,    1,    1,    1,    1,    1,    3,    1,    5,
+        5,    5,    5,    5,    5,    5,    5,    5,    5,    1,
+        1,    1,    1,    1,    6,    7,    7,    5,    5,    8,
+        9,   10,   11,   11,   11,    9,   11,    9,   12,   11,
+       13,    9,    9,    9,    9,   11,   11,   11,   11,   11,
+        1,    1,   11,    6,    7,    7,    5,    5,    8,    9,
+       10,   11,   11,    9,   11,    9,   12,   11,   13,    9,
+        9,    9,    9,   11,   11,   11,   11,   11,    3
     } ;
 
-static yyconst flex_int16_t yy_base[1215] =
+static yyconst flex_int16_t yy_base[1171] =
     {   0,
-        0,   88,    0,    0,    0,    0, 1215,   93, 1196,   91,
-        0,    0, 1179,   64,   97,  117,  132,   87,  124,   98,
-       99,  142,  173,  154,  108,  135,  134,  254,  172,  179,
-      175,  178,  219,  180,  323,  388,  384,  318,  386,  319,
-      186,  128,  250,  256,  392,  404,  438,  428,  204,  455,
-      432,  465,  544,  120,  537,  548,  627,  624,  622,  544,
-      644,  658,  251, 9159, 1175, 9159,  267,   99,  162,  569,
-      572,  620,  745,  164,  107,  262,  307,  335,  376,  522,
-        0,  167,  157, 1162, 9159,  278,  321, 1160, 1118,  372,
-      304,  532,  593,  567, 9159,  633,  832, 9159, 9159,  911,
-
-      798,  318,  319,  450,  799,  552,  320,  354, 9159,  978,
-      834, 9159,  865,  860,  862,  866,  914,  863,  973,  980,
-      974, 1013, 1024, 1045,  869, 1049, 1075, 1095, 1098, 1101,
-     1182, 1177, 1161, 1181, 1214, 1212, 1237, 1239, 1235, 1270,
-     1290, 1316, 1325, 1293, 1346, 1323, 1366, 1368, 1391, 1399,
-     1403, 1429, 1430, 1455, 1452, 1478, 1498, 1482, 1523, 1521,
-     1554, 1548, 1579, 1586, 1606, 1629, 1649, 1675, 1681, 1698,
-     1707, 1729,  871, 1114, 1109,  140, 1023,  187,  372,  403,
-      553,  401, 1095,  565, 1792, 1818, 1083, 9159,  643,  669,
-      589, 1844, 1870, 1580, 1865, 1867, 1868, 1905, 1926, 1922,
-
-     1925, 1078, 9159,  837,  437,  677,  249,  660, 1072,  712,
-     9159, 1062,  844,  625, 1874, 1993, 2022, 1042,  864,  473,
-      904,  621,  506,  651,  721,  798,  791,  890,  912,  936,
-      907,  725, 1029, 1143,  729, 9159, 1114, 1179, 2097, 2112,
-     2127,  229,  937, 1033, 1012, 1006,  994,  943,  883,  974,
-      891, 9159, 1476, 2142, 2157, 2172, 2182, 2202, 2178, 2180,
-     2200, 2203, 2223, 2243, 2246, 2244, 2276, 2269, 2299, 2307,
-     2301, 2324, 2344, 2351, 2377,  901, 1018, 2374, 2394, 2397,
-     2414, 2495, 2434, 2440, 2465, 2472, 2518, 2521, 2515, 2548,
-     2556, 1138, 2564,  968, 9159, 2581, 2597, 2604, 2627, 2649,
-
-     2650, 2690, 2693, 2686, 2726, 2738, 2746, 2747, 2763, 2783,
-     2799, 2800, 2803, 2820, 2840, 2843, 2870, 2891, 2895, 2903,
-     2926, 2928, 2935, 2961, 2981, 2958, 2984, 2978, 3004, 3011,
-     3027, 3052, 3048, 3059, 3085, 3068, 3105, 3111,  196,  203,
-      976,  383,  974,  988, 1018, 1014, 1025, 1029, 1042,  253,
-     3174, 3200, 3226, 1067, 1182, 1172, 3252,    0,  418,  288,
-     1096, 3228, 3229, 3231, 3251, 3267, 3287, 3290, 1188, 1566,
-      973,  740, 9159,  938,  866, 9159, 1268, 1178,  931, 1170,
-     1241, 1299, 3354, 3381,    0,  903, 3408, 1148, 1116, 1177,
-     1322, 1145,  410, 1415, 1235,  460, 1292, 1218, 1323, 1022,
-
-      963, 1520, 1662, 3418, 3430, 3440, 3450, 3460, 3470,  889,
-     9159,  865, 9159, 9159, 9159, 9159, 9159, 1239,  853, 9159,
-      846, 2472, 3480, 3490, 3500, 3510, 3520, 3530, 3545, 3555,
-     3575, 9159, 3289, 3553, 3573, 3551, 3574, 3590, 3596, 3612,
-     3628, 3634, 3635, 3655, 3671, 3651, 3687, 3688, 3696,  459,
-     3728, 3736, 3740, 3784, 3868, 9159, 3780, 3776, 3807, 3811,
-     3850, 3912, 3872, 3920, 3921, 1351, 9159, 3828, 4005, 4060,
-     4095, 3904, 4063, 4069, 1258, 4096, 4104, 4126, 4134, 4156,
-     4165, 4196, 4205, 1409, 9159, 4208, 4197, 1476, 9159, 4235,
-     4241, 4257, 4261, 4273, 4284, 4293, 4305, 4309, 4332, 4336,
-
-     4353, 4316, 4359, 4362, 4384, 4407, 4385, 4416, 4423, 4448,
-     4455, 4456, 4486, 4494, 4488, 4511, 4527, 4519, 4531, 4554,
-     1498, 9159, 4552, 4575, 4584, 4587, 4607, 4610,  493,  529,
-      551,  476, 1287,  816,  953, 1119, 1293,  841, 4678, 4704,
-     4730, 1607, 1346, 1458, 4756, 1362, 1397, 4733, 4732, 4759,
-     4627, 4768, 4817,  733, 1619, 1594, 1406,  728, 1537, 9159,
-     1571, 1651, 1625, 1613, 4839, 4867, 4894, 1627, 1658, 1686,
-     1714, 1394,    0, 1756, 1574,    0, 1668,  724, 1709,  724,
-     1763, 1775, 9159, 9159,  708, 9159, 9159, 4904, 4916, 4926,
-     4936, 4771, 4931, 5013, 4934, 5068, 5069, 5071, 5075, 5072,
-
-     5120, 5121, 5123, 1725, 5127, 5153, 5176, 1832, 5175, 5179,
-     1458, 1493, 1739, 1516, 1519, 1873, 1592, 1739, 5201, 5224,
-     5202, 5241, 5240, 5257, 5278, 5280, 5301, 5284, 5352, 9159,
-     5351, 5346, 5349, 5353, 1802, 9159, 5355, 5385, 5401, 9159,
-     5405, 5408, 5412, 5428, 5449, 5451, 5458, 5460, 5495, 5501,
-     5531, 5527, 5539, 5571, 5564, 5575, 5591, 5602, 5623, 5614,
-     5634, 5635, 5660,  693, 5666, 5667, 5692, 5703, 5715, 9159,
-     5723, 5719, 5740, 5746,  846, 1103, 1234, 1788, 1768, 1386,
-     1788, 1615, 1847, 1854,  236,  590, 1781, 1913,  715, 5809,
-     1790, 1645, 2264, 9159, 5785, 5805, 1690, 5806, 5807, 2344,
-
-     9159, 1951, 1858, 1924, 2256,  679, 1930, 1879, 5870, 5880,
-     5907, 5917, 1811,  658, 5946,  624,    0, 9159, 6034,    0,
-        0,  613,  609, 9159,  604,  586, 2245, 2364, 2389, 9159,
-     9159, 6063, 6118, 6139, 6138, 6134, 6135, 6141, 6161, 6173,
-     6184, 6209, 6217, 1654, 6260, 6248, 6216, 1844, 1864, 6239,
-     6280, 9159, 1689, 9159, 1930, 1750, 1763, 1934, 1933, 2077,
-     6300, 6292, 6317, 6337, 6338, 6344, 6369, 6376, 2212, 9159,
-     6360, 6413, 6392, 6412, 6424, 6433, 6456, 6435, 6465, 6476,
-     6488, 6497, 6508, 6509, 6552, 6529, 6540, 6549, 6560, 6585,
-     6593, 6605, 6628, 2392, 6636, 6637, 6648, 6659, 6694, 6685,
-
-     6686, 6775, 2286,  518, 2092, 2103, 1938, 2148, 2420, 2303,
-      472,  442, 2196,    0, 1803, 6692, 6717, 6768, 6756, 2424,
-     2334,  426,  422, 2432,  378, 1883, 6858, 6945, 6974,  337,
-     9159, 1922, 9159,    0,  328, 9159,  314, 2481, 2510, 9159,
-     6929, 6757, 7029, 7031, 7037, 7040, 7033, 7077, 7070, 7086,
-     2264, 2842, 7093, 7097, 7118, 9159, 2372, 7129, 2384, 2060,
-     2411, 2418, 2078, 2421, 2139, 7138, 7149, 7170, 7179, 7195,
-     7201, 7227, 7234, 7236, 2483, 3160, 7259, 7257, 7279, 7280,
-     7282, 7302, 7318, 2564, 7325, 7319, 7345, 7356, 7377, 7357,
-     7368, 7388, 2513, 2467, 7400, 2603, 7389, 7425, 2468, 2371,
-
-     2235, 2479,  361,  296,  182, 7409, 7432, 2249, 7455,  622,
-     2529,  227, 1008, 7505,    0,  207, 7482, 7503, 7505, 7514,
-     7535, 7536, 7544, 9159, 2413, 2526, 7567, 7571, 2546, 7593,
-     2547, 2562, 2567, 2526, 2575, 9159, 2526, 7587, 7625, 7594,
-     7631, 7632, 7648, 7657, 7668, 3179, 3203, 2672, 3229, 3335,
-     7684, 7688, 7709, 2597, 7705, 7725, 7732, 7736,  178, 7758,
-     2596, 7775, 7769, 2619, 2617, 2641, 2696, 2668, 7795, 7801,
-     7807, 2677, 2720, 3150, 7827, 7818, 7834, 7867, 7850, 2625,
-     2685, 7870, 7890, 2688, 7859, 2699, 2731, 2741, 2661, 2665,
-     9159, 7911, 7907, 7910, 7927, 7933, 7963, 2822, 3360, 3384,
-
-     3411, 4103, 4220, 7959, 2702, 7970, 7966, 2741, 7986, 2738,
-     8003, 8019, 2758, 9159, 2765, 2781, 2809, 2818, 8030, 8026,
-     2900, 2883, 2903, 2951, 8042, 8051, 2820, 2829, 8063, 8086,
-     9159, 2838, 9159, 2846, 9159, 2846, 8088, 8090, 8113, 8134,
-     3067, 4430, 2880, 8136,  175, 2911, 8125, 8156, 2877, 9159,
-     1190, 2938, 2908, 8157, 3034, 3081, 3049, 3028, 8173, 2959,
-     2985, 8189, 8182, 3029, 9159, 3039, 8205, 8212, 8214, 3241,
-     4684, 3056, 8235, 3049, 9159, 3056, 3212, 3072,    0, 8237,
-     1210, 3169, 3157,  144, 3103, 3103, 8257, 8260, 9159, 3110,
-     8283, 3255, 4708, 3110, 8290,  123, 9159, 3235, 3207, 3329,
-
-     3387, 3558, 3232, 3256, 8306, 8313, 3278, 8315, 8396, 4870,
-     3259, 8391, 3280, 3664,    0, 3349, 3414, 9159,  103, 9159,
-     3346, 8392, 9159, 3745, 4900, 8473, 3347, 8450,   90, 1237,
-     1328, 3570, 8470, 4973, 4977, 3380, 8471, 9159, 3676, 3645,
-     9159, 9159, 3693, 3608, 3764, 3684, 3616, 1433, 3705, 3782,
-     3810, 3774, 3875, 9159, 3852, 3697, 3910, 3892, 3896, 9159,
-     9159, 8553, 8565, 8577, 8589, 8601, 8613, 8621, 8623, 8635,
-     8647, 8659, 8671, 8678, 8687, 8699, 8711, 8723, 8735, 8747,
-     8754, 8762, 8774, 8786, 8798, 8810, 8822, 8834, 8846, 8858,
-     8870, 8882, 8894, 8906, 8918, 8930, 8942, 8954, 8966, 8978,
-
-     8990, 9002, 9014, 9026, 9038, 9050, 9062, 9074, 9086, 9098,
-     9110, 9122, 9134, 9146
+        0,   88,    0,    0,    0,    0,  984,   93,    0,   85,
+        0,    0,  891,   64,   98,  103,   80,  129,   96,   99,
+      134,  137,  145,  133,  168,  135,  249,  180,  318,  136,
+      156,  172,  212,  239,  246,  297,  366,  341,  414,  461,
+      247,  294,  398,  334,  407,  476,  506,  517,  459,  566,
+      572,  522,  571,  367,  653,  226,  656,  658,  737,  638,
+      785,  655,  698,  806,  652, 4012,  878, 4012,  241,  116,
+      124,  455,  893,   59,   76,  229,  253,  256,    0,  122,
+      127,  872, 4012,  157,  188,  869,  866,  327,  302,  349,
+      740,  416, 4012,  768,  592, 4012, 4012,  981,  730,  147,
+
+      184,  438,  495,  328,  184,  190, 4012, 1048,  335,  969,
+     4012, 4012,    0,  269,  315,  149,  319,  486,  462,  248,
+      318,  325,  269,  426,  736,  336,  767,  470,  500,  518,
+      512,  403,  516,  525,  535,  801,  544,  620,  565,  570,
+      589,  768,  483,  589,  810,  592,  613,  638,  650,  664,
+      678,  736,  737,  740,  741,  949,  736,  788,  646,  956,
+      756,  999,  739,  753,  804,  749, 1043,  972,  962,  769,
+      813,  963,  972,  969,    0, 1057,    0,  839,  238, 1044,
+      986,  789,  956, 1030,  965,  429, 1109, 1136,  830, 4012,
+     1061, 1087, 1091, 1162, 1188,  990, 1095, 1120, 1006, 1042,
+
+     1170, 1050, 1046,  823, 4012, 1201, 1099, 1115, 1190,  797,
+      483, 4012,  790, 1167, 1100, 1194, 1269, 1358, 1255, 1254,
+     1195, 1103, 1098,  625, 1148, 1163, 1217, 1237, 1222, 1238,
+     1095, 1305, 1325, 1234, 4012, 1334, 1302, 1326, 1107, 1182,
+      738,  735,  731,  730, 1244, 1166,  713, 1242, 4012, 1428,
+     1374, 1389, 1419, 1244, 1252, 1261, 1263, 1192, 1266, 1301,
+     1333, 1333, 1352, 1352, 1387, 1392, 1388, 1389, 1390, 1404,
+     1401, 1405, 1407, 1404, 1506, 1471, 1417, 1476, 1430,    0,
+     1422, 1437, 1442, 1432, 1484, 1440, 1454, 1497, 1444, 1448,
+     1451, 1443, 1445, 1475, 1459, 1530, 1536, 1464, 1477, 1470,
+
+     1531, 1490, 1491, 1482, 1509, 1511,    0, 1526, 1513, 1519,
+     1524, 1527, 1524, 1555, 1516, 1519, 1522, 1546, 1557, 1564,
+     1558, 1565, 1555, 1557, 1562, 1561, 1615, 1573, 1575, 1573,
+     1576, 1570, 1574, 1582, 1576,  719,  351,  666, 1572,  713,
+     1580, 1587, 1584, 1593, 1589, 1596, 1608, 1658, 1684, 1710,
+     1652, 1645, 1661, 1741, 1626, 1629, 1635, 1634, 1637, 1703,
+     1653,  709, 1654, 1744,  707,  998, 4012, 1712, 1674, 1715,
+     1664, 1708, 1725, 1738, 1749, 1622, 1684, 1379, 1672, 1735,
+     1743, 1771, 1723, 1772, 1787, 1804, 1815, 1807, 1821,  656,
+     4012,  646, 4012, 4012, 4012, 4012, 4012, 1735,  614, 4012,
+
+      613, 1849, 4012,    0, 1741, 1751,    0, 1796,    0, 1799,
+     1799,    0, 1820, 1819, 1811, 1816, 1808, 1821,    0, 1826,
+     1822, 1814, 1822, 1825, 1819, 1871, 1955, 4012, 1825, 1821,
+     1837, 1830, 1829, 1850, 1823, 1844, 1899, 4012, 1836, 1909,
+     4012, 1841, 2040, 1856, 1915, 1858, 1874, 1920, 4012, 1886,
+     1872, 1878,    0, 1886, 1879, 1881, 1888, 1896, 1895, 1902,
+     1967, 4012, 1897, 1906, 1971, 4012, 1900, 1912, 1906, 1915,
+        0, 1980, 4012,    0, 1988,    0,    0, 1929, 1939, 1926,
+     1933, 1936, 1946, 1939, 1953,    0,  602, 1949, 1958, 1955,
+     1963,    0, 1960, 2063,    0,  598,    0,    0, 1985, 2064,
+
+     4012,    0, 1960,    0,    0, 2019, 2022, 2024, 2025, 4012,
+      792,  880, 2030, 2023, 2043, 2043, 2041, 2042,  581, 2092,
+     2118, 2144, 2079, 2080, 2084, 2170, 2045, 1005, 2060, 1022,
+     2071, 2134, 2199,  574, 2082, 2174, 2108, 2147, 2148, 2101,
+     2154, 2184, 2187, 2190, 2087,    0, 1422, 2144,    0, 2200,
+      138, 2202,  571, 2221, 2233, 4012, 4012,  514, 4012, 4012,
+     2174, 2192, 2051, 2289, 2080, 2193,    0, 2109, 2194, 2193,
+     2199,    0, 2201, 2207, 2204, 2195, 2198, 2270, 2240, 2240,
+     2215, 2229, 2246, 2239, 2258, 2275, 2258, 2276,    0, 2276,
+        0, 2287, 2279, 2283, 2295, 2283, 2295, 2300, 2335, 4012,
+
+        0, 2293, 2342, 4012,    0,    0, 2294, 2293, 4012, 2316,
+     2321,    0, 2297, 2323, 2312, 2319, 2335, 2334, 2327, 2337,
+     2333, 2341, 2338,  197,  451, 2343, 2337, 2347,    0, 2348,
+        0, 2335, 2355, 2355,  477, 2343, 2343, 2350, 2355, 2348,
+     2275, 4012, 4012, 2349, 2351, 2404, 4012,    0,    0,    0,
+     1140, 1249, 1797, 2376, 2082, 2379, 2366, 2432, 2263,  424,
+      569, 2417, 2420,  499, 2486, 2384, 2087, 2385, 2427, 2389,
+     2398, 2437, 4012, 2448, 2444, 2439, 2452,  479, 2451, 2431,
+     2410, 2565, 2416,    0, 4012, 2653,    0,    0,  475,  445,
+     4012,  441,  436, 2458, 2462, 2468, 4012, 4012, 2682, 2404,
+
+     2428,    0, 2441, 2444,    0, 2442, 2449, 2447, 2480, 2465,
+     2479, 2553,    0, 2487, 2489,    0, 2493, 4012, 2486, 4012,
+     2497, 2509, 2513, 2527, 2535, 2549, 2552, 2538, 2550, 2555,
+     2548, 2562, 2552, 2559, 2604, 4012, 2572, 2480, 2561, 2568,
+     2573, 2575, 2564,    0, 2569, 2578,    0,    0,    0,    0,
+     2660, 2572,  508, 4012, 2583, 2594, 2591, 2650, 2664, 2658,
+        0, 2536, 2663,    0,    0,    0, 2715, 2654,    0, 2539,
+     2479, 2668, 2663, 2678, 2644, 2682,  426,  421, 2680, 2677,
+     2540, 2686, 2701, 2720,  411,  365, 2721, 2790, 2691, 4012,
+     2725, 4012,    0,  343, 4012,  307, 2753, 2755, 4012,    0,
+
+     2747, 2692, 2702, 2706,    0, 2707, 2709, 2719,    0, 2685,
+     2776, 2708, 2732, 4012, 2748, 2737, 2773, 2763, 2773, 2780,
+     2773, 2788, 2777, 2776, 2785, 2780, 2796, 2786,    0, 2797,
+     2798, 2794, 2647, 2867, 2796, 2791,    0,    0,    0, 2795,
+        0, 2845, 2798, 2801,    0, 2815, 2825,    0,    0,    0,
+     2872, 2840, 2825, 2883, 2847, 2843, 2840, 2548, 2855,  827,
+      303,  239, 2841, 2765, 2855, 1020, 2888,  288, 1687, 2861,
+     2861,    0, 2851, 2861, 2850, 2855,    0, 2851, 2858, 2858,
+     2856, 2863, 2873, 2862, 2878, 2870, 2882, 2880, 2881, 2888,
+     4012, 2904, 2901, 2906, 2913, 2885, 2895,    0, 2903,    0,
+
+     2951, 2978, 2955, 2982, 2994,    0,    0, 2933, 2910, 2917,
+        0,    0, 2923,  248, 2932, 2941, 2930, 2939, 2936, 2956,
+     2998, 2964,    0, 2967, 3005, 3006, 3007, 2966, 2959,    0,
+        0, 2960, 2979,    0, 2973, 2982, 2973, 2987, 2986, 3025,
+     2983, 2989, 2995, 2978, 2978, 4012, 2985,    0, 2991,    0,
+     2985, 3006, 3066, 3074, 3078, 3090, 3094, 3106,    0, 3009,
+     3019,    0, 3041,    0, 3018, 3050, 3056, 4012, 3062, 3076,
+     3056,    0, 3087, 3103, 3099, 3072, 3111,    0,    0, 3064,
+     3080, 3075, 3079, 3124, 3125, 4012, 3082, 4012, 3085, 4012,
+     3080, 3093,    0, 3096, 3104, 3152, 3171, 3113, 3118,  245,
+
+     3119,    0,    0, 4012, 1737,  184, 3142, 3141, 1922,    0,
+     3181, 3186, 3115, 3122, 3127, 3111, 3122, 4012, 3128,    0,
+     3129,    0, 3208, 3211, 3152, 3158, 3150, 4012, 3194, 3154,
+     2097, 3179, 3201, 3224, 3231, 3169, 3153, 3159, 3179, 4012,
+     3183, 3184, 3251, 3258, 3191, 3183,  207, 3229, 3207, 3237,
+      194, 3233, 3261, 4012, 3209, 3200,    0, 3220, 3211,    0,
+     3309, 3283, 3218, 3228, 3221, 3285, 3236, 3273,  142, 4012,
+     3286, 4012, 3243, 3250, 4012, 3339, 3342, 3367, 3248, 3286,
+      108, 2482,   40, 2606, 2838, 3273,    0, 3395, 3399, 3290,
+        0, 4012, 3302, 3294, 3311, 3350, 4012, 4012, 3299, 3320,
+
+     3357, 3358, 3375, 3318, 3359, 3380, 3404, 3376, 3300, 3412,
+     3362, 3363, 3370, 3415, 3418, 3423, 3420, 3426, 3433, 4012,
+     3447, 4012, 3428, 3451, 4012, 3430, 3439, 3454, 3457, 4012,
+     4012, 3521, 3534, 3547, 3560, 3573, 3586, 3595, 3608, 3621,
+     3634, 3647, 3656, 3669, 3678, 3686, 3699, 3712, 3725, 3738,
+     3751, 3764, 3777, 3790, 3803, 3816, 3829, 3842, 3855, 3868,
+     3881, 3894, 3907, 3920, 3933, 3946, 3959, 3972, 3985, 3998
     } ;
 
-static yyconst flex_int16_t yy_def[1215] =
+static yyconst flex_int16_t yy_def[1171] =
     {   0,
-     1161,    1, 1162, 1162,    1,    2, 1163, 1163,    1,    2,
-        1,    2, 1161, 1161, 1161, 1161, 1161, 1164, 1165, 1161,
-     1161, 1166, 1167, 1161, 1161, 1161, 1161, 1161, 1161, 1168,
-     1161, 1161, 1161, 1161, 1169, 1169,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36, 1161, 1161,   53, 1170, 1161,   36,   36,   36,
-       36,   36,   36, 1161, 1171, 1161, 1171, 1171, 1171, 1161,
-     1161, 1172, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1164, 1164, 1164, 1165, 1161, 1165, 1165, 1166, 1161, 1166,
-     1166, 1167, 1173, 1167, 1161, 1167, 1167, 1161, 1161, 1161,
-
-     1174, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1175,
-     1161, 1161, 1161,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-     1169,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   53,  173, 1176, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161,  173, 1161,  173, 1161, 1170, 1161, 1170, 1170,
-     1170, 1161, 1161, 1177,   36,   36,   36,   36,   36,   36,
-
-       36, 1171, 1161, 1171, 1171, 1171, 1171, 1178, 1179, 1179,
-     1161, 1179, 1179, 1179, 1180, 1179, 1161,  217,  217,  217,
-      217,  217, 1161, 1161, 1161, 1164, 1164, 1165, 1165, 1166,
-     1166, 1173, 1173, 1173, 1173, 1161, 1167, 1167, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1181, 1161, 1161, 1161, 1161, 1161,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36, 1182,  131,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36, 1161,   36, 1161, 1161,   36,   36,   36,   36,   36,
-
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,  173,  173,
-     1161,  173, 1176, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-      185, 1161, 1161, 1170, 1170, 1170, 1161, 1177, 1177, 1177,
-     1177,   36,   36,   36,   36,   36,   36,   36, 1171, 1171,
-     1183, 1183, 1161, 1179, 1179, 1161, 1179, 1179, 1180, 1180,
-     1180, 1180, 1179, 1179,  217,  217, 1179,  217,  217,  217,
-      217, 1161, 1161, 1161, 1164, 1164, 1165, 1165, 1166, 1166,
-
-     1173, 1167, 1167, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1181, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36, 1161,
-       36,   36,   36,   36, 1161, 1161,   36,   36,   36,   36,
-       36,   36,   36,   36,   36, 1161, 1161,   36, 1161,   36,
-       36,   36,   36,   36, 1161,   36,   36,   36,   36,   36,
-       36,   36,   36, 1161, 1161,   36,   36, 1161, 1161,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-     1161, 1161,   36,   36,   36,   36,   36,   36,  173,  173,
-      173, 1161, 1161, 1161, 1161, 1161, 1161, 1161,  185, 1161,
-     1161, 1170, 1170, 1170, 1161, 1177, 1177,   36,   36,   36,
-       36,   36,   36, 1161, 1171, 1171, 1171, 1183, 1183, 1161,
-     1179, 1179, 1180, 1180, 1179, 1179, 1179,  217,  217,  217,
-      217, 1161, 1184, 1161, 1164, 1185, 1165, 1186, 1187, 1188,
-     1189, 1190, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161,   36,   36, 1161,   36,   36,   36,   36,   36,   36,
-
-       36,   36,   36, 1161,   36,   36,   36, 1161,   36,   36,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36, 1161,
-     1161,   36,   36,   36, 1161, 1161,   36,   36,   36, 1161,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36, 1161,   36,   36,   36,   36,   36, 1161,
-       36,   36,   36,   36,  173,  173,  173, 1161, 1161, 1161,
-     1161, 1161, 1161,  173, 1161, 1161, 1170, 1170, 1191, 1161,
-     1177, 1192, 1161, 1161,   36,   36, 1161,   36,   36, 1161,
-
-     1161, 1161, 1171, 1171, 1179, 1193, 1180, 1194, 1179, 1179,
-     1179, 1179,  217,  217, 1161,  217, 1195, 1161, 1161, 1196,
-     1197, 1198, 1199, 1161, 1200, 1201, 1202, 1203, 1203, 1161,
-     1161, 1161,   36, 1161,   36,   36,   36,   36,   36,   36,
-       36,   36,   36, 1161,   36,   36,   36, 1161, 1161,   36,
-       36, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-       36,   36,   36,   36,   36,   36,   36,   36, 1161, 1161,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-       36,   36,   36, 1161,   36,   36,   36,   36,   36,   36,
-
-       36, 1161,  802,  802, 1161, 1161, 1161, 1161,  802, 1204,
-     1205, 1204, 1206, 1207, 1207,   36,   36,   36,   36, 1208,
-     1208, 1209, 1210, 1211, 1212, 1212, 1161, 1210, 1161,  829,
-     1161, 1161, 1161, 1197, 1199, 1161, 1201, 1203, 1203, 1161,
-     1161,   36,   36,   36,   36,   36,   36,   36,   36,   36,
-     1161, 1161,   36,   36,   36, 1161, 1161,   36, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161,   36,   36,   36,   36,   36,
-       36,   36,   36,   36, 1161, 1213,   36,   36,   36,   36,
-       36,   36,   36, 1161,   36,   36,   36,   36,   36,   36,
-       36,   36, 1161, 1161,   36, 1161,   36,   36, 1161, 1161,
-
-     1161, 1161, 1204, 1204, 1206,   36,   36, 1161,   36, 1208,
-     1208, 1210, 1211, 1210,  829,  829,   36,   36,   36,   36,
-       36,   36,   36, 1161, 1161, 1161,   36,   36, 1161,   36,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161,   36,   36,   36,
-       36,   36,   36,   36,   36, 1213, 1213, 1161, 1214, 1213,
-       36,   36,   36, 1161,   36,   36,   36,   36, 1161,   36,
-     1161,   36,   36, 1161, 1161, 1161, 1204, 1206,   36,   36,
-       36, 1208, 1208, 1211,   36,   36,   36,   36,   36, 1161,
-     1161,   36,   36, 1161,   36, 1161, 1161, 1161, 1161, 1161,
-     1161,   36,   36,   36,   36,   36,   36, 1161, 1214, 1214,
-
-     1213, 1214, 1214,   36, 1161,   36,   36, 1161,   36, 1161,
-       36,   36, 1161, 1161, 1161, 1204, 1206, 1206,   36,   36,
-     1208, 1208, 1211, 1211,   36,   36, 1161, 1161,   36,   36,
-     1161, 1161, 1161, 1161, 1161, 1161,   36,   36,   36,   36,
-     1161, 1213, 1161,   36, 1161, 1161,   36,   36, 1161, 1161,
-     1204, 1206, 1206,   36, 1208, 1208, 1211, 1211,   36, 1161,
-     1161,   36,   36, 1161, 1161, 1161,   36,   36,   36, 1161,
-     1213, 1161,   36, 1161, 1161, 1161, 1204, 1206, 1206,   36,
-     1208, 1208, 1211, 1211, 1161, 1161,   36,   36, 1161, 1161,
-       36, 1161, 1213, 1161,   36, 1161, 1161, 1204, 1206, 1208,
-
-     1208, 1211, 1161, 1161,   36,   36, 1161,   36, 1161, 1213,
-     1161,   36, 1161, 1204, 1206, 1208, 1208, 1161, 1211, 1161,
-     1161,   36, 1161, 1161, 1213, 1213, 1161,   36, 1161, 1204,
-     1208, 1161,   36, 1213, 1214, 1161,   36, 1161, 1204, 1208,
-     1161, 1161, 1204, 1208, 1204, 1208, 1204, 1208, 1204, 1208,
-     1204, 1208, 1204, 1161, 1208, 1208, 1208, 1208, 1208, 1161,
-        0, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161
+     1131,    1, 1132, 1132,    1,    2, 1133, 1133,    1,    2,
+        1,    2, 1131, 1131, 1131, 1131, 1134, 1135, 1131, 1131,
+     1136, 1137, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138,   40, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1131, 1131,   55, 1139, 1131,   37,
+     1138, 1138, 1138, 1138, 1138, 1131, 1140, 1131, 1140, 1140,
+     1140, 1141, 1131, 1131, 1131, 1131, 1131, 1131, 1134, 1134,
+     1134, 1135, 1131, 1135, 1135, 1136, 1131, 1136, 1136, 1137,
+     1142, 1137, 1131, 1137, 1137, 1131, 1131, 1131, 1143, 1131,
+
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1144,   29, 1131,
+     1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1145,   55,  176, 1146, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131,  176, 1131, 1139, 1131,
+     1139, 1139, 1139, 1131, 1131, 1131, 1138, 1138, 1138, 1138,
+
+     1138, 1138, 1138, 1140, 1131, 1140, 1140, 1140, 1140, 1147,
+     1147, 1131, 1147, 1147, 1147, 1147, 1148, 1148,  218,  218,
+      218, 1131, 1131, 1131, 1134, 1134, 1135, 1135, 1136, 1136,
+     1142, 1142, 1142, 1142, 1131, 1137, 1137, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1144,
+     1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1131, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1145,  176,  176, 1131, 1146,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131,  187, 1131, 1131,
+     1139, 1139, 1139, 1131, 1131, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1140, 1140, 1147, 1147, 1131, 1147, 1147, 1147,
+      218,  218,  218,  218,  218, 1131, 1131, 1131, 1134, 1134,
+     1135, 1135, 1136, 1136, 1142, 1137, 1137, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+
+     1131, 1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1131, 1131, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1131, 1131, 1138, 1131,
+     1131, 1138, 1149, 1138, 1138, 1138, 1138, 1131, 1131, 1138,
+     1138, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1131, 1131, 1138, 1138, 1131, 1131, 1138, 1138, 1138, 1138,
+     1138, 1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1131,
+
+     1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1131,
+      176,  176, 1131, 1131, 1131, 1131, 1131, 1131, 1131,  187,
+     1131, 1131, 1139, 1139, 1139, 1131, 1131, 1138, 1138, 1138,
+     1138, 1138, 1138, 1131, 1140, 1140, 1140, 1147, 1147, 1147,
+      218,  218,  218,  218, 1131, 1150, 1131, 1134, 1151, 1135,
+     1152, 1136, 1153, 1137, 1154, 1131, 1131, 1131, 1131, 1131,
+     1138, 1138, 1138, 1155, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1131, 1138, 1138,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1131,
+
+     1138, 1138, 1131, 1131, 1138, 1138, 1138, 1138, 1131, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1131, 1131, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1131, 1138, 1138, 1138, 1138, 1138,
+     1131, 1131, 1131, 1138, 1138, 1131, 1131, 1138, 1138, 1138,
+      176,  176, 1131, 1131, 1131, 1131, 1131, 1131,  176, 1131,
+     1131, 1139, 1139, 1156, 1131, 1131, 1131, 1138, 1131, 1138,
+     1138, 1131, 1131, 1131, 1140, 1140, 1147, 1157, 1147,  218,
+      218, 1158,  218, 1159, 1131, 1131, 1160, 1134, 1161, 1135,
+     1131, 1162, 1136, 1163, 1137, 1137, 1131, 1131, 1164, 1138,
+
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1131, 1131, 1138, 1138, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1131, 1131, 1138, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138,  176,
+      176, 1131, 1131, 1131,  176, 1139, 1165, 1139, 1131, 1138,
+     1138, 1138, 1140, 1140, 1166, 1147, 1147, 1167,  218, 1131,
+     1131, 1131, 1134, 1135, 1131, 1136, 1137, 1137, 1131, 1138,
+
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1131, 1138, 1138, 1131, 1131, 1138, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1138, 1131, 1168, 1138, 1138, 1138, 1138, 1138, 1138,
+     1138, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+     1131, 1131, 1138, 1131, 1138, 1138, 1131, 1131, 1131, 1139,
+     1139, 1131, 1138, 1131, 1138, 1140, 1140, 1147, 1147,  218,
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1131,
+     1131, 1138, 1138, 1131, 1138, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138,
+
+     1168, 1168, 1131, 1169, 1168, 1138, 1138, 1138, 1131, 1138,
+     1138, 1138, 1138, 1131, 1138, 1131, 1138, 1138, 1131, 1131,
+     1139, 1131, 1138, 1138, 1140, 1140, 1147, 1138, 1138, 1138,
+     1138, 1138, 1138, 1138, 1131, 1131, 1138, 1138, 1131, 1138,
+     1131, 1131, 1131, 1131, 1131, 1131, 1138, 1138, 1138, 1138,
+     1138, 1138, 1131, 1169, 1169, 1168, 1169, 1169, 1138, 1131,
+     1138, 1138, 1131, 1138, 1131, 1138, 1138, 1131, 1131, 1139,
+     1131, 1138, 1140, 1140, 1147, 1138, 1138, 1138, 1138, 1131,
+     1131, 1138, 1138, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1138, 1138, 1138, 1138, 1131, 1168, 1131, 1138, 1131,
+
+     1131, 1138, 1138, 1131, 1139, 1131, 1140, 1140, 1147, 1138,
+     1131, 1131, 1131, 1131, 1138, 1138, 1131, 1131, 1131, 1138,
+     1138, 1138, 1131, 1168, 1131, 1138, 1131, 1131, 1139, 1131,
+     1140, 1140, 1147, 1131, 1131, 1131, 1131, 1138, 1138, 1131,
+     1131, 1138, 1131, 1168, 1131, 1138, 1131, 1139, 1131, 1140,
+     1170, 1147, 1131, 1131, 1131, 1131, 1138, 1138, 1131, 1138,
+     1131, 1168, 1131, 1138, 1131, 1139, 1131, 1140, 1170, 1131,
+     1147, 1131, 1131, 1138, 1131, 1131, 1168, 1168, 1131, 1138,
+     1131, 1139, 1131, 1140, 1147, 1131, 1138, 1168, 1169, 1131,
+     1138, 1131, 1139, 1131, 1140, 1147, 1131, 1131, 1139, 1131,
+
+     1140, 1147, 1139, 1131, 1140, 1147, 1139, 1131, 1140, 1147,
+     1139, 1131, 1140, 1147, 1139, 1131, 1140, 1147, 1139, 1131,
+     1131, 1131, 1140, 1147, 1131, 1140, 1140, 1140, 1140, 1131,
+        0, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131
     } ;
 
-static yyconst flex_int16_t yy_nxt[9249] =
+static yyconst flex_int16_t yy_nxt[4102] =
     {   0,
-       14,   15,   16,   17,   18,   19,   14,   20,   21,   22,
-       23,   24,   25,   26,   25,   27,   25,   28,   29,   30,
-       30,   30,   30,   30,   30,   30,   30,   30,   30,   25,
+       14,   15,   16,   15,   17,   18,   14,   19,   20,   21,
+       22,   23,   24,   25,   24,   26,   24,   27,   28,   29,
+       29,   29,   29,   29,   29,   29,   29,   29,   29,   30,
        31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
        41,   42,   43,   42,   42,   44,   45,   46,   47,   48,
-       42,   49,   50,   51,   42,   42,   52,   42,   42,   42,
-       25,   25,   42,   35,   36,   37,   38,   39,   40,   41,
+       42,   49,   50,   51,   52,   42,   53,   42,   42,   54,
+       24,   24,   42,   35,   36,   37,   38,   39,   40,   41,
        42,   43,   42,   44,   45,   46,   47,   48,   42,   49,
-       50,   51,   42,   42,   52,   42,   42,   42,   14,   53,
-       54,   55,   56,   71,   67,   66,   67,   68,   76,   77,
-
-       78,  203, 1138,   74,   72,  211,  206,   57,   57,   57,
-       57,   57,   57,   57,   57,   57,   57,   75,   79,   77,
-       79,   79,   77,   79,   58,   59,   82,   73,   60,   85,
-       61,   69,   74,   78,   77,   80,   74,   74,   74, 1113,
-       83,   62,   63,  176,   89,   75,  211,   74,   99,  176,
-       75,   75,   75,   58,   59,   82,   73,   60,  224,   61,
-       69,   75,  115,   86,  203,   74,   74,   74,   83,   62,
-       63,   74,   98,   74,   74,   93,   74,   87,   75,   75,
-       75,   90,   94,   95,  109,   75,  224,   75,   75,   75,
-     1074,  115,   86,   74, 1008,   91,  110,  529,  223,  530,
-
-       74,  226,   74,   74,  531,   87,  530,   75,  227,  207,
-       90,   74,   96,   75,   74,   75,   75,   74,   74,   74,
-      115,  346,   74,   91,  387,   75,   97,  223,   75,  211,
-      226,   75,   75,   75,  142,   75,  227,  207,  115,  176,
-       74,   96,  161,   74,  968,  176,   74,   74,   74,  115,
-      346,  203,  112,   75,   97,  100,   75,  100,   74,   75,
-       75,   75,  142,   76,   77,   78,  410,  115,  204,  203,
-      204,  161,   75,  101,  101,  101,  101,  101,  101,  101,
-      101,  101,  101,   85,  115,  115,  370,   74,  102,  143,
-      115,  538,  103,   74,  104,  410,  144,  145,  188,  105,
-
-       75,  106,  107,  201,  146,  205,   89,   75,   79,   77,
-       79,  108,  228,  115,  115,  370,   89,  102,  143,  115,
-      538,  103,   74,  104,  144,  145,   85,  105,  546,  106,
-      107,  201,  146,   85,  205,   75,   78,   77,   78,  108,
-      113,  228,  114,  114,  114,  114,  114,  114,  114,  114,
-      114,  114,  115,  115,  387,  231,  129,  546,  116,  117,
-      130,  138,  118,  188,  139,  242,  131,  140,  119,  243,
-      132,  250,  229,  141,   89,  120,  121,  225,   77,  225,
-      211,  115,  115,  231,  531,  129,  530,  116,  117,  130,
-      138,  118,  139,  242,  131,  140,  119,  243,  132,  250,
-
-      229,  141,  251,  120,  121,  113,  230,  114,  114,  114,
-      114,  114,  114,  114,  114,  114,  114,  347,  124,  359,
-      115,  359,  122,  967,  211,  125,  147,  118,  211,  126,
-      251,  133,  127,  134,  148,  230,  135,  136,  150,  203,
-      149,  123,  128,  137,  188,  347,  151,  124,  573,  115,
-      348,  122,  152,  350,  125,  147,  118,  126,  153,  133,
-      127,  134,  157,  148,  135,  136,  168,  150,  149,  123,
-      128,  137,  115,  169,  188,  151,  158,  573,  348,  159,
-      152,  350,  160,  170,  207,  154,  153,  155,  244,  162,
-      387,  157,  156,  163,  675,  168,  676,  164,  576,  115,
-
-      604,  115,  169,  245,  158,  165,  171,  159,  166,  167,
-      160,  170,  207,  154,  678,  155,  172,  244,  162,  804,
-      156,  389,  163,   78,   77,   80,  164,  576,  115,  604,
-      677,  245,  676,  165,   93,  171,  166,  167,  183,  184,
-      185,   94,   95,  678,  172,  173,   77,  174,  175,  389,
-      188,  392,  677,  176,  676,  189,  186,  186,  186,  186,
-      186,  186,  186,  186,  186,  186,   79,   77,   79,   93,
-       79,   77,   79,   79,   77,   79,   94,   95,  115,  392,
-      177,  178,  208,   74,  179,  208,  180,  190,   89,  198,
-      248,  188,  142,  176,  233,  234,  233,  181,  182,  176,
-
-      249,  191,  235,  236,  224,  208,   89,  115,  208,  177,
-      178,  349,   74,  179,   85,  180,  190,  198,  836,  248,
-      142,  210,  211,  210,  203,  181,  182,  211,  249,  191,
-      192,  194,  224,  212,  208,   93,  176,  208,  387,  349,
-      356,  387,   94,   95,  110,  188,  193,  193,  193,  193,
-      193,  193,  193,  193,  193,  193,  197,  391,  195,  213,
-      129,  372,  373,  372,  130,  125,   74,  237,  356,  126,
-      131,  188,  196,  214,  132,  387,  378,  354,  115,  203,
-       75,  211,  128,  143,  972,  197,  391,  195,  213,  129,
-      144,  199,  168,  130,  125,   74,  237,  126,  131,  169,
-
-      196,  214,  132,  355,  378,  393,  354,  115,   75,  170,
-      128,  369,  143,  375,  376,  375,  200,  188,  144,  199,
-      794,  168,  394,   77,  394,  731,   89,  234,  169,  724,
-      373,  234,  355,  393,  401,  236,  554,  170,  401,  236,
-      369,  559,  560,  559,  200,  209,  210,  211,  210,  209,
-      209,  209,  215,  209,  209,  209,  209,  209,  209,  209,
-      209,  209,  216,  209,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  209,  209,  209,  209,  209,  195,
-      218,  218,  218,  218,  219,  218,  125,  218,  218,  218,
-      220,  218,  218,  196,  218,  218,  218,  218,  221,  218,
-
-      218,  218,  218,  222,  218,  209,  209,  218,  195,  218,
-      218,  218,  218,  219,  218,  125,  218,  218,  220,  218,
-      218,  196,  218,  218,  218,  218,  221,  218,  218,  218,
-      218,  222,  218,  209,   93,  239,  240,  246,  204,  203,
-      204,   94,   95,  395,  554,  396,  211,  802,  241,  803,
-      680,  110,  247,  111,  111,  111,  111,  111,  111,  111,
-      111,  111,  111,  587,  239,  240,  246,  375,  376,  375,
-      586,  395,  339,  396,  340,  205,  241,  258,  377,  680,
-      247,  387,  584,  238,  257,  257,  257,  257,  257,  257,
-      257,  257,  257,  257,  115,   85,  115,  261,  388,  115,
-
-      115,  115,  115,  268,  205,  115,  583,  377,  115,   89,
-     1161,  238,  100,  115,  100,  115,  115,   85,  259,  115,
-      387,  387,  115,  115,  341,  115,  261,  388,  115,  115,
-      115,  115,  268,  211,  115,  397,  419,  115,   89, 1161,
-      211,  115,  421,  115,  115,  102,  259,  115,  115,  103,
-      115,  104,  341,  115,  411,  390,  105,  450,  106,  107,
-      417,  400,  260,  397,  419,  234,  398,  115,  108,  294,
-      421,  294,  401,  236,  102,  373,  188,  115,  103,  295,
-      104,  399,  115,  390,  105,  450,  106,  107,  681,  400,
-      260,  420,  412,  418,  398,  115,  108,  253,  253,  253,
-
-      253,  253,  253,  253,  253,  253,  253,  115,  264,  399,
-      211,  416,  115,  115,  115,  254,  255,  681,  262,  115,
-      412,  418,  263,  415,   89,  265,  115,  115,  256,  414,
-      233,  234,  233,  115,  349,  258,  115,  264,  235,  236,
-      532,  115,  115,  115,  254,  255,  262,  115,  115,  266,
-      413,  263,  115,  265,  115,  115,  256,  344,  115,  387,
-      580,  115,  349,  115,  211,  533,  115,  534,  532,  188,
-      974,  345,  115,  535,  211,  265,  115,  115,  266,  115,
-      203,  115,  536,  115,  115,  188,  344,  115,  115,  580,
-      267,  537,  115,  533,  115,  534,  342,  269,  115,  345,
-
-      115,  535,  115,  265,  804,  115,  803,  542,  115,  115,
-      536,  188,  115,  115,  115,  342,   93,  115,  267,  537,
-       89,  270,  271,   94,   95,  269,  115,  272,  115,  115,
-      115,  273,  274,  387,  115,  115,  542,  115,  115,  292,
-      115,  292,  547,  115,  233,  234,  233,  275,  115,  270,
-      271,  115,  235,  236,  115,  272,  115,  682,  115,  402,
-      273,  274,   89,  115,  115,  387,  115,   85,  569,  115,
-      547,  380,  211,  380,  188,  275,  115,  203, 1161,  115,
-      211,   93,  115,  276,  188,  276,  682,  402,   94,   95,
-      203,  475,  188,  568,  387,  115,  569,  572,   70,  113,
-
-      115,  277,  277,  277,  277,  277,  277,  277,  277,  277,
-      277,  115,  203,  281,  115,  115,  115,   66,  282,  475,
-      115,  568,  280,   85,  115,  572,  544,  543,  555,  115,
-      115,  570,  562,  403,  115,  804,  278,  803,  279,  188,
-      115,  281,  115,  211,  115,  115,  115,  282,  115,  115,
-      280,  115, 1077,  115,  544,  543,  578,  555,  115,  570,
-      562,  403,  115,  284,  278,  115,  279,  115,  283,  115,
-      211,  115, 1100,  115,  115,  115,  115,  115,  115,  285,
-      115,  563,  115,  289,  288,  578,  286,  575,  115, 1161,
-      287,  284,  115,  115,  585,  115,  283,   85,  115, 1139,
-
-      115,  211,  115,  115,  115,  115,  640,  115,  285,  115,
-      563,  289,  288,  561,  286,  575,  115,  292,  287,  292,
-      115,  290,  585,  115,  115,   89,  294,  115,  294,  115,
-      203,  683,  115,  115,  640, 1161,  295,  291,  115,  387,
-      679,  561,  296,  115,  577,  564,  115, 1161,  188,  290,
-      115,  115,  466,  115,  466,  115,  115,  115,  115,  261,
-      683,  115,  115,  301,  115,  291, 1161,  571,  679,  293,
-      296,  115,  577,  564,  115,  579,  115, 1161,  115,  115,
-      115, 1161,  297,  467,  115,  115,  115,  697,  261,  697,
-     1140,  115,  301,  115,  298,  571,  299,  293,  688,  300,
-
-      115, 1161,  115,  579,  115,  115,  115,  115,  203,  115,
-      484,  297,  484,  691,  115,  303,  574,   77,  574,  115,
-      485,  115,  298,  302,  299,  115,  688,  300,  304,  115,
-      115,  115,  717,  115,  115,  203,  115,  115,  115, 1161,
-     1161,  691,  115,  303,  115,  305,  692,  115, 1161,  115,
-      306,  302,  115,  704,  115, 1161,  115,  304, 1161,  115,
-      188,  717,  115,  115,  115, 1161,  115,  115,  115,  115,
-     1161,  115,  115,  305,  692,  308,  307,  488,  306,  488,
-      115,  704,  115,  115,  115, 1161,  115,  489, 1161,  115,
-      310,  115,  115,  115,  115, 1150,  689,  115,  115,  521,
-
-      309,  521, 1161,  308,  307,  311,  752, 1161,  115,  522,
-      115,  115,  115,  239,  240,  115,  115,  115,  115,  310,
-      115,  115,   93,  115,  315,  689,  241, 1161,  309,   94,
-       95,  312,  115,  311,  752,  115,  115,  115,  559,  560,
-      559,  115,  239,  240, 1161,  115,  115,  753, 1161,  313,
-      115,  115,  314,  315,  241,  115,  318,  115, 1161,  312,
-      115,  115,  115,  115,  755,  316,  115,  556,  203,  556,
-      756,  317,  581,  211,  115,  753,  115,  313, 1161,  115,
-      314,  359,  115,  359,  115,  318,  115,  115,  319,  115,
-      320,  115,  755,  115,  316,  556,  203,  556,  756,  317,
-
-      581,  115,  115,  324,  115, 1161,  321,  322,  557,  188,
-      323,  115,  720,  115,  360,  211,  115,  319,  115,  320,
-      115,  203,  115,  705,  325,  115,  326,  211,  361,  115,
-     1161,  324,  115,  327,  321,  322,  557,  557,  323,  115,
-      115,  720,  115,  360,  387,  115,  815,  115,  815,  115,
-      759,  705,  325,  211,  115,  326,  361,  328,  687,  115,
-      115,  327,  708,  329,   93,  557,  808,  115,  115,  115,
-      703,   94,   95,   85,  115,  387,  707,  330,  759,  713,
-      265, 1161,  115,  115,  331,  328,  687,  115,  115,  706,
-      708,  697,  329,  697,  808,  332,  714,  115,  703,  851,
-
-      582, 1161,  115,  387,  707,  330,  722,  713,  265,  115,
-      115,   89,  115,  331,  115,  115, 1161,  115,  706,  335,
-      115, 1161,  333,  332,  715,  714,  334,  851,  115,  582,
-      115,  387,  115, 1161,  115,  722,  859,  115,  115, 1161,
-      336,  115, 1161,  115,  115,  337,  115,  725,  335,  115,
-      333,  115,  716,  715,  334, 1161,  115,  719,   77,  719,
-      115,  115,  115,  115,  859,   93,  115,  744,  115,  336,
-      115,  338,   94,   95,  337,  115,  725,   93,  754,  115,
-      760,  716,  115,  188,  729,  730, 1161, 1161,  115,  693,
-     1161,  693,  115,  342,  184,  351,  744,  115,  861,  694,
-
-      338,  727,  806,  635,  815,  635,  815,  754,  862,  760,
-      115,  352,  352,  352,  352,  352,  352,  352,  352,  352,
-      352,  353,  807,  810, 1161,  805,  861,  176,  387, 1161,
-      727,  806,  813,  608,  636,  608,  862,  352,  352,  352,
-      352,  352,  352,  352,  352,  352,  352,  353,  700,  827,
-      700,  807,  810,  176,  805,  804,  184,  809,  701, 1161,
-      203,  813,  702,  352,  352,  352,  352,  352,  352,  352,
-      352,  352,  352,  353,  748,  380,  211,  380,  827,  176,
-      826,  211,  826,  856,  826,  211,  826,  110,  749,  357,
-      357,  357,  357,  357,  357,  357,  357,  357,  357,  115,
-
-      820,  115,  115,  748,  115,  857,  115,  115,  381, 1161,
-      267,  757,  856,  270,  363,  188,  749,  362,  115,  272,
-      115,  364,  382,  832,   77,  832,  203,  758,  115,  820,
-      115,  115,  211,  115,  857,  115,  115,  381,  267,  115,
-      757,  270,  363, 1161,  115,  362,  115,  272,  115,  364,
-      382,  811,  702,  365,  702,  758,  115, 1161,  115,  115,
-      115,  115,  297,  368,  115,  115,  702,  860,  115,  863,
-     1161,  367,  824,  115,  298,  115,  299,  821,  115,  366,
-      811,  365,  864,  901, 1161,  115,  115, 1161,  115,  115,
-      115,  297,  368,  115,  115,  211,  860, 1161,  863,  367,
-
-     1161,  824,  298,  115,  299,  821,  115,  366, 1161, 1161,
-      864,  901,  383,  383,  383,  383,  383,  383,  383,  383,
-      383,  383,  374,  374,  211,  374,  374,  374,  374,  374,
-      374,  374,  374,  374,  374,  374,  374,  374,  374,  384,
-      374,  385,  385,  385,  385,  385,  385,  385,  385,  385,
-      385,  374,  374,  374,  374,  374,  386,  386,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      386,  386,  374,  374,  386,  386,  386,  386,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      374,  404, 1161,  404,  932,  865,  405,  405,  405,  405,
-      405,  405,  405,  405,  405,  405,  406, 1161,  406,  935,
-      899,  407,  407,  407,  407,  407,  407,  407,  407,  407,
-      407,  408,  932,  408,  865,  900,  409,  409,  409,  409,
-      409,  409,  409,  409,  409,  409,  423,  935,  423,  899,
-     1161,  424,  424,  424,  424,  424,  424,  424,  424,  424,
-      424,  425, 1161,  425,  900, 1161,  426,  426,  426,  426,
-      426,  426,  426,  426,  426,  426,  427,  902,  427,  432,
-      937,  428,  428,  428,  428,  428,  428,  428,  428,  428,
-
-      428,  257,  257,  257,  257,  257,  257,  257,  257,  257,
-      257, 1161,  115,  769,  115,  769,  902,  115,  937,  115,
-      429,  430,  430,  430,  430,  430,  430,  430,  430,  430,
-      430,  115,  433,  115,  115,  905,  908,  115,  908,  115,
-      431,  115,  115,  115,  770,  434,  115,   93,  115,  429,
-      908,  435,  908,  115,  839,  840,  115,  115,  211,  115,
-      433,  115,  115,  115,  905,  693,  115,  693,  115,  431,
-      436,  115, 1161,  434, 1161,  694,  115,  115,  115,  435,
-      115,  115,  115,  115,  115,  115,  115,  804,  439,  803,
-      437,  115, 1161, 1161,  822,  176,  115,  115,  436,  115,
-
-      438,  805,  924,  115,  115,  188,  115,  115,  115,  115,
-      115,  115,  115, 1161,  115,  115,  439, 1161,  437, 1161,
-      441,  440,  115,  822,  115,  115, 1161,  115,  438,  115,
-      805,  924,  115,  115, 1161,  115,  203,  115,  115,  115,
-      115,  115,  903, 1161,  115,  700,  115,  700,  441,  440,
-      115,  442,  115,  443,  445,  701,  444,  115,  115,  702,
-      115, 1161,  115,  115,  115,  446,   93,  115, 1161,  115,
-      115,  903,  911,   94,   95,  115, 1161,  115,  115,  442,
-      115,  443,  445,  115,  444,  115, 1161,  115,  115,  447,
-      115,   93,  115,  893,  446,  893,  448,  115,   94,   95,
-
-     1161,  911, 1161,  894,  115,  115, 1161,  115,  115,  451,
-      929,  115,  115,  115,  115,  449,  115,  447,  965,  115,
-      931,  804,  184,  809,  448,  115,  203,  115,  115,  176,
-      115,  453,  115,  115,  211,  452,  115,  115,  451,  929,
-      115,  466,  115,  466,  449,  115,  965,  115,  115,  931,
-      115,  933,  454,  115, 1161,  115,  934,  115,  115,  936,
-      453,  980,  115,  910,  452,  115, 1161,  115,  115, 1161,
-     1161,  913,  467,  115,  115,  115,  465,  115,  115,  115,
-      933,  454,  115,   93,  875,  934,  875,  115,  936,  980,
-       94,   95,  910,  115,  876,  115,  455,  115,  455,  115,
-
-      913,  959,  115,  115,  115,  465,  115,  964,  115,  239,
-      240,  115,   93,  966,  893,  115,  893,  468,  469,   94,
-       95,  115,  241, 1161,  894,  115, 1161,  456,  115,  115,
-      959,  203,  457,  115,  458,  115,  964,  459,  239,  240,
-      115,  460,  966, 1161,  461,  468,  469,  462,  463,  472,
-      241,  464,  115,  115,  115,  115,  470,  115,  115,  471,
-      115,  457,  989,  458,  991,  884,  459,  884,  115,  460,
-     1161,  115,  461, 1161,  115,  462,  463,  981,  472,  464,
-      973,  115,  115,  115,  115,  470,  115,  115,  471,  115,
-      115,  989,  474,  991,  473,  115,  115,  984,  115,  115,
-
-      986,  115,  115,  115,  896,  981,  896,  987,  973,  115,
-     1161,  115,  476,  954, 1161,  115,  115,  115,  988,  115,
-      115,  474,  473,  990,  115,  984,  477,  115,  986,  115,
-     1010,  115,  115, 1161,  115,  987,  115,  115,  115,  961,
-      476,  954,  478,  115,  115,  115,  988, 1161, 1005,  115,
-      115,  990, 1161, 1013,  477, 1161, 1161,  115,  479, 1010,
-      115,  115,  115, 1161, 1161,  115,  115,  115,  961, 1014,
-      478, 1027,  115,  998,  948,  998, 1005, 1015,  115,  203,
-      115,  480, 1013,  115,  115,  115,  479,  481,  115,  115,
-      115,  484,  483,  484,  488,  115,  488, 1014,  188, 1027,
-
-      482,  485,  115,  115,  489, 1017, 1015, 1018,  115,  480,
-     1161, 1161,  115,  115, 1035, 1021,  481,  115,  115, 1036,
-      115,  483,  203, 1028,  115,  115, 1031,  115,  482,  115,
-      115,  115,  115, 1016, 1017,  486, 1018, 1161,  490,  115,
-      492, 1032, 1035,  115, 1021,  487,  115, 1036,  491,  115,
-     1043, 1161, 1028,  115,  115, 1031,  115, 1161,  115, 1022,
-      115,  115, 1016,  486,  493,  115,  490,  115,  492, 1033,
-     1032,  115,  115,  487,  115, 1034,  491,  115, 1043,  115,
-      115,  115, 1045,  188,  495,  115,  115, 1161, 1022,  115,
-     1046,  494,  496,  493,  115, 1161, 1161,  115, 1033,  115,
-
-      115,  115,  115, 1050, 1034, 1161,  115,  115, 1161,  115,
-      115, 1045, 1049,  495,  115,  115,  115,  115, 1046,  494,
-      496,  497,  115, 1041,  948, 1041,  115,  115,  115, 1051,
-      498,  115, 1050,  115,  115, 1161,  115,  500,  115,  115,
-     1049,  499,  115,  852,  115,  852,  115, 1052, 1161,  497,
-     1161,  115,  115,  115,  115, 1161,  115, 1051,  498,  115,
-     1053, 1161,  115,  115,  115, 1061,  500,  115,  115, 1060,
-      499,  115,  501,  115,  115, 1161, 1052,  115,  925,  115,
-      115,  115,  115,  115,  115,  203, 1064,  502,  115, 1053,
-      503,  926, 1065,  115, 1061, 1161,  115, 1060,  504, 1066,
-
-      501,  115,  203,  115,  115,  211,  115,  925,  115,  115,
-      505,  115, 1161, 1161, 1064,  502, 1072, 1056,  503,  926,
-     1065,  115, 1076,  115,  115,  115,  504, 1066, 1161,  115,
-      115, 1161,  507,  115,  115, 1161,  506,  115,  115,  505,
-      508, 1057,  115, 1161,  115, 1072, 1056, 1055,  115, 1075,
-     1076,  115, 1161,  211,  115, 1079,  115,  509,  115,  115,
-      115,  507,  115,  115,  506,  115,  115,  115,  508,  115,
-     1057,  115,  115, 1078,  115, 1055,  115,  512, 1075,  115,
-      510,  115,  511, 1079,  115,  509, 1161, 1161,  115,  115,
-     1161,  115,  115, 1058,  115,  115,  115,  115,  115,  513,
-
-      115, 1161, 1078,  115, 1085,  515,  512,  115,  510,  115,
-      511,  115,  115, 1161,  115,  115,  115,  115,  115,  514,
-      115,  115, 1058,  115,  115,  516,  115, 1086,  513,  115,
-      211,  517, 1085,  515,  115, 1161,  203,  115,  115,  115,
-     1161,  115,  115,  115,  115,  115,  115,  115,  514,  115,
-      115,  211,  115,  521,  516,  521, 1086,  518, 1161,  517,
-      519,  115,  115,  522,  115,  115,  115,  115, 1070,  948,
-     1070, 1081,  115, 1161,  115, 1084, 1089, 1161,  520,  115,
-      115, 1090,  115,  203, 1083,  518,  115,  115,  519,  523,
-      115,  115,  115,  115, 1094,  115, 1161, 1096,  115,  524,
-
-     1081,  115,  115, 1084, 1089,  115,  520,  115,  115, 1097,
-     1090,  115,  115, 1083,  526,  115,  115, 1082,  523,  115,
-      115,  115,  115, 1094,  115, 1096, 1099,  115,  524,  115,
-     1161,  115,  525,  115, 1161, 1161,  115, 1097,  115,  115,
-      115, 1103,  526, 1161,  115,  115, 1082, 1111,  115,  115,
-      115, 1161,  211,  115, 1099, 1104,  527, 1107,  115,  211,
-      525,  947,  948,  947,  528, 1161,  115, 1161,  115,  949,
-     1103,  203,  950,  115,  115,  531, 1111,  539, 1161,  115,
-      947,  948,  947, 1104,  527, 1107,  115, 1023,  949, 1024,
-     1161,  950,  528,  540,  540,  540,  540,  540,  540,  540,
-
-      540,  540,  540,  541,  947,  948,  947, 1101, 1161,  176,
-     1161, 1102,  949, 1161,  188,  950, 1023, 1161, 1024,  540,
-      540,  540,  540,  540,  540,  540,  540,  540,  540,  541,
-     1000, 1001, 1000, 1161, 1161,  176, 1101,  188, 1002, 1102,
-     1161, 1003, 1092,  948, 1092,  540,  540,  540,  540,  540,
-      540,  540,  540,  540,  540,  541, 1109,  948, 1109, 1098,
-     1115,  176,  115,  115, 1161,  550,  548,  115,  115,  110,
-      115,  545,  545,  545,  545,  545,  545,  545,  545,  545,
-      545,  115,  549, 1114,  115,  115,  551, 1098, 1115, 1120,
-      115,  115,  115,  554,  550,  548,  115,  115, 1121,  115,
-
-     1161,  115, 1161, 1161,  115,  552,  115, 1161, 1161,  115,
-      549, 1114,  115, 1127,  115,  551, 1123, 1120,  482,  115,
-      115,  115, 1161,  115,  115,  553,  115, 1121,  115,  115,
-      115,  203,  115, 1161,  552,  115,  947,  948,  947, 1129,
-      115, 1127,  115,  115,  949, 1123,  482,  950,  115, 1161,
-      115,  203,  115,  115,  553,  115,  211,  115,  115, 1161,
-     1161, 1000, 1001, 1000, 1161, 1161, 1116, 1129,  115, 1002,
-      115,  115, 1003,  383,  383,  383,  383,  383,  383,  383,
-      383,  383,  383,  211, 1161, 1000, 1001, 1000, 1117, 1118,
-     1117, 1161,  565, 1002, 1132, 1116, 1003, 1131, 1136, 1161,
-
-      566,  566,  566,  566,  566,  566,  566,  566,  566,  566,
-      211, 1161, 1042, 1001, 1042, 1117, 1118, 1117, 1142,  567,
-      949,  565, 1132,  950, 1161, 1131, 1136,  383,  383,  383,
-      383,  383,  383,  383,  383,  383,  383,  405,  405,  405,
-      405,  405,  405,  405,  405,  405,  405, 1142,  567,  405,
-      405,  405,  405,  405,  405,  405,  405,  405,  405,  407,
-      407,  407,  407,  407,  407,  407,  407,  407,  407,  407,
-      407,  407,  407,  407,  407,  407,  407,  407,  407,  409,
-      409,  409,  409,  409,  409,  409,  409,  409,  409,  409,
-      409,  409,  409,  409,  409,  409,  409,  409,  409,  424,
-
-      424,  424,  424,  424,  424,  424,  424,  424,  424,  424,
-      424,  424,  424,  424,  424,  424,  424,  424,  424,  426,
-      426,  426,  426,  426,  426,  426,  426,  426,  426,  426,
-      426,  426,  426,  426,  426,  426,  426,  426,  426,  428,
-      428,  428,  428,  428,  428,  428,  428,  428,  428,  428,
-      428,  428,  428,  428,  428,  428,  428,  428,  428,  588,
-      211,  588, 1161, 1161,  589,  589,  589,  589,  589,  589,
-      589,  589,  589,  589,  430,  430,  430,  430,  430,  430,
-      430,  430,  430,  430, 1161,  115, 1161,  115, 1161,  590,
-      115,  590,  115,  429,  591,  591,  591,  591,  591,  591,
-
-      591,  591,  591,  591,  115,  592,  115,  115,  115,  593,
-      203, 1119,  115,  115,  115, 1161,  115, 1141,  188,  115,
-     1161,  115,  429, 1161,  115, 1161,  115,  115,  594,  115,
-      115, 1161,  115,  592,  115,  115,  115,  115,  593, 1119,
-     1161,  115,  115,  115, 1161, 1141,  115,  203,  595,  115,
-     1149,  115, 1161,  115,  115,  115, 1146,  594,  115,  115,
-     1161, 1161,  596, 1161,  115,  115,  188,  115,  115,  115,
-     1161,  115,  597,  115,  115,  115,  595,  115,  188, 1149,
-      115,  115, 1161,  598, 1146,  115,  203,  115,  115,  115,
-      115,  596, 1144,  115,  115,  188,  115,  115,  115,  203,
-
-      599,  597,  115,  115,  115,  115, 1161,  188,  115,  115,
-      115,  598, 1161,  600,  115,  115,  115, 1130,  115,  115,
-     1144,  115,  115,  115,  115,  601,  115,  115,  599, 1143,
-      115, 1157,  115,  602,  115,  115,  115, 1148, 1161,  115,
-      115,  115,  600,  603, 1145, 1130, 1124,  948, 1124,  115,
-      115,  115,  115, 1161,  601,  115,  115, 1143, 1151,  115,
-     1157,  602,  115, 1161,  115, 1148,  188,  115,  115,  115,
-      115,  603, 1145,  605,  115,  115,  203,  115,  606,  115,
-     1161,  115, 1161, 1161,  203,  608, 1151,  608, 1161,  115,
-     1161,  115,  607,  115, 1161, 1161,  115, 1161, 1161,  115,
-
-     1161,  605, 1147,  115,  115, 1161, 1161,  606,  115,  115,
-      115, 1153, 1154, 1153,  115,  115, 1161,  115,  115,  115,
-      607,  115, 1161,  115, 1161, 1155,  609, 1161,  619,  115,
-      620, 1147, 1161,  115, 1161, 1152, 1161,  115, 1161,  115,
-      610,  115, 1161,  115,  115,  115,  621,  115,  115, 1161,
-      115, 1161,  115, 1155,  203,  609,  619,  115,  620,  622,
-      115,  115,  115, 1152,  115,  115, 1161,  115,  610,  455,
-      115,  455, 1161, 1161,  115,  621, 1153, 1154, 1153,  115,
-     1161,  629, 1161, 1161,  115, 1161, 1161,  622,  115,  115,
-     1156,  115,  115, 1159, 1160, 1159,  115, 1159, 1160, 1159,
-
-      456,  623, 1161,  115, 1161,  611,  115,  612, 1161,  629,
-      613,  115,  203,  115,  614, 1161, 1161,  615,  115, 1156,
-      616,  617, 1161, 1161,  618,  115, 1161, 1161, 1161,  623,
-      626,  115, 1161, 1161,  611,  115,  612, 1161,  115,  613,
-      115, 1161,  614,  115, 1161,  615,  115, 1161,  616,  617,
-      624,  115,  618,  115,  115,  115, 1161,  637,  626,  115,
-      115,  627, 1161, 1158, 1161,  115,  625,  115, 1161, 1161,
-     1161, 1161,  115,  115,  115,  115,  628, 1161, 1161,  624,
-      115, 1161, 1161,  115,  115,  637, 1161, 1161,  115,  115,
-      627, 1158, 1161,  115,  625, 1161, 1161, 1161, 1161, 1161,
-
-     1161,  115,  115, 1161,  628,  630,  630,  630,  630,  630,
-      630,  630,  630,  630,  630,  630, 1161,  630,  630,  630,
-      630,  630,  631,  630,  632,  632,  632,  632,  632,  632,
-      632,  632,  632,  632,  630,  630,  630,  630,  630,  633,
-      633,  633,  633,  633,  633,  633,  633,  633,  633,  633,
-      633,  633,  633,  633,  633,  633,  633,  633,  633,  633,
-      633,  633,  633,  633,  633,  630,  630,  633,  633,  633,
-      633,  633,  633,  633,  633,  633,  633,  633,  633,  633,
-      633,  633,  633,  633,  633,  633,  633,  633,  633,  633,
-      633,  633,  633,  630,  115, 1161,  635,  638,  635,  115,
-
-     1161, 1161,  115,  115, 1000, 1001, 1000, 1161,  115, 1161,
-     1161,  634, 1002,  115, 1161, 1003,  115, 1161, 1161, 1161,
-     1161, 1161,  639,  115, 1161, 1161,  638,  636,  115,  115,
-      115,  115,  115, 1161,  115,  115, 1161,  115,  115,  634,
-     1161,  115, 1161,  115,  115, 1161,  641, 1161,  115,  115,
-      639, 1161, 1161, 1161, 1161, 1161, 1161,  115,  115,  115,
-      115, 1161, 1161,  115,  115,  115, 1161,  115,  115, 1161,
-     1161, 1161,  115,  115, 1161,  641,  115,  115, 1161,  115,
-      642, 1161, 1161, 1161, 1161,  115, 1161,  643, 1161,  115,
-      115, 1161, 1161, 1161,  115,  115, 1161,  115,  644,  115,
-
-     1161, 1161,  115, 1161,  115,  645, 1161,  115,  642,  115,
-     1161, 1161,  646, 1161, 1161,  643, 1161, 1161,  115,  115,
-     1161, 1000, 1001, 1000,  115, 1161, 1161,  644,  115, 1002,
-      115,  650, 1003,  115,  645,  115,  115,  115,  647,  115,
-      646,  648,  115, 1161,  115, 1161,  115,  115, 1161,  115,
-      115, 1161, 1161, 1161, 1161, 1161,  649, 1161,  115,  115,
-      650,  115, 1161, 1161,  115,  115, 1161,  647,  115,  115,
-      648,  115, 1161,  115,  115,  652,  115,  115,  115, 1161,
-      115, 1161, 1161,  651,  649, 1161,  115, 1161,  115,  115,
-     1161,  115, 1161, 1161,  115,  115,  115, 1161,  115, 1161,
-
-      115, 1161,  653,  115,  652, 1161,  654,  115, 1161,  115,
-      115,  651,  115, 1161,  115, 1161,  115, 1161,  115, 1161,
-      115, 1161,  115,  115,  115,  115,  115,  115, 1161,  115,
-      653, 1161,  115, 1161,  654,  655,  115,  115,  115,  115,
-     1161,  115,  115,  115,  115, 1161,  115,  115,  115, 1161,
-      115, 1161,  115, 1161,  115,  115,  115, 1161,  115, 1161,
-     1161,  115,  115, 1161,  655,  115,  115, 1161,  115,  659,
-      115,  115,  115,  115,  115,  115, 1161,  115, 1161,  115,
-      656, 1161,  657, 1161,  115,  115,  115,  115, 1161,  115,
-      115,  658,  115,  115, 1161,  115,  661,  659,  115,  115,
-
-      115,  115, 1161, 1161,  115, 1161,  115, 1161,  656, 1161,
-      657, 1161,  660,  115, 1161,  115,  115,  115,  115,  115,
-      658,  115,  115,  115,  115,  661, 1161,  115, 1161,  664,
-      115, 1071,  948, 1071,  115,  662, 1161,  115,  115,  949,
-      660,  115,  950,  115, 1161, 1161,  115,  115,  115,  663,
-      115, 1161,  115,  115, 1161,  115, 1161,  115, 1161, 1161,
-      115, 1161,  115,  662, 1161,  115,  115, 1161, 1161,  115,
-      115, 1161, 1161, 1161,  665,  115,  115, 1161,  663,  115,
-     1161, 1161,  115, 1161,  115, 1161,  115,  115,  115,  115,
-      115,  115, 1161,  666,  115,  115, 1161,  115, 1161, 1161,
-
-     1161,  115,  665,  668,  115, 1161,  667, 1161,  115,  115,
-     1161,  115, 1161, 1161, 1161, 1161,  115, 1161,  115,  115,
-      115,  666,  115,  115,  115,  115, 1161,  115,  115,  115,
-      669,  668, 1161,  115,  667, 1161,  115,  115,  670,  115,
-     1161,  115, 1161, 1161, 1161,  115, 1161,  115, 1161,  115,
-      115,  115, 1161,  115,  115, 1161,  115,  115,  115,  669,
-     1161,  115,  115, 1161,  115,  115,  115,  115, 1161,  115,
-      115, 1161,  115, 1161,  115,  115, 1161, 1161, 1161,  115,
-      115, 1161,  115, 1161,  115, 1161,  115,  115,  115, 1161,
-      115,  115,  115,  115,  115,  115, 1161, 1161, 1161,  115,
-
-      115, 1161,  671, 1161, 1161,  115, 1161,  115,  115,  115,
-     1161, 1161,  115,  672,  115,  115, 1161,  115,  115, 1161,
-      115,  115,  115,  115, 1161, 1161,  115, 1161,  115, 1161,
-      671, 1161, 1161,  115, 1161,  115, 1161,  115,  115, 1161,
-      115,  115,  672,  115,  115,  673,  115,  115,  674,  115,
-      115, 1161,  115, 1161, 1161,  115,  115, 1161, 1161, 1161,
-      115,  698, 1161,  115, 1161,  115,  115, 1161,  115, 1161,
-      115, 1161, 1161,  115,  673,  115, 1161,  674,  115,  677,
-      115,  684, 1161, 1161, 1161, 1093,  948, 1093,  115, 1161,
-      698,  115, 1161,  949, 1161,  115,  950,  685,  685,  685,
-
-      685,  685,  685,  685,  685,  685,  685,  686,  115, 1110,
-      948, 1110, 1161,  176, 1161, 1161, 1161,  949, 1161, 1161,
-      950, 1161, 1161,  685,  685,  685,  685,  685,  685,  685,
-      685,  685,  685,  686,  693, 1161,  693, 1161, 1161,  176,
-     1161, 1161, 1161, 1161,  694, 1161, 1161, 1161, 1161,  685,
-      685,  685,  685,  685,  685,  685,  685,  685,  685,  686,
-      697, 1161,  697, 1161, 1161,  176,  696,  115, 1161, 1161,
-      695,  115,  115,  110,  600,  690,  690,  690,  690,  690,
-      690,  690,  690,  690,  690,  115,  115, 1161, 1161, 1161,
-     1161, 1161, 1161,  115, 1161,  696,  115, 1161,  115,  695,
-
-      115,  115,  115,  600, 1161,  115, 1161,  115,  645,  732,
-      115, 1161,  115,  115,  115,  646, 1161, 1161,  700,  699,
-      700,  115,  115, 1161,  115, 1161, 1161,  115,  701, 1161,
-     1161,  115,  702, 1161,  115, 1161,  115,  645,  732,  115,
-      115,  211, 1161,  646, 1161, 1161, 1161,  699, 1161,  115,
-     1161,  115,  115,  709, 1161,  709,  115, 1161,  710,  710,
-      710,  710,  710,  710,  710,  710,  710,  710, 1161,  211,
-      115, 1126,  948, 1126, 1161, 1161, 1161, 1161, 1161,  949,
-      115, 1161,  950, 1161, 1161,  115,  566,  566,  566,  566,
-      566,  566,  566,  566,  566,  566,  211, 1161,  115, 1161,
-
-     1161,  947,  948,  947, 1161,  565, 1161, 1161,  711,  949,
-      711, 1161,  950,  712,  712,  712,  712,  712,  712,  712,
-      712,  712,  712,  589,  589,  589,  589,  589,  589,  589,
-      589,  589,  589, 1161,  565,  589,  589,  589,  589,  589,
-      589,  589,  589,  589,  589,  591,  591,  591,  591,  591,
-      591,  591,  591,  591,  591,  591,  591,  591,  591,  591,
-      591,  591,  591,  591,  591,  733, 1161, 1161,  115, 1161,
-      115, 1161, 1161,  115,  947,  948,  947, 1161, 1000, 1001,
-     1000, 1161,  949,  737,  115,  950, 1002,  115, 1161, 1003,
-     1161, 1161, 1161, 1161,  733, 1161, 1161,  115, 1161,  115,
-
-     1161, 1161,  115, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161,  737,  115,  718,  718,  115,  718,  718,  718,  718,
-      718,  718,  718,  718,  718,  718,  718,  718,  718,  718,
-      734,  718,  735,  735,  735,  735,  735,  735,  735,  735,
-      735,  735,  718,  718,  718,  718,  718,  736,  736,  736,
-      736,  736,  736,  736,  736,  736,  736,  736,  736,  736,
-      736,  736,  736,  736,  736,  736,  736,  736,  736,  736,
-      736,  736,  736,  718,  718,  736,  736,  736,  736,  736,
-      736,  736,  736,  736,  736,  736,  736,  736,  736,  736,
-      736,  736,  736,  736,  736,  736,  736,  736,  736,  736,
-
-      736,  718,  115,  115,  738,  115,  115,  115,  115,  115,
-      115,  115, 1161,  740,  115, 1161, 1161, 1161,  739,  741,
-     1161,  115,  115, 1161,  115,  115, 1161, 1161,  115, 1161,
-     1161,  115,  115,  738,  115,  115,  115,  115,  115,  115,
-      115, 1161,  740,  115, 1161, 1161,  739,  741, 1161,  115,
-      115, 1161,  115,  115,  115,  115,  115,  115, 1161,  115,
-      115,  115,  115, 1161, 1161,  745,  115, 1161, 1161,  742,
-     1161, 1161, 1161,  115,  115,  743,  115, 1161, 1161, 1161,
-      115, 1161, 1161,  115,  115, 1161,  115,  115,  115,  115,
-      115,  115,  115, 1161,  745,  115, 1161,  742,  746, 1161,
-
-     1161,  115,  115,  743,  115, 1161,  115, 1161,  115,  115,
-      115, 1161, 1161,  115,  750,  115,  115,  747,  115, 1161,
-      751,  115, 1161, 1161, 1161, 1161,  746, 1161,  115,  115,
-     1161, 1161,  115, 1161,  115,  115,  115, 1161,  115,  115,
-      115,  115,  115,  750,  115, 1161,  747,  115, 1161,  751,
-     1161, 1161, 1161, 1161,  115,  115,  115,  115,  115, 1161,
-      115, 1161, 1161,  115,  115,  115, 1161, 1161, 1161,  115,
-      115,  761, 1161, 1161,  115,  115, 1161,  115,  762,  115,
-      115, 1161,  115,  115, 1161, 1161, 1161,  115,  763, 1161,
-     1161,  115,  115,  115,  115, 1161,  115, 1161, 1161,  761,
-
-     1161, 1161,  764,  115,  115,  115, 1161,  762,  115,  115,
-      115, 1161,  115,  765,  115, 1161,  763,  115,  768,  115,
-      115,  115,  115,  115, 1161,  115, 1161, 1161, 1161,  766,
-      764,  115, 1161,  115, 1161,  115, 1161,  115,  115,  767,
-      115,  115,  765,  115, 1161, 1161,  115,  768,  115, 1161,
-     1161, 1161,  115,  769,  115,  769, 1161,  766, 1161,  115,
-     1161,  115, 1161,  258,  115,  115, 1161, 1161,  767,  115,
-      257,  257,  257,  257,  257,  257,  257,  257,  257,  257,
-      115, 1161,  115,  115,  770,  115,  115,  115,  115,  115,
-     1161,  115,  115, 1161,  115, 1161, 1161, 1161, 1161,  115,
-
-      771, 1161,  115, 1161, 1161,  115,  115, 1161,  115,  115,
-     1161, 1161,  115, 1161,  115,  115,  115,  115,  115,  115,
-      115,  115, 1161,  115,  115, 1161, 1161,  115,  771, 1161,
-      115, 1161, 1161,  115,  115,  115,  115, 1161,  772,  115,
-      115,  774,  115,  773,  115,  775,  115,  115,  115, 1161,
-     1161,  115, 1161,  115,  115, 1161, 1161, 1161,  115, 1161,
-     1161,  115,  115, 1161,  115,  115,  772,  115,  115,  115,
-      774,  115,  773,  115,  775,  115,  115, 1161, 1161,  776,
-      115,  115,  115,  115, 1161,  115,  115,  777,  115,  115,
-      115,  115,  115,  115,  780, 1161,  115,  115, 1161,  115,
-
-     1161, 1161,  115, 1161,  778,  779, 1161,  776, 1161,  115,
-     1161,  115,  115,  115,  115, 1161,  777,  115, 1161,  115,
-     1161,  115, 1161,  780, 1161, 1161,  115, 1161,  115,  115,
-      115,  781,  778,  779,  115,  115, 1161, 1161, 1161,  115,
-      115,  115, 1161, 1161, 1161, 1161,  782, 1161,  115, 1161,
-     1161, 1161, 1161, 1161,  115, 1161, 1161, 1161,  115, 1161,
-      781,  115, 1161,  115,  115,  115,  115,  783, 1161,  115,
-      115, 1161,  784,  115,  782, 1161,  115,  785,  115, 1161,
-      115, 1161,  115, 1161,  115, 1161, 1161, 1161, 1161, 1161,
-      115, 1161,  115, 1161,  115,  115,  783, 1161,  115,  115,
-
-      784, 1161,  115,  787, 1161,  115,  785,  115,  115,  115,
-      115, 1161,  115,  786,  115, 1161, 1161,  115, 1161, 1161,
-      115, 1161,  788, 1161,  115,  115, 1161,  115,  115,  789,
-      115, 1161,  787, 1161,  115, 1161,  115, 1161,  115,  115,
-     1161,  115,  786,  115,  115,  115, 1161, 1161,  115, 1161,
-      788, 1161,  115,  115,  115,  115,  115,  115,  789,  115,
-     1161,  790,  115, 1161, 1161,  115, 1161,  115,  115,  792,
-      115, 1161,  115,  115,  115, 1161,  115,  115, 1161, 1161,
-     1161, 1161,  115,  115, 1161, 1161,  115,  791,  115, 1161,
-      790,  115, 1161, 1161,  115,  115,  793,  115,  792,  115,
-
-      115,  115,  115,  115,  115,  115,  115, 1161, 1161, 1161,
-     1161, 1161, 1161,  115, 1161,  791,  115, 1161,  795,  115,
-      796, 1161, 1161,  115, 1161,  793,  115, 1161,  115,  115,
-      115,  115, 1161, 1161,  115,  115, 1161,  115, 1161,  797,
-      798,  115,  115, 1161, 1161,  115,  795,  115,  796,  115,
-     1161, 1161, 1161,  115,  115,  115,  115,  115,  115, 1161,
-      115, 1161,  115, 1161, 1161, 1161,  115,  797,  799,  798,
-     1161,  115,  801,  115,  115, 1161,  115,  800,  115,  115,
-      115, 1161,  115,  115,  115,  115,  115,  115, 1161, 1161,
-     1161,  115, 1161,  115, 1161, 1161,  799, 1161, 1161,  115,
-
-      801, 1161, 1161,  115,  115,  800, 1161, 1161,  115,  115,
-     1161, 1161,  176, 1161,  115, 1161, 1161, 1161,  176,  115,
-     1161,  115, 1161,  816,  115, 1161,  110,  115,  111,  111,
-      111,  111,  111,  111,  111,  111,  111,  111,  115,  115,
-      115,  115, 1161, 1161,  115,  115,  819,  817,  115, 1161,
-     1161,  818,  816,  115, 1161, 1161, 1161, 1161,  115,  115,
-      115, 1161, 1161, 1161, 1161, 1161,  115, 1161,  115,  115,
-      115, 1161,  211,  115,  115,  819,  817, 1161, 1161,  818,
-     1161, 1161,  211, 1161, 1161, 1161,  115,  115,  115,  710,
-      710,  710,  710,  710,  710,  710,  710,  710,  710,  710,
-
-      710,  710,  710,  710,  710,  710,  710,  710,  710,  211,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,  211,
-     1161, 1161, 1161, 1161, 1161, 1161,  712,  712,  712,  712,
-      712,  712,  712,  712,  712,  712,  712,  712,  712,  712,
-      712,  712,  712,  712,  712,  712,  823,  823,  211,  823,
-      823,  823,  823,  823,  823,  823,  823,  823,  823,  823,
-      823,  823,  823,  828,  823,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  823,  823,  823,  823,  823,
-      830,  830,  830,  830,  830,  830,  830,  830,  830,  830,
-      830,  830,  830,  830,  830,  830,  830,  830,  830,  830,
-
-      830,  830,  830,  830,  830,  830,  823,  823,  830,  830,
-      830,  830,  830,  830,  830,  830,  830,  830,  830,  830,
-      830,  830,  830,  830,  830,  830,  830,  830,  830,  830,
-      830,  830,  830,  830,  823,  832,   77,  832, 1161, 1161,
-      833,  833, 1161,  833, 1161, 1161, 1161,  833,  833, 1161,
-     1161,  833, 1161, 1161,  833,  833,  833,  833,  833,  833,
-      833,  833,  833,  831,  831, 1161,  831,  831,  831,  831,
-      831,  831,  831,  831,  831,  831,  831,  831,  831,  831,
-      841,  831,  842,  842,  842,  842,  842,  842,  842,  842,
-      842,  842,  831,  831,  831,  831,  831,  843,  843,  843,
-
-      843,  843,  843,  843,  843,  843,  843,  843,  843,  843,
-      843,  843,  843,  843,  843,  843,  843,  843,  843,  843,
-      843,  843,  843,  831,  831,  843,  843,  843,  843,  843,
-      843,  843,  843,  843,  843,  843,  843,  843,  843,  843,
-      843,  843,  843,  843,  843,  843,  843,  843,  843,  843,
-      843,  831,  115, 1161, 1161,  258, 1161,  115,  257,  257,
-      257,  257,  257,  257,  257,  257,  257,  257,  115,  845,
-     1161,  844,  115,  115,  115,  115, 1161,  115, 1161, 1161,
-      115,  115, 1161, 1161, 1161, 1161,  115,  115,  115, 1161,
-     1161,  115, 1161, 1161,  846,  115, 1161,  115,  845,  844,
-
-      115,  115,  115,  115,  115, 1161,  115,  115, 1161,  115,
-     1161, 1161,  115, 1161,  115,  115,  115, 1161,  115,  115,
-     1161, 1161,  846,  115,  115, 1161,  115, 1161, 1161,  115,
-      847, 1161, 1161, 1161, 1161, 1161,  115,  115,  848, 1161,
-     1161,  115,  115,  115, 1161,  849, 1161,  115,  115, 1161,
-      115,  115,  115, 1161,  115,  115,  115, 1161,  847,  850,
-     1161,  852,  115,  852, 1161,  115,  848, 1161, 1161,  115,
-      115, 1161,  115,  115,  849, 1161, 1161,  115,  115,  115,
-      115, 1161,  115, 1161,  115,  115,  855,  115,  850, 1161,
-      115, 1161,  115, 1161,  115, 1161,  853,  115,  115,  115,
-
-     1161,  115,  115, 1161, 1161, 1161, 1161,  115, 1161,  854,
-     1161,  115, 1161,  115,  115,  855,  115, 1161,  858,  115,
-      115, 1161, 1161,  115, 1161,  853,  115, 1161,  115,  115,
-     1161,  115, 1161,  115,  115, 1161,  866,  854, 1161,  115,
-     1161,  115, 1161,  115, 1161,  115,  867,  858,  115, 1161,
-     1161,  115, 1161,  115, 1161,  115,  115,  868, 1161, 1161,
-      115,  115, 1161,  115, 1161,  866, 1161, 1161,  115, 1161,
-      115,  115,  115,  115,  867,  869,  115,  115,  115, 1161,
-      115,  115,  871,  115, 1161,  115,  868, 1161, 1161,  870,
-      115,  115, 1161, 1161,  874, 1161, 1161,  115,  115,  115,
-
-      115,  115, 1161,  115,  869,  115,  115,  115,  115, 1161,
-      115,  871,  115,  115,  875,  115,  875,  870,  115,  115,
-      872,  873,  115,  874,  876,  115,  115, 1161,  115,  115,
-     1161,  115,  115, 1161, 1161, 1161, 1161,  115, 1161,  115,
-      877,  115, 1161, 1161,  115,  115,  115,  115,  872,  873,
-      115,  115,  115, 1161,  878,  115, 1161,  115,  115, 1161,
-      115, 1161,  879,  115, 1161,  115,  115,  115,  877,  115,
-     1161,  880,  115,  115,  115,  115,  115,  115, 1161, 1161,
-      115,  115, 1161,  878, 1161, 1161,  115,  115,  115, 1161,
-      115,  879,  115,  115,  115,  115,  115, 1161,  115,  115,
-
-      880,  115, 1161,  115,  115,  115, 1161,  881, 1161,  115,
-      115, 1161, 1161, 1161,  115,  115,  115,  882,  115,  115,
-     1161,  883,  115, 1161,  115, 1161, 1161,  115,  115,  115,
-     1161,  115, 1161,  115, 1161,  881,  115,  115, 1161,  115,
-     1161,  115,  115,  115,  115,  882,  115,  115,  115,  883,
-      115,  115, 1161,  884, 1161,  884,  115,  115, 1161, 1161,
-      115,  115,  115,  115, 1161,  115, 1161, 1161,  115,  115,
-     1161,  115,  115, 1161,  115, 1161,  115,  115,  115,  115,
-     1161,  886,  115,  888, 1161, 1161,  115, 1161,  115,  115,
-      115,  115,  115,  115,  115, 1161, 1161,  115,  887,  115,
-
-     1161,  885,  115,  115, 1161,  115, 1161, 1161,  115,  886,
-      115, 1161,  888,  889, 1161,  115, 1161,  115, 1161,  115,
-      115,  115, 1161,  115,  115, 1161,  887,  115,  115,  885,
-      115,  891,  115,  115, 1161, 1161,  890, 1161,  115,  115,
-     1161,  889, 1161, 1161,  115, 1161,  115, 1161,  115, 1161,
-     1161,  892, 1161,  115, 1161, 1161,  115, 1161,  115, 1161,
-      891,  115,  115, 1161,  890, 1161,  115,  115,  115, 1161,
-      115,  115, 1161,  115,  115,  115,  115, 1161,  895,  892,
-     1161,  115,  115, 1161, 1161, 1161,  115,  115, 1161,  115,
-      115,  115, 1161,  115, 1161,  896,  115,  896,  115,  115,
-
-      115,  115, 1161, 1161,  115,  115, 1161,  895, 1161,  115,
-     1161,  115,  115, 1161, 1161, 1161,  115,  115,  115,  115,
-      115, 1161,  115, 1161,  115,  115,  115,  115,  115,  115,
-      897,  906, 1161,  115, 1161, 1161, 1161, 1161,  898,  115,
-      115, 1161, 1161, 1161, 1161,  115, 1161,  115,  115,  115,
-     1161,  115, 1161,  115,  115,  115,  115,  115, 1161,  897,
-      906, 1161,  115, 1161,  907, 1161,  898,  115, 1161,  908,
-      115,  908, 1161,  115,  258,  115,  802,   77,  804,  175,
-      115, 1161, 1161, 1161, 1161,  115, 1161, 1161, 1161, 1161,
-      909,  115,  907, 1161, 1161,  115,  115, 1161,  115, 1161,
-
-     1161, 1161,  115, 1161, 1161, 1161, 1161,  115, 1161,  115,
-      115,  177,  178, 1161, 1161,  179, 1161,  180, 1161,  909,
-      115,  115, 1161, 1161,  115,  115, 1161, 1161,  341,  182,
-     1161,  115, 1161, 1161, 1161, 1161,  115,  115,  115, 1161,
-      177,  178, 1161, 1161,  179, 1161,  180, 1161, 1161,  115,
-     1161, 1161, 1161, 1161, 1161, 1161,  341,  182,  912,  912,
-      211,  912,  912,  912,  912,  912,  912,  912,  912,  912,
-      912,  912,  912,  912,  912,  914,  912,  915,  915,  915,
-      915,  915,  915,  915,  915,  915,  915,  912,  912,  912,
-      912,  912,  916,  916,  916,  916,  916,  916,  916,  916,
-
-      916,  916,  916,  916,  916,  916,  916,  916,  916,  916,
-      916,  916,  916,  916,  916,  916,  916,  916,  912,  912,
-      916,  916,  916,  916,  916,  916,  916,  916,  916,  916,
-      916,  916,  916,  916,  916,  916,  916,  916,  916,  916,
-      916,  916,  916,  916,  916,  916,  912,  211,  257,  257,
-      257,  257,  257,  257,  257,  257,  257,  257, 1161, 1161,
-     1161, 1161, 1161, 1161,  383,  383,  383,  383,  383,  383,
-      383,  383,  383,  383,  374,  374,  211,  374,  374,  374,
-      374,  374,  374,  374,  374,  374,  374,  374,  374,  374,
-      374,  384,  374,  385,  385,  385,  385,  385,  385,  385,
-
-      385,  385,  385,  374,  374,  374,  374,  374,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      386,  386,  386,  386,  374,  374,  386,  386,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      386,  386,  386,  386,  386,  386,  386,  386,  386,  386,
-      386,  386,  374,  115, 1161,  917, 1161,  115,  115,  918,
-      115,  115,  115,  919,  115, 1161,  115, 1161,  920,  115,
-     1161, 1161,  115, 1161,  115, 1161,  115, 1161, 1161, 1161,
-      115, 1161,  115,  115,  917, 1161,  115,  115,  918,  115,
-
-      115,  115,  919,  115,  922,  115, 1161,  920,  115,  115,
-      115,  115,  115, 1161,  115,  921,  115, 1161,  115, 1161,
-      115,  115, 1161,  115, 1161,  115, 1161,  115, 1161, 1161,
-      115,  115,  115,  922,  923, 1161,  115, 1161,  115,  115,
-      115,  927, 1161, 1161,  921,  115,  115, 1161,  928,  115,
-      115,  115,  115, 1161,  115, 1161,  115,  115,  115, 1161,
-      115,  115,  923,  115, 1161,  115, 1161,  115,  115,  927,
-     1161,  115,  115, 1161,  115, 1161,  928,  115,  115, 1161,
-      930,  115,  115,  115, 1161, 1161,  115, 1161,  115, 1161,
-     1161,  938,  115, 1161,  939, 1161, 1161,  115, 1161,  115,
-
-     1161,  115,  115, 1161,  115, 1161,  115, 1161,  930,  115,
-      115, 1161,  115,  115, 1161,  941, 1161,  115,  115,  938,
-     1161,  940,  939,  115, 1161, 1161, 1161, 1161, 1161,  115,
-      115, 1161,  115,  115,  115,  115, 1161, 1161,  115, 1161,
-      115, 1161,  115,  942,  941, 1161, 1161,  115,  115,  940,
-     1161,  115, 1161, 1161,  115, 1161, 1161, 1161,  115, 1161,
-      115,  115, 1161,  115,  115,  943,  115, 1161,  115,  115,
-      115,  942,  944,  115, 1161,  115,  115, 1161, 1161, 1161,
-      115,  945,  115, 1161, 1161, 1161, 1161,  115, 1161,  115,
-      115,  115, 1161,  115,  943,  115,  115,  115,  115,  115,
-
-     1161,  944,  115, 1161,  115, 1161,  951, 1161,  115,  945,
-      952, 1161,  115,  115,  115,  115,  115,  115,  115,  115,
-      115,  115,  115, 1161, 1161,  115, 1161,  115, 1161, 1161,
-     1161, 1161,  115,  115,  951,  115,  115, 1161,  952, 1161,
-      115,  115,  115,  115,  953,  115, 1161,  115,  115, 1161,
-      115, 1161,  115,  115, 1161,  115, 1161,  115,  115,  115,
-      115,  115, 1161,  115,  115,  115, 1161, 1161, 1161, 1161,
-      115,  115,  956,  953, 1161, 1161,  955, 1161,  115,  115,
-     1161,  115,  115,  115,  115, 1161,  115,  115,  115, 1161,
-      115,  115, 1161,  115, 1161,  115,  115, 1161,  115,  115,
-
-      956,  957,  115, 1161,  955, 1161,  115,  115,  115,  115,
-      115,  115, 1161,  115, 1161,  958,  115, 1161, 1161,  115,
-      115,  115,  115,  962,  115,  115,  115,  115,  115,  957,
-      115,  115, 1161, 1161,  115, 1161,  115,  115,  115,  115,
-      115,  115,  115,  969,  958,  115, 1161, 1161,  115,  115,
-     1161,  115,  962,  115, 1161,  960,  115,  115,  115,  115,
-     1161, 1161,  115,  115,  115, 1161,  115,  963,  115,  115,
-      115,  115,  969, 1161, 1161, 1161, 1161,  115,  115, 1161,
-     1161,  115, 1161,  960,  970,  115, 1161, 1161,  115,  115,
-      115,  971, 1161,  115,  115,  115,  963, 1161, 1161, 1161,
-
-      115, 1161, 1161, 1161, 1161, 1161,  115,  211,  115, 1161,
-     1161, 1161,  970,  115, 1161, 1161,  115,  975,  115, 1161,
-      971,  115, 1161,  115,  383,  383,  383,  383,  383,  383,
-      383,  383,  383,  383, 1161,  115,  115,  115, 1161,  115,
-     1161, 1161,  115,  976,  115,  115,  975, 1161,  115, 1161,
-      115, 1161, 1161,  115, 1161, 1161,  115, 1161,  115, 1161,
-     1161, 1161, 1161,  115, 1161,  977,  115,  115,  115,  115,
-      115,  115,  976,  115,  115,  115, 1161,  115,  115, 1161,
-     1161, 1161,  115,  115,  115, 1161,  115, 1161,  115,  978,
-     1161,  979, 1161,  977, 1161,  115, 1161,  115,  115,  115,
-
-     1161,  115, 1161,  115,  115,  115,  115,  115, 1161,  983,
-      115, 1161,  115,  982, 1161, 1161,  115,  978, 1161,  979,
-      115,  115, 1161, 1161,  115,  115,  115,  115,  994,  992,
-      115,  985,  115,  115,  115,  115, 1161, 1161,  983,  115,
-      115,  982, 1161, 1161, 1161, 1161,  115,  115,  115, 1161,
-      115, 1161,  115, 1161, 1161,  115,  115,  994,  992,  115,
-      985,  115,  115,  993,  115,  115,  115, 1161,  115, 1161,
-      115,  115, 1161, 1161,  115,  115, 1161, 1161,  115, 1161,
-     1161, 1161,  115, 1161,  995,  115,  996,  115,  115, 1161,
-     1161,  115,  993,  115,  115,  115,  115, 1161, 1161,  115,
-
-      115,  115,  115, 1161,  997, 1161,  115,  115, 1161, 1161,
-      115,  115,  995,  115,  996, 1161,  115, 1161,  115, 1161,
-      115,  115,  115,  115, 1161,  115, 1161,  115, 1161,  115,
-     1161,  115,  997, 1161, 1161, 1161,  115,  115,  115,  115,
-     1161,  115, 1161,  115,  115, 1004, 1161,  115,  115,  115,
-     1161,  115,  115, 1006, 1161, 1161,  115, 1161,  115,  115,
-     1161, 1161,  115, 1161,  115,  115,  115, 1161,  115,  115,
-      115,  115,  115,  115, 1004,  115, 1161,  115,  115, 1161,
-     1161, 1006, 1161, 1161, 1161,  115,  115, 1007,  115,  115,
-      115, 1161,  115,  115, 1161,  115, 1009,  115, 1161,  115,
-
-      115, 1161, 1161,  115,  115, 1161,  115, 1161,  115,  115,
-     1161,  115, 1161,  115,  115, 1007, 1012,  115, 1161, 1161,
-     1161,  115,  115, 1161, 1161, 1009,  115, 1011,  115,  115,
-     1161, 1161,  115, 1161,  115,  115, 1161,  115,  115,  115,
-      115,  115, 1161,  115, 1012, 1020,  115, 1161,  115, 1019,
-      115, 1161,  115, 1161,  115, 1011,  115,  115,  115, 1161,
-      115,  115, 1161,  115,  115, 1161,  115, 1161,  115,  115,
-      115,  115, 1025,  115, 1020,  115,  115, 1019, 1161, 1161,
-      115,  115,  115, 1161,  115, 1161,  115,  115,  115,  115,
-      115, 1161, 1161,  115, 1161,  115, 1161,  115,  115,  115,
-
-     1025,  115,  115,  115,  115, 1026,  115, 1161,  115,  115,
-     1161, 1161,  115,  115, 1161,  115, 1161, 1161,  115, 1029,
-      115, 1161,  115,  115,  115, 1161, 1030,  115, 1161,  115,
-      115,  115, 1161,  115, 1026,  115, 1161, 1161,  115, 1161,
-      115,  115, 1161,  115,  115,  115,  115, 1029,  115,  115,
-      115,  115, 1161,  115, 1161, 1030, 1038, 1161,  115, 1037,
-      115,  115, 1161,  115,  115, 1161,  115,  115, 1161, 1161,
-      115,  115,  115,  115,  115,  115, 1161, 1161,  115,  115,
-      115, 1161, 1161, 1161, 1038, 1161, 1039, 1037,  115, 1161,
-      115,  115,  115,  115, 1161,  115,  115,  115,  115, 1040,
-
-      115,  115,  115, 1161,  115,  115, 1044, 1161,  115,  115,
-     1161, 1161,  115, 1161, 1039, 1161,  115, 1161, 1161,  115,
-      115, 1161,  115,  115, 1161,  115,  115,  115, 1040,  115,
-     1161,  115, 1161,  115,  115, 1044, 1161,  115,  115,  115,
-      115, 1047,  115, 1161,  115, 1161, 1161,  115, 1161,  115,
-     1161,  115, 1161,  115,  115, 1161,  115, 1048,  115, 1161,
-      115, 1161, 1161, 1161,  115,  115,  115,  115, 1161,  115,
-     1047,  115,  115, 1161, 1161, 1054,  115, 1161, 1161,  115,
-     1059,  115,  115,  115,  115,  115, 1048,  115, 1161,  115,
-      115, 1161, 1161,  115,  115,  115, 1161,  115,  115, 1161,
-
-      115, 1161,  115, 1054,  115,  115, 1161,  115, 1062, 1059,
-      115,  115, 1161, 1161,  115, 1161,  115, 1161, 1161,  115,
-      115, 1161,  115,  115,  115,  115,  115,  115, 1063,  115,
-     1161,  115,  115, 1161, 1161, 1067, 1062, 1161, 1161,  115,
-     1161,  115, 1161,  115,  115, 1161, 1161,  115, 1161,  115,
-     1161,  115,  115,  115,  115, 1068,  115, 1063,  115,  115,
-     1161, 1161, 1161, 1067,  115, 1161,  115,  115,  115,  115,
-      115,  115, 1069,  115, 1073,  115,  115, 1161,  115, 1161,
-     1161,  115, 1161, 1161, 1068, 1161, 1161,  115,  115,  115,
-      115,  115, 1161,  115,  115,  115,  115,  115, 1161,  115,
-
-     1161, 1069,  115, 1073,  115, 1161,  115,  115, 1161,  115,
-     1080, 1161,  115, 1161, 1161,  115,  115,  115, 1161,  115,
-      115,  115, 1161,  115,  115,  115,  115, 1087,  115, 1161,
-     1161, 1161, 1161, 1161, 1088,  115,  115,  115, 1080,  115,
-     1161,  115,  115, 1161,  115,  115,  115, 1161,  115, 1161,
-      115,  115,  115,  115,  115, 1161, 1087,  115,  115, 1091,
-     1161, 1161, 1088,  115, 1161,  115, 1161,  115,  115,  115,
-      115,  115, 1095,  115,  115,  115,  115,  115, 1161, 1161,
-      115, 1161,  115, 1161, 1161, 1161,  115, 1091,  115, 1161,
-      115,  115, 1161,  115,  115,  115,  115, 1161,  115,  115,
-
-      115, 1095, 1106,  115, 1161,  115, 1161, 1161, 1161, 1161,
-      115, 1161, 1161,  115, 1105, 1161,  115,  115,  115, 1161,
-      115, 1108,  115,  115,  115,  115, 1161, 1161,  115,  115,
-     1161, 1106, 1161, 1161, 1161, 1161,  115, 1161,  115, 1161,
-      115,  115, 1105,  115, 1112,  115,  115,  115, 1161,  115,
-     1108,  115,  115,  115,  115, 1161, 1161, 1161,  115,  115,
-     1161, 1122, 1161, 1161,  115, 1161,  115, 1161,  115,  115,
-     1161,  115, 1112, 1161,  115, 1161,  115, 1161,  115, 1161,
-     1161,  115, 1161,  115, 1161, 1161, 1161,  115, 1161, 1122,
-     1161, 1161, 1161, 1161,  115, 1161,  115, 1124,  948, 1124,
-
-     1161, 1161, 1125, 1125, 1161, 1125, 1161, 1161, 1161, 1125,
-     1125, 1161, 1161, 1125, 1161, 1161, 1125, 1125, 1125, 1125,
-     1125, 1125, 1125, 1125, 1125,  115,  115, 1161, 1161, 1161,
-      115,  115, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1133,
-     1161, 1161, 1128, 1161,  115,  115, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161,  115,  115, 1161, 1161, 1161,  115,
-      115, 1161, 1161, 1161, 1161, 1161, 1161, 1133, 1161, 1161,
-     1128, 1161,  115,  115,  947,  948,  947, 1161, 1161, 1134,
-     1134, 1161, 1135, 1161,  115,  950, 1134, 1134, 1137,  115,
-     1134, 1161, 1161, 1134, 1134, 1134, 1134, 1134, 1134, 1134,
-
-     1134, 1134, 1161,  115,  115,  115, 1161, 1161, 1161,  115,
-      115, 1161, 1161,  115, 1161, 1161, 1161, 1137,  115, 1161,
-     1161, 1161, 1161,  115,  115, 1161, 1161, 1161, 1161, 1161,
-     1161,  115, 1161,  115,  115, 1161, 1161, 1161,  115,  115,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161,  115,  115,   64,   64,   64,   64,   64,   64,   64,
-       64,   64,   64,   64,   64,   65,   65,   65,   65,   65,
-       65,   65,   65,   65,   65,   65,   65,   81,   81, 1161,
-       81,   81,   81,   81,   81,   81,   81,   81,   81,   84,
-       84, 1161,   84,   84,   84,   84,   84,   84,   84,   84,
-
-       84,   88,   88,   88,   88,   88,   88,   88,   88,   88,
-       88,   88,   88,   92,   92,   92,   92,   92,   92,   92,
-       92,   92,   92,   92,   92,  111,  111,  115,  115,  115,
-      115,  115,  115,  115,  115,  187,  187,  187,  187,  187,
-      187,  187,  187,  187,  187,  187,  187,  202,  202,  202,
-      202,  202,  202,  202,  202,  202,  202,  202,  202,  209,
-      209,  209,  209,  209,  209, 1161,  209,  209,  209, 1161,
-      209,  232,  232,  232,  232,  232,  232,  232,  232,  232,
-      232,  232,  232,  101, 1161, 1161,  101,  252,  252,  252,
-     1161, 1161,  252, 1161,  252,  252, 1161,  252,  252,  343,
-
-      343,  343,  343,  343,  343,  343,  343,  343,  343,  343,
-      343,  358,  358, 1161,  358,  358,  358,  358,  358,  358,
-      358,  358,  358,  371,  371,  371,  371,  371,  371, 1161,
-      371,  371,  371, 1161,  371,  374,  374,  374,  374,  374,
-      374,  374,  374,  374,  374,  374,  374,  379,  379,  379,
-      379,  379,  379,  379,  379,  379,  379,  379,  379,  422,
-     1161, 1161,  422,  276, 1161, 1161, 1161,  276, 1161, 1161,
-     1161, 1161, 1161,  276,  558,  558,  558,  558,  558,  558,
-      558,  558,  558,  558,  558,  558,  718,  718, 1161,  718,
-      718,  718,  718,  718,  718,  718,  718,  718,  721,  721,
-
-     1161,  721,  721,  721,  721,  721,  721,  721,  721,  721,
-      723,  723, 1161,  723,  723,  723,  723,  723,  723,  723,
-      723,  723,   88,   88,   88,   88,   88,   88,   88,   88,
-       88,   88,   88,   88,  726,  726,  726,  726,  726,  726,
-      726,  726,  726,  726,  726,  726,   92,   92,   92,   92,
-       92,   92,   92,   92,   92,   92,   92,   92,  728,  728,
-      728,  728,  728,  728,  728,  728,  728,  728,  728,  728,
-      812,  812,  812,  812,  812,  812,  812,  812,  812,  812,
-      812,  812,  814,  814, 1161,  814,  814,  814,  814,  814,
-      814,  814,  814,  814,  823,  823,  823,  823,  823,  823,
-
-      823,  823,  823,  823,  823,  823,  825,  825,  825,  825,
-      825,  825,  825,  825,  825,  825,  825,  825,  831,  831,
-     1161,  831,  831,  831,  831,  831,  831,  831,  831,  831,
-      834,  834, 1161,  834,  834,  834,  834,  834,  834,  834,
-      834,  834,   81,   81, 1161,   81,   81,   81,   81,   81,
-       81,   81,   81,   81,  835,  835, 1161,  835,  835,  835,
-      835,  835,  835,  835,  835,  835,   84,   84, 1161,   84,
-       84,   84,   84,   84,   84,   84,   84,   84,  837,  837,
-      837,  837,  837,  837,  837,  837,  837,  837,  837,  837,
-       88,   88,   88,   88,   88,   88,   88,   88,   88,   88,
-
-       88,   88,  838,  838,  838,  838,  838,  838,  838,  838,
-      838,  838,  838,  838,   92,   92,   92,   92,   92,   92,
-       92,   92,   92,   92,   92,   92,  187,  187,  187,  187,
-      187,  187,  187,  187,  187,  187,  187,  187,  904,  904,
-      904,  904,  904,  904,  904,  904,  904,  904,  904,  904,
-      358,  358, 1161,  358,  358,  358,  358,  358,  358,  358,
-      358,  358,  814,  814, 1161,  814,  814,  814,  814,  814,
-      814,  814,  814,  814,  202,  202,  202,  202,  202,  202,
-      202,  202,  202,  202,  202,  202,  912,  912,  912,  912,
-      912,  912,  912,  912,  912,  912,  912,  912,  374,  374,
-
-      374,  374,  374,  374,  374,  374,  374,  374,  374,  374,
-      379,  379,  379,  379,  379,  379,  379,  379,  379,  379,
-      379,  379,  825,  825,  825,  825,  825,  825,  825,  825,
-      825,  825,  825,  825,  946,  946,  946,  946,  946,  946,
-      946,  946,  946,  946,  946,  946,  999,  999,  999,  999,
-      999,  999,  999,  999,  999,  999,  999,  999,   13, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161
+       50,   51,   52,   42,   53,   42,   42,   54,   14,   55,
+       56,   57,   58,  222,   69,   68,   69,   70,   72,   76,
+
+       77,   76, 1094,   74,   78,   77,   78,   59,   59,   59,
+       59,   59,   59,   59,   59,   59,   59,   75,  205,   80,
+     1092,   73,  222,  208,   60,   61,  205,  223,   62,   70,
+       63,   71,   74,   81,   83,   74,   87,   74,   74,   91,
+       82,   64,   65,  691, 1070,   75,   92,   93,   80,   75,
+       73,   75,   75,   60,   61,  223,  225,   62,   70,   63,
+       71,   81,   83,   96,   74,  111,   74,   74,   84,   64,
+       65,  209,   74,   88,   74,   74,   94,   75,  226,   75,
+       75,   97,   85,  255,   74,  225,   75,   89,   75,   75,
+       95,  227,  107,   83,  239,   74, 1070,   84,   75,  209,
+
+      624,   74,   88,   74,   74,   94,  226,   74,  625,   75,
+       85,   74,  255,   74,   75,   89,   75,   75,   95,   74,
+      227,   75,  239, 1065,   74,   75,   75,   78,   77,   78,
+       76,   77,   76,   75,  240,  247,   74,   75,  248,  228,
+       74,  179,  206,  205,  206,  112, 1030,  179,   74,   75,
+       98,   74,   98,   75,   78,   77,   78,  224,   77,  224,
+     1027,   75,  240,  247,  963,   75,  248,  228,   99,   99,
+       99,   99,   99,   99,   99,   99,   99,   99,   74,  207,
+       74,  114,  115,  100,  261,  116,  116,  101,   74,  102,
+      212,  117,   75,   75,  103,  142,  104,  105,  118,  119,
+
+      121,  922,   75,  263,   87,  190,  106,   74,  207,   87,
+      114,  115,  100,  261,  116,  116,  101,   74,  102,  117,
+       75,  253,  103,  142,  104,  105,  118,  119,  121,   87,
+       75,  120,  263,  116,  106,  108,  116,  109,  109,  109,
+      109,  109,  109,  109,  109,  109,  109,  121,   83,  253,
+      121,   91,  511,  230,  512,  110,  110,   74,   92,   93,
+      120,  229,  116,  254,  256,  116,  245,  212,  110,  260,
+      262,   75,  268,  116, 1131,  121,  246,  175,  121,  127,
+      116,  230,  146,  128,  110,  110,   74,  121, 1131,  129,
+      229,  254,  256,  130,  121,  245,  110,  260,  262,   75,
+
+      122,  268,  116, 1131,  246,  116,  116,  123,  127,  116,
+      146,  124,  128,  212,  125,  121, 1131,  129,   91,  121,
+      121,  130,  121,  190,  126,   92,   93,  179,  190,  122,
+       78,   77,   78,  179,  116,  116,  123,  143,   87,  124,
+      275,  147,  125,   87,  144,  145,  116,  121,  121,  148,
+       83,  121,  126,  116,  753,  149,  211,  212,  211,  131,
+      121,  132,  133,  754,  134,  135,  143,  121,  213,  275,
+      147,  136,  144,  145,  264,  116,  241,   82,  148,  121,
+      795,  212,  116,  149,  366,  367,  366,  131,  121,  132,
+      133,  242,  134,  135,  214,  121,  259,  162,  116,  136,
+
+      116,  190,  264,  137,  762,  241,  138,  139,  215,  140,
+      150,  753,  121,  260,  121,  141,  271,  255,  151,  242,
+      754,  113,  152,  214,  153,  259,  162,  116,  257,  116,
+      154,  698,  137,  243,  138,  139,  215,  140,  258,  150,
+      121,  260,  121,  141,  271,  116,  255,  151,  244,  113,
+      152,  158,  153,  155,  272,  156,  116,  257,  154,  121,
+      157,  116,  243,  273,  274,  159,  258,  276,  160,  172,
+      121,  161,  179,   87,  116,  121,  244,  534,  179,  277,
+      158,  155,  272,  156,  534,  116,  278,  121,  157,  282,
+      116,  273,  274,  159,   91,  276,  160,  172,  121,  161,
+
+      163,   92,   93,  121,  164,  116,  169,  277,  165,  643,
+      116,  116,  173,  170,  278,  635,  166,  282,  285,  167,
+      168,  286,  174,  171,  121,  121,  378,   77,  378,  163,
+      560,  559,  295,  164,  116,  169,  287,  165,  290,  116,
+      116,  173,  170,  237,  166,  196,  285,  167,  168,  286,
+      174,  171,  121,  121,  176,   77,  177,  178,  186,  187,
+      190,  295,  179,  557,  287,  191,  290,  511,  283,  512,
+      296,  237,  197,  556,  284,  188,  188,  188,  188,  188,
+      188,  188,  188,  188,  188,  297,  198,  298,  310,  180,
+      181,  116,   74,  182,  116,  183,  283,  192,  296,  172,
+
+      200,  197,  284,  142,  203,  121,  184,  185,  121,  212,
+      299,  193,  534,  297,  198,  190,  298,  310,  180,  181,
+      116,   74,  182,  116,  183,  300,  192,  172,  200,  510,
+      400,  142,  203,  121,  184,  185,  121,  143,  299,  193,
+      194,  232,  233,  232,  144,  201,  179,  396,  395,  234,
+      235,  121,  394,  300,  108,  393,  195,  195,  195,  195,
+      195,  195,  195,  195,  195,  195,  143,  238,  238,  288,
+       91,  288,  144,  201,  110,  110,   74,   92,   93,  121,
+      238,  301,  265,  266,  302,  303,  304,  110,  267,  307,
+       75,  313,  212,  651,  319,  652,  238,  238,  320,  212,
+
+      323,  269,  236,  110,  110,   74,  270,  330,  238,  301,
+      265,  266,  302,  303,  304,  110,  267,  307,   75,  199,
+      313,  289,  319,  127,  116,  205,  320,  128,  323,  190,
+      269,  236,  190,  129,  344,  270,  330,  130,  121,  308,
+      169,  190,  309,  279,  321,  116,  291,  170,  199,  289,
+      280,  322,  127,  116,  281,  331,  128,  171,  292,  121,
+      293,  129,  344,  294,  202,  130,  121,  308,   87,  169,
+      309,   87,  279,  321,  116,  291,  170,   83,  280,  322,
+      205,  651,  281,  652,  331,  171,  292,  121,  293,  921,
+     1131,  294,  202,  210,  211,  212,  211,  210,  210,  210,
+
+      216,  210,  210,  210,  210,  210,  210,  210,  210,  210,
+      210,  210,  217,  217,  217,  217,  217,  217,  217,  217,
+      217,  217,  210,  210,  210,  210,  210,  197,  217,  217,
+      217,  217,  218,  217,  123,  217,  217,  217,  219,  217,
+      217,  198,  217,  217,  217,  217,  220,  217,  217,  217,
+      217,  221,  217,  210,  210,  217,  197,  217,  217,  217,
+      217,  218,  217,  123,  217,  217,  219,  217,  217,  198,
+      217,  217,  217,  217,  220,  217,  217,  217,  217,  221,
+      217,  210,   98,  251,   98,  251,   68,  305,  252,  252,
+      252,  252,  252,  252,  252,  252,  252,  252,  311,  366,
+
+      367,  366,  306,  345,  312,  332,  667,  326,  667,  328,
+      333,  335, 1131,  329,  334,  100,  305,  347,  327,  101,
+      343,  102,  205,  669,  355,  669,  103,  311,  104,  105,
+      306,  345,  312,  314,  332,  315,  326,  328,  106,  333,
+      335,  329, 1131,  334,  100,  347,  327, 1131,  101,  343,
+      102,  316,  317,  355,  103,  318,  104,  105,  337,  358,
+      338, 1131,  314,  190,  315, 1131,  106,  250,  250,  250,
+      250,  250,  250,  250,  250,  250,  250,  324,  341,  316,
+      317,  223,  925,  318,  362,  110,  110,  358,  346,  190,
+      359,  325,  342,  190,  260,  351, 1131,  233,  110,  361,
+
+     1131,  205,  212, 1131,  385,  235,  324,  341, 1131,  223,
+      339,  186,  348,  362,  110,  110,  346,  205,  359,  325,
+      342,  352,  260, 1131,  351, 1131,  110,  361,  349,  349,
+      349,  349,  349,  349,  349,  349,  349,  349,  339,  350,
+      262,  770,  353,  771,  390,  179,  209,  356,  376,  363,
+      352,  369,  377, 1131, 1131,  349,  349,  349,  349,  349,
+      349,  349,  349,  349,  349,  350,  265,  357,  262,  212,
+      353,  179,  267,  390,  209,  356,  376, 1131,  363,  369,
+      377,  349,  349,  349,  349,  349,  349,  349,  349,  349,
+      349,  350,  205,  379,  265,  357,  212,  179, 1131,  391,
+
+      267,  368,  206,  205,  206,  108,  291,  354,  354,  354,
+      354,  354,  354,  354,  354,  354,  354,  380,  292,  399,
+      293,  379,   83,  360,   87,  110,  110,  364,  370,  371,
+      368,  375, 1131, 1131,  408,  291,  233,  392,  110,  207,
+       87, 1131,   83,  385,  235,  380,  292,  399,  293, 1131,
+      770,  360,  771, 1131,  110,  110,  364,  370,  371, 1131,
+      375,  397,  381,  408, 1131,  392,  110,  383,  207,  365,
+      365,  212,  365,  365,  365,  365,  365,  365,  365,  365,
+      365,  365,  365,  365,  365,  365,  365,  365,  371,  371,
+      381,  382,  384,  401,  398,  383,  404,  405,  365,  365,
+
+      365,  365,  365,  373,   91,  374,  232,  233,  232,  406,
+      407,   92,   93,  409,  234,  235, 1131,  371,  371,  382,
+      384,  401,  398, 1131,  404,  405,  232,  233,  232,  365,
+      365,  373, 1131,  374,  234,  235,   91,  406,  407, 1131,
+      388,  409,  388,   92,   93,  389,  389,  389,  389,  389,
+      389,  389,  389,  389,  389,  410,  387,  365,  365,  365,
+      212,  365,  365,  365,  365,  365,  365,  365,  365,  365,
+      365,  365,  365,  365,  365,  365,  365,  411,  412,  386,
+      547,   77,  547,  410,  387, 1131, 1131,  365,  365,  365,
+      365,  365,  372,  252,  252,  252,  252,  252,  252,  252,
+
+      252,  252,  252,  413,  414,  411,  412,  386,  252,  252,
+      252,  252,  252,  252,  252,  252,  252,  252,  365,  365,
+      402,  372,  402,  686,   77,  686, 1131, 1131,  417,  419,
+      403,  413,  414,  415,  420,  421,  416, 1131,  422,  423,
+      424,  425,  426, 1131, 1131,  418,  365,  250,  250,  250,
+      250,  250,  250,  250,  250,  250,  250,  417,  419,  439,
+      444,  415,  420,  421,  416,  238,  238,  422,  423,  424,
+      425,  426,  437,  418,  437,  445,  446,  440,  238,  440,
+     1131, 1131,  442,  443,  447,  448,  450,  448,  439,  444,
+      451, 1131,  453,  454,  238,  238,  455,  456,  288,  457,
+
+      288,  460, 1131,  438,  445,  446,  238,  427,  441,  427,
+      442,  443,  447,  458,  450,  470,  449, 1131,  469,  451,
+      453,  454, 1131,  471,  455,  456,  459,  457,  474, 1131,
+      460,  461,  472,  461,  472, 1131,  475,  465,  428,  465,
+      476,  462,  458,  429,  470,  430,  469,  466,  431, 1131,
+      452,  471,  432,  478,  459,  433,  477,  474,  434,  435,
+      479, 1131,  436,  473,  475,  480,  481,  484,  476,  485,
+      488,  482,  429,  489,  430,  463,  490,  431,  452,  483,
+      432,  467,  478,  433,  477,  464,  434,  435,  491,  479,
+      436,  468,  486,  480,  481,  492,  484,  485,  488,  482,
+
+      487,  489,  493,  463,  490,  494,  495,  483,  496,  467,
+      497,  498,  499,  464,  502,  503,  500,  491,  500,  468,
+      504,  486,  505,  506,  492,  507,  501,  508,  487,  509,
+      346,  493,  513,  494,  514,  495,  496,  515,  497,  498,
+      499,  516,  517,  502,  503,  518,  519,  190,  504, 1131,
+      505,  506, 1131,  507,  190,  508,  205,  509,  346,  511,
+      513,  520,  514,  190, 1131,  515,  527,  528,  530,  516,
+      517,  417,  531,  518,  545,  519,  212,  521,  521,  521,
+      521,  521,  521,  521,  521,  521,  521,  522,  529,  212,
+      524,  533,  523,  179,  535,  527,  528,  530,  371, 1131,
+
+      417,  531,  545,  521,  521,  521,  521,  521,  521,  521,
+      521,  521,  521,  522,  212,  525,  529,  212,  524,  179,
+      533,  523,  546,  535,  548,   87, 1131,  371,  539,  521,
+      521,  521,  521,  521,  521,  521,  521,  521,  521,  190,
+     1131,  532,  371,  525,  522,  536,  205,  536,   83,  927,
+      179,  546,  548,  541,  459,  540,  539,  538,  108,  371,
+      526,  526,  526,  526,  526,  526,  526,  526,  526,  526,
+      532,  371,  371,  549,   87,  552,   83,  542,  110,  110,
+     1131,  541,  459,  371,  540,  538,  537,  562,  371,  233,
+      558,  110,  543,  561,  544,  550,  385,  235,  667, 1029,
+
+      667,  371,  549,  552, 1131,  542,   91,  110,  110,  551,
+      553, 1131,  371,   92,   93,  537,  562,   91,  558,  110,
+      543,  561,  544,  550,   92,   93,  389,  389,  389,  389,
+      389,  389,  389,  389,  389,  389,  563,  564,  551,  553,
+      389,  389,  389,  389,  389,  389,  389,  389,  389,  389,
+      402,  565,  402,  555,  566, 1131,  554,  567, 1131,  568,
+      403,  569,  570,  571,  572,  563,  564,  573,  574,  575,
+      576,  577,  578,  589,  578,  590,  591, 1131,  592,  565,
+      593,  596,  555,  566,  554,  597,  567,  568,  594,  569,
+      570,  598,  571,  572,  599,  573,  574,  575,  576,  577,
+
+      437,  589,  437,  590,  595,  591,  592,  602,  593,  596,
+      440,  605,  440,  579,  597,  606,  603,  594,  603,  598,
+      607,  448,  599,  448,  212,  608,  609,  580,  610, 1131,
+      613,  438,  595,  611,  612,  602,  614,  616,  617,  605,
+      619,  441,  579,  615,  606,  618,  621,  604,  620,  607,
+     1131,  622,  449,  608,  609,  580,  427,  610,  427,  613,
+      623,  611,  612, 1131,  629,  614,  616,  617,  461,  619,
+      461,  615,  465,  618,  465,  621,  620,  627,  462,  622,
+      632,  472,  466,  472, 1033,  628,  630,  428,  623,  631,
+      633,  624,  581,  629,  582,  634,  640,  583,  645,  625,
+
+      636,  584, 1131,  637,  585,  627,  638,  586,  587,  632,
+      639,  588,  473,  628,  630, 1131, 1131,  631,  633, 1131,
+      646,  581,  646,  582,  634,  640,  583,  645,  636,  584,
+      626,  637,  585,  644,  638,  586,  587, 1131,  639,  588,
+      600,  600,  600,  600,  600,  600,  600,  600,  600,  600,
+      600,  647,  600,  600,  600,  600,  600,  600,  600,  626,
+      648,  644,  649,  650,  641,  500,  641,  500,  653,  600,
+      600,  600,  600,  600,  642,  501,  654,  655,  656,  657,
+      658,  190,  190,  669,  205,  669,  190, 1131,  667,  648,
+      667,  649,  650,  651,  668,  659,  666,  653,  701,  205,
+
+      600,  600,  571,  212,  654,  670,  655,  656,  657,  658,
+      205,  660,  660,  660,  660,  660,  660,  660,  660,  660,
+      660,  661,  664,  668,  666,  684,  701,  179,  600,  703,
+      662,  571,  663,  675,  670, 1131, 1131,  660,  660,  660,
+      660,  660,  660,  660,  660,  660,  660,  661, 1131,  212,
+      212,  664,  679,  179,  684,  676,  705,  703,  662, 1050,
+      663,  675, 1131,  660,  660,  660,  660,  660,  660,  660,
+      660,  660,  660,  661,  614,  536,  205,  536, 1131,  179,
+      679,  615,  687,  676,  705,  671,  678,  108,  371,  665,
+      665,  665,  665,  665,  665,  665,  665,  665,  665,  677,
+
+      672, 1131,  672,  614,   87,   83,  680,  110,  110,  615,
+      673,  687,  699,  671,  674,  678,  537,  371,  371, 1131,
+      110,  371,  681,   91,  371,  682,  700,  677,  683,  704,
+       92,   93,  706,  712,  680,   91,  110,  110,  689,  713,
+      692,  699,  696,  697,  707,  537,  708,  371,  110,  709,
+      371,  681,  710,  371,  682,  700,  711,  683,  704,  694,
+     1131,  706,  712,  718,  770,  186,  775,  689,  713,  692,
+     1131,  578,  707,  578,  708, 1131,  641,  709,  641,  716,
+      710,  717, 1131,  719,  711,  720,  642,  721,  694,  685,
+      685,  718,  685,  685,  685,  685,  685,  685,  685,  685,
+
+      685,  685,  685,  685,  685,  685,  685,  685,  716,  722,
+      717,  719,  714,  723,  720,  721,  725,  726,  685,  685,
+      685,  685,  685,  727,  728, 1131,  715,  729,  730,  724,
+      731, 1131,  732,  733,  734,  739,  735,  722,  735, 1131,
+      737,  714,  723,  603,  725,  603,  726,  738,  742,  685,
+      685,  727,  740,  728,  715,  729,  730,  724,  741,  731,
+      732,  743,  733,  734,  739,  744,  745,  736,  737,  746,
+      747, 1131,  748,  749,  604,  738,  742,  685,  750,  751,
+      752,  740,  755, 1131,  756,  757,  758,  741,  759,  760,
+      743,  761,  766,  744,  745,  763,  764,  765,  746,  747,
+
+      748,  767,  749,  768,  769,  646,  750,  646,  751,  752,
+      772,  755,  756,  773,  757,  758,  759,  774,  760,  190,
+      761,  766,  190,  763,  764,  765,  779,  780,  669,  767,
+      669,  768,  769,  672,  781,  672,  647,  782,  672,  772,
+      672,  205,  773,  673,  371,  774,  205,  674,  673,  674,
+      371,  674,  674,  212,  212,  779,  780,  801,  777,  776,
+       91, 1131,  781,  674,   91,  371,  782,  798,  799,  788,
+       91,   92,   93,  371,  802,  803, 1131,   92,   93,  371,
+      770,  833,  771,  833,  190,  801,  783,  777,  776,  179,
+      785,  834,  784,  787,  371,  179, 1131,  804,  788,  805,
+
+      806,  807,  802,  108,  803,  109,  109,  109,  109,  109,
+      109,  109,  109,  109,  109,  783,  808, 1131,  809,  785,
+      784,  810,  787,  110,  110,  804,  814,  805,  806,  807,
+      815,  816, 1131,  817,  818, 1131,  110,  851, 1131,  851,
+      770,  864,  770,  864, 1093,  808,  809,  852, 1131,  864,
+      810,  864,  110,  110,  811,  814,  811,  819,  820,  815,
+      816,  817,  821,  818,  110,  786,  786,  212,  786,  786,
+      786,  786,  786,  786,  786,  786,  786,  786,  786,  786,
+      786,  786,  786,  786,  822,  819,  820,  823,  824,  812,
+      826,  821,  825,  827,  786,  786,  786,  786,  786,  828,
+
+      829, 1131,  813,  830,  831,  735,  832,  735,  205,  835,
+      836,  837,  822,  838, 1131,  839,  823,  824,  812,  826,
+      825,  840,  827,  841,  844,  786,  786,  828,  846,  829,
+      813,  830,  831, 1131, 1131,  832,  736,  835, 1131,  836,
+      837,  845,  838,  839,  847,  770,  186,  775,  833,  840,
+      833,  841,  844,  786,  791,   77,  791,  846,  834,  792,
+      792,  842,  792,  842, 1131, 1131,  792,  792, 1095,  845,
+      792, 1131,  847,  792,  792,  792,  792,  792,  792,  792,
+      792,  792,  790,  790,  190,  790,  790,  790,  790,  790,
+      790,  790,  790,  790,  790,  790,  790,  790,  790,  790,
+
+      790,  848,  849,  205,  850,  853, 1131,  856,  858,  843,
+      857,  790,  790,  790,  790,  790,  854,  859,  854,  862,
+      865,  860,  205,  212,  863,  371,  791,   77,  791,  848,
+      873,  849,  850,  879,  853,  856,  858,  843,  874,  857,
+      866, 1131,  790,  790,  875,  876,  859,  877,  862,  865,
+      860,  855,  863,  878,  371,   91,  882,   91,  867,  873,
+      869,  879,   92,   93,   92,   93,  864,  874,  864,  866,
+      790, 1131, 1131,  875,  876, 1131,  877,  811, 1131,  811,
+      855,  871,  878,  883,  882,  872,  884,  867,  885,  869,
+      868,  868,  212,  868,  868,  868,  868,  868,  868,  868,
+
+      868,  868,  868,  868,  868,  868,  868,  868,  868,  886,
+      871,  883,  880,  888,  872,  884,  885,  887,  889,  868,
+      868,  868,  868,  868,  890,  881,  891, 1131,  892,  893,
+      894,  895,  896, 1131,  897,  898,  899,  908,  886,  900,
+      212,  880,  888,  906,  907,  887,  842,  889,  842,  910,
+      868,  868,  890,  881,  911,  891,  892,  893,  894,  895,
+      912,  896,  897,  913,  898,  899,  908,  900,  902,  903,
+      902,  906,  907,  851,  914,  851,  904,  910,  868,  905,
+      915,  917,  911,  852,  854,  918,  854,  919,  912,  920,
+      205,  924,  913,  923,  909,  371,  928, 1131,  929,  930,
+
+     1096,  931,  932,  914,  933,  934,  935,  936,  915,  937,
+      917,  938, 1131,  939,  918,  919,  940,  944,  920,  916,
+      924,  923,  909,  941,  371,  928,  929,  942,  930,  931,
+      932,  943,  933,  934,  935,  936,  945,  937,  950,  926,
+      938,  939,  946,  947,  948,  940,  944,  949,  916,  951,
+      952,  941,  902,  903,  902,  942,  953,  903,  953,  943,
+      904,  960, 1131,  905,  945,  961,  950,  926, 1131,  959,
+      964,  946,  947,  948,  962,  965,  949,  951,  952,  902,
+      903,  902,  966,  955,  956,  955,  967,  904,  968,  960,
+      905,  957,  969,  961,  958,  902,  903,  902,  959,  964,
+
+      190,  971,  962,  904,  965,  972,  905,  205,  205,  212,
+      966,  976,  977,  978,  967, 1131,  968,  979, 1131,  980,
+      981,  969,  982,  983,  984,  987,  985,  988,  985,  989,
+      971,  990,  991,  992,  972,  970,  986,  993,  994,  976,
+      977,  978,  995,  973,  975,  974,  979,  980, 1131,  981,
+      982, 1131,  983,  984,  987,  999,  988,  998,  989,  990,
+      991,  992, 1131, 1131,  970,  993,  994,  996,  903,  996,
+     1001,  995,  973,  975,  974,  955,  956,  955,  190,  955,
+      956,  955, 1000,  957,  999,  998,  958,  957, 1002,  205,
+      958,  997,  956,  997, 1003,  955,  956,  955, 1001,  904,
+
+     1004,  212,  905,  957, 1006,  205,  958,  955,  956,  955,
+     1010, 1000, 1011, 1013, 1011,  957, 1014, 1002,  958, 1131,
+     1015, 1016, 1012, 1003, 1005,  985,  985,  985,  985, 1004,
+     1017, 1018, 1006, 1019, 1007,  986,  986, 1008, 1021, 1010,
+     1020, 1013, 1022,  205,  205, 1014, 1131, 1009, 1015, 1025,
+     1016, 1131, 1005, 1023,  903, 1023, 1026, 1028, 1017, 1018,
+     1036, 1019, 1007, 1039, 1037, 1038, 1008, 1021, 1020, 1040,
+     1041, 1022, 1024,  903, 1024, 1009, 1042, 1032, 1025, 1031,
+      904,  205, 1011,  905, 1011, 1026, 1028, 1034, 1036, 1034,
+     1045, 1039, 1012, 1037, 1038, 1046,  190, 1040, 1047, 1041,
+
+     1035, 1049, 1035,  212, 1042, 1056, 1032, 1055, 1031, 1043,
+      903, 1043, 1044,  903, 1044, 1131, 1057, 1051, 1035, 1045,
+      904, 1058, 1060,  905, 1046, 1034, 1047, 1034, 1063, 1049,
+     1059,  190, 1053, 1056, 1053,  212, 1055, 1064, 1035,  205,
+     1035, 1048, 1073, 1054, 1057, 1035, 1051, 1035, 1052, 1075,
+     1058, 1060, 1061,  903, 1061, 1067, 1035, 1063, 1059, 1062,
+      903, 1062, 1053, 1035, 1053, 1064, 1072,  904, 1074, 1048,
+      905, 1073, 1079, 1054, 1068,  205, 1052, 1066, 1075, 1080,
+     1081, 1071, 1131, 1067, 1078,  903, 1078,  190,  212, 1083,
+     1131, 1086,  904, 1131, 1072,  905, 1074, 1087, 1131, 1090,
+
+     1079,  190,  205, 1068,  190, 1066, 1131, 1080, 1081, 1071,
+     1076,  903, 1076,  205, 1131, 1077, 1077, 1083, 1077, 1086,
+     1097, 1084, 1077, 1077, 1091, 1087, 1077, 1090, 1098, 1077,
+     1077, 1077, 1077, 1077, 1077, 1077, 1077, 1077, 1082, 1085,
+     1076,  903, 1076,  902,  903,  902, 1131, 1100, 1097, 1084,
+     1103,  904,  212, 1091,  905, 1099, 1108, 1098, 1101,  205,
+      212,  205, 1113, 1131,  190, 1131, 1082, 1085,  902,  903,
+      902, 1104,  205, 1088, 1088, 1100, 1089,  190, 1103,  905,
+     1088, 1088,  212, 1099, 1088, 1108, 1101, 1088, 1088, 1088,
+     1088, 1088, 1088, 1088, 1088, 1088,  902,  903,  902, 1104,
+
+      955,  956,  955, 1102,  904, 1105,  190,  905,  957, 1106,
+     1112,  958, 1109, 1107,  212, 1115, 1116,  212, 1110, 1119,
+     1120, 1119,  205, 1117, 1121, 1122, 1121, 1124, 1125, 1124,
+      205, 1102,  205, 1105, 1119, 1120, 1119, 1106, 1111, 1112,
+     1109,  205, 1107, 1115, 1116, 1131, 1114, 1110, 1121, 1122,
+     1121, 1117, 1124, 1125, 1124, 1129, 1130, 1129, 1129, 1130,
+     1129, 1131, 1131, 1131, 1127, 1131, 1126, 1111, 1118, 1131,
+     1131, 1123, 1131, 1131, 1131, 1114, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1128, 1127, 1131, 1126, 1118, 1131, 1131, 1123,
+
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1128,   66,   66,   66,   66,   66,   66,   66,   66,   66,
+       66,   66,   66,   66,   67,   67,   67,   67,   67,   67,
+       67,   67,   67,   67,   67,   67,   67,   79, 1131,   79,
+       79,   79,   79,   79,   79,   79,   79,   79,   79,   79,
+       82,   82,   82,   82,   82,   82,   82,   82,   82,   82,
+       82,   82,   82,   86,   86,   86,   86,   86,   86,   86,
+       86,   86,   86,   86,   86,   86,   90,   90,   90,   90,
+       90,   90,   90,   90,   90,   90,   90,   90,   90,  113,
+
+      113,  113,  113,  113,  113,  113,  113,  113,  189,  189,
+      189,  189,  189,  189,  189,  189,  189,  189,  189,  189,
+      189,  204,  204,  204,  204,  204,  204,  204,  204,  204,
+      204,  204,  204,  204,  210,  210,  210,  210,  210, 1131,
+      210,  210,  210, 1131,  210, 1131,  210,  231,  231,  231,
+      231,  231,  231,  231,  231,  231,  231,  231,  231,  231,
+       99, 1131, 1131, 1131, 1131, 1131, 1131, 1131,   99,  249,
+      249, 1131,  249,  249, 1131,  249, 1131, 1131,  249,  249,
+     1131,  249,  336,  336,  336,  336,  340,  340,  340,  340,
+      340,  340,  340,  340,  340,  340,  340,  340,  340,  365,
+
+      365,  365,  365,  365,  365,  365,  365,  365,  365,  365,
+      365,  365,  371,  371,  371,  371,  371,  371,  371,  371,
+      371,  371,  371,  371,  371,  601,  601,  601, 1131,  601,
+      601,  601,  601,  601,  601,  601,  601,  601,  685, 1131,
+      685,  685,  685,  685,  685,  685,  685,  685,  685,  685,
+      685,  688, 1131,  688,  688,  688,  688,  688,  688,  688,
+      688,  688,  688,  688,  690,  690,  690,  690,  690,  690,
+      690,  690,  690,  690,  690,  690,  690,  693,  693,  693,
+      693,  693,  693,  693,  693,  693,  693,  693,  693,  693,
+      695,  695,  695,  695,  695,  695,  695,  695,  695,  695,
+
+      695,  695,  695,  702, 1131,  702,  702,  702,  702,  702,
+      702,  702,  702,  702,  702,  702,  778,  778,  778,  778,
+      778,  778,  778,  778,  778,  778,  778,  778,  778,  786,
+      786,  786,  786,  786,  786,  786,  786,  786,  786,  786,
+      786,  786,  789,  789,  789,  789,  789,  789,  789,  789,
+      789,  789,  789,  789,  789,  790, 1131,  790,  790,  790,
+      790,  790,  790,  790,  790,  790,  790,  790,  793, 1131,
+      793,  793,  793,  793,  793,  793,  793,  793,  793,  793,
+      793,  794,  794,  794,  794,  794,  794,  794,  794,  794,
+      794,  794,  794,  794,  796,  796,  796,  796,  796,  796,
+
+      796,  796,  796,  796,  796,  796,  796,  797,  797,  797,
+      797,  797,  797,  797,  797,  797,  797,  797,  797,  797,
+      800, 1131,  800,  800,  800,  800,  800,  800,  800,  800,
+      800,  800,  800,  861,  861,  861,  861,  861,  861,  861,
+      861,  861,  861,  861,  861,  861,  868,  868,  868,  868,
+      868,  868,  868,  868,  868,  868,  868,  868,  868,  870,
+      870,  870,  870,  870,  870,  870,  870,  870,  870,  870,
+      870,  870,  901,  901,  901,  901,  901,  901,  901,  901,
+      901,  901,  901,  901,  901,  954,  954,  954,  954,  954,
+      954,  954,  954,  954,  954,  954,  954,  954, 1069, 1069,
+
+     1069, 1069, 1069, 1069, 1069, 1069, 1069, 1069, 1069, 1069,
+     1069,   13, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+
+     1131
     } ;
 
-static yyconst flex_int16_t yy_chk[9249] =
+static yyconst flex_int16_t yy_chk[4102] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -8737,77 +7708,94 @@
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    2,
-        2,    2,    2,   10,    8,    8,    8,    8,   15,   15,
-
-       15,   68, 1129,   14,   10, 1119,   68,    2,    2,    2,
-        2,    2,    2,    2,    2,    2,    2,   14,   16,   16,
-       16,   54,   54,   54,    2,    2,   18,   10,    2,   19,
-        2,    8,   14,   17,   17,   17,   15,   20,   21, 1096,
-       18,    2,    2,  176,   22,   14, 1084,   25,   26,  176,
-       15,   20,   21,    2,    2,   18,   10,    2,   75,    2,
-        8,   25,   42,   19,   69,   15,   20,   21,   18,    2,
-        2,   17,   24,   27,   26,   23,   25,   19,   15,   20,
-       21,   22,   23,   23,   29,   17,   75,   27,   26,   25,
-     1045,   42,   19,   24,  959,   22,   30,  339,   74,  339,
-
-       17,   82,   27,   26,  340,   19,  340,   24,   83,   69,
-       22,   29,   23,   17,   31,   27,   26,   32,   30,   34,
-       41,  178,   24,   22,  916,   29,   23,   74,   31,  912,
-       82,   32,   30,   34,   41,   24,   83,   69,   49,  685,
-       29,   23,   49,   31,  905,  685,   32,   30,   34,   41,
-      178,  207,   33,   29,   23,   28,   31,   28,   33,   32,
-       30,   34,   41,   76,   76,   76,  242,   49,   67,   67,
-       67,   49,   33,   28,   28,   28,   28,   28,   28,   28,
-       28,   28,   28,   86,   43,   63,  207,   33,   28,   43,
-       44,  350,   28,   28,   28,  242,   43,   43,  904,   28,
-
-       33,   28,   28,   63,   44,   67,   91,   28,   77,   77,
-       77,   28,   86,   43,   63,  207,  837,   28,   43,   44,
-      350,   28,   28,   28,   43,   43,   87,   28,  360,   28,
-       28,   63,   44,  835,   67,   28,   78,   78,   78,   28,
-       35,   86,   35,   35,   35,   35,   35,   35,   35,   35,
-       35,   35,   38,   40,  830,   91,   38,  360,   35,   35,
-       38,   40,   35,  903,   40,  102,   38,   40,   35,  103,
-       38,  107,   87,   40,   90,   35,   35,   79,   79,   79,
-      825,   38,   40,   91,  342,   38,  342,   35,   35,   38,
-       40,   35,   40,  102,   38,   40,   35,  103,   38,  107,
-
-       87,   40,  108,   35,   35,   36,   90,   36,   36,   36,
-       36,   36,   36,   36,   36,   36,   36,  179,   37,  359,
-       39,  359,   36,  903,  823,   37,   45,   36,  822,   37,
-      108,   39,   37,   39,   45,   90,   39,   39,   46,  205,
-       45,   36,   37,   39,  812,  179,   46,   37,  393,   39,
-      180,   36,   46,  182,   37,   45,   36,   37,   46,   39,
-       37,   39,   48,   45,   39,   39,   51,   46,   45,   36,
-       37,   39,   47,   51,  811,   46,   48,  393,  180,   48,
-       46,  182,   48,   51,  205,   47,   46,   47,  104,   50,
-      220,   48,   47,   50,  529,   51,  529,   50,  396,   52,
-
-      450,   47,   51,  104,   48,   50,   52,   48,   50,   50,
-       48,   51,  205,   47,  532,   47,   52,  104,   50,  804,
-       47,  220,   50,   80,   80,   80,   50,  396,   52,  450,
-      530,  104,  530,   50,   92,   52,   50,   50,   55,   55,
-       55,   92,   92,  532,   52,   53,   53,   53,   53,  220,
-       56,  223,  531,   53,  531,   56,   55,   55,   55,   55,
-       55,   55,   55,   55,   55,   55,  184,  184,  184,   94,
-       70,   70,   70,   71,   71,   71,   94,   94,   60,  223,
-       53,   53,   70,   53,   53,   71,   53,   56,  726,   60,
-      106,  191,   60,  686,   93,   93,   93,   53,   53,  686,
-
-      106,   56,   93,   93,  181,   70,  725,   60,   71,   53,
-       53,  181,   53,   53,  723,   53,   56,   60,  722,  106,
-       60,   72,   72,   72,  910,   53,   53,  214,  106,   56,
-       57,   58,  181,   72,   70,   96,   57,   71,  222,  181,
-      191,  716,   96,   96,   57,  189,   57,   57,   57,   57,
-       57,   57,   57,   57,   57,   57,   59,  222,   58,   72,
-       59,  208,  208,  208,   59,   58,   57,   96,  191,   58,
-       59,  190,   58,   72,   59,  714,  214,  189,   61,  206,
-       57,  706,   58,   61,  910,   59,  222,   58,   72,   59,
-       61,   61,   62,   59,   58,   57,   96,   58,   59,   62,
-
-       58,   72,   59,  190,  214,  224,  189,   61,   57,   62,
-       58,  206,   61,  210,  210,  210,   62,  689,   61,   61,
-      664,   62,  225,  225,  225,  585,  580,  232,   62,  578,
-      558,  235,  190,  224,  232,  232,  554,   62,  235,  235,
-      206,  372,  372,  372,   62,   73,   73,   73,   73,   73,
+        2,    2,    2,   74,    8,    8,    8,    8,   10,   15,
+
+       15,   15, 1083,   14,   16,   16,   16,    2,    2,    2,
+        2,    2,    2,    2,    2,    2,    2,   14,   70,   17,
+     1081,   10,   74,   70,    2,    2,   71,   75,    2,    8,
+        2,    8,   14,   17,   18,   19,   21,   15,   20,   22,
+      551,    2,    2,  551, 1069,   14,   22,   22,   17,   19,
+       10,   15,   20,    2,    2,   75,   80,    2,    8,    2,
+        8,   17,   84,   23,   19,   30,   15,   20,   18,    2,
+        2,   71,   24,   21,   26,   30,   22,   19,   81,   15,
+       20,   25,   18,  116,   23,   80,   24,   21,   26,   30,
+       22,   84,   28,   85,  100,   31, 1051,   18,   23,   71,
+
+      624,   24,   21,   26,   30,   22,   81,   25,  624,   31,
+       18,   32,  116,   23,   24,   21,   26,   30,   22,   28,
+       84,   25,  100, 1047,   31,   32,   23,   56,   56,   56,
+       76,   76,   76,   28,  101,  105,   25,   31,  106,   85,
+       32,  179,   69,   69,   69,   33, 1006,  179,   28,   25,
+       27,   33,   27,   32,   77,   77,   77,   78,   78,   78,
+     1000,   28,  101,  105,  914,   33,  106,   85,   27,   27,
+       27,   27,   27,   27,   27,   27,   27,   27,   34,   69,
+       33,   35,   35,   27,  120,   35,   41,   27,   27,   27,
+      868,   35,   34,   33,   27,   41,   27,   27,   35,   35,
+
+       41,  862,   27,  123,   89,  861,   27,   34,   69,  796,
+       35,   35,   27,  120,   35,   41,   27,   27,   27,   35,
+       34,  114,   27,   41,   27,   27,   35,   35,   41,   88,
+       27,   36,  123,   42,   27,   29,   36,   29,   29,   29,
+       29,   29,   29,   29,   29,   29,   29,   42,  794,  114,
+       36,   90,  337,   89,  337,   29,   29,   29,   90,   90,
+       36,   88,   42,  115,  117,   36,  104,  786,   29,  121,
+      122,   29,  126,   44,  109,   42,  104,   54,   36,   38,
+       38,   89,   44,   38,   29,   29,   29,   44,  109,   38,
+       88,  115,  117,   38,   38,  104,   29,  121,  122,   29,
+
+       37,  126,   44,  109,  104,   37,   54,   37,   38,   38,
+       44,   37,   38,  785,   37,   44,  109,   38,   92,   37,
+       54,   38,   38,  778,   37,   92,   92,  660,  777,   37,
+      186,  186,  186,  660,   37,   54,   37,   43,  693,   37,
+      132,   45,   37,  692,   43,   43,   45,   37,   54,   45,
+      690,   43,   37,   39,  625,   45,   72,   72,   72,   39,
+       45,   39,   39,  625,   39,   39,   43,   39,   72,  132,
+       45,   39,   43,   43,  124,   45,  102,  689,   45,   43,
+      689,  678,   39,   45,  211,  211,  211,   39,   45,   39,
+       39,  102,   39,   39,   72,   39,  119,   49,   49,   39,
+
+       40,  664,  124,   40,  635,  102,   40,   40,   72,   40,
+       46,  753,   49,  119,   40,   40,  128,  143,   46,  102,
+      753,   46,   46,   72,   46,  119,   49,   49,  118,   40,
+       46,  558,   40,  103,   40,   40,   72,   40,  118,   46,
+       49,  119,   40,   40,  128,   47,  143,   46,  103,   46,
+       46,   48,   46,   47,  129,   47,   48,  118,   46,   47,
+       47,   52,  103,  130,  131,   48,  118,  133,   48,   52,
+       48,   48,  661,  553,   47,   52,  103,  534,  661,  134,
+       48,   47,  129,   47,  519,   48,  135,   47,   47,  137,
+       52,  130,  131,   48,   95,  133,   48,   52,   48,   48,
+
+       50,   95,   95,   52,   50,   50,   51,  134,   50,  496,
+       53,   51,   53,   51,  135,  487,   50,  137,  139,   50,
+       50,  140,   53,   51,   53,   51,  224,  224,  224,   50,
+      401,  399,  146,   50,   50,   51,  141,   50,  144,   53,
+       51,   53,   51,   95,   50,   60,  139,   50,   50,  140,
+       53,   51,   53,   51,   55,   55,   55,   55,   57,   57,
+       58,  146,   55,  392,  141,   58,  144,  338,  138,  338,
+      147,   95,   60,  390,  138,   57,   57,   57,   57,   57,
+       57,   57,   57,   57,   57,  148,   60,  149,  159,   55,
+       55,   65,   55,   55,   62,   55,  138,   58,  147,   65,
+
+       62,   60,  138,   62,   65,   65,   55,   55,   62,  365,
+      150,   58,  362,  148,   60,  340,  149,  159,   55,   55,
+       65,   55,   55,   62,   55,  151,   58,   65,   62,  336,
+      247,   62,   65,   65,   55,   55,   62,   63,  150,   58,
+       59,   91,   91,   91,   63,   63,   59,  244,  243,   91,
+       91,   63,  242,  151,   59,  241,   59,   59,   59,   59,
+       59,   59,   59,   59,   59,   59,   63,   99,   99,  142,
+       94,  142,   63,   63,   59,   59,   59,   94,   94,   63,
+       99,  152,  125,  125,  153,  154,  155,   59,  125,  157,
+       59,  161,  213,  511,  163,  511,   99,   99,  164,  210,
+
+      166,  127,   94,   59,   59,   59,  127,  170,   99,  152,
+      125,  125,  153,  154,  155,   59,  125,  157,   59,   61,
+      161,  142,  163,   61,   61,  204,  164,   61,  166,  860,
+      127,   94,  189,   61,  182,  127,  170,   61,   61,  158,
+       64,  178,  158,  136,  165,   64,  145,   64,   61,  142,
+      136,  165,   61,   61,  136,  171,   61,   64,  145,   64,
+      145,   61,  182,  145,   64,   61,   61,  158,   87,   64,
+      158,   86,  136,  165,   64,  145,   64,   82,  136,  165,
+       67,  512,  136,  512,  171,   64,  145,   64,  145,  860,
+       13,  145,   64,   73,   73,   73,   73,   73,   73,   73,
+
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
@@ -8815,934 +7803,352 @@
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
-
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
        73,   73,   73,   73,   73,   73,   73,   73,   73,   73,
-       73,   73,   73,   73,   97,  101,  101,  105,  204,  204,
-      204,   97,   97,  226,  538,  227,  213,  675,  101,  675,
-      534,  111,  105,  111,  111,  111,  111,  111,  111,  111,
-      111,  111,  111,  421,  101,  101,  105,  375,  375,  375,
-      419,  226,  173,  227,  173,  204,  101,  114,  213,  534,
-      105,  219,  412,   97,  113,  113,  113,  113,  113,  113,
-      113,  113,  113,  113,  114,  228,  115,  118,  219,  114,
-
-      116,  115,  118,  125,  204,  116,  410,  213,  125,  231,
-      173,   97,  100,  114,  100,  115,  118,  229,  116,  116,
-      386,  221,  125,  114,  173,  115,  118,  219,  114,  116,
-      115,  118,  125,  379,  116,  228,  249,  125,  230,  173,
-      374,  114,  251,  115,  118,  100,  116,  116,  117,  100,
-      125,  100,  173,  117,  243,  221,  100,  276,  100,  100,
-      248,  231,  117,  228,  249,  401,  229,  117,  100,  294,
-      251,  294,  401,  401,  100,  371,  343,  117,  100,  294,
-      100,  230,  117,  221,  100,  276,  100,  100,  535,  231,
-      117,  250,  243,  248,  229,  117,  100,  110,  110,  110,
-
-      110,  110,  110,  110,  110,  110,  110,  119,  121,  230,
-      913,  247,  119,  121,  120,  110,  110,  535,  119,  120,
-      243,  248,  120,  246,  400,  121,  119,  121,  110,  245,
-      233,  233,  233,  120,  341,  277,  119,  121,  233,  233,
-      344,  119,  121,  120,  110,  110,  119,  122,  120,  122,
-      244,  120,  122,  121,  119,  121,  110,  177,  123,  218,
-      400,  120,  341,  123,  212,  345,  122,  346,  344,  354,
-      913,  177,  277,  347,  209,  123,  122,  123,  122,  124,
-      202,  122,  348,  126,  124,  187,  177,  123,  126,  400,
-      124,  349,  123,  345,  122,  346,  183,  126,  124,  177,
-
-      277,  347,  126,  123,  676,  123,  676,  354,  124,  127,
-      348,  175,  126,  124,  127,  174,  237,  126,  124,  349,
-       89,  127,  127,  237,  237,  126,  124,  127,  127,  128,
-      126,  128,  129,  389,  128,  130,  354,  129,  127,  292,
-      130,  292,  361,  127,  234,  234,  234,  130,  128,  127,
-      127,  129,  234,  234,  130,  127,  127,  536,  128,  237,
-      128,  129,   88,  128,  130,  388,  129,   84,  389,  130,
-      361,  380,  380,  380,  356,  130,  128,   65,   13,  129,
-      378,  238,  130,  131,  355,  131,  536,  237,  238,  238,
-      369,  292, 1051,  388,  390,  133,  389,  392,    9,  131,
-
-      133,  131,  131,  131,  131,  131,  131,  131,  131,  131,
-      131,  132, 1081,  133,  133,  134,  132,    7,  134,  292,
-      134,  388,  132,  398,  133,  392,  356,  355,  369,  133,
-      132,  390,  378,  238,  134,  677,  131,  677,  131, 1130,
-      132,  133,  133,  381,  134,  132,  136,  134,  135,  134,
-      132,  136, 1051,  135,  356,  355,  398,  369,  132,  390,
-      378,  238,  134,  136,  131,  136,  131,  135,  135,  139,
-      377,  137, 1081,  138,  139,  136,  137,  135,  138,  137,
-      136,  381,  135,  139,  138,  398,  137,  395,  139,    0,
-      137,  136,  138,  136,  418,  135,  135,  397,  139, 1130,
-
-      137,  382,  138,  139,  140,  137,  475,  138,  137,  140,
-      381,  139,  138,  377,  137,  395,  139,  142,  137,  142,
-      138,  140,  418,  140,  141,  399,  143,  144,  143,  141,
-     1131,  537,  144,  140,  475,    0,  143,  141,  140,  391,
-      533,  377,  144,  141,  397,  382,  144,    0,  543,  140,
-      142,  140,  466,  141,  466,  142,  144,  146,  141,  143,
-      537,  144,  146,  146,  143,  141,    0,  391,  533,  142,
-      144,  141,  397,  382,  144,  399,  146,    0,  143,  142,
-      145,    0,  145,  466,  142,  145,  146,  680,  143,  680,
-     1131,  146,  146,  143,  145,  391,  145,  142,  543,  145,
-
-      147,    0,  148,  399,  146,  147,  143,  148,  557,  145,
-      484,  145,  484,  546,  145,  148,  394,  394,  394,  147,
-      484,  148,  145,  147,  145,  149,  543,  145,  149,  147,
-      149,  148,  572,  150,  147, 1148,  148,  151,  150,    0,
-        0,  546,  151,  148,  149,  150,  547,  147,    0,  148,
-      151,  147,  150,  557,  149,    0,  151,  149,    0,  149,
-      544,  572,  150,  152,  153,    0,  151,  150,  152,  153,
-        0,  151,  149,  150,  547,  153,  152,  488,  151,  488,
-      150,  557,  152,  153,  151,    0,  155,  488,    0,  154,
-      155,  155,  152,  153,  154, 1148,  544,  152,  153,  521,
-
-      154,  521,    0,  153,  152,  155,  611,    0,  154,  521,
-      152,  153,  156,  253,  253,  155,  158,  156,  154,  155,
-      155,  158,  402,  154,  158,  544,  253,    0,  154,  402,
-      402,  156,  157,  155,  611,  158,  154,  157,  559,  559,
-      559,  156,  253,  253,    0,  158,  156,  612,    0,  157,
-      158,  157,  157,  158,  253,  160,  160,  159,    0,  156,
-      160,  157,  159,  158,  614,  159,  157,  370,  370,  370,
-      615,  159,  402,  561,  160,  612,  159,  157,    0,  157,
-      157,  194,  162,  194,  160,  160,  159,  162,  161,  160,
-      161,  159,  614,  161,  159,  556,  556,  556,  615,  159,
-
-      402,  162,  160,  162,  159,    0,  161,  161,  370,  542,
-      161,  162,  575,  163,  194,  564,  162,  161,  163,  161,
-      164,  555,  161,  561,  163,  164,  164,  563,  194,  162,
-        0,  162,  163,  164,  161,  161,  556,  370,  161,  164,
-      165,  575,  163,  194,  568,  165,  692,  163,  692,  164,
-      617,  561,  163,  562,  164,  164,  194,  165,  542,  165,
-      163,  164,  564,  166,  403,  556,  682,  164,  166,  165,
-      555,  403,  403,  577,  165,  569,  563,  166,  617,  568,
-      166,    0,  166,  167,  167,  165,  542,  165,  167,  562,
-      564,  697,  166,  697,  682,  167,  569,  166,  555,  744,
-
-      403,    0,  167,  570,  563,  166,  577,  568,  166,  168,
-      166,  579,  167,  167,  168,  169,    0,  167,  562,  169,
-      169,    0,  168,  167,  570,  569,  168,  744,  168,  403,
-      167,  571,  170,    0,  169,  577,  753,  170,  168,    0,
-      170,  171,    0,  168,  169,  171,  171,  579,  169,  169,
-      168,  170,  571,  570,  168,    0,  168,  574,  574,  574,
-      171,  170,  169,  172,  753,  581,  170,  604,  172,  170,
-      171,  172,  581,  581,  171,  171,  579,  582,  613,  170,
-      618,  571,  172,  687,  582,  582,    0,    0,  171,  678,
-        0,  678,  172,  185,  185,  185,  604,  172,  756,  678,
-
-      172,  581,  679,  635,  815,  635,  815,  613,  757,  618,
-      172,  185,  185,  185,  185,  185,  185,  185,  185,  185,
-      185,  186,  681,  687,    0,  678,  756,  186,  713,    0,
-      581,  679,  691,  608,  635,  608,  757,  186,  186,  186,
-      186,  186,  186,  186,  186,  186,  186,  192,  683,  713,
-      683,  681,  687,  192,  678,  684,  684,  684,  683,    0,
-      703,  691,  683,  192,  192,  192,  192,  192,  192,  192,
-      192,  192,  192,  193,  608,  215,  215,  215,  713,  193,
-      708,  708,  708,  748,  826,  826,  826,  193,  608,  193,
-      193,  193,  193,  193,  193,  193,  193,  193,  193,  195,
-
-      703,  196,  197,  608,  195,  749,  196,  197,  215,    0,
-      195,  616,  748,  196,  196,  688,  608,  195,  195,  196,
-      196,  197,  215,  832,  832,  832,  704,  616,  195,  703,
-      196,  197,  707,  195,  749,  196,  197,  215,  195,  198,
-      616,  196,  196,    0,  198,  195,  195,  196,  196,  197,
-      215,  688,  702,  198,  702,  616,  200,    0,  198,  201,
-      199,  200,  199,  201,  201,  199,  702,  755,  198,  758,
-        0,  200,  707,  198,  199,  200,  199,  704,  201,  199,
-      688,  198,  759,  807,    0,  200,  198,    0,  201,  199,
-      200,  199,  201,  201,  199,  216,  755,    0,  758,  200,
-
-        0,  707,  199,  200,  199,  704,  201,  199,    0,    0,
-      759,  807,  216,  216,  216,  216,  216,  216,  216,  216,
-      216,  216,  217,  217,  217,  217,  217,  217,  217,  217,
+       73,   73,   98,  110,   98,  110,    7,  156,  110,  110,
+      110,  110,  110,  110,  110,  110,  110,  110,  160,  366,
+
+      366,  366,  156,  183,  160,  172,  528,  168,  528,  169,
+      173,  174,    0,  169,  173,   98,  156,  185,  168,   98,
+      181,   98,  866,  530,  196,  530,   98,  160,   98,   98,
+      156,  183,  160,  162,  172,  162,  168,  169,   98,  173,
+      174,  169,    0,  173,   98,  185,  168,    0,   98,  181,
+       98,  162,  162,  196,   98,  162,   98,   98,  176,  199,
+      176,    0,  162,  191,  162,    0,   98,  108,  108,  108,
+      108,  108,  108,  108,  108,  108,  108,  167,  180,  162,
+      162,  184,  866,  162,  203,  108,  108,  199,  184,  192,
+      200,  167,  180,  193,  167,  191,  176,  231,  108,  202,
+
+        0,  207,  215,    0,  231,  231,  167,  180,    0,  184,
+      176,  187,  187,  203,  108,  108,  184,  208,  200,  167,
+      180,  192,  167,    0,  191,  176,  108,  202,  187,  187,
+      187,  187,  187,  187,  187,  187,  187,  187,  176,  188,
+      197,  651,  193,  651,  239,  188,  207,  197,  222,  208,
+      192,  215,  223,    0,    0,  188,  188,  188,  188,  188,
+      188,  188,  188,  188,  188,  194,  198,  198,  197,  214,
+      193,  194,  198,  239,  207,  197,  222,    0,  208,  215,
+      223,  194,  194,  194,  194,  194,  194,  194,  194,  194,
+      194,  195,  209,  225,  198,  198,  216,  195,    0,  240,
+
+      198,  214,  206,  206,  206,  195,  201,  195,  195,  195,
+      195,  195,  195,  195,  195,  195,  195,  226,  201,  246,
+      201,  225,  227,  201,  229,  195,  195,  209,  216,  221,
+      214,  221,    0,    0,  258,  201,  234,  240,  195,  206,
+      230,    0,  228,  234,  234,  226,  201,  246,  201,    0,
+      652,  201,  652,    0,  195,  195,  209,  216,  221,    0,
+      221,  245,  227,  258,    0,  240,  195,  229,  206,  217,
       217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-
-      217,  217,  217,  217,  217,  217,  217,  217,  217,  217,
-      217,  239,    0,  239,  860,  760,  239,  239,  239,  239,
-      239,  239,  239,  239,  239,  239,  240,    0,  240,  863,
-      805,  240,  240,  240,  240,  240,  240,  240,  240,  240,
-      240,  241,  860,  241,  760,  806,  241,  241,  241,  241,
-      241,  241,  241,  241,  241,  241,  254,  863,  254,  805,
-        0,  254,  254,  254,  254,  254,  254,  254,  254,  254,
-      254,  255,    0,  255,  806,    0,  255,  255,  255,  255,
-      255,  255,  255,  255,  255,  255,  256,  808,  256,  259,
-      865,  256,  256,  256,  256,  256,  256,  256,  256,  256,
-
-      256,  257,  257,  257,  257,  257,  257,  257,  257,  257,
-      257,    0,  259,  769,  260,  769,  808,  259,  865,  260,
-      257,  258,  258,  258,  258,  258,  258,  258,  258,  258,
-      258,  259,  260,  260,  261,  813,  901,  262,  901,  261,
-      258,  259,  262,  260,  769,  261,  259,  727,  260,  257,
-      908,  262,  908,  261,  727,  727,  262,  263,  705,  259,
-      260,  260,  263,  261,  813,  693,  262,  693,  261,  258,
-      263,  262,    0,  261,    0,  693,  263,  264,  266,  262,
-      265,  261,  264,  266,  262,  265,  263,  803,  266,  803,
-      264,  263,    0,    0,  705,  803,  264,  266,  263,  265,
-
-      265,  693,  851,  268,  263,  810,  264,  266,  268,  265,
-      267,  264,  266,    0,  265,  267,  266,    0,  264,    0,
-      268,  267,  268,  705,  264,  266,    0,  265,  265,  267,
-      693,  851,  268,  269,    0,  271,  821,  268,  269,  267,
-      271,  270,  810,    0,  267,  700,  270,  700,  268,  267,
-      268,  269,  269,  270,  271,  700,  270,  267,  272,  700,
-      270,    0,  269,  272,  271,  272,  728,  269,    0,  271,
-      270,  810,  821,  728,  728,  270,    0,  272,  273,  269,
-      269,  270,  271,  273,  270,  274,    0,  272,  270,  273,
-      274,  729,  272,  794,  272,  794,  274,  273,  729,  729,
-
-        0,  821,    0,  794,  274,  272,    0,  273,  278,  278,
-      857,  275,  273,  278,  274,  275,  275,  273,  900,  274,
-      859,  809,  809,  809,  274,  273,  820,  278,  279,  809,
-      275,  280,  274,  279,  824,  279,  280,  278,  278,  857,
-      275,  284,  278,  284,  275,  275,  900,  279,  281,  859,
-      280,  861,  281,  281,    0,  278,  862,  279,  275,  864,
-      280,  925,  279,  820,  279,  280,    0,  281,  283,    0,
-        0,  824,  284,  283,  284,  279,  283,  281,  280,  284,
-      861,  281,  281,  838,  875,  862,  875,  283,  864,  925,
-      838,  838,  820,  284,  875,  281,  282,  283,  282,  285,
-
-      824,  894,  283,  284,  285,  283,  286,  899,  284,  422,
-      422,  286,  839,  902,  893,  283,  893,  285,  285,  839,
-      839,  284,  422,    0,  893,  286,    0,  282,  285,  282,
-      894,  911,  282,  285,  282,  286,  899,  282,  422,  422,
-      286,  282,  902,    0,  282,  285,  285,  282,  282,  289,
-      422,  282,  287,  286,  289,  288,  287,  287,  282,  288,
-      288,  282,  934,  282,  937,  884,  282,  884,  289,  282,
-        0,  287,  282,    0,  288,  282,  282,  926,  289,  282,
-      911,  287,  290,  289,  288,  287,  287,  290,  288,  288,
-      291,  934,  291,  937,  290,  291,  289,  929,  293,  287,
-
-      931,  290,  288,  293,  896,  926,  896,  932,  911,  291,
-        0,  290,  293,  884,    0,  296,  290,  293,  933,  291,
-      296,  291,  290,  935,  291,  929,  296,  293,  931,  290,
-      961,  297,  293,    0,  296,  932,  297,  291,  298,  896,
-      293,  884,  297,  298,  296,  293,  933,    0,  954,  296,
-      297,  935,    0,  964,  296,    0,    0,  298,  298,  961,
-      297,  299,  296,    0,    0,  297,  299,  298,  896,  965,
-      297,  980,  298,  948,  948,  948,  954,  966,  297,  972,
-      299,  299,  964,  300,  301,  298,  298,  300,  300,  301,
-      299,  302,  301,  302,  303,  299,  303,  965,  967,  980,
-
-      300,  302,  300,  301,  303,  968,  966,  968,  299,  299,
-        0,    0,  300,  301,  989,  972,  300,  300,  301,  990,
-      304,  301,  973,  981,  302,  304,  984,  303,  300,  302,
-      300,  301,  303,  967,  968,  302,  968,    0,  303,  304,
-      304,  986,  989,  302,  972,  302,  303,  990,  303,  304,
-     1005,    0,  981,  302,  304,  984,  303,    0,  302,  973,
-      305,  303,  967,  302,  305,  305,  303,  304,  304,  987,
-      986,  302,  306,  302,  303,  988,  303,  306, 1005,  305,
-      307,  308, 1008, 1016,  307,  307,  308,    0,  973,  305,
-     1010,  306,  308,  305,  305,    0,    0,  309,  987,  307,
-
-      308,  306,  309, 1015,  988,    0,  306,  305,    0,  307,
-      308, 1008, 1013,  307,  307,  308,  309,  310, 1010,  306,
-      308,  309,  310,  998,  998,  998,  309,  307,  308, 1016,
-      310,  309, 1015,  311,  312,    0,  310,  313,  311,  312,
-     1013,  311,  313,  852,  309,  852,  310, 1017,    0,  309,
-        0,  310,  311,  312,  314,    0,  313, 1016,  310,  314,
-     1018,    0,  311,  312,  310, 1028,  313,  311,  312, 1027,
-      311,  313,  314,  314,  315,    0, 1017,  316,  852,  315,
-      311,  312,  316,  314,  313, 1022, 1032,  315,  314, 1018,
-      316,  852, 1034,  315, 1028,    0,  316, 1027,  316, 1036,
-
-      314,  314, 1021,  315,  317, 1023,  316,  852,  315,  317,
-      317,  316,    0,    0, 1032,  315, 1043, 1022,  316,  852,
-     1034,  315, 1049,  317,  316,  318,  316, 1036,    0,  319,
-      318,    0,  319,  317,  319,    0,  318,  320,  317,  317,
-      319, 1023,  320,    0,  318, 1043, 1022, 1021,  319, 1046,
-     1049,  317,    0, 1024,  318, 1053,  320,  320,  319,  318,
-      321,  319,  322,  319,  318,  321,  320,  322,  319,  323,
-     1023,  320,  318, 1052,  323, 1021,  319,  323, 1046,  321,
-      321,  322,  322, 1053,  320,  320,    0,    0,  323,  321,
-        0,  322,  326, 1024,  321,  324,  322,  326,  323,  324,
-
-      324,    0, 1052,  323, 1060,  326,  323,  321,  321,  322,
-      322,  326,  328,    0,  324,  325,  323,  328,  327,  325,
-      325,  326, 1024,  327,  324,  327,  326, 1061,  324,  324,
-     1058,  328, 1060,  326,  325,    0, 1055,  327,  329,  326,
-        0,  328,  324,  329,  325,  330,  328,  327,  325,  325,
-      330, 1057,  327,  332,  327,  332, 1061,  329,    0,  328,
-      330,  331,  325,  332,  330,  327,  331,  329, 1041, 1041,
-     1041, 1055,  329,    0,  330, 1058, 1064,    0,  331,  330,
-      331, 1066,  333, 1056, 1057,  329,  332,  333,  330,  333,
-      331,  332,  330,  334, 1072,  331,    0, 1074,  334,  334,
-
-     1055,  333,  336, 1058, 1064,  332,  331,  336,  331, 1076,
-     1066,  333,  334, 1057,  336,  332,  333, 1056,  333,  335,
-      332,  336,  334, 1072,  335, 1074, 1078,  334,  334,  333,
-        0,  336,  335,  332,    0,    0,  336, 1076,  335,  337,
-      334, 1085,  336,    0,  337,  338, 1056, 1094,  335,  336,
-      338,    0,  974,  335, 1078, 1086,  337, 1090,  337, 1083,
-      335,  876,  876,  876,  338,    0,  335,    0,  337,  876,
-     1085, 1082,  876,  337,  338,  351, 1094,  351,    0,  338,
-      946,  946,  946, 1086,  337, 1090,  337,  974,  946,  974,
-        0,  946,  338,  351,  351,  351,  351,  351,  351,  351,
-
-      351,  351,  351,  352,  947,  947,  947, 1082,    0,  352,
-        0, 1083,  947,    0, 1077,  947,  974,    0,  974,  352,
-      352,  352,  352,  352,  352,  352,  352,  352,  352,  353,
-      949,  949,  949,    0,    0,  353, 1082, 1098,  949, 1083,
-        0,  949, 1070, 1070, 1070,  353,  353,  353,  353,  353,
-      353,  353,  353,  353,  353,  357, 1092, 1092, 1092, 1077,
-     1099,  357,  362,  363,    0,  364,  362,  362,  363,  357,
-      364,  357,  357,  357,  357,  357,  357,  357,  357,  357,
-      357,  362,  363, 1098,  364,  365,  365, 1077, 1099, 1103,
-      365,  362,  363,  368,  364,  362,  362,  363, 1104,  364,
-
-        0,  366,    0,    0,  365,  366,  366,    0,    0,  362,
-      363, 1098,  364, 1111,  365,  365, 1107, 1103,  366,  365,
-      366,  367,    0,  433,  368,  367,  367, 1104,  433,  368,
-      366, 1100,  365,    0,  366,  366,  950,  950,  950, 1113,
-      367, 1111,  433,  368,  950, 1107,  366,  950,  366,    0,
-      367, 1116,  433,  368,  367,  367,  383,  433,  368,    0,
-        0,  999,  999,  999,    0,    0, 1100, 1113,  367,  999,
-      433,  368,  999,  383,  383,  383,  383,  383,  383,  383,
-      383,  383,  383,  384,    0, 1000, 1000, 1000, 1101, 1101,
-     1101,    0,  383, 1000, 1121, 1100, 1000, 1116, 1127,    0,
-
-      384,  384,  384,  384,  384,  384,  384,  384,  384,  384,
-      387,    0, 1001, 1001, 1001, 1117, 1117, 1117, 1136,  384,
-     1001,  383, 1121, 1001,    0, 1116, 1127,  387,  387,  387,
-      387,  387,  387,  387,  387,  387,  387,  404,  404,  404,
-      404,  404,  404,  404,  404,  404,  404, 1136,  384,  405,
-      405,  405,  405,  405,  405,  405,  405,  405,  405,  406,
-      406,  406,  406,  406,  406,  406,  406,  406,  406,  407,
-      407,  407,  407,  407,  407,  407,  407,  407,  407,  408,
-      408,  408,  408,  408,  408,  408,  408,  408,  408,  409,
-      409,  409,  409,  409,  409,  409,  409,  409,  409,  423,
-
-      423,  423,  423,  423,  423,  423,  423,  423,  423,  424,
-      424,  424,  424,  424,  424,  424,  424,  424,  424,  425,
-      425,  425,  425,  425,  425,  425,  425,  425,  425,  426,
-      426,  426,  426,  426,  426,  426,  426,  426,  426,  427,
-      427,  427,  427,  427,  427,  427,  427,  427,  427,  428,
-      428,  428,  428,  428,  428,  428,  428,  428,  428,  429,
-     1102,  429,    0,    0,  429,  429,  429,  429,  429,  429,
-      429,  429,  429,  429,  430,  430,  430,  430,  430,  430,
-      430,  430,  430,  430,    0,  436,    0,  434,    0,  431,
-      436,  431,  434,  430,  431,  431,  431,  431,  431,  431,
-
-      431,  431,  431,  431,  436,  434,  434,  435,  437,  435,
-     1144, 1102,  435,  437,  436,    0,  434, 1132, 1147,  436,
-        0,  434,  430,    0,  438,    0,  435,  437,  438,  438,
-      439,    0,  436,  434,  434,  439,  435,  437,  435, 1102,
-        0,  435,  437,  438,    0, 1132,  440, 1140,  439,  439,
-     1147,  440,    0,  438,  435,  437, 1144,  438,  438,  439,
-        0,    0,  441,    0,  439,  440, 1114,  441,  442,  443,
-        0,  438,  442,  442,  443,  440,  439,  439, 1139, 1147,
-      440,  441,    0,  443, 1144,  446, 1146,  442,  443,  444,
-      446,  441, 1140,  440,  444, 1143,  441,  442,  443, 1156,
-
-      444,  442,  442,  443,  446,  445,    0, 1149,  444,  441,
-      445,  443,    0,  445,  446,  442,  443, 1114,  444,  446,
-     1140,  447,  448,  444,  445,  447,  447,  448,  444, 1139,
-      449, 1156,  446,  448,  445,  449,  444, 1146,    0,  445,
-      447,  448,  445,  449, 1143, 1114, 1124, 1124, 1124,  449,
-      447,  448,  445,    0,  447,  447,  448, 1139, 1149,  449,
-     1156,  448,  451,    0,  449, 1146, 1145,  451,  447,  448,
-      452,  449, 1143,  451,  453,  452, 1152,  449,  452,  453,
-        0,  451,    0,    0, 1150,  454, 1149,  454,    0,  452,
-        0,  451,  453,  453,    0,    0,  451,    0,    0,  452,
-
-        0,  451, 1145,  453,  452,    0,    0,  452,  453,  451,
-      458, 1151, 1151, 1151,  457,  458,    0,  452,  454,  457,
-      453,  453,    0,  454,    0, 1152,  454,    0,  457,  458,
-      458, 1145,    0,  457,    0, 1150,    0,  454,    0,  458,
-      454,  459,    0,  457,  458,  460,  459,  454,  457,    0,
-      460,    0,  454, 1152, 1155,  454,  457,  458,  458,  460,
-      459,  457,  468, 1150,  460,  454,    0,  468,  454,  455,
-      459,  455,    0,    0,  460,  459, 1153, 1153, 1153,  460,
-        0,  468,    0,    0,  461,    0,    0,  460,  459,  461,
-     1155,  468,  460, 1158, 1158, 1158,  468, 1159, 1159, 1159,
-
-      455,  461,    0,  461,    0,  455,  463,  455,    0,  468,
-      455,  463, 1157,  461,  455,    0,    0,  455,  461, 1155,
-      455,  455,    0,    0,  455,  463,    0,    0,    0,  461,
-      463,  461,    0,    0,  455,  463,  455,    0,  472,  455,
-      463,    0,  455,  472,    0,  455,  462,    0,  455,  455,
-      462,  462,  455,  463,  464,  465,    0,  472,  463,  464,
-      465,  464,    0, 1157,    0,  462,  462,  472,    0,    0,
-        0,    0,  472,  464,  465,  462,  465,    0,    0,  462,
-      462,    0,    0,  464,  465,  472,    0,    0,  464,  465,
-      464, 1157,    0,  462,  462,    0,    0,    0,    0,    0,
-
-        0,  464,  465,    0,  465,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,    0,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  469,  469,  469,  469,  469,  469,
-      469,  469,  469,  469,  470,    0,  471,  473,  471,  470,
-
-        0,    0,  473,  474, 1002, 1002, 1002,    0,  474,    0,
-        0,  470, 1002,  470,    0, 1002,  473,    0,    0,    0,
-        0,    0,  474,  470,    0,    0,  473,  471,  470,  471,
-      476,  473,  474,    0,  471,  476,    0,  474,  477,  470,
-        0,  470,    0,  477,  473,    0,  477,    0,  471,  476,
-      474,    0,    0,    0,    0,    0,    0,  477,  471,  476,
-      478,    0,    0,  471,  476,  478,    0,  477,  479,    0,
-        0,    0,  477,  479,    0,  477,  471,  476,    0,  478,
-      478,    0,    0,    0,    0,  477,    0,  479,    0,  478,
-      480,    0,    0,    0,  478,  480,    0,  479,  480,  481,
-
-        0,    0,  479,    0,  481,  481,    0,  478,  478,  480,
-        0,    0,  481,    0,    0,  479,    0,    0,  481,  480,
-        0, 1003, 1003, 1003,  480,    0,    0,  480,  481, 1003,
-      482,  487, 1003,  481,  481,  482,  487,  480,  482,  483,
-      481,  483,  486,    0,  483,    0,  481,  486,    0,  482,
-      487,    0,    0,    0,    0,    0,  486,    0,  483,  482,
-      487,  486,    0,    0,  482,  487,    0,  482,  483,  490,
-      483,  486,    0,  483,  490,  491,  486,  482,  487,    0,
-      491,    0,    0,  490,  486,    0,  483,    0,  490,  486,
-        0,  492,    0,    0,  491,  493,  492,    0,  490,    0,
-
-      493,    0,  492,  490,  491,    0,  493,  494,    0,  491,
-      492,  490,  494,    0,  493,    0,  490,    0,  495,    0,
-      492,    0,  491,  495,  493,  492,  494,  496,    0,  493,
-      492,    0,  496,    0,  493,  496,  494,  495,  492,  497,
-        0,  494,  493,  498,  497,    0,  496,  495,  498,    0,
-      502,    0,  495,    0,  494,  502,  496,    0,  497,    0,
-        0,  496,  498,    0,  496,  495,  499,    0,  497,  502,
-      500,  499,  498,  497,  496,  500,    0,  498,    0,  502,
-      499,    0,  500,    0,  502,  499,  497,  501,    0,  500,
-      498,  501,  501,  503,    0,  499,  504,  502,  503,  500,
-
-      499,  504,    0,    0,  500,    0,  501,    0,  499,    0,
-      500,    0,  503,  499,    0,  504,  501,  500,  505,  507,
-      501,  501,  503,  505,  507,  504,    0,  503,    0,  508,
-      504, 1042, 1042, 1042,  501,  505,    0,  505,  507, 1042,
-      503,  506, 1042,  504,    0,    0,  506,  505,  507,  506,
-      508,    0,  505,  507,    0,  508,    0,  509,    0,    0,
-      506,    0,  509,  505,    0,  505,  507,    0,    0,  508,
-      506,    0,    0,    0,  509,  506,  509,    0,  506,  508,
-        0,    0,  510,    0,  508,    0,  509,  510,  506,  511,
-      512,  509,    0,  510,  511,  512,    0,  508,    0,    0,
-
-        0,  510,  509,  512,  509,    0,  511,    0,  511,  512,
-        0,  510,    0,    0,    0,    0,  510,    0,  511,  512,
-      513,  510,  515,  511,  512,  513,    0,  515,  514,  510,
-      514,  512,    0,  514,  511,    0,  511,  512,  517,  513,
-        0,  515,    0,    0,    0,  516,    0,  514,    0,  513,
-      516,  515,    0,  518,  513,    0,  515,  514,  518,  514,
-        0,  517,  514,    0,  516,  519,  517,  513,    0,  515,
-      519,    0,  518,    0,  516,  514,    0,    0,    0,  516,
-      517,    0,  518,    0,  519,    0,  523,  518,  520,    0,
-      517,  523,  516,  520,  519,  517,    0,    0,    0,  519,
-
-      518,    0,  520,    0,    0,  523,    0,  520,  517,  524,
-        0,    0,  519,  524,  524,  523,    0,  520,  525,    0,
-      523,  526,  520,  525,    0,    0,  526,    0,  524,    0,
-      520,    0,    0,  523,    0,  520,    0,  525,  524,    0,
-      526,  527,  524,  524,  528,  527,  527,  525,  528,  528,
-      526,    0,  525,    0,    0,  526,  524,    0,    0,    0,
-      527,  551,    0,  528,    0,  525,  551,    0,  526,    0,
-      527,    0,    0,  528,  527,  527,    0,  528,  528,  539,
-      551,  539,    0,    0,    0, 1071, 1071, 1071,  527,    0,
-      551,  528,    0, 1071,    0,  551, 1071,  539,  539,  539,
-
-      539,  539,  539,  539,  539,  539,  539,  540,  551, 1093,
-     1093, 1093,    0,  540,    0,    0,    0, 1093,    0,    0,
-     1093,    0,    0,  540,  540,  540,  540,  540,  540,  540,
-      540,  540,  540,  541,  548,    0,  548,    0,    0,  541,
-        0,    0,    0,    0,  548,    0,    0,    0,    0,  541,
-      541,  541,  541,  541,  541,  541,  541,  541,  541,  545,
-      550,    0,  550,    0,    0,  545,  549,  548,    0,    0,
-      548,  549,  548,  545,  549,  545,  545,  545,  545,  545,
-      545,  545,  545,  545,  545,  549,  548,    0,    0,    0,
-        0,    0,    0,  550,    0,  549,  548,    0,  550,  548,
-
-      549,  548,  552,  549,    0,  592,    0,  552,  552,  592,
-      592,    0,  550,  549,  548,  552,    0,    0,  553,  552,
-      553,  552,  550,    0,  592,    0,    0,  550,  553,    0,
-        0,  552,  553,    0,  592,    0,  552,  552,  592,  592,
-      550,  565,    0,  552,    0,    0,    0,  552,    0,  552,
-        0,  553,  592,  565,    0,  565,  553,    0,  565,  565,
-      565,  565,  565,  565,  565,  565,  565,  565,    0,  566,
-      553, 1110, 1110, 1110,    0,    0,    0,    0,    0, 1110,
-      553,    0, 1110,    0,    0,  553,  566,  566,  566,  566,
-      566,  566,  566,  566,  566,  566,  567,    0,  553,    0,
-
-        0, 1125, 1125, 1125,    0,  566,    0,    0,  567, 1125,
-      567,    0, 1125,  567,  567,  567,  567,  567,  567,  567,
-      567,  567,  567,  588,  588,  588,  588,  588,  588,  588,
-      588,  588,  588,    0,  566,  589,  589,  589,  589,  589,
-      589,  589,  589,  589,  589,  590,  590,  590,  590,  590,
-      590,  590,  590,  590,  590,  591,  591,  591,  591,  591,
-      591,  591,  591,  591,  591,  593,    0,    0,  595,    0,
-      593,    0,    0,  595, 1134, 1134, 1134,    0, 1135, 1135,
-     1135,    0, 1134,  595,  593, 1134, 1135,  595,    0, 1135,
-        0,    0,    0,    0,  593,    0,    0,  595,    0,  593,
-
-        0,    0,  595,    0,    0,    0,    0,    0,    0,    0,
-        0,  595,  593,  594,  594,  595,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-      594,  594,  594,  594,  594,  594,  594,  594,  594,  594,
-
-      594,  594,  596,  597,  596,  598,  600,  596,  597,  599,
-      598,  600,    0,  599,  599,    0,    0,    0,  598,  600,
-        0,  596,  597,    0,  598,  600,    0,    0,  599,    0,
-        0,  596,  597,  596,  598,  600,  596,  597,  599,  598,
-      600,    0,  599,  599,    0,    0,  598,  600,    0,  596,
-      597,    0,  598,  600,  601,  602,  599,  603,    0,  601,
-      602,  605,  603,    0,    0,  605,  605,    0,    0,  602,
-        0,    0,    0,  601,  602,  603,  603,    0,    0,    0,
-      605,    0,    0,  601,  602,    0,  603,  606,  601,  602,
-      605,  603,  606,    0,  605,  605,    0,  602,  606,    0,
-
-        0,  601,  602,  603,  603,    0,  606,    0,  605,  609,
-      607,    0,    0,  610,  609,  607,  606,  607,  610,    0,
-      610,  606,    0,    0,    0,    0,  606,    0,  609,  607,
-        0,    0,  610,    0,  606,  619,  621,    0,  609,  607,
-      619,  621,  610,  609,  607,    0,  607,  610,    0,  610,
-        0,    0,    0,    0,  619,  621,  609,  607,  620,    0,
-      610,    0,    0,  620,  619,  621,    0,    0,    0,  619,
-      621,  620,    0,    0,  623,  622,    0,  620,  622,  623,
-      622,    0,  619,  621,    0,    0,    0,  620,  623,    0,
-        0,  624,  620,  623,  622,    0,  624,    0,    0,  620,
-
-        0,    0,  624,  623,  622,  620,    0,  622,  623,  622,
-      624,    0,  625,  625,  626,    0,  623,  625,  628,  626,
-      624,  623,  622,  628,    0,  624,    0,    0,    0,  626,
-      624,  625,    0,  626,    0,  627,    0,  628,  624,  627,
-      627,  625,  625,  626,    0,    0,  625,  628,  626,    0,
-        0,    0,  628,  629,  627,  629,    0,  626,    0,  625,
-        0,  626,    0,  632,  627,  628,    0,    0,  627,  627,
-      631,  631,  631,  631,  631,  631,  631,  631,  631,  631,
-      632,    0,  627,  633,  629,  632,  629,  634,  633,  637,
-        0,  629,  634,    0,  637,    0,    0,    0,    0,  632,
-
-      634,    0,  633,    0,    0,  629,  634,    0,  637,  632,
-        0,    0,  633,    0,  632,  629,  634,  633,  637,  638,
-      629,  634,    0,  637,  638,    0,    0,  632,  634,    0,
-      633,    0,    0,  629,  634,  639,  637,    0,  638,  641,
-      639,  641,  642,  639,  641,  642,  643,  642,  638,    0,
-        0,  643,    0,  638,  639,    0,    0,    0,  641,    0,
-        0,  642,  644,    0,  639,  643,  638,  644,  641,  639,
-      641,  642,  639,  641,  642,  643,  642,    0,    0,  644,
-      643,  644,  639,  645,    0,  646,  641,  645,  645,  642,
-      646,  644,  647,  643,  648,    0,  644,  647,    0,  648,
-
-        0,    0,  645,    0,  646,  647,    0,  644,    0,  644,
-        0,  647,  645,  648,  646,    0,  645,  645,    0,  646,
-        0,  647,    0,  648,    0,    0,  647,    0,  648,  649,
-      645,  649,  646,  647,  649,  650,    0,    0,    0,  647,
-      650,  648,    0,    0,    0,    0,  650,    0,  649,    0,
-        0,    0,    0,    0,  650,    0,    0,    0,  649,    0,
-      649,  652,    0,  649,  650,  651,  652,  651,    0,  650,
-      651,    0,  652,  653,  650,    0,  649,  653,  653,    0,
-      652,    0,  650,    0,  651,    0,    0,    0,    0,    0,
-      652,    0,  653,    0,  651,  652,  651,    0,  655,  651,
-
-      652,    0,  653,  655,    0,  654,  653,  653,  652,  656,
-      654,    0,  651,  654,  656,    0,    0,  655,    0,    0,
-      653,    0,  656,    0,  654,  657,    0,  655,  656,  657,
-      657,    0,  655,    0,  654,    0,  658,    0,  656,  654,
-        0,  658,  654,  656,  657,  655,    0,    0,  660,    0,
-      656,    0,  654,  660,  657,  658,  656,  659,  657,  657,
-        0,  659,  659,    0,    0,  658,    0,  660,  661,  662,
-      658,    0,  657,  661,  662,    0,  659,  660,    0,    0,
-        0,    0,  660,  658,    0,    0,  659,  661,  662,    0,
-      659,  659,    0,    0,  663,  660,  663,  661,  662,  663,
-
-      665,  666,  661,  662,  659,  665,  666,    0,    0,    0,
-        0,    0,    0,  663,    0,  661,  662,    0,  665,  665,
-      666,    0,    0,  663,    0,  663,  667,    0,  663,  665,
-      666,  667,    0,    0,  665,  666,    0,  668,    0,  667,
-      668,  663,  668,    0,    0,  667,  665,  665,  666,  669,
-        0,    0,    0,  672,  669,  667,  668,  671,  672,    0,
-      667,    0,  671,    0,    0,    0,  668,  667,  669,  668,
-        0,  668,  672,  667,  673,    0,  671,  671,  669,  673,
-      674,    0,  672,  669,  668,  674,  671,  672,    0,    0,
-        0,  671,    0,  673,    0,    0,  669,    0,    0,  674,
-
-      672,    0,    0,  673,  671,  671,    0,    0,  673,  674,
-        0,    0,  690,    0,  674,    0,    0,    0,  690,  695,
-        0,  673,    0,  695,  695,    0,  690,  674,  690,  690,
-      690,  690,  690,  690,  690,  690,  690,  690,  695,  696,
-      698,  699,    0,    0,  696,  698,  699,  696,  695,    0,
-        0,  698,  695,  695,    0,    0,    0,    0,  696,  698,
-      699,    0,    0,    0,    0,    0,  695,    0,  696,  698,
-      699,    0,  709,  696,  698,  699,  696,    0,    0,  698,
-        0,    0,  710,    0,    0,    0,  696,  698,  699,  709,
-      709,  709,  709,  709,  709,  709,  709,  709,  709,  710,
-
-      710,  710,  710,  710,  710,  710,  710,  710,  710,  711,
-        0,    0,    0,    0,    0,    0,    0,    0,    0,  712,
-        0,    0,    0,    0,    0,    0,  711,  711,  711,  711,
-      711,  711,  711,  711,  711,  711,  712,  712,  712,  712,
-      712,  712,  712,  712,  712,  712,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  715,  715,  715,  715,  715,
-      715,  715,  715,  715,  715,  719,  719,  719,    0,    0,
-      719,  719,    0,  719,    0,    0,    0,  719,  719,    0,
-        0,  719,    0,    0,  719,  719,  719,  719,  719,  719,
-      719,  719,  719,  732,  732,    0,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  732,  732,  732,  732,  732,  732,  732,  732,
-      732,  732,  733,    0,    0,  735,    0,  733,  734,  734,
-      734,  734,  734,  734,  734,  734,  734,  734,  736,  737,
-        0,  733,  735,  736,  737,  738,    0,  735,    0,    0,
-      738,  733,    0,    0,    0,    0,  733,  736,  737,    0,
-        0,  735,    0,    0,  738,  739,    0,  736,  737,  733,
-
-      739,  735,  736,  737,  738,    0,  735,  740,    0,  738,
-        0,    0,  740,    0,  739,  736,  737,    0,  741,  735,
-        0,    0,  738,  741,  739,    0,  740,    0,    0,  739,
-      740,    0,    0,    0,    0,    0,  740,  741,  741,    0,
-        0,  740,  739,  742,    0,  742,    0,  741,  742,    0,
-      747,  743,  741,    0,  740,  747,  743,    0,  740,  743,
-        0,  745,  742,  745,    0,  741,  741,    0,    0,  747,
-      743,    0,  742,  750,  742,    0,    0,  742,  750,  747,
-      743,    0,  746,    0,  747,  743,  746,  746,  743,    0,
-      742,    0,  750,    0,  745,    0,  745,  747,  743,  745,
-
-        0,  746,  750,    0,    0,    0,    0,  750,    0,  745,
-        0,  746,    0,  745,  751,  746,  746,    0,  751,  751,
-      750,    0,    0,  745,    0,  745,  762,    0,  745,  746,
-        0,  762,    0,  751,  761,    0,  761,  745,    0,  761,
-        0,  745,    0,  751,    0,  762,  762,  751,  751,    0,
-        0,  763,    0,  761,    0,  762,  763,  763,    0,    0,
-      762,  751,    0,  761,    0,  761,    0,    0,  761,    0,
-      763,  764,  765,  762,  762,  764,  764,  765,  766,    0,
-      763,  761,  766,  766,    0,  763,  763,    0,    0,  765,
-      764,  765,    0,    0,  771,    0,    0,  766,  763,  771,
-
-      764,  765,    0,  767,  764,  764,  765,  766,  767,    0,
-      768,  766,  766,  771,  772,  768,  772,  765,  764,  765,
-      767,  768,  767,  771,  772,  766,  773,    0,  771,  768,
-        0,  773,  767,    0,    0,    0,    0,  767,    0,  768,
-      773,  771,    0,    0,  768,  773,  774,  772,  767,  768,
-      767,  774,  772,    0,  774,  773,    0,  768,  775,    0,
-      773,    0,  775,  775,    0,  774,  772,  776,  773,  778,
-        0,  776,  776,  773,  778,  774,  772,  775,    0,    0,
-      774,  772,    0,  774,    0,    0,  776,  775,  778,    0,
-      777,  775,  775,  774,  772,  777,  776,    0,  778,  779,
-
-      776,  776,    0,  778,  779,  775,    0,  777,    0,  777,
-      780,    0,    0,    0,  776,  780,  778,  779,  779,  777,
-        0,  780,  781,    0,  777,    0,    0,  781,  779,  780,
-        0,  782,    0,  779,    0,  777,  782,  777,    0,  780,
-        0,  781,  783,  784,  780,  779,  779,  783,  784,  780,
-      782,  781,    0,  785,    0,  785,  781,  780,    0,    0,
-      782,  783,  784,  786,    0,  782,    0,    0,  786,  781,
-        0,  783,  784,    0,  787,    0,  783,  784,  782,  787,
-        0,  786,  786,  788,    0,    0,  785,    0,  788,  783,
-      784,  785,  786,  787,  789,    0,    0,  786,  787,  789,
-
-        0,  785,  788,  787,    0,  785,    0,    0,  787,  786,
-      786,    0,  788,  789,    0,  785,    0,  788,    0,  790,
-      785,  787,    0,  789,  790,    0,  787,  791,  789,  785,
-      788,  791,  791,  785,    0,    0,  790,    0,  790,  792,
-        0,  789,    0,    0,  792,    0,  791,    0,  790,    0,
-        0,  792,    0,  790,    0,    0,  791,    0,  792,    0,
-      791,  791,  793,    0,  790,    0,  790,  793,  792,    0,
-      795,  796,    0,  792,  791,  795,  796,    0,  795,  792,
-        0,  793,  797,    0,    0,    0,  792,  797,    0,  795,
-      796,  793,    0,  798,    0,  799,  793,  799,  798,  795,
-
-      796,  797,    0,    0,  795,  796,    0,  795,    0,  793,
-        0,  797,  798,    0,    0,    0,  797,  795,  796,  800,
-      801,    0,  798,    0,  800,  801,  816,  798,  799,  797,
-      799,  816,    0,  799,    0,    0,    0,    0,  800,  801,
-      798,    0,    0,    0,    0,  816,    0,  799,  800,  801,
-        0,  817,    0,  800,  801,  816,  817,  799,    0,  799,
-      816,    0,  799,    0,  817,    0,  800,  801,    0,  818,
-      817,  818,    0,  816,  842,  799,  802,  802,  802,  802,
-      817,    0,    0,    0,    0,  817,    0,    0,    0,    0,
-      819,  842,  817,    0,    0,  819,  842,    0,  817,    0,
-
-        0,    0,  818,    0,    0,    0,    0,  818,    0,  819,
-      842,  802,  802,    0,    0,  802,    0,  802,    0,  819,
-      842,  818,    0,    0,  819,  842,    0,    0,  802,  802,
-        0,  818,    0,    0,    0,    0,  818,  819,  842,    0,
-      802,  802,    0,    0,  802,    0,  802,    0,    0,  818,
-        0,    0,    0,    0,    0,    0,  802,  802,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
-      827,  827,  827,  827,  827,  827,  827,  828,  841,  841,
-      841,  841,  841,  841,  841,  841,  841,  841,    0,    0,
-        0,    0,    0,    0,  828,  828,  828,  828,  828,  828,
-      828,  828,  828,  828,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  829,  829,  829,  829,  829,  829,  829,
-      829,  829,  829,  843,    0,  844,    0,  847,  843,  844,
-      844,  845,  847,  845,  846,    0,  845,    0,  846,  846,
-        0,    0,  843,    0,  844,    0,  847,    0,    0,    0,
-      845,    0,  843,  846,  844,    0,  847,  843,  844,  844,
-
-      845,  847,  845,  846,  849,  845,    0,  846,  846,  849,
-      843,  848,  844,    0,  847,  848,  848,    0,  845,    0,
-      850,  846,    0,  849,    0,  850,    0,  853,    0,    0,
-      848,  854,  853,  849,  850,    0,  854,    0,  849,  850,
-      848,  853,    0,    0,  848,  848,  853,    0,  854,  850,
-      854,  849,  855,    0,  850,    0,  853,  855,  848,    0,
-      854,  853,  850,  858,    0,  854,    0,  850,  858,  853,
-        0,  855,  866,    0,  853,    0,  854,  866,  854,    0,
-      858,  855,  858,  867,    0,    0,  855,    0,  867,    0,
-        0,  866,  858,    0,  867,    0,    0,  858,    0,  855,
-
-        0,  866,  867,    0,  868,    0,  866,    0,  858,  868,
-      858,    0,  867,  869,    0,  869,    0,  867,  869,  866,
-        0,  868,  867,  868,    0,    0,    0,    0,    0,  870,
-      867,    0,  869,  868,  870,  871,    0,    0,  868,    0,
-      871,    0,  869,  870,  869,    0,    0,  869,  870,  868,
-        0,  868,    0,    0,  871,    0,    0,    0,  870,    0,
-      869,  872,    0,  870,  871,  872,  872,    0,  873,  871,
-      874,  870,  873,  873,    0,  874,  870,    0,    0,    0,
-      872,  874,  871,    0,    0,    0,    0,  873,    0,  874,
-      872,  878,    0,  877,  872,  872,  878,  873,  877,  874,
-
-        0,  873,  873,    0,  874,    0,  877,    0,  872,  874,
-      878,    0,  877,  879,  880,  873,  881,  874,  879,  880,
-      878,  881,  877,    0,    0,  878,    0,  877,    0,    0,
-        0,    0,  879,  880,  877,  881,  882,    0,  878,    0,
-      877,  882,  879,  880,  882,  881,    0,  879,  880,    0,
-      881,    0,  883,  886,    0,  882,    0,  883,  886,  885,
-      879,  880,    0,  881,  885,  882,    0,    0,    0,    0,
-      882,  883,  886,  882,    0,    0,  885,    0,  885,  887,
-        0,  883,  886,  882,  887,    0,  883,  886,  885,    0,
-      888,  890,    0,  885,    0,  888,  890,    0,  887,  883,
-
-      886,  888,  891,    0,  885,    0,  885,  891,  887,  888,
-      890,  889,    0,  887,    0,  889,  889,    0,    0,  888,
-      890,  891,  892,  897,  888,  890,  887,  892,  897,  888,
-      889,  891,    0,    0,  895,    0,  891,  888,  890,  895,
-      889,  892,  897,  906,  889,  889,    0,    0,  906,  891,
-        0,  892,  897,  895,    0,  895,  892,  897,  889,  898,
-        0,    0,  906,  895,  898,    0,  907,  898,  895,  892,
-      897,  907,  906,    0,    0,    0,    0,  906,  898,    0,
-        0,  895,    0,  895,  907,  907,    0,    0,  898,  909,
-      906,  909,    0,  898,  909,  907,  898,    0,    0,    0,
-
-      907,    0,    0,    0,    0,    0,  898,  914,  909,    0,
-        0,    0,  907,  907,    0,    0,  917,  917,  909,    0,
-      909,  917,    0,  909,  914,  914,  914,  914,  914,  914,
-      914,  914,  914,  914,    0,  917,  909,  918,    0,  919,
-        0,    0,  918,  919,  919,  917,  917,    0,  920,    0,
-      917,    0,    0,  920,    0,    0,  918,    0,  919,    0,
-        0,    0,    0,  917,    0,  920,  918,  920,  919,  921,
-      922,  918,  919,  919,  921,  922,    0,  920,  923,    0,
-        0,    0,  920,  923,  918,    0,  919,    0,  921,  922,
-        0,  923,    0,  920,    0,  920,    0,  923,  921,  922,
-
-        0,  927,    0,  921,  922,  928,  927,  923,    0,  928,
-      928,    0,  923,  927,    0,    0,  921,  922,    0,  923,
-      927,  938,    0,    0,  928,  923,  938,  930,  940,  938,
-      927,  930,  930,  940,  928,  927,    0,    0,  928,  928,
-      938,  927,    0,    0,    0,    0,  930,  940,  927,    0,
-      938,    0,  928,    0,    0,  938,  930,  940,  938,  939,
-      930,  930,  940,  939,  939,  941,  942,    0,  938,    0,
-      941,  942,    0,    0,  930,  940,    0,    0,  939,    0,
-        0,    0,  943,    0,  941,  942,  942,  943,  939,    0,
-        0,  944,  939,  939,  941,  942,  944,    0,    0,  941,
-
-      942,  943,  945,    0,  944,    0,  939,  945,    0,    0,
-      944,  943,  941,  942,  942,    0,  943,    0,  951,    0,
-      944,  945,  952,  951,    0,  944,    0,  952,    0,  943,
-        0,  945,  944,    0,    0,    0,  945,  951,  944,  955,
-        0,  952,    0,  953,  955,  953,    0,  951,  953,  945,
-        0,  952,  951,  955,    0,    0,  952,    0,  955,  956,
-        0,    0,  953,    0,  956,  951,  957,    0,  955,  952,
-      958,  957,  953,  955,  953,  958,    0,  953,  956,    0,
-        0,  955,    0,    0,    0,  957,  955,  958,  956,  958,
-      953,    0,  960,  956,    0,  957,  960,  960,    0,  958,
-
-      957,    0,    0,  963,  958,    0,  956,    0,  963,  962,
-        0,  960,    0,  957,  962,  958,  963,  958,    0,    0,
-        0,  960,  963,    0,    0,  960,  960,  962,  962,  969,
-        0,    0,  963,    0,  969,  970,    0,  963,  962,  960,
-      970,  971,    0,  962,  963,  971,  971,    0,  969,  969,
-      963,    0,  976,    0,  970,  962,  962,  976,  969,    0,
-      971,  975,    0,  969,  970,    0,  975,    0,  977,  970,
-      971,  976,  975,  977,  971,  971,  969,  969,    0,    0,
-      975,  976,  970,    0,  979,    0,  976,  977,  971,  979,
-      975,    0,    0,  985,    0,  975,    0,  977,  985,  976,
-
-      975,  978,  977,  979,  982,  978,  978,    0,  975,  982,
-        0,    0,  985,  979,    0,  977,    0,    0,  979,  982,
-      978,    0,  985,  982,  983,    0,  983,  985,    0,  983,
-      978,  979,    0,  982,  978,  978,    0,    0,  982,    0,
-      985,  993,    0,  983,  994,  992,  993,  982,  978,  994,
-      992,  982,    0,  983,    0,  983,  994,    0,  983,  992,
-      993,  995,    0,  994,  992,    0,  995,  996,    0,    0,
-      993,  983,  996,  994,  992,  993,    0,    0,  994,  992,
-      995,    0,    0,    0,  994,    0,  996,  992,  993,    0,
-      995,  994,  992, 1004,    0,  995,  996,  997, 1004,  997,
-
-     1007,  996,  997,    0, 1006, 1007, 1006,    0,  995, 1006,
-        0,    0, 1004,    0,  996,    0,  997,    0,    0, 1007,
-     1009,    0, 1004, 1006,    0, 1009,  997, 1004,  997, 1007,
-        0,  997,    0, 1006, 1007, 1006,    0, 1011, 1006, 1009,
-     1004, 1011, 1011,    0,  997,    0,    0, 1007,    0, 1009,
-        0, 1006,    0, 1012, 1009,    0, 1011, 1012, 1012,    0,
-     1020,    0,    0,    0, 1019, 1020, 1011, 1009,    0, 1019,
-     1011, 1011, 1012,    0,    0, 1019, 1025,    0,    0, 1020,
-     1025, 1025, 1012, 1019, 1011, 1026, 1012, 1012,    0, 1020,
-     1026,    0,    0, 1019, 1020, 1025,    0, 1029, 1019,    0,
-
-     1012,    0, 1029, 1019, 1026, 1025,    0, 1020, 1029, 1025,
-     1025, 1019,    0,    0, 1026,    0, 1029,    0,    0, 1026,
-     1030,    0, 1037, 1025, 1038, 1030, 1029, 1037, 1030, 1038,
-        0, 1029, 1026,    0,    0, 1037, 1029,    0,    0, 1030,
-        0, 1037,    0, 1038, 1029,    0,    0, 1039,    0, 1030,
-        0, 1037, 1039, 1038, 1030, 1039, 1037, 1030, 1038, 1047,
-        0,    0,    0, 1037, 1047,    0, 1039, 1030, 1040, 1037,
-     1044, 1038, 1040, 1040, 1044, 1044, 1039,    0, 1047,    0,
-        0, 1039,    0,    0, 1039,    0,    0, 1040, 1047, 1044,
-     1048, 1054,    0, 1047, 1039, 1048, 1054, 1040,    0, 1044,
-
-        0, 1040, 1040, 1044, 1044,    0, 1047, 1059,    0, 1048,
-     1054,    0, 1059,    0,    0, 1040, 1063, 1044,    0, 1048,
-     1054, 1063,    0, 1062, 1048, 1054, 1059, 1062, 1062,    0,
-        0,    0,    0,    0, 1063, 1063, 1059, 1048, 1054, 1067,
-        0, 1059, 1062,    0, 1067, 1063, 1068,    0, 1069,    0,
-     1063, 1068, 1062, 1069, 1059,    0, 1062, 1062, 1067, 1068,
-        0,    0, 1063, 1063,    0, 1068,    0, 1069, 1067, 1073,
-     1062, 1080, 1073, 1067, 1073, 1068, 1080, 1069,    0,    0,
-     1068,    0, 1069,    0,    0,    0, 1067, 1068, 1073,    0,
-     1080, 1087,    0, 1068, 1088, 1069, 1087,    0, 1073, 1088,
-
-     1080, 1073, 1088, 1073,    0, 1080,    0,    0,    0,    0,
-     1087,    0,    0, 1088, 1087,    0, 1073, 1091, 1080,    0,
-     1087, 1091, 1091, 1088, 1095, 1087,    0,    0, 1088, 1095,
-        0, 1088,    0,    0,    0,    0, 1091,    0, 1087,    0,
-     1105, 1088, 1087, 1095, 1095, 1105, 1091, 1106,    0, 1108,
-     1091, 1091, 1106, 1095, 1108,    0,    0,    0, 1095, 1105,
-        0, 1106,    0,    0, 1091,    0, 1106,    0, 1108, 1105,
-        0, 1095, 1095,    0, 1105,    0, 1106,    0, 1108,    0,
-        0, 1106,    0, 1108,    0,    0,    0, 1105,    0, 1106,
-        0,    0,    0,    0, 1106,    0, 1108, 1109, 1109, 1109,
-
-        0,    0, 1109, 1109,    0, 1109,    0,    0,    0, 1109,
-     1109,    0,    0, 1109,    0,    0, 1109, 1109, 1109, 1109,
-     1109, 1109, 1109, 1109, 1109, 1112, 1122,    0,    0,    0,
-     1112, 1122,    0,    0,    0,    0,    0,    0,    0, 1122,
-        0,    0, 1112,    0, 1112, 1122,    0,    0,    0,    0,
-        0,    0,    0,    0, 1112, 1122,    0,    0,    0, 1112,
-     1122,    0,    0,    0,    0,    0,    0, 1122,    0,    0,
-     1112,    0, 1112, 1122, 1126, 1126, 1126,    0,    0, 1126,
-     1126,    0, 1126,    0, 1128, 1126, 1126, 1126, 1128, 1128,
-     1126,    0,    0, 1126, 1126, 1126, 1126, 1126, 1126, 1126,
-
-     1126, 1126,    0, 1128, 1133, 1137,    0,    0,    0, 1133,
-     1137,    0,    0, 1128,    0,    0,    0, 1128, 1128,    0,
-        0,    0,    0, 1133, 1137,    0,    0,    0,    0,    0,
-        0, 1128,    0, 1133, 1137,    0,    0,    0, 1133, 1137,
+      217,  217,  217,  217,  217,  217,  217,  217,  220,  219,
+      227,  228,  230,  248,  245,  229,  254,  255,  217,  217,
+
+      217,  217,  217,  219,  237,  220,  232,  232,  232,  256,
+      257,  237,  237,  259,  232,  232,    0,  220,  219,  228,
+      230,  248,  245,    0,  254,  255,  233,  233,  233,  217,
+      217,  219,    0,  220,  233,  233,  236,  256,  257,    0,
+      238,  259,  238,  236,  236,  238,  238,  238,  238,  238,
+      238,  238,  238,  238,  238,  260,  237,  217,  218,  218,
+      218,  218,  218,  218,  218,  218,  218,  218,  218,  218,
+      218,  218,  218,  218,  218,  218,  218,  261,  262,  236,
+      378,  378,  378,  260,  237,    0,    0,  218,  218,  218,
+      218,  218,  218,  251,  251,  251,  251,  251,  251,  251,
+
+      251,  251,  251,  263,  264,  261,  262,  236,  252,  252,
+      252,  252,  252,  252,  252,  252,  252,  252,  218,  218,
+      253,  218,  253,  547,  547,  547,    0,    0,  266,  267,
+      253,  263,  264,  265,  268,  269,  265,    0,  270,  271,
+      272,  273,  274,    0,    0,  266,  218,  250,  250,  250,
+      250,  250,  250,  250,  250,  250,  250,  266,  267,  277,
+      281,  265,  268,  269,  265,  250,  250,  270,  271,  272,
+      273,  274,  276,  266,  276,  282,  283,  278,  250,  278,
+        0,    0,  279,  279,  284,  285,  286,  285,  277,  281,
+      287,    0,  289,  290,  250,  250,  291,  292,  288,  293,
+
+      288,  295,    0,  276,  282,  283,  250,  275,  278,  275,
+      279,  279,  284,  294,  286,  299,  285,    0,  298,  287,
+      289,  290,    0,  300,  291,  292,  294,  293,  302,    0,
+      295,  296,  301,  296,  301,    0,  303,  297,  275,  297,
+      304,  296,  294,  275,  299,  275,  298,  297,  275,    0,
+      288,  300,  275,  306,  294,  275,  305,  302,  275,  275,
+      308,    0,  275,  301,  303,  309,  310,  312,  304,  313,
+      315,  311,  275,  316,  275,  296,  317,  275,  288,  311,
+      275,  297,  306,  275,  305,  296,  275,  275,  318,  308,
+      275,  297,  314,  309,  310,  319,  312,  313,  315,  311,
+
+      314,  316,  320,  296,  317,  321,  322,  311,  323,  297,
+      324,  325,  326,  296,  328,  329,  327,  318,  327,  297,
+      330,  314,  331,  332,  319,  333,  327,  334,  314,  335,
+      339,  320,  341,  321,  342,  322,  323,  343,  324,  325,
+      326,  344,  345,  328,  329,  346,  347,  352,  330,    0,
+      331,  332,    0,  333,  351,  334,  363,  335,  339,  348,
+      341,  348,  342,  353,    0,  343,  355,  356,  358,  344,
+      345,  357,  359,  346,  376,  347,  369,  348,  348,  348,
+      348,  348,  348,  348,  348,  348,  348,  349,  357,  869,
+      352,  361,  351,  349,  363,  355,  356,  358,  371,    0,
+
+      357,  359,  376,  349,  349,  349,  349,  349,  349,  349,
+      349,  349,  349,  350,  368,  353,  357,  370,  352,  350,
+      361,  351,  377,  363,  379,  383,    0,  371,  369,  350,
+      350,  350,  350,  350,  350,  350,  350,  350,  350, 1005,
+        0,  360,  372,  353,  354,  364,  364,  364,  381,  869,
+      354,  377,  379,  372,  360,  370,  369,  368,  354,  373,
+      354,  354,  354,  354,  354,  354,  354,  354,  354,  354,
+      360,  372,  374,  380,  384,  383,  382,  373,  354,  354,
+        0,  372,  360,  375,  370,  368,  364,  406,  373,  385,
+      398,  354,  374,  405,  375,  381,  385,  385,  653, 1005,
+
+      653,  374,  380,  383,    0,  373,  386,  354,  354,  382,
+      384,    0,  375,  386,  386,  364,  406,  387,  398,  354,
+      374,  405,  375,  381,  387,  387,  388,  388,  388,  388,
+      388,  388,  388,  388,  388,  388,  408,  410,  382,  384,
+      389,  389,  389,  389,  389,  389,  389,  389,  389,  389,
+      402,  411,  402,  387,  413,    0,  386,  414,    0,  415,
+      402,  416,  417,  418,  420,  408,  410,  421,  422,  423,
+      424,  425,  426,  429,  426,  430,  431,    0,  432,  411,
+      433,  435,  387,  413,  386,  436,  414,  415,  434,  416,
+      417,  439,  418,  420,  442,  421,  422,  423,  424,  425,
+
+      437,  429,  437,  430,  434,  431,  432,  444,  433,  435,
+      440,  446,  440,  426,  436,  447,  445,  434,  445,  439,
+      450,  448,  442,  448, 1009,  451,  452,  426,  454,    0,
+      457,  437,  434,  455,  456,  444,  458,  459,  460,  446,
+      464,  440,  426,  458,  447,  463,  468,  445,  467,  450,
+        0,  469,  448,  451,  452,  426,  427,  454,  427,  457,
+      470,  455,  456,    0,  480,  458,  459,  460,  461,  464,
+      461,  458,  465,  463,  465,  468,  467,  478,  461,  469,
+      483,  472,  465,  472, 1009,  479,  481,  427,  470,  482,
+      484,  475,  427,  480,  427,  485,  493,  427,  503,  475,
+
+      488,  427,    0,  489,  427,  478,  490,  427,  427,  483,
+      491,  427,  472,  479,  481,    0,    0,  482,  484,    0,
+      506,  427,  506,  427,  485,  493,  427,  503,  488,  427,
+      475,  489,  427,  499,  490,  427,  427,    0,  491,  427,
+      443,  443,  443,  443,  443,  443,  443,  443,  443,  443,
+      443,  506,  443,  443,  443,  443,  443,  443,  443,  475,
+      507,  499,  508,  509,  494,  500,  494,  500,  513,  443,
+      443,  443,  443,  443,  494,  500,  514,  515,  516,  517,
+      518,  523,  524,  655,  535,  655,  525,    0,  667,  507,
+      667,  508,  509,  520,  529,  520,  527,  513,  563, 1031,
+
+      443,  443,  529,  540,  514,  531,  515,  516,  517,  518,
+      537,  520,  520,  520,  520,  520,  520,  520,  520,  520,
+      520,  521,  525,  529,  527,  545,  563,  521,  443,  565,
+      523,  529,  524,  535,  531,    0,    0,  521,  521,  521,
+      521,  521,  521,  521,  521,  521,  521,  522,    0,  538,
+      539,  525,  540,  522,  545,  537,  568,  565,  523, 1031,
+      524,  535,    0,  522,  522,  522,  522,  522,  522,  522,
+      522,  522,  522,  526,  532,  536,  536,  536,    0,  526,
+      540,  532,  548,  537,  568,  532,  539,  526,  541,  526,
+      526,  526,  526,  526,  526,  526,  526,  526,  526,  538,
+
+      533,    0,  533,  532,  552,  550,  541,  526,  526,  532,
+      533,  548,  561,  532,  533,  539,  536,  541,  542,    0,
+      526,  543,  542,  554,  544,  543,  562,  538,  544,  566,
+      554,  554,  569,  576,  541,  555,  526,  526,  550,  577,
+      552,  561,  555,  555,  570,  536,  571,  542,  526,  573,
+      543,  542,  574,  544,  543,  562,  575,  544,  566,  554,
+        0,  569,  576,  581,  659,  659,  659,  550,  577,  552,
+        0,  578,  570,  578,  571,    0,  641,  573,  641,  579,
+      574,  580,    0,  582,  575,  583,  641,  584,  554,  564,
+      564,  581,  564,  564,  564,  564,  564,  564,  564,  564,
+
+      564,  564,  564,  564,  564,  564,  564,  564,  579,  585,
+      580,  582,  578,  586,  583,  584,  587,  588,  564,  564,
+      564,  564,  564,  590,  592,    0,  578,  593,  594,  586,
+      595,    0,  596,  597,  598,  608,  599,  585,  599,    0,
+      602,  578,  586,  603,  587,  603,  588,  607,  613,  564,
+      564,  590,  610,  592,  578,  593,  594,  586,  611,  595,
+      596,  614,  597,  598,  608,  615,  616,  599,  602,  617,
+      618,    0,  619,  620,  603,  607,  613,  564,  621,  622,
+      623,  610,  626,    0,  627,  628,  630,  611,  632,  633,
+      614,  634,  639,  615,  616,  636,  637,  638,  617,  618,
+
+      619,  640,  620,  644,  645,  646,  621,  646,  622,  623,
+      654,  626,  627,  656,  628,  630,  632,  657,  633,  662,
+      634,  639,  663,  636,  637,  638,  666,  668,  669,  640,
+      669,  644,  645,  658,  670,  658,  646,  671,  672,  654,
+      672,  676,  656,  658,  681,  657,  675,  658,  672,  674,
+      683,  674,  672,  679,  677,  666,  668,  700,  663,  662,
+      694,    0,  670,  674,  695,  680,  671,  694,  694,  680,
+      696,  695,  695,  681,  701,  703,    0,  696,  696,  683,
+      771,  738,  771,  738, 1082,  700,  675,  663,  662,  665,
+      677,  738,  676,  679,  680,  665,    0,  704,  680,  706,
+
+      707,  708,  701,  665,  703,  665,  665,  665,  665,  665,
+      665,  665,  665,  665,  665,  675,  709,    0,  710,  677,
+      676,  711,  679,  665,  665,  704,  714,  706,  707,  708,
+      715,  717,    0,  719,  721,    0,  665,  762,    0,  762,
+      770,  781,  770,  781, 1082,  709,  710,  762,  770,  858,
+      711,  858,  665,  665,  712,  714,  712,  722,  723,  715,
+      717,  719,  724,  721,  665,  682,  682,  682,  682,  682,
+      682,  682,  682,  682,  682,  682,  682,  682,  682,  682,
+      682,  682,  682,  682,  725,  722,  723,  726,  727,  712,
+      729,  724,  728,  730,  682,  682,  682,  682,  682,  731,
+
+      732,    0,  712,  733,  734,  735,  737,  735, 1084,  739,
+      740,  741,  725,  742,    0,  743,  726,  727,  712,  729,
+      728,  745,  730,  746,  752,  682,  682,  731,  756,  732,
+      712,  733,  734,    0,    0,  737,  735,  739,    0,  740,
+      741,  755,  742,  743,  757,  775,  775,  775,  833,  745,
+      833,  746,  752,  682,  686,  686,  686,  756,  833,  686,
+      686,  751,  686,  751,    0,    0,  686,  686, 1084,  755,
+      686,    0,  757,  686,  686,  686,  686,  686,  686,  686,
+      686,  686,  699,  699,  776,  699,  699,  699,  699,  699,
+      699,  699,  699,  699,  699,  699,  699,  699,  699,  699,
+
+      699,  758,  759,  783,  760,  763,    0,  768,  773,  751,
+      772,  699,  699,  699,  699,  699,  767,  774,  767,  779,
+      782,  776,  784,  787,  780,  789,  791,  791,  791,  758,
+      802,  759,  760,  810,  763,  768,  773,  751,  803,  772,
+      783,    0,  699,  699,  804,  806,  774,  807,  779,  782,
+      776,  767,  780,  808,  789,  797,  812,  798,  784,  802,
+      787,  810,  797,  797,  798,  798,  864,  803,  864,  783,
+      699,    0,    0,  804,  806,    0,  807,  811,    0,  811,
+      767,  801,  808,  813,  812,  801,  815,  784,  816,  787,
+      788,  788,  788,  788,  788,  788,  788,  788,  788,  788,
+
+      788,  788,  788,  788,  788,  788,  788,  788,  788,  817,
+      801,  813,  811,  819,  801,  815,  816,  818,  820,  788,
+      788,  788,  788,  788,  821,  811,  822,    0,  823,  824,
+      825,  826,  827,    0,  828,  830,  831,  840,  817,  832,
+     1085,  811,  819,  835,  836,  818,  842,  820,  842,  843,
+      788,  788,  821,  811,  844,  822,  823,  824,  825,  826,
+      846,  827,  828,  847,  830,  831,  840,  832,  834,  834,
+      834,  835,  836,  851,  852,  851,  834,  843,  788,  834,
+      853,  855,  844,  851,  854,  856,  854,  857,  846,  859,
+      867,  865,  847,  863,  842,  870,  871,    0,  873,  874,
+
+     1085,  875,  876,  852,  878,  879,  880,  881,  853,  882,
+      855,  883,    0,  884,  856,  857,  885,  889,  859,  854,
+      865,  863,  842,  886,  870,  871,  873,  887,  874,  875,
+      876,  888,  878,  879,  880,  881,  890,  882,  896,  867,
+      883,  884,  892,  893,  894,  885,  889,  895,  854,  897,
+      899,  886,  901,  901,  901,  887,  903,  903,  903,  888,
+      901,  909,    0,  901,  890,  910,  896,  867,    0,  908,
+      915,  892,  893,  894,  913,  916,  895,  897,  899,  902,
+      902,  902,  917,  904,  904,  904,  918,  902,  919,  909,
+      902,  904,  920,  910,  904,  905,  905,  905,  908,  915,
+
+      921,  922,  913,  905,  916,  924,  905,  925,  926,  927,
+      917,  928,  929,  932,  918,    0,  919,  933,    0,  935,
+      936,  920,  937,  938,  939,  941,  940,  942,  940,  943,
+      922,  944,  945,  947,  924,  921,  940,  949,  951,  928,
+      929,  932,  952,  925,  927,  926,  933,  935,    0,  936,
+      937,    0,  938,  939,  941,  961,  942,  960,  943,  944,
+      945,  947,    0,    0,  921,  949,  951,  953,  953,  953,
+      965,  952,  925,  927,  926,  954,  954,  954,  970,  955,
+      955,  955,  963,  954,  961,  960,  954,  955,  966,  973,
+      955,  956,  956,  956,  967,  957,  957,  957,  965,  956,
+
+      969,  975,  956,  957,  971,  974,  957,  958,  958,  958,
+      976,  963,  977,  980,  977,  958,  981,  966,  958,    0,
+      982,  983,  977,  967,  970,  984,  985,  984,  985,  969,
+      987,  989,  971,  991,  973,  984,  985,  974,  994,  976,
+      992,  980,  995, 1008, 1007,  981,    0,  975,  982,  998,
+      983,    0,  970,  996,  996,  996,  999, 1001,  987,  989,
+     1013,  991,  973, 1016, 1014, 1015,  974,  994,  992, 1017,
+     1019,  995,  997,  997,  997,  975, 1021, 1008,  998, 1007,
+      997, 1032, 1011,  997, 1011,  999, 1001, 1012, 1013, 1012,
+     1025, 1016, 1011, 1014, 1015, 1026, 1029, 1017, 1027, 1019,
+
+     1012, 1030, 1012, 1033, 1021, 1037, 1008, 1036, 1007, 1023,
+     1023, 1023, 1024, 1024, 1024,    0, 1038, 1032, 1012, 1025,
+     1024, 1039, 1042, 1024, 1026, 1034, 1027, 1034, 1045, 1030,
+     1041, 1048, 1035, 1037, 1035, 1052, 1036, 1046, 1034, 1050,
+     1034, 1029, 1056, 1035, 1038, 1035, 1032, 1035, 1033, 1059,
+     1039, 1042, 1043, 1043, 1043, 1049, 1034, 1045, 1041, 1044,
+     1044, 1044, 1053, 1035, 1053, 1046, 1055, 1044, 1058, 1029,
+     1044, 1056, 1063, 1053, 1050, 1068, 1033, 1048, 1059, 1064,
+     1065, 1052,    0, 1049, 1062, 1062, 1062, 1066, 1071, 1067,
+        0, 1073, 1062,    0, 1055, 1062, 1058, 1074,    0, 1079,
+
+     1063, 1099, 1109, 1050, 1093, 1048,    0, 1064, 1065, 1052,
+     1061, 1061, 1061, 1095,    0, 1061, 1061, 1067, 1061, 1073,
+     1086, 1068, 1061, 1061, 1080, 1074, 1061, 1079, 1090, 1061,
+     1061, 1061, 1061, 1061, 1061, 1061, 1061, 1061, 1066, 1071,
+     1076, 1076, 1076, 1077, 1077, 1077,    0, 1094, 1086, 1068,
+     1099, 1077, 1096, 1080, 1077, 1093, 1104, 1090, 1095, 1101,
+     1102, 1105, 1109,    0, 1111,    0, 1066, 1071, 1078, 1078,
+     1078, 1100, 1113, 1078, 1078, 1094, 1078, 1103, 1099, 1078,
+     1078, 1078, 1106, 1093, 1078, 1104, 1095, 1078, 1078, 1078,
+     1078, 1078, 1078, 1078, 1078, 1078, 1088, 1088, 1088, 1100,
+
+     1089, 1089, 1089, 1096, 1088, 1101, 1107, 1088, 1089, 1102,
+     1108, 1089, 1105, 1103, 1110, 1111, 1112, 1114, 1106, 1115,
+     1115, 1115, 1117, 1113, 1116, 1116, 1116, 1118, 1118, 1118,
+     1123, 1096, 1126, 1101, 1119, 1119, 1119, 1102, 1107, 1108,
+     1105, 1127, 1103, 1111, 1112,    0, 1110, 1106, 1121, 1121,
+     1121, 1113, 1124, 1124, 1124, 1128, 1128, 1128, 1129, 1129,
+     1129,    0,    0,    0, 1126,    0, 1123, 1107, 1114,    0,
+        0, 1117,    0,    0,    0, 1110,    0,    0,    0,    0,
         0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-        0, 1133, 1137, 1162, 1162, 1162, 1162, 1162, 1162, 1162,
-     1162, 1162, 1162, 1162, 1162, 1163, 1163, 1163, 1163, 1163,
-     1163, 1163, 1163, 1163, 1163, 1163, 1163, 1164, 1164,    0,
-     1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1165,
-     1165,    0, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165,
-
-     1165, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166,
-     1166, 1166, 1166, 1167, 1167, 1167, 1167, 1167, 1167, 1167,
-     1167, 1167, 1167, 1167, 1167, 1168, 1168, 1169, 1169, 1169,
-     1169, 1169, 1169, 1169, 1169, 1170, 1170, 1170, 1170, 1170,
-     1170, 1170, 1170, 1170, 1170, 1170, 1170, 1171, 1171, 1171,
-     1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1172,
-     1172, 1172, 1172, 1172, 1172,    0, 1172, 1172, 1172,    0,
-     1172, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173,
-     1173, 1173, 1173, 1174,    0,    0, 1174, 1175, 1175, 1175,
-        0,    0, 1175,    0, 1175, 1175,    0, 1175, 1175, 1176,
-
-     1176, 1176, 1176, 1176, 1176, 1176, 1176, 1176, 1176, 1176,
-     1176, 1177, 1177,    0, 1177, 1177, 1177, 1177, 1177, 1177,
-     1177, 1177, 1177, 1178, 1178, 1178, 1178, 1178, 1178,    0,
-     1178, 1178, 1178,    0, 1178, 1179, 1179, 1179, 1179, 1179,
-     1179, 1179, 1179, 1179, 1179, 1179, 1179, 1180, 1180, 1180,
-     1180, 1180, 1180, 1180, 1180, 1180, 1180, 1180, 1180, 1181,
-        0,    0, 1181, 1182,    0,    0,    0, 1182,    0,    0,
-        0,    0,    0, 1182, 1183, 1183, 1183, 1183, 1183, 1183,
-     1183, 1183, 1183, 1183, 1183, 1183, 1184, 1184,    0, 1184,
-     1184, 1184, 1184, 1184, 1184, 1184, 1184, 1184, 1185, 1185,
-
-        0, 1185, 1185, 1185, 1185, 1185, 1185, 1185, 1185, 1185,
-     1186, 1186,    0, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
-     1186, 1186, 1187, 1187, 1187, 1187, 1187, 1187, 1187, 1187,
-     1187, 1187, 1187, 1187, 1188, 1188, 1188, 1188, 1188, 1188,
-     1188, 1188, 1188, 1188, 1188, 1188, 1189, 1189, 1189, 1189,
-     1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1190, 1190,
-     1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190,
-     1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
-     1191, 1191, 1192, 1192,    0, 1192, 1192, 1192, 1192, 1192,
-     1192, 1192, 1192, 1192, 1193, 1193, 1193, 1193, 1193, 1193,
-
-     1193, 1193, 1193, 1193, 1193, 1193, 1194, 1194, 1194, 1194,
-     1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1195, 1195,
-        0, 1195, 1195, 1195, 1195, 1195, 1195, 1195, 1195, 1195,
-     1196, 1196,    0, 1196, 1196, 1196, 1196, 1196, 1196, 1196,
-     1196, 1196, 1197, 1197,    0, 1197, 1197, 1197, 1197, 1197,
-     1197, 1197, 1197, 1197, 1198, 1198,    0, 1198, 1198, 1198,
-     1198, 1198, 1198, 1198, 1198, 1198, 1199, 1199,    0, 1199,
-     1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1200, 1200,
-     1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200,
-     1201, 1201, 1201, 1201, 1201, 1201, 1201, 1201, 1201, 1201,
-
-     1201, 1201, 1202, 1202, 1202, 1202, 1202, 1202, 1202, 1202,
-     1202, 1202, 1202, 1202, 1203, 1203, 1203, 1203, 1203, 1203,
-     1203, 1203, 1203, 1203, 1203, 1203, 1204, 1204, 1204, 1204,
-     1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1205, 1205,
-     1205, 1205, 1205, 1205, 1205, 1205, 1205, 1205, 1205, 1205,
-     1206, 1206,    0, 1206, 1206, 1206, 1206, 1206, 1206, 1206,
-     1206, 1206, 1207, 1207,    0, 1207, 1207, 1207, 1207, 1207,
-     1207, 1207, 1207, 1207, 1208, 1208, 1208, 1208, 1208, 1208,
-     1208, 1208, 1208, 1208, 1208, 1208, 1209, 1209, 1209, 1209,
-     1209, 1209, 1209, 1209, 1209, 1209, 1209, 1209, 1210, 1210,
-
-     1210, 1210, 1210, 1210, 1210, 1210, 1210, 1210, 1210, 1210,
-     1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211,
-     1211, 1211, 1212, 1212, 1212, 1212, 1212, 1212, 1212, 1212,
-     1212, 1212, 1212, 1212, 1213, 1213, 1213, 1213, 1213, 1213,
-     1213, 1213, 1213, 1213, 1213, 1213, 1214, 1214, 1214, 1214,
-     1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
-     1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161
+        0,    0, 1127, 1126,    0, 1123, 1114,    0,    0, 1117,
+
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+     1127, 1132, 1132, 1132, 1132, 1132, 1132, 1132, 1132, 1132,
+     1132, 1132, 1132, 1132, 1133, 1133, 1133, 1133, 1133, 1133,
+     1133, 1133, 1133, 1133, 1133, 1133, 1133, 1134,    0, 1134,
+     1134, 1134, 1134, 1134, 1134, 1134, 1134, 1134, 1134, 1134,
+     1135, 1135, 1135, 1135, 1135, 1135, 1135, 1135, 1135, 1135,
+     1135, 1135, 1135, 1136, 1136, 1136, 1136, 1136, 1136, 1136,
+     1136, 1136, 1136, 1136, 1136, 1136, 1137, 1137, 1137, 1137,
+     1137, 1137, 1137, 1137, 1137, 1137, 1137, 1137, 1137, 1138,
+
+     1138, 1138, 1138, 1138, 1138, 1138, 1138, 1138, 1139, 1139,
+     1139, 1139, 1139, 1139, 1139, 1139, 1139, 1139, 1139, 1139,
+     1139, 1140, 1140, 1140, 1140, 1140, 1140, 1140, 1140, 1140,
+     1140, 1140, 1140, 1140, 1141, 1141, 1141, 1141, 1141,    0,
+     1141, 1141, 1141,    0, 1141,    0, 1141, 1142, 1142, 1142,
+     1142, 1142, 1142, 1142, 1142, 1142, 1142, 1142, 1142, 1142,
+     1143,    0,    0,    0,    0,    0,    0,    0, 1143, 1144,
+     1144,    0, 1144, 1144,    0, 1144,    0,    0, 1144, 1144,
+        0, 1144, 1145, 1145, 1145, 1145, 1146, 1146, 1146, 1146,
+     1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1147,
+
+     1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147,
+     1147, 1147, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148,
+     1148, 1148, 1148, 1148, 1148, 1149, 1149, 1149,    0, 1149,
+     1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1150,    0,
+     1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150,
+     1150, 1151,    0, 1151, 1151, 1151, 1151, 1151, 1151, 1151,
+     1151, 1151, 1151, 1151, 1152, 1152, 1152, 1152, 1152, 1152,
+     1152, 1152, 1152, 1152, 1152, 1152, 1152, 1153, 1153, 1153,
+     1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153,
+     1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154,
+
+     1154, 1154, 1154, 1155,    0, 1155, 1155, 1155, 1155, 1155,
+     1155, 1155, 1155, 1155, 1155, 1155, 1156, 1156, 1156, 1156,
+     1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1157,
+     1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157,
+     1157, 1157, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158,
+     1158, 1158, 1158, 1158, 1158, 1159,    0, 1159, 1159, 1159,
+     1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1160,    0,
+     1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160,
+     1160, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
+     1161, 1161, 1161, 1161, 1162, 1162, 1162, 1162, 1162, 1162,
+
+     1162, 1162, 1162, 1162, 1162, 1162, 1162, 1163, 1163, 1163,
+     1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163,
+     1164,    0, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164,
+     1164, 1164, 1164, 1165, 1165, 1165, 1165, 1165, 1165, 1165,
+     1165, 1165, 1165, 1165, 1165, 1165, 1166, 1166, 1166, 1166,
+     1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1167,
+     1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167,
+     1167, 1167, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168,
+     1168, 1168, 1168, 1168, 1168, 1169, 1169, 1169, 1169, 1169,
+     1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1170, 1170,
+
+     1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170,
+     1170, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+     1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
+
+     1131
     } ;
 
@@ -9750,6 +8156,6 @@
 static char *yy_last_accepting_cpos;
 
-extern int fortran_flex_debug;
-int fortran_flex_debug = 0;
+extern int fortran__flex_debug;
+int fortran__flex_debug = 0;
 
 /* The intent behind this definition is that it'll catch
@@ -9760,5 +8166,5 @@
 #define YY_MORE_ADJ 0
 #define YY_RESTORE_YY_MORE_OFFSET
-char *fortrantext;
+char *fortran_text;
 #line 1 "fortran.lex"
 /******************************************************************************/
@@ -9801,17 +8207,17 @@
 
 
-#line 41 "fortran.lex"
+#line 44 "fortran.lex"
 #include <math.h>
 #include <stdlib.h>
 #include <string.h>
-extern FILE * fortranin;
+extern FILE * fortran_in;
 #define MAX_INCLUDE_DEPTH 30
-#define tabsize 6
 YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
-int line_num_fortran=1;
-int line_num_fortran_common=1;
+int line_num_input = 1;
 int newlinef90 = 0;
-char *tmp;
 char tmpc;
+#define PRINT_LINE_NUM()     // { fprintf(stderr,"== Parsing l.%4d...\n", line_num_input); }
+#define INCREMENT_LINE_NUM() { line_num_input++; PRINT_LINE_NUM(); }
+
 /******************************************************************************/
 /**************PETITS PB NON PREVUS *******************************************/
@@ -9823,21 +8229,9 @@
 /*            Normalement NEXTLINEF77 \n+[ ]{5}[^ ]                           */
 /******************************************************************************/
-#define YY_USER_ACTION \
-        {\
-           if (firstpass == 0) \
-           {\
-              strcat(curbuf,fortrantext); \
-              Save_Length(curbuf,38); \
-              strcpy(motparse,fortrantext);\
-              Save_Length(motparse,32); \
-              colnum = colnum + strlen(motparse);\
-              ECHO; \
-           }\
-           strcpy(motparse1,fortrantext);\
-/*           printf("fortrantext = %s\n",fortrantext);*/\
-        /*if ( firstpass == 1 ) 
-                      printf("fortrantext = %s %d\n",fortrantext,strlen(fortrantext));*/\
-        }
-#line 2979 "fortran.yy.c"
+#define YY_USER_ACTION  if (firstpass == 0) ECHO;
+
+void out_of_donottreat(void);
+
+#line 1826 "fortran.yy.c"
 
 #define INITIAL 0
@@ -9865,29 +8259,29 @@
    These are made visible to non-reentrant scanners for convenience. */
 
-int fortranlex_destroy (void );
-
-int fortranget_debug (void );
-
-void fortranset_debug (int debug_flag  );
-
-YY_EXTRA_TYPE fortranget_extra (void );
-
-void fortranset_extra (YY_EXTRA_TYPE user_defined  );
-
-FILE *fortranget_in (void );
-
-void fortranset_in  (FILE * in_str  );
-
-FILE *fortranget_out (void );
-
-void fortranset_out  (FILE * out_str  );
-
-yy_size_t fortranget_leng (void );
-
-char *fortranget_text (void );
-
-int fortranget_lineno (void );
-
-void fortranset_lineno (int line_number  );
+int fortran_lex_destroy (void );
+
+int fortran_get_debug (void );
+
+void fortran_set_debug (int debug_flag  );
+
+YY_EXTRA_TYPE fortran_get_extra (void );
+
+void fortran_set_extra (YY_EXTRA_TYPE user_defined  );
+
+FILE *fortran_get_in (void );
+
+void fortran_set_in  (FILE * in_str  );
+
+FILE *fortran_get_out (void );
+
+void fortran_set_out  (FILE * out_str  );
+
+yy_size_t fortran_get_leng (void );
+
+char *fortran_get_text (void );
+
+int fortran_get_lineno (void );
+
+void fortran_set_lineno (int line_number  );
 
 /* Macros after this point can all be overridden by user definitions in
@@ -9897,7 +8291,7 @@
 #ifndef YY_SKIP_YYWRAP
 #ifdef __cplusplus
-extern "C" int fortranwrap (void );
+extern "C" int fortran_wrap (void );
 #else
-extern int fortranwrap (void );
+extern int fortran_wrap (void );
 #endif
 #endif
@@ -9933,5 +8327,5 @@
  * we now use fwrite().
  */
-#define ECHO fwrite( fortrantext, fortranleng, 1, fortranout )
+#define ECHO fwrite( fortran_text, fortran_leng, 1, fortran_out )
 #endif
 
@@ -9946,9 +8340,9 @@
 		yy_size_t n; \
 		for ( n = 0; n < max_size && \
-			     (c = getc( fortranin )) != EOF && c != '\n'; ++n ) \
+			     (c = getc( fortran_in )) != EOF && c != '\n'; ++n ) \
 			buf[n] = (char) c; \
 		if ( c == '\n' ) \
 			buf[n++] = (char) c; \
-		if ( c == EOF && ferror( fortranin ) ) \
+		if ( c == EOF && ferror( fortran_in ) ) \
 			YY_FATAL_ERROR( "input in flex scanner failed" ); \
 		result = n; \
@@ -9957,5 +8351,5 @@
 		{ \
 		errno=0; \
-		while ( (result = fread(buf, 1, max_size, fortranin))==0 && ferror(fortranin)) \
+		while ( (result = fread(buf, 1, max_size, fortran_in))==0 && ferror(fortran_in)) \
 			{ \
 			if( errno != EINTR) \
@@ -9965,5 +8359,5 @@
 				} \
 			errno=0; \
-			clearerr(fortranin); \
+			clearerr(fortran_in); \
 			} \
 		}\
@@ -9998,10 +8392,10 @@
 #define YY_DECL_IS_OURS 1
 
-extern int fortranlex (void);
-
-#define YY_DECL int fortranlex (void)
+extern int fortran_lex (void);
+
+#define YY_DECL int fortran_lex (void)
 #endif /* !YY_DECL */
 
-/* Code executed at the beginning of each rule, after fortrantext and fortranleng
+/* Code executed at the beginning of each rule, after fortran_text and fortran_leng
  * have been set up.
  */
@@ -10016,7 +8410,7 @@
 
 #define YY_RULE_SETUP \
-	if ( fortranleng > 0 ) \
+	if ( fortran_leng > 0 ) \
 		YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \
-				(fortrantext[fortranleng - 1] == '\n'); \
+				(fortran_text[fortran_leng - 1] == '\n'); \
 	YY_USER_ACTION
 
@@ -10029,10 +8423,10 @@
 	register int yy_act;
     
-#line 107 "fortran.lex"
+#line 97 "fortran.lex"
 
   if (infixed) BEGIN(fortran77style) ;
-  if (infree) BEGIN(fortran90style)  ;
-
-#line 3174 "fortran.yy.c"
+  if (infree)  BEGIN(fortran90style) ;
+
+#line 2021 "fortran.yy.c"
 
 	if ( !(yy_init) )
@@ -10047,17 +8441,17 @@
 			(yy_start) = 1;	/* first start state */
 
-		if ( ! fortranin )
-			fortranin = stdin;
-
-		if ( ! fortranout )
-			fortranout = stdout;
+		if ( ! fortran_in )
+			fortran_in = stdin;
+
+		if ( ! fortran_out )
+			fortran_out = stdout;
 
 		if ( ! YY_CURRENT_BUFFER ) {
-			fortranensure_buffer_stack ();
+			fortran_ensure_buffer_stack ();
 			YY_CURRENT_BUFFER_LVALUE =
-				fortran_create_buffer(fortranin,YY_BUF_SIZE );
+				fortran__create_buffer(fortran_in,YY_BUF_SIZE );
 		}
 
-		fortran_load_buffer_state( );
+		fortran__load_buffer_state( );
 		}
 
@@ -10066,5 +8460,5 @@
 		yy_cp = (yy_c_buf_p);
 
-		/* Support of fortrantext. */
+		/* Support of fortran_text. */
 		*yy_cp = (yy_hold_char);
 
@@ -10088,5 +8482,5 @@
 				{
 				yy_current_state = (int) yy_def[yy_current_state];
-				if ( yy_current_state >= 1162 )
+				if ( yy_current_state >= 1132 )
 					yy_c = yy_meta[(unsigned int) yy_c];
 				}
@@ -10094,5 +8488,5 @@
 			++yy_cp;
 			}
-		while ( yy_base[yy_current_state] != 9159 );
+		while ( yy_base[yy_current_state] != 4012 );
 
 yy_find_action:
@@ -10120,969 +8514,913 @@
 case 1:
 YY_RULE_SETUP
+#line 101 "fortran.lex"
+{ return TOK_REAL8; }
+	YY_BREAK
+case 2:
+YY_RULE_SETUP
+#line 102 "fortran.lex"
+{ return TOK_SUBROUTINE; }
+	YY_BREAK
+case 3:
+YY_RULE_SETUP
+#line 103 "fortran.lex"
+{ return TOK_PROGRAM; }
+	YY_BREAK
+case 4:
+YY_RULE_SETUP
+#line 104 "fortran.lex"
+{ inallocate = 1; return TOK_ALLOCATE; }
+	YY_BREAK
+case 5:
+YY_RULE_SETUP
+#line 105 "fortran.lex"
+{ return TOK_NULLIFY; }
+	YY_BREAK
+case 6:
+YY_RULE_SETUP
+#line 106 "fortran.lex"
+{ return TOK_NULL_PTR; }
+	YY_BREAK
+case 7:
+YY_RULE_SETUP
+#line 107 "fortran.lex"
+{ inallocate = 1; return TOK_DEALLOCATE; }
+	YY_BREAK
+case 8:
+YY_RULE_SETUP
+#line 108 "fortran.lex"
+{ return TOK_RESULT; }
+	YY_BREAK
+case 9:
+YY_RULE_SETUP
+#line 109 "fortran.lex"
+{ return TOK_FUNCTION; }
+	YY_BREAK
+case 10:
+YY_RULE_SETUP
+#line 110 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_ENDPROGRAM;}
+	YY_BREAK
+case 11:
+YY_RULE_SETUP
 #line 111 "fortran.lex"
-return TOK_DEBUT;
-	YY_BREAK
-case 2:
+{ strcpy(yylval.na,fortran_text); return TOK_ENDMODULE; }
+	YY_BREAK
+case 12:
 YY_RULE_SETUP
 #line 112 "fortran.lex"
-return TOK_FIN;
-	YY_BREAK
-case 3:
+{ strcpy(yylval.na,fortran_text); return TOK_ENDSUBROUTINE;}
+	YY_BREAK
+case 13:
 YY_RULE_SETUP
 #line 113 "fortran.lex"
-return TOK_OMP;
-	YY_BREAK
-case 4:
+{ strcpy(yylval.na,fortran_text); return TOK_ENDFUNCTION;}
+	YY_BREAK
+case 14:
 YY_RULE_SETUP
 #line 114 "fortran.lex"
-return TOK_DOLLAR;
-	YY_BREAK
-case 5:
+{ strcpy(yylval.na,fortran_text); return TOK_ENDUNIT;}
+	YY_BREAK
+case 15:
+YY_RULE_SETUP
+#line 115 "fortran.lex"
+{ pos_curinclude = setposcur()-9; return TOK_INCLUDE;}
+	YY_BREAK
+case 16:
 YY_RULE_SETUP
 #line 116 "fortran.lex"
-{return TOK_REAL8;}
-	YY_BREAK
-case 6:
-YY_RULE_SETUP
-#line 117 "fortran.lex"
-{return TOK_SUBROUTINE;}
-	YY_BREAK
-case 7:
-YY_RULE_SETUP
-#line 118 "fortran.lex"
-{return TOK_PROGRAM;}
-	YY_BREAK
-case 8:
-YY_RULE_SETUP
-#line 119 "fortran.lex"
-{inallocate = 1; return TOK_ALLOCATE;}
-	YY_BREAK
-case 9:
-YY_RULE_SETUP
-#line 120 "fortran.lex"
-{return TOK_NULLIFY;}
-	YY_BREAK
-case 10:
-YY_RULE_SETUP
-#line 121 "fortran.lex"
-{inallocate = 1; return TOK_DEALLOCATE;}
-	YY_BREAK
-case 11:
+{ strcpy(yylval.na,fortran_text);
+                              tmpc = (char) input(); unput(tmpc);
+                              if ( ( tmpc >= 'a' && tmpc <= 'z' ) ||
+                                   ( tmpc >= 'A' && tmpc <= 'Z' )  )  return TOK_USE;
+                              else                                    return TOK_NAME;
+                            }
+	YY_BREAK
+case 17:
 YY_RULE_SETUP
 #line 122 "fortran.lex"
-{return TOK_RESULT;}
-	YY_BREAK
-case 12:
+{ return TOK_REWIND; }
+	YY_BREAK
+case 18:
 YY_RULE_SETUP
 #line 123 "fortran.lex"
-{return TOK_FUNCTION;}
-	YY_BREAK
-case 13:
+{ return TOK_IMPLICIT; }
+	YY_BREAK
+case 19:
 YY_RULE_SETUP
 #line 124 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_ENDSUBROUTINE;}
-	YY_BREAK
-case 14:
+{ return TOK_NONE; }
+	YY_BREAK
+case 20:
 YY_RULE_SETUP
 #line 125 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_ENDPROGRAM;}
-	YY_BREAK
-case 15:
+{ return TOK_CALL; }
+	YY_BREAK
+case 21:
 YY_RULE_SETUP
 #line 126 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_ENDFUNCTION;}
-	YY_BREAK
-case 16:
+{ return TOK_TRUE; }
+	YY_BREAK
+case 22:
 YY_RULE_SETUP
 #line 127 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_ENDUNIT;}
-	YY_BREAK
-case 17:
+{ return TOK_FALSE; }
+	YY_BREAK
+case 23:
 YY_RULE_SETUP
 #line 128 "fortran.lex"
-return TOK_INCLUDE;
-	YY_BREAK
-case 18:
+{ return TOK_POINT_TO; }
+	YY_BREAK
+case 24:
 YY_RULE_SETUP
 #line 129 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_ASSIGNTYPE;}
+	YY_BREAK
+case 25:
+YY_RULE_SETUP
+#line 130 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_DASTER; }
+	YY_BREAK
+case 26:
+YY_RULE_SETUP
+#line 131 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_EQV; }
+	YY_BREAK
+case 27:
+YY_RULE_SETUP
+#line 132 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_EQ;  }
+	YY_BREAK
+case 28:
+YY_RULE_SETUP
+#line 133 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_GT;  }
+	YY_BREAK
+case 29:
+YY_RULE_SETUP
+#line 134 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_GE;  }
+	YY_BREAK
+case 30:
+YY_RULE_SETUP
+#line 135 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_LT;  }
+	YY_BREAK
+case 31:
+YY_RULE_SETUP
+#line 136 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_LE;  }
+	YY_BREAK
+case 32:
+YY_RULE_SETUP
+#line 137 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_NEQV;}
+	YY_BREAK
+case 33:
+YY_RULE_SETUP
+#line 138 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_NE;  }
+	YY_BREAK
+case 34:
+YY_RULE_SETUP
+#line 139 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_NOT; }
+	YY_BREAK
+case 35:
+YY_RULE_SETUP
+#line 140 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_OR;  }
+	YY_BREAK
+case 36:
+YY_RULE_SETUP
+#line 141 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_XOR; }
+	YY_BREAK
+case 37:
+YY_RULE_SETUP
+#line 142 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_AND; }
+	YY_BREAK
+case 38:
+YY_RULE_SETUP
+#line 143 "fortran.lex"
+{ return TOK_MODULE; }
+	YY_BREAK
+case 39:
+YY_RULE_SETUP
+#line 144 "fortran.lex"
+{ return TOK_WHILE; }
+	YY_BREAK
+case 40:
+YY_RULE_SETUP
+#line 145 "fortran.lex"
+{ return TOK_CONCURRENT; }
+	YY_BREAK
+case 41:
+YY_RULE_SETUP
+#line 146 "fortran.lex"
+{ return TOK_ENDDO; }
+	YY_BREAK
+case 42:
+YY_RULE_SETUP
+#line 147 "fortran.lex"
+{ return TOK_PLAINDO;}
+	YY_BREAK
+case 43:
+YY_RULE_SETUP
+#line 148 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_REAL; }
+	YY_BREAK
+case 44:
+YY_RULE_SETUP
+#line 149 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_INTEGER; }
+	YY_BREAK
+case 45:
+YY_RULE_SETUP
+#line 150 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_LOGICAL; }
+	YY_BREAK
+case 46:
+YY_RULE_SETUP
+#line 151 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_CHARACTER; }
+	YY_BREAK
+case 47:
+YY_RULE_SETUP
+#line 152 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_HEXA;}
+	YY_BREAK
+case 48:
+YY_RULE_SETUP
+#line 153 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_DOUBLEPRECISION; }
+	YY_BREAK
+case 49:
+YY_RULE_SETUP
+#line 154 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_DOUBLECOMPLEX; }
+	YY_BREAK
+case 50:
+YY_RULE_SETUP
+#line 155 "fortran.lex"
+{ return TOK_COMPLEX; }
+	YY_BREAK
+case 51:
+YY_RULE_SETUP
+#line 156 "fortran.lex"
+{ return TOK_ALLOCATABLE; }
+	YY_BREAK
+case 52:
+YY_RULE_SETUP
+#line 157 "fortran.lex"
+{ return TOK_CLOSE; }
+	YY_BREAK
+case 53:
+YY_RULE_SETUP
+#line 158 "fortran.lex"
+{ return TOK_INQUIRE; }
+	YY_BREAK
+case 54:
+YY_RULE_SETUP
+#line 159 "fortran.lex"
+{ return TOK_DIMENSION; }
+	YY_BREAK
+case 55:
+YY_RULE_SETUP
+#line 160 "fortran.lex"
+{ return TOK_PAUSE; }
+	YY_BREAK
+case 56:
+YY_RULE_SETUP
+#line 161 "fortran.lex"
+{ return TOK_EQUIVALENCE; }
+	YY_BREAK
+case 57:
+YY_RULE_SETUP
+#line 162 "fortran.lex"
+{ return TOK_STOP; }
+	YY_BREAK
+case 58:
+YY_RULE_SETUP
+#line 163 "fortran.lex"
+{ return TOK_WHERE; }
+	YY_BREAK
+case 59:
+YY_RULE_SETUP
+#line 164 "fortran.lex"
+{ return TOK_ENDWHERE; }
+	YY_BREAK
+case 60:
+YY_RULE_SETUP
+#line 165 "fortran.lex"
+{ return TOK_ELSEWHEREPAR; }
+	YY_BREAK
+case 61:
+YY_RULE_SETUP
+#line 166 "fortran.lex"
+{ return TOK_ELSEWHERE; }
+	YY_BREAK
+case 62:
+YY_RULE_SETUP
+#line 167 "fortran.lex"
+{ return TOK_CONTAINS; }
+	YY_BREAK
+case 63:
+YY_RULE_SETUP
+#line 168 "fortran.lex"
+{ return TOK_ONLY; }
+	YY_BREAK
+case 64:
+YY_RULE_SETUP
+#line 169 "fortran.lex"
+{ return TOK_PARAMETER; }
+	YY_BREAK
+case 65:
+YY_RULE_SETUP
+#line 170 "fortran.lex"
+{ return TOK_RECURSIVE; }
+	YY_BREAK
+case 66:
+YY_RULE_SETUP
+#line 171 "fortran.lex"
+{ return TOK_COMMON; }
+	YY_BREAK
+case 67:
+YY_RULE_SETUP
+#line 172 "fortran.lex"
+{ return TOK_GLOBAL; }
+	YY_BREAK
+case 68:
+YY_RULE_SETUP
+#line 173 "fortran.lex"
+{ return TOK_EXTERNAL; }
+	YY_BREAK
+case 69:
+YY_RULE_SETUP
+#line 174 "fortran.lex"
+{ return TOK_INTENT; }
+	YY_BREAK
+case 70:
+YY_RULE_SETUP
+#line 175 "fortran.lex"
+{ return TOK_POINTER; }
+	YY_BREAK
+case 71:
+YY_RULE_SETUP
+#line 176 "fortran.lex"
+{ return TOK_OPTIONAL; }
+	YY_BREAK
+case 72:
+YY_RULE_SETUP
+#line 177 "fortran.lex"
+{ return TOK_SAVE; }
+	YY_BREAK
+case 73:
+YY_RULE_SETUP
+#line 178 "fortran.lex"
+{ pos_cur_decl = setposcur()-5; return TOK_TYPEPAR; }
+	YY_BREAK
+case 74:
+YY_RULE_SETUP
+#line 179 "fortran.lex"
+{ return TOK_TYPE; }
+	YY_BREAK
+case 75:
+YY_RULE_SETUP
+#line 180 "fortran.lex"
+{ return TOK_ENDTYPE; }
+	YY_BREAK
+case 76:
+YY_RULE_SETUP
+#line 181 "fortran.lex"
+{ if (inallocate == 1) return TOK_STAT; else { strcpy(yylval.na,fortran_text); return TOK_NAME; } }
+	YY_BREAK
+case 77:
+YY_RULE_SETUP
+#line 182 "fortran.lex"
+{ return TOK_OPEN; }
+	YY_BREAK
+case 78:
+YY_RULE_SETUP
+#line 183 "fortran.lex"
+{ return TOK_RETURN; }
+	YY_BREAK
+case 79:
+/* rule 79 can match eol */
+YY_RULE_SETUP
+#line 184 "fortran.lex"
+{ return TOK_EXIT; }
+	YY_BREAK
+case 80:
+YY_RULE_SETUP
+#line 185 "fortran.lex"
+{ return TOK_PRINT; }
+	YY_BREAK
+case 81:
+YY_RULE_SETUP
+#line 186 "fortran.lex"
+{ return TOK_PROCEDURE; }
+	YY_BREAK
+case 82:
+YY_RULE_SETUP
+#line 187 "fortran.lex"
+{ return TOK_READ; }
+	YY_BREAK
+case 83:
+YY_RULE_SETUP
+#line 188 "fortran.lex"
+{ return TOK_NAMELIST; }
+	YY_BREAK
+case 84:
+YY_RULE_SETUP
+#line 189 "fortran.lex"
+{ return TOK_WRITE; }
+	YY_BREAK
+case 85:
+YY_RULE_SETUP
+#line 190 "fortran.lex"
+{ return TOK_FLUSH; }
+	YY_BREAK
+case 86:
+YY_RULE_SETUP
+#line 191 "fortran.lex"
+{ return TOK_TARGET; }
+	YY_BREAK
+case 87:
+YY_RULE_SETUP
+#line 192 "fortran.lex"
+{ return TOK_PUBLIC; }
+	YY_BREAK
+case 88:
+YY_RULE_SETUP
+#line 193 "fortran.lex"
+{ return TOK_PRIVATE; }
+	YY_BREAK
+case 89:
+YY_RULE_SETUP
+#line 194 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_IN; }
+	YY_BREAK
+case 90:
+YY_RULE_SETUP
+#line 195 "fortran.lex"
+{ pos_curdata = setposcur()-strlen(fortran_text); Init_List_Data_Var(); return TOK_DATA; }
+	YY_BREAK
+case 91:
+YY_RULE_SETUP
+#line 196 "fortran.lex"
+{ return TOK_CONTINUE; }
+	YY_BREAK
+case 92:
+YY_RULE_SETUP
+#line 197 "fortran.lex"
+{ return TOK_PLAINGOTO; }
+	YY_BREAK
+case 93:
+YY_RULE_SETUP
+#line 198 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_OUT; }
+	YY_BREAK
+case 94:
+YY_RULE_SETUP
+#line 199 "fortran.lex"
+{ strcpy(yylval.na,fortran_text); return TOK_INOUT; }
+	YY_BREAK
+case 95:
+YY_RULE_SETUP
+#line 200 "fortran.lex"
+{ return TOK_INTRINSIC; }
+	YY_BREAK
+case 96:
+YY_RULE_SETUP
+#line 201 "fortran.lex"
+{ return TOK_THEN; }
+	YY_BREAK
+case 97:
+YY_RULE_SETUP
+#line 202 "fortran.lex"
+{ return TOK_ELSEIF; }
+	YY_BREAK
+case 98:
+YY_RULE_SETUP
+#line 203 "fortran.lex"
+{ return TOK_ELSE; }
+	YY_BREAK
+case 99:
+YY_RULE_SETUP
+#line 204 "fortran.lex"
+{ return TOK_ENDIF; }
+	YY_BREAK
+case 100:
+YY_RULE_SETUP
+#line 205 "fortran.lex"
+{ return TOK_LOGICALIF; }
+	YY_BREAK
+case 101:
+YY_RULE_SETUP
+#line 206 "fortran.lex"
+{ return TOK_SUM; }
+	YY_BREAK
+case 102:
+YY_RULE_SETUP
+#line 207 "fortran.lex"
+{ return TOK_MAX; }
+	YY_BREAK
+case 103:
+YY_RULE_SETUP
+#line 208 "fortran.lex"
+{ return TOK_TANH; }
+	YY_BREAK
+case 104:
+YY_RULE_SETUP
+#line 209 "fortran.lex"
+{ return TOK_MAXVAL; }
+	YY_BREAK
+case 105:
+YY_RULE_SETUP
+#line 210 "fortran.lex"
+{ return TOK_TRIM; }
+	YY_BREAK
+case 106:
+YY_RULE_SETUP
+#line 211 "fortran.lex"
+{ return TOK_SQRT; }
+	YY_BREAK
+case 107:
+YY_RULE_SETUP
+#line 212 "fortran.lex"
+{ return TOK_SELECTCASE; }
+	YY_BREAK
+case 108:
+YY_RULE_SETUP
+#line 213 "fortran.lex"
+{ return TOK_CASE; }
+	YY_BREAK
+case 109:
+YY_RULE_SETUP
+#line 214 "fortran.lex"
+{ return TOK_DEFAULT; }
+	YY_BREAK
+case 110:
+YY_RULE_SETUP
+#line 215 "fortran.lex"
+{ return TOK_ENDSELECT; }
+	YY_BREAK
+case 111:
+YY_RULE_SETUP
+#line 216 "fortran.lex"
+{ return TOK_FILE; }
+	YY_BREAK
+case 112:
+YY_RULE_SETUP
+#line 217 "fortran.lex"
+{ return TOK_UNIT; }
+	YY_BREAK
+case 113:
+YY_RULE_SETUP
+#line 218 "fortran.lex"
+{ return TOK_FMT; }
+	YY_BREAK
+case 114:
+YY_RULE_SETUP
+#line 219 "fortran.lex"
+{ return TOK_NML; }
+	YY_BREAK
+case 115:
+YY_RULE_SETUP
+#line 220 "fortran.lex"
+{ return TOK_END; }
+	YY_BREAK
+case 116:
+YY_RULE_SETUP
+#line 221 "fortran.lex"
+{ return TOK_EOR; }
+	YY_BREAK
+case 117:
+YY_RULE_SETUP
+#line 222 "fortran.lex"
+{ return TOK_ERR; }
+	YY_BREAK
+case 118:
+YY_RULE_SETUP
+#line 223 "fortran.lex"
+{ return TOK_EXIST; }
+	YY_BREAK
+case 119:
+YY_RULE_SETUP
+#line 224 "fortran.lex"
+{ return TOK_MIN; }
+	YY_BREAK
+case 120:
+YY_RULE_SETUP
+#line 225 "fortran.lex"
+{ return TOK_NINT; }
+	YY_BREAK
+case 121:
+YY_RULE_SETUP
+#line 226 "fortran.lex"
+{ return TOK_FLOAT; }
+	YY_BREAK
+case 122:
+YY_RULE_SETUP
+#line 227 "fortran.lex"
+{ return TOK_EXP; }
+	YY_BREAK
+case 123:
+YY_RULE_SETUP
+#line 228 "fortran.lex"
+{ return TOK_COS; }
+	YY_BREAK
+case 124:
+YY_RULE_SETUP
+#line 229 "fortran.lex"
+{ return TOK_COSH; }
+	YY_BREAK
+case 125:
+YY_RULE_SETUP
+#line 230 "fortran.lex"
+{ return TOK_ACOS; }
+	YY_BREAK
+case 126:
+YY_RULE_SETUP
+#line 231 "fortran.lex"
+{ return TOK_SIN; }
+	YY_BREAK
+case 127:
+YY_RULE_SETUP
+#line 232 "fortran.lex"
+{ return TOK_SINH; }
+	YY_BREAK
+case 128:
+YY_RULE_SETUP
+#line 233 "fortran.lex"
+{ return TOK_ASIN; }
+	YY_BREAK
+case 129:
+YY_RULE_SETUP
+#line 234 "fortran.lex"
+{ return TOK_LOG; }
+	YY_BREAK
+case 130:
+YY_RULE_SETUP
+#line 235 "fortran.lex"
+{ return TOK_TAN; }
+	YY_BREAK
+case 131:
+YY_RULE_SETUP
+#line 236 "fortran.lex"
+{ return TOK_ATAN; }
+	YY_BREAK
+case 132:
+YY_RULE_SETUP
+#line 237 "fortran.lex"
+{ return TOK_CYCLE; }
+	YY_BREAK
+case 133:
+YY_RULE_SETUP
+#line 238 "fortran.lex"
+{ return TOK_ABS; }
+	YY_BREAK
+case 134:
+YY_RULE_SETUP
+#line 239 "fortran.lex"
+{ return TOK_MOD; }
+	YY_BREAK
+case 135:
+YY_RULE_SETUP
+#line 240 "fortran.lex"
+{ return TOK_SIGN; }
+	YY_BREAK
+case 136:
+YY_RULE_SETUP
+#line 241 "fortran.lex"
+{ return TOK_MINLOC; }
+	YY_BREAK
+case 137:
+YY_RULE_SETUP
+#line 242 "fortran.lex"
+{ return TOK_MAXLOC; }
+	YY_BREAK
+case 138:
+YY_RULE_SETUP
+#line 243 "fortran.lex"
+{ return TOK_MINVAL; }
+	YY_BREAK
+case 139:
+YY_RULE_SETUP
+#line 244 "fortran.lex"
+{ return TOK_BACKSPACE; }
+	YY_BREAK
+case 140:
+YY_RULE_SETUP
+#line 245 "fortran.lex"
+{ return TOK_FOURDOTS;  }
+	YY_BREAK
+case 141:
+YY_RULE_SETUP
+#line 246 "fortran.lex"
+{ return TOK_LEFTAB; }
+	YY_BREAK
+case 142:
+YY_RULE_SETUP
+#line 247 "fortran.lex"
+{ return TOK_RIGHTAB; }
+	YY_BREAK
+case 143:
+/* rule 143 can match eol */
+YY_RULE_SETUP
+#line 248 "fortran.lex"
 {
-                            strcpy(yylval.na,fortrantext);
-                            tmpc = input();
-                            unput(tmpc);
-                            if ( (
-                               tmpc >= 'a' && tmpc <= 'z'
-                                  ) || (
-                               tmpc >= 'A' && tmpc <= 'Z'
-                               )  )
-                               {
-                                  return TOK_USE;
-                               }
-                               else
-                               {
-                                  return TOK_NAME;
-                               }
-                         }
-	YY_BREAK
-case 19:
-YY_RULE_SETUP
-#line 146 "fortran.lex"
-{return TOK_REWIND;}
-	YY_BREAK
-case 20:
-YY_RULE_SETUP
-#line 147 "fortran.lex"
-return TOK_IMPLICIT;
-	YY_BREAK
-case 21:
-YY_RULE_SETUP
-#line 148 "fortran.lex"
-return TOK_NONE;
-	YY_BREAK
-case 22:
-YY_RULE_SETUP
-#line 149 "fortran.lex"
-return TOK_CALL;
-	YY_BREAK
-case 23:
-YY_RULE_SETUP
-#line 150 "fortran.lex"
-return TOK_TRUE;
-	YY_BREAK
-case 24:
-YY_RULE_SETUP
-#line 151 "fortran.lex"
-return TOK_FALSE;
-	YY_BREAK
-case 25:
-YY_RULE_SETUP
-#line 152 "fortran.lex"
-{return TOK_POINT_TO;}
-	YY_BREAK
-case 26:
-YY_RULE_SETUP
-#line 153 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_DASTER;}
-	YY_BREAK
-case 27:
-YY_RULE_SETUP
-#line 154 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_EQV;}
-	YY_BREAK
-case 28:
-YY_RULE_SETUP
-#line 155 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_EQ;}
-	YY_BREAK
-case 29:
-YY_RULE_SETUP
-#line 156 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_GT;}
-	YY_BREAK
-case 30:
-YY_RULE_SETUP
-#line 157 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_GE;}
-	YY_BREAK
-case 31:
-YY_RULE_SETUP
-#line 158 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_LT;}
-	YY_BREAK
-case 32:
-YY_RULE_SETUP
-#line 159 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_LE;}
-	YY_BREAK
-case 33:
-YY_RULE_SETUP
-#line 160 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_NEQV;}
-	YY_BREAK
-case 34:
-YY_RULE_SETUP
-#line 161 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_NE;}
-	YY_BREAK
-case 35:
-YY_RULE_SETUP
-#line 162 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_NOT;}
-	YY_BREAK
-case 36:
-YY_RULE_SETUP
-#line 163 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_OR;}
-	YY_BREAK
-case 37:
-YY_RULE_SETUP
-#line 164 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_XOR;}
-	YY_BREAK
-case 38:
-YY_RULE_SETUP
-#line 165 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_AND;}
-	YY_BREAK
-case 39:
-YY_RULE_SETUP
-#line 166 "fortran.lex"
-{return TOK_MODULE;}
-	YY_BREAK
-case 40:
-YY_RULE_SETUP
-#line 167 "fortran.lex"
-{return TOK_DOWHILE;}
-	YY_BREAK
-case 41:
-YY_RULE_SETUP
-#line 168 "fortran.lex"
-return TOK_ENDMODULE;
-	YY_BREAK
-case 42:
-YY_RULE_SETUP
-#line 169 "fortran.lex"
-return TOK_ENDDO;
-	YY_BREAK
-case 43:
-YY_RULE_SETUP
-#line 170 "fortran.lex"
-{return TOK_PLAINDO;}
-	YY_BREAK
-case 44:
-YY_RULE_SETUP
-#line 171 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_REAL;}
-	YY_BREAK
-case 45:
-YY_RULE_SETUP
-#line 172 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_INTEGER;}
-	YY_BREAK
-case 46:
-YY_RULE_SETUP
-#line 173 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_LOGICAL;}
-	YY_BREAK
-case 47:
-YY_RULE_SETUP
-#line 174 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CHARACTER;}
-	YY_BREAK
-case 48:
-YY_RULE_SETUP
-#line 175 "fortran.lex"
-{return TOK_ALLOCATABLE;}
-	YY_BREAK
-case 49:
-YY_RULE_SETUP
-#line 176 "fortran.lex"
-return TOK_CLOSE;
-	YY_BREAK
-case 50:
-YY_RULE_SETUP
-#line 177 "fortran.lex"
-return TOK_INQUIRE;
-	YY_BREAK
-case 51:
-YY_RULE_SETUP
-#line 178 "fortran.lex"
-{return TOK_DIMENSION;}
-	YY_BREAK
-case 52:
-YY_RULE_SETUP
-#line 179 "fortran.lex"
-return TOK_PAUSE;
-	YY_BREAK
-case 53:
-YY_RULE_SETUP
-#line 180 "fortran.lex"
-return TOK_EQUIVALENCE;
-	YY_BREAK
-case 54:
-YY_RULE_SETUP
-#line 181 "fortran.lex"
-return TOK_STOP;
-	YY_BREAK
-case 55:
-YY_RULE_SETUP
-#line 182 "fortran.lex"
-return TOK_WHERE;
-	YY_BREAK
-case 56:
-YY_RULE_SETUP
-#line 183 "fortran.lex"
-return TOK_ENDWHERE;
-	YY_BREAK
-case 57:
-YY_RULE_SETUP
-#line 184 "fortran.lex"
-return TOK_ELSEWHERE;
-	YY_BREAK
-case 58:
-YY_RULE_SETUP
-#line 185 "fortran.lex"
-{return TOK_COMPLEX;}
-	YY_BREAK
-case 59:
-YY_RULE_SETUP
-#line 186 "fortran.lex"
-{return TOK_CONTAINS;}
-	YY_BREAK
-case 60:
-YY_RULE_SETUP
-#line 187 "fortran.lex"
-{return TOK_ONLY;}
-	YY_BREAK
-case 61:
-YY_RULE_SETUP
-#line 188 "fortran.lex"
-{return TOK_PARAMETER;}
-	YY_BREAK
-case 62:
-YY_RULE_SETUP
-#line 189 "fortran.lex"
-{return TOK_RECURSIVE;}
-	YY_BREAK
-case 63:
-YY_RULE_SETUP
-#line 190 "fortran.lex"
-{return TOK_COMMON;}
-	YY_BREAK
-case 64:
-YY_RULE_SETUP
-#line 191 "fortran.lex"
-{return TOK_GLOBAL;}
-	YY_BREAK
-case 65:
-YY_RULE_SETUP
-#line 192 "fortran.lex"
-{return TOK_EXTERNAL;}
-	YY_BREAK
-case 66:
-YY_RULE_SETUP
-#line 193 "fortran.lex"
-{return TOK_INTENT;}
-	YY_BREAK
-case 67:
-YY_RULE_SETUP
-#line 194 "fortran.lex"
-{return TOK_POINTER;}
-	YY_BREAK
-case 68:
-YY_RULE_SETUP
-#line 195 "fortran.lex"
-{return TOK_OPTIONAL;}
-	YY_BREAK
-case 69:
-YY_RULE_SETUP
-#line 196 "fortran.lex"
-{return TOK_SAVE;}
-	YY_BREAK
-case 70:
-YY_RULE_SETUP
-#line 197 "fortran.lex"
-{return TOK_TYPE;}
-	YY_BREAK
-case 71:
-YY_RULE_SETUP
-#line 198 "fortran.lex"
-{return TOK_TYPEPAR;}
-	YY_BREAK
-case 72:
-YY_RULE_SETUP
-#line 199 "fortran.lex"
-{if (inallocate == 1) return TOK_STAT; else {strcpy(yylval.na,fortrantext);return TOK_NAME;}}
-	YY_BREAK
-case 73:
-YY_RULE_SETUP
-#line 200 "fortran.lex"
-{return TOK_ENDTYPE;}
-	YY_BREAK
-case 74:
-YY_RULE_SETUP
-#line 201 "fortran.lex"
-return TOK_OPEN;
-	YY_BREAK
-case 75:
-YY_RULE_SETUP
-#line 202 "fortran.lex"
-return TOK_RETURN;
-	YY_BREAK
-case 76:
-/* rule 76 can match eol */
-YY_RULE_SETUP
-#line 203 "fortran.lex"
-return TOK_EXIT;
-	YY_BREAK
-case 77:
-YY_RULE_SETUP
-#line 204 "fortran.lex"
-return TOK_PRINT;
-	YY_BREAK
-case 78:
-YY_RULE_SETUP
-#line 205 "fortran.lex"
-{return TOK_PROCEDURE;}
-	YY_BREAK
-case 79:
-YY_RULE_SETUP
-#line 206 "fortran.lex"
-{return TOK_READ;}
-	YY_BREAK
-case 80:
-YY_RULE_SETUP
-#line 207 "fortran.lex"
-{return TOK_NAMELIST;}
-	YY_BREAK
-case 81:
-YY_RULE_SETUP
-#line 208 "fortran.lex"
-{return TOK_WRITE;}
-	YY_BREAK
-case 82:
-YY_RULE_SETUP
-#line 209 "fortran.lex"
-{return TOK_TARGET;}
-	YY_BREAK
-case 83:
-YY_RULE_SETUP
-#line 210 "fortran.lex"
-{return TOK_PUBLIC;}
-	YY_BREAK
-case 84:
-YY_RULE_SETUP
-#line 211 "fortran.lex"
-{return TOK_PRIVATE;}
-	YY_BREAK
-case 85:
-YY_RULE_SETUP
-#line 212 "fortran.lex"
-{strcpy(yylval.nac,fortrantext);return TOK_IN;}
-	YY_BREAK
-case 86:
-YY_RULE_SETUP
-#line 213 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_DATA;}
-	YY_BREAK
-case 87:
-YY_RULE_SETUP
-#line 214 "fortran.lex"
-return TOK_CONTINUE;
-	YY_BREAK
-case 88:
-YY_RULE_SETUP
-#line 215 "fortran.lex"
-{return TOK_PLAINGOTO;}
-	YY_BREAK
-case 89:
-YY_RULE_SETUP
-#line 216 "fortran.lex"
-{strcpy(yylval.nac,fortrantext);return TOK_OUT;}
-	YY_BREAK
-case 90:
-YY_RULE_SETUP
-#line 217 "fortran.lex"
-{strcpy(yylval.nac,fortrantext);return TOK_INOUT;}
-	YY_BREAK
-case 91:
-YY_RULE_SETUP
-#line 218 "fortran.lex"
-{return TOK_INTRINSIC;}
-	YY_BREAK
-case 92:
-YY_RULE_SETUP
-#line 219 "fortran.lex"
-{return TOK_THEN;}
-	YY_BREAK
-case 93:
-YY_RULE_SETUP
-#line 220 "fortran.lex"
-{return TOK_ELSEIF;}
-	YY_BREAK
-case 94:
-YY_RULE_SETUP
-#line 221 "fortran.lex"
-{return TOK_ELSE;}
-	YY_BREAK
-case 95:
-YY_RULE_SETUP
-#line 222 "fortran.lex"
-{return TOK_ENDIF;}
-	YY_BREAK
-case 96:
-YY_RULE_SETUP
-#line 223 "fortran.lex"
-{return TOK_LOGICALIF;}
-	YY_BREAK
-case 97:
-YY_RULE_SETUP
-#line 224 "fortran.lex"
-{return TOK_SUM;}
-	YY_BREAK
-case 98:
-YY_RULE_SETUP
-#line 225 "fortran.lex"
-{return TOK_MAX;}
-	YY_BREAK
-case 99:
-YY_RULE_SETUP
-#line 226 "fortran.lex"
-{return TOK_TANH;}
-	YY_BREAK
-case 100:
-YY_RULE_SETUP
-#line 227 "fortran.lex"
-{return TOK_MAXVAL;}
-	YY_BREAK
-case 101:
-YY_RULE_SETUP
-#line 228 "fortran.lex"
-{return TOK_TRIM;}
-	YY_BREAK
-case 102:
-YY_RULE_SETUP
-#line 229 "fortran.lex"
-{return TOK_SQRT;}
-	YY_BREAK
-case 103:
-YY_RULE_SETUP
-#line 230 "fortran.lex"
-{return TOK_SELECTCASE;}
-	YY_BREAK
-case 104:
-YY_RULE_SETUP
-#line 231 "fortran.lex"
-{return TOK_CASE;}
-	YY_BREAK
-case 105:
-YY_RULE_SETUP
-#line 232 "fortran.lex"
-{return TOK_CASEDEFAULT;}
-	YY_BREAK
-case 106:
-YY_RULE_SETUP
-#line 233 "fortran.lex"
-{return TOK_ENDSELECT;}
-	YY_BREAK
-case 107:
-YY_RULE_SETUP
-#line 234 "fortran.lex"
-{return TOK_FILE;}
-	YY_BREAK
-case 108:
-YY_RULE_SETUP
-#line 235 "fortran.lex"
-{return TOK_END;}
-	YY_BREAK
-case 109:
-YY_RULE_SETUP
-#line 236 "fortran.lex"
-{return TOK_ERR;}
-	YY_BREAK
-case 110:
-YY_RULE_SETUP
-#line 237 "fortran.lex"
-{return TOK_EXIST;}
-	YY_BREAK
-case 111:
-YY_RULE_SETUP
-#line 238 "fortran.lex"
-{return TOK_MIN;}
-	YY_BREAK
-case 112:
-YY_RULE_SETUP
-#line 239 "fortran.lex"
-{return TOK_NINT;}
-	YY_BREAK
-case 113:
-YY_RULE_SETUP
-#line 240 "fortran.lex"
-{return TOK_FLOAT;}
-	YY_BREAK
-case 114:
-YY_RULE_SETUP
-#line 241 "fortran.lex"
-{return TOK_EXP;}
-	YY_BREAK
-case 115:
-YY_RULE_SETUP
-#line 242 "fortran.lex"
-{return TOK_COS;}
-	YY_BREAK
-case 116:
-YY_RULE_SETUP
-#line 243 "fortran.lex"
-{return TOK_COSH;}
-	YY_BREAK
-case 117:
-YY_RULE_SETUP
-#line 244 "fortran.lex"
-{return TOK_ACOS;}
-	YY_BREAK
-case 118:
-YY_RULE_SETUP
-#line 245 "fortran.lex"
-{return TOK_SIN;}
-	YY_BREAK
-case 119:
-YY_RULE_SETUP
-#line 246 "fortran.lex"
-{return TOK_SINH;}
-	YY_BREAK
-case 120:
-YY_RULE_SETUP
-#line 247 "fortran.lex"
-{return TOK_ASIN;}
-	YY_BREAK
-case 121:
-YY_RULE_SETUP
-#line 248 "fortran.lex"
-{return TOK_LOG;}
-	YY_BREAK
-case 122:
-YY_RULE_SETUP
-#line 249 "fortran.lex"
-{return TOK_TAN;}
-	YY_BREAK
-case 123:
+                              return TOK_FORMAT; }
+	YY_BREAK
+case 144:
 YY_RULE_SETUP
 #line 250 "fortran.lex"
-{return TOK_ATAN;}
-	YY_BREAK
-case 124:
+{ strcpy(yylval.na,fortran_text); return TOK_SLASH; }
+	YY_BREAK
+case 145:
 YY_RULE_SETUP
 #line 251 "fortran.lex"
-{return TOK_CYCLE;}
-	YY_BREAK
-case 125:
+{ strcpy(yylval.na,fortran_text); return TOK_DSLASH; }
+	YY_BREAK
+case 146:
+/* rule 146 can match eol */
 YY_RULE_SETUP
 #line 252 "fortran.lex"
-{return TOK_ABS;}
-	YY_BREAK
-case 126:
-YY_RULE_SETUP
-#line 253 "fortran.lex"
-{return TOK_MOD;}
-	YY_BREAK
-case 127:
+{
+                              strcpy(yylval.na,fortran_text); return TOK_CHAR_CUT; }
+	YY_BREAK
+case 147:
+/* rule 147 can match eol */
 YY_RULE_SETUP
 #line 254 "fortran.lex"
-{return TOK_SIGN;}
-	YY_BREAK
-case 128:
+{ strcpy(yylval.na,fortran_text);return TOK_CHAR_CONSTANT; }
+	YY_BREAK
+case 148:
+/* rule 148 can match eol */
 YY_RULE_SETUP
 #line 255 "fortran.lex"
-{return TOK_MINLOC;}
-	YY_BREAK
-case 129:
+{ strcpy(yylval.na,fortran_text);return TOK_CHAR_MESSAGE; }
+	YY_BREAK
+case 149:
 YY_RULE_SETUP
 #line 256 "fortran.lex"
-{return TOK_MAXLOC;}
-	YY_BREAK
-case 130:
+{ BEGIN(donottreat); }
+	YY_BREAK
+case 150:
+/* rule 150 can match eol */
 YY_RULE_SETUP
 #line 257 "fortran.lex"
-{return TOK_MINVAL;}
-	YY_BREAK
-case 131:
+{ out_of_donottreat(); return '\n'; }
+	YY_BREAK
+case 151:
 YY_RULE_SETUP
 #line 258 "fortran.lex"
-{return TOK_BACKSPACE;}
-	YY_BREAK
-case 132:
+{ strcpy(yylval.na,fortran_text); return TOK_NAME; }
+	YY_BREAK
+case 152:
+/* rule 152 can match eol */
+*yy_cp = (yy_hold_char); /* undo effects of setting up fortran_text */
+(yy_c_buf_p) = yy_cp -= 1;
+YY_DO_BEFORE_ACTION; /* set up fortran_text again */
 YY_RULE_SETUP
 #line 259 "fortran.lex"
-{return TOK_LEFTAB;}
-	YY_BREAK
-case 133:
-YY_RULE_SETUP
-#line 260 "fortran.lex"
-{return TOK_RIGHTAB;}
-	YY_BREAK
-case 134:
-/* rule 134 can match eol */
+{  // REAL1
+                              strcpy(yylval.na,fortran_text); return TOK_CSTREAL; }
+	YY_BREAK
+case 153:
 YY_RULE_SETUP
 #line 261 "fortran.lex"
-{return TOK_FORMAT;}
-	YY_BREAK
-case 135:
-YY_RULE_SETUP
-#line 262 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_DOUBLEPRECISION;}
-	YY_BREAK
-case 136:
+{  // REAL2
+                              strcpy(yylval.na,fortran_text); return TOK_CSTREAL; }
+	YY_BREAK
+case 154:
 YY_RULE_SETUP
 #line 263 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_DOUBLECOMPLEX;}
-	YY_BREAK
-case 137:
+{ strcpy(yylval.na,fortran_text); return TOK_CSTINT; }
+	YY_BREAK
+case 155:
 YY_RULE_SETUP
 #line 264 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_SLASH;}
-	YY_BREAK
-case 138:
+{}
+	YY_BREAK
+case 156:
 YY_RULE_SETUP
 #line 265 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_DSLASH;}
-	YY_BREAK
-case 139:
-/* rule 139 can match eol */
+{}
+	YY_BREAK
+case 157:
 YY_RULE_SETUP
 #line 266 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CHAR_CUT;}
-	YY_BREAK
-case 140:
+{ strcpy(yylval.na,fortran_text); return (int) *fortran_text; }
+	YY_BREAK
+case 158:
 YY_RULE_SETUP
 #line 267 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CHAR_CONSTANT;}
-	YY_BREAK
-case 141:
+{ strcpy(yylval.na,fortran_text); return (int) *fortran_text; }
+	YY_BREAK
+case 159:
 YY_RULE_SETUP
 #line 268 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CHAR_MESSAGE;}
-	YY_BREAK
-case 142:
+{ return TOK_SEMICOLON; }
+	YY_BREAK
+case 160:
 YY_RULE_SETUP
 #line 269 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CHAR_INT;}
-	YY_BREAK
-case 143:
+{ return (int) *fortran_text; }
+	YY_BREAK
+case 161:
 YY_RULE_SETUP
 #line 270 "fortran.lex"
-{printf("debug interfacer\n");BEGIN(donottreat);}
-	YY_BREAK
-case 144:
-/* rule 144 can match eol */
+{ return (int) *fortran_text; }
+	YY_BREAK
+case 162:
 YY_RULE_SETUP
 #line 271 "fortran.lex"
-{
-						BEGIN(INITIAL);
-                        if (infixed) BEGIN(fortran77style) ;
-                        if (infree) BEGIN(fortran90style)  ;
-                        line_num_fortran++;line_num_fortran_common++;
-                        return '\n';
-						}
-	YY_BREAK
-case 145:
-YY_RULE_SETUP
-#line 278 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_NAME;}
-	YY_BREAK
-case 146:
-YY_RULE_SETUP
-#line 279 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CSTREAL;}
-	YY_BREAK
-case 147:
-YY_RULE_SETUP
-#line 280 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CSTREALDP;}
-	YY_BREAK
-case 148:
-YY_RULE_SETUP
-#line 281 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CSTREALQP;}
-	YY_BREAK
-case 149:
-/* rule 149 can match eol */
-*yy_cp = (yy_hold_char); /* undo effects of setting up fortrantext */
+{ return (int) *fortran_text; }
+	YY_BREAK
+case 163:
+YY_RULE_SETUP
+#line 272 "fortran.lex"
+{ return (int) *fortran_text; }
+	YY_BREAK
+case 164:
+/* rule 164 can match eol */
+YY_RULE_SETUP
+#line 273 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; return '\n'; }
+	YY_BREAK
+case 165:
+*yy_cp = (yy_hold_char); /* undo effects of setting up fortran_text */
 (yy_c_buf_p) = yy_cp -= 1;
-YY_DO_BEFORE_ACTION; /* set up fortrantext again */
-YY_RULE_SETUP
-#line 282 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CSTREAL;}
-	YY_BREAK
-case 150:
-YY_RULE_SETUP
-#line 283 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return TOK_CSTINT;}
-	YY_BREAK
-case 151:
-YY_RULE_SETUP
-#line 284 "fortran.lex"
+YY_DO_BEFORE_ACTION; /* set up fortran_text again */
+YY_RULE_SETUP
+#line 274 "fortran.lex"
 {}
 	YY_BREAK
-case 152:
-YY_RULE_SETUP
-#line 285 "fortran.lex"
-{return TOK_QUOTE;}
-	YY_BREAK
-case 153:
-YY_RULE_SETUP
-#line 286 "fortran.lex"
+case 166:
+YY_RULE_SETUP
+#line 275 "fortran.lex"
 {}
 	YY_BREAK
-case 154:
-YY_RULE_SETUP
-#line 287 "fortran.lex"
-{strcpy(yylval.na,fortrantext);return (int) *fortrantext;}
-	YY_BREAK
-case 155:
-YY_RULE_SETUP
-#line 288 "fortran.lex"
-{afterpercent = 1; strcpy(yylval.na,fortrantext);return (int) *fortrantext;}
-	YY_BREAK
-case 156:
-YY_RULE_SETUP
-#line 289 "fortran.lex"
-{return TOK_SEMICOLON;}
-	YY_BREAK
-case 157:
-YY_RULE_SETUP
-#line 290 "fortran.lex"
-{return (int) *fortrantext;}
-	YY_BREAK
-case 158:
-YY_RULE_SETUP
-#line 291 "fortran.lex"
-{return (int) *fortrantext;}
-	YY_BREAK
-case 159:
-YY_RULE_SETUP
-#line 292 "fortran.lex"
-{return (int) *fortrantext;}
-	YY_BREAK
-case 160:
-YY_RULE_SETUP
-#line 293 "fortran.lex"
-{return (int) *fortrantext;}
-	YY_BREAK
-case 161:
-/* rule 161 can match eol */
-YY_RULE_SETUP
-#line 294 "fortran.lex"
-{colnum=0;line_num_fortran++;line_num_fortran_common++; return (int) *fortrantext;}
-	YY_BREAK
-case 162:
-*yy_cp = (yy_hold_char); /* undo effects of setting up fortrantext */
-(yy_c_buf_p) = yy_cp -= 1;
-YY_DO_BEFORE_ACTION; /* set up fortrantext again */
-YY_RULE_SETUP
-#line 295 "fortran.lex"
-
-	YY_BREAK
-case 163:
-YY_RULE_SETUP
-#line 296 "fortran.lex"
-{if (newlinef90 == 0) return TOK_LABEL; else newlinef90 = 0;}
-	YY_BREAK
-case 164:
-YY_RULE_SETUP
-#line 297 "fortran.lex"
-
-	YY_BREAK
-case 165:
-YY_RULE_SETUP
-#line 298 "fortran.lex"
-{colnum=colnum-1+tabsize;}
-	YY_BREAK
-case 166:
-YY_RULE_SETUP
-#line 299 "fortran.lex"
-;
-	YY_BREAK
 case 167:
-/* rule 167 can match eol */
-YY_RULE_SETUP
-#line 300 "fortran.lex"
-{line_num_fortran++;line_num_fortran_common++;newlinef90=1;colnum=0;}
+YY_RULE_SETUP
+#line 276 "fortran.lex"
+{ if (newlinef90 == 0) return TOK_LABEL; else newlinef90 = 0; }
 	YY_BREAK
 case 168:
 /* rule 168 can match eol */
 YY_RULE_SETUP
-#line 301 "fortran.lex"
-{line_num_fortran++;line_num_fortran_common++;colnum=0;}
+#line 277 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; newlinef90=1; }
 	YY_BREAK
 case 169:
 /* rule 169 can match eol */
 YY_RULE_SETUP
-#line 302 "fortran.lex"
-{
-                           convert2lower(motparse1);
-                           if ( strncasecmp(motparse1,"contains",8) == 0 )
-                           {
-                              return TOK_CONTAINS;
-                           }
-                           else
-                           {
-                            /*  colnum=0;line_num_fortran++;line_num_fortran_common++;*/
-                             if ( !strcasecmp(motparse1,"C$AGRIF_DO_NOT_TREAT\n")) 
-                             return TOK_DONOTTREAT;
-                             if ( !strcasecmp(motparse1,"C$AGRIF_END_DO_NOT_TREAT\n")) return TOK_ENDDONOTTREAT;
-                             unput('\n');
-                           }
-                         }
+#line 278 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; }
 	YY_BREAK
 case 170:
 /* rule 170 can match eol */
 YY_RULE_SETUP
-#line 317 "fortran.lex"
-{
-                           convert2lower(&motparse1[1]);
-                           if ( strncasecmp(&motparse1[1],"contains",8) == 0 )
-                           {
-                              return TOK_CONTAINS;
-                           }
-                           else
-                           {
-                             /* colnum=0;line_num_fortran++;line_num_fortran_common++;*/
-                             if ( !strcasecmp(&motparse1[1],"C$AGRIF_DO_NOT_TREAT\n")) 
-                             return TOK_DONOTTREAT;
-                             if ( !strcasecmp(&motparse1[1],"C$AGRIF_END_DO_NOT_TREAT\n")) return TOK_ENDDONOTTREAT;
-                             unput('\n');
-                           }
-                         }                            
+#line 280 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; BEGIN(donottreat); }
 	YY_BREAK
 case 171:
 /* rule 171 can match eol */
 YY_RULE_SETUP
-#line 332 "fortran.lex"
-{
-						BEGIN(donottreat);
-						}
+#line 281 "fortran.lex"
+{ out_of_donottreat(); return '\n'; }
 	YY_BREAK
 case 172:
 /* rule 172 can match eol */
 YY_RULE_SETUP
-#line 335 "fortran.lex"
-{
-						BEGIN(INITIAL);
-                        if (infixed) BEGIN(fortran77style) ;
-                        if (infree) BEGIN(fortran90style)  ;
-                        line_num_fortran++;line_num_fortran_common++;
-                        return '\n';
-						}
+#line 282 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; }
 	YY_BREAK
 case 173:
 /* rule 173 can match eol */
 YY_RULE_SETUP
-#line 342 "fortran.lex"
-{line_num_fortran++;line_num_fortran_common++;}
+#line 283 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; }
 	YY_BREAK
 case 174:
 /* rule 174 can match eol */
 YY_RULE_SETUP
-#line 343 "fortran.lex"
-{
-                             colnum = 0;
-                             if ( !strcasecmp(motparse1,"!$AGRIF_DO_NOT_TREAT\n")) return TOK_DONOTTREAT;
-                             if ( !strcasecmp(motparse1,"!$AGRIF_END_DO_NOT_TREAT\n")) return TOK_ENDDONOTTREAT;
-                          }
+#line 284 "fortran.lex"
+{ INCREMENT_LINE_NUM() ; }
 	YY_BREAK
 case 175:
 YY_RULE_SETUP
-#line 348 "fortran.lex"
-{
-                             colnum = 0;
-                             if ( !strcasecmp(motparse1,"!$AGRIF_DO_NOT_TREAT\n")) return TOK_DONOTTREAT;
-                             if ( !strcasecmp(motparse1,"!$AGRIF_END_DO_NOT_TREAT\n")) return TOK_ENDDONOTTREAT;
-                          }
+#line 285 "fortran.lex"
+{}
 	YY_BREAK
 case 176:
 YY_RULE_SETUP
-#line 353 "fortran.lex"
+#line 286 "fortran.lex"
 ECHO;
 	YY_BREAK
-#line 4224 "fortran.yy.c"
+#line 3015 "fortran.yy.c"
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(parameter):
@@ -11106,6 +9444,6 @@
 			/* We're scanning a new file or input source.  It's
 			 * possible that this happened because the user
-			 * just pointed fortranin at a new source and called
-			 * fortranlex().  If so, then we have to assure
+			 * just pointed fortran_in at a new source and called
+			 * fortran_lex().  If so, then we have to assure
 			 * consistency between YY_CURRENT_BUFFER and our
 			 * globals.  Here is the right place to do so, because
@@ -11114,5 +9452,5 @@
 			 */
 			(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-			YY_CURRENT_BUFFER_LVALUE->yy_input_file = fortranin;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = fortran_in;
 			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
 			}
@@ -11167,9 +9505,9 @@
 				(yy_did_buffer_switch_on_eof) = 0;
 
-				if ( fortranwrap( ) )
+				if ( fortran_wrap( ) )
 					{
 					/* Note: because we've taken care in
 					 * yy_get_next_buffer() to have set up
-					 * fortrantext, we can now set up
+					 * fortran_text, we can now set up
 					 * yy_c_buf_p so that if some total
 					 * hoser (like flex itself) wants to
@@ -11220,5 +9558,5 @@
 	} /* end of action switch */
 		} /* end of scanning one token */
-} /* end of fortranlex */
+} /* end of fortran_lex */
 
 /* yy_get_next_buffer - try to read in a new buffer
@@ -11298,5 +9636,5 @@
 				b->yy_ch_buf = (char *)
 					/* Include room in for 2 EOB chars. */
-					fortranrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
+					fortran_realloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
 				}
 			else
@@ -11330,5 +9668,5 @@
 			{
 			ret_val = EOB_ACT_END_OF_FILE;
-			fortranrestart(fortranin  );
+			fortran_restart(fortran_in  );
 			}
 
@@ -11347,5 +9685,5 @@
 		/* Extend the array by 50%, plus the number we really need. */
 		yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
-		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) fortranrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) fortran_realloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
 		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
 			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
@@ -11382,5 +9720,5 @@
 			{
 			yy_current_state = (int) yy_def[yy_current_state];
-			if ( yy_current_state >= 1162 )
+			if ( yy_current_state >= 1132 )
 				yy_c = yy_meta[(unsigned int) yy_c];
 			}
@@ -11410,9 +9748,9 @@
 		{
 		yy_current_state = (int) yy_def[yy_current_state];
-		if ( yy_current_state >= 1162 )
+		if ( yy_current_state >= 1132 )
 			yy_c = yy_meta[(unsigned int) yy_c];
 		}
 	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-	yy_is_jam = (yy_current_state == 1161);
+	yy_is_jam = (yy_current_state == 1131);
 
 	return yy_is_jam ? 0 : yy_current_state;
@@ -11425,5 +9763,5 @@
     yy_cp = (yy_c_buf_p);
 
-	/* undo effects of setting up fortrantext */
+	/* undo effects of setting up fortran_text */
 	*yy_cp = (yy_hold_char);
 
@@ -11497,5 +9835,5 @@
 
 					/* Reset buffer status. */
-					fortranrestart(fortranin );
+					fortran_restart(fortran_in );
 
 					/*FALLTHROUGH*/
@@ -11503,5 +9841,5 @@
 				case EOB_ACT_END_OF_FILE:
 					{
-					if ( fortranwrap( ) )
+					if ( fortran_wrap( ) )
 						return 0;
 
@@ -11523,5 +9861,5 @@
 
 	c = *(unsigned char *) (yy_c_buf_p);	/* cast for 8-bit char's */
-	*(yy_c_buf_p) = '\0';	/* preserve fortrantext */
+	*(yy_c_buf_p) = '\0';	/* preserve fortran_text */
 	(yy_hold_char) = *++(yy_c_buf_p);
 
@@ -11537,15 +9875,15 @@
  * @note This function does not reset the start condition to @c INITIAL .
  */
-    void fortranrestart  (FILE * input_file )
+    void fortran_restart  (FILE * input_file )
 {
     
 	if ( ! YY_CURRENT_BUFFER ){
-        fortranensure_buffer_stack ();
+        fortran_ensure_buffer_stack ();
 		YY_CURRENT_BUFFER_LVALUE =
-            fortran_create_buffer(fortranin,YY_BUF_SIZE );
+            fortran__create_buffer(fortran_in,YY_BUF_SIZE );
 	}
 
-	fortran_init_buffer(YY_CURRENT_BUFFER,input_file );
-	fortran_load_buffer_state( );
+	fortran__init_buffer(YY_CURRENT_BUFFER,input_file );
+	fortran__load_buffer_state( );
 }
 
@@ -11554,13 +9892,13 @@
  * 
  */
-    void fortran_switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
+    void fortran__switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
 {
     
 	/* TODO. We should be able to replace this entire function body
 	 * with
-	 *		fortranpop_buffer_state();
-	 *		fortranpush_buffer_state(new_buffer);
+	 *		fortran_pop_buffer_state();
+	 *		fortran_push_buffer_state(new_buffer);
      */
-	fortranensure_buffer_stack ();
+	fortran_ensure_buffer_stack ();
 	if ( YY_CURRENT_BUFFER == new_buffer )
 		return;
@@ -11575,9 +9913,9 @@
 
 	YY_CURRENT_BUFFER_LVALUE = new_buffer;
-	fortran_load_buffer_state( );
+	fortran__load_buffer_state( );
 
 	/* We don't actually know whether we did this switch during
-	 * EOF (fortranwrap()) processing, but the only time this flag
-	 * is looked at is after fortranwrap() is called, so it's safe
+	 * EOF (fortran_wrap()) processing, but the only time this flag
+	 * is looked at is after fortran_wrap() is called, so it's safe
 	 * to go ahead and always set it.
 	 */
@@ -11585,9 +9923,9 @@
 }
 
-static void fortran_load_buffer_state  (void)
+static void fortran__load_buffer_state  (void)
 {
     	(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
 	(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
-	fortranin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	fortran_in = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
 	(yy_hold_char) = *(yy_c_buf_p);
 }
@@ -11599,11 +9937,11 @@
  * @return the allocated buffer state.
  */
-    YY_BUFFER_STATE fortran_create_buffer  (FILE * file, int  size )
+    YY_BUFFER_STATE fortran__create_buffer  (FILE * file, int  size )
 {
 	YY_BUFFER_STATE b;
     
-	b = (YY_BUFFER_STATE) fortranalloc(sizeof( struct yy_buffer_state )  );
+	b = (YY_BUFFER_STATE) fortran_alloc(sizeof( struct yy_buffer_state )  );
 	if ( ! b )
-		YY_FATAL_ERROR( "out of dynamic memory in fortran_create_buffer()" );
+		YY_FATAL_ERROR( "out of dynamic memory in fortran__create_buffer()" );
 
 	b->yy_buf_size = size;
@@ -11612,11 +9950,11 @@
 	 * we need to put in 2 end-of-buffer characters.
 	 */
-	b->yy_ch_buf = (char *) fortranalloc(b->yy_buf_size + 2  );
+	b->yy_ch_buf = (char *) fortran_alloc(b->yy_buf_size + 2  );
 	if ( ! b->yy_ch_buf )
-		YY_FATAL_ERROR( "out of dynamic memory in fortran_create_buffer()" );
+		YY_FATAL_ERROR( "out of dynamic memory in fortran__create_buffer()" );
 
 	b->yy_is_our_buffer = 1;
 
-	fortran_init_buffer(b,file );
+	fortran__init_buffer(b,file );
 
 	return b;
@@ -11624,8 +9962,8 @@
 
 /** Destroy the buffer.
- * @param b a buffer created with fortran_create_buffer()
+ * @param b a buffer created with fortran__create_buffer()
  * 
  */
-    void fortran_delete_buffer (YY_BUFFER_STATE  b )
+    void fortran__delete_buffer (YY_BUFFER_STATE  b )
 {
     
@@ -11637,7 +9975,7 @@
 
 	if ( b->yy_is_our_buffer )
-		fortranfree((void *) b->yy_ch_buf  );
-
-	fortranfree((void *) b  );
+		fortran_free((void *) b->yy_ch_buf  );
+
+	fortran_free((void *) b  );
 }
 
@@ -11648,18 +9986,18 @@
 /* Initializes or reinitializes a buffer.
  * This function is sometimes called more than once on the same buffer,
- * such as during a fortranrestart() or at EOF.
+ * such as during a fortran_restart() or at EOF.
  */
-    static void fortran_init_buffer  (YY_BUFFER_STATE  b, FILE * file )
+    static void fortran__init_buffer  (YY_BUFFER_STATE  b, FILE * file )
 
 {
 	int oerrno = errno;
     
-	fortran_flush_buffer(b );
+	fortran__flush_buffer(b );
 
 	b->yy_input_file = file;
 	b->yy_fill_buffer = 1;
 
-    /* If b is the current buffer, then fortran_init_buffer was _probably_
-     * called from fortranrestart() or through yy_get_next_buffer.
+    /* If b is the current buffer, then fortran__init_buffer was _probably_
+     * called from fortran_restart() or through yy_get_next_buffer.
      * In that case, we don't want to reset the lineno or column.
      */
@@ -11678,5 +10016,5 @@
  * 
  */
-    void fortran_flush_buffer (YY_BUFFER_STATE  b )
+    void fortran__flush_buffer (YY_BUFFER_STATE  b )
 {
     	if ( ! b )
@@ -11698,5 +10036,5 @@
 
 	if ( b == YY_CURRENT_BUFFER )
-		fortran_load_buffer_state( );
+		fortran__load_buffer_state( );
 }
 
@@ -11707,12 +10045,12 @@
  *  
  */
-void fortranpush_buffer_state (YY_BUFFER_STATE new_buffer )
+void fortran_push_buffer_state (YY_BUFFER_STATE new_buffer )
 {
     	if (new_buffer == NULL)
 		return;
 
-	fortranensure_buffer_stack();
-
-	/* This block is copied from fortran_switch_to_buffer. */
+	fortran_ensure_buffer_stack();
+
+	/* This block is copied from fortran__switch_to_buffer. */
 	if ( YY_CURRENT_BUFFER )
 		{
@@ -11728,6 +10066,6 @@
 	YY_CURRENT_BUFFER_LVALUE = new_buffer;
 
-	/* copied from fortran_switch_to_buffer. */
-	fortran_load_buffer_state( );
+	/* copied from fortran__switch_to_buffer. */
+	fortran__load_buffer_state( );
 	(yy_did_buffer_switch_on_eof) = 1;
 }
@@ -11737,10 +10075,10 @@
  *  
  */
-void fortranpop_buffer_state (void)
+void fortran_pop_buffer_state (void)
 {
     	if (!YY_CURRENT_BUFFER)
 		return;
 
-	fortran_delete_buffer(YY_CURRENT_BUFFER );
+	fortran__delete_buffer(YY_CURRENT_BUFFER );
 	YY_CURRENT_BUFFER_LVALUE = NULL;
 	if ((yy_buffer_stack_top) > 0)
@@ -11748,5 +10086,5 @@
 
 	if (YY_CURRENT_BUFFER) {
-		fortran_load_buffer_state( );
+		fortran__load_buffer_state( );
 		(yy_did_buffer_switch_on_eof) = 1;
 	}
@@ -11756,5 +10094,5 @@
  *  Guarantees space for at least one push.
  */
-static void fortranensure_buffer_stack (void)
+static void fortran_ensure_buffer_stack (void)
 {
 	yy_size_t num_to_alloc;
@@ -11767,9 +10105,9 @@
          */
 		num_to_alloc = 1;
-		(yy_buffer_stack) = (struct yy_buffer_state**)fortranalloc
+		(yy_buffer_stack) = (struct yy_buffer_state**)fortran_alloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
 		if ( ! (yy_buffer_stack) )
-			YY_FATAL_ERROR( "out of dynamic memory in fortranensure_buffer_stack()" );
+			YY_FATAL_ERROR( "out of dynamic memory in fortran_ensure_buffer_stack()" );
 								  
 		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -11786,10 +10124,10 @@
 
 		num_to_alloc = (yy_buffer_stack_max) + grow_size;
-		(yy_buffer_stack) = (struct yy_buffer_state**)fortranrealloc
+		(yy_buffer_stack) = (struct yy_buffer_state**)fortran_realloc
 								((yy_buffer_stack),
 								num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
 		if ( ! (yy_buffer_stack) )
-			YY_FATAL_ERROR( "out of dynamic memory in fortranensure_buffer_stack()" );
+			YY_FATAL_ERROR( "out of dynamic memory in fortran_ensure_buffer_stack()" );
 
 		/* zero only the new slots.*/
@@ -11805,5 +10143,5 @@
  * @return the newly allocated buffer state object. 
  */
-YY_BUFFER_STATE fortran_scan_buffer  (char * base, yy_size_t  size )
+YY_BUFFER_STATE fortran__scan_buffer  (char * base, yy_size_t  size )
 {
 	YY_BUFFER_STATE b;
@@ -11815,7 +10153,7 @@
 		return 0;
 
-	b = (YY_BUFFER_STATE) fortranalloc(sizeof( struct yy_buffer_state )  );
+	b = (YY_BUFFER_STATE) fortran_alloc(sizeof( struct yy_buffer_state )  );
 	if ( ! b )
-		YY_FATAL_ERROR( "out of dynamic memory in fortran_scan_buffer()" );
+		YY_FATAL_ERROR( "out of dynamic memory in fortran__scan_buffer()" );
 
 	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
@@ -11829,10 +10167,10 @@
 	b->yy_buffer_status = YY_BUFFER_NEW;
 
-	fortran_switch_to_buffer(b  );
+	fortran__switch_to_buffer(b  );
 
 	return b;
 }
 
-/** Setup the input buffer state to scan a string. The next call to fortranlex() will
+/** Setup the input buffer state to scan a string. The next call to fortran_lex() will
  * scan from a @e copy of @a str.
  * @param yystr a NUL-terminated string to scan
@@ -11840,13 +10178,13 @@
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
- *       fortran_scan_bytes() instead.
+ *       fortran__scan_bytes() instead.
  */
-YY_BUFFER_STATE fortran_scan_string (yyconst char * yystr )
+YY_BUFFER_STATE fortran__scan_string (yyconst char * yystr )
 {
     
-	return fortran_scan_bytes(yystr,strlen(yystr) );
+	return fortran__scan_bytes(yystr,strlen(yystr) );
 }
 
-/** Setup the input buffer state to scan the given bytes. The next call to fortranlex() will
+/** Setup the input buffer state to scan the given bytes. The next call to fortran_lex() will
  * scan from a @e copy of @a bytes.
  * @param bytes the byte buffer to scan
@@ -11855,5 +10193,5 @@
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE fortran_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybytes_len )
+YY_BUFFER_STATE fortran__scan_bytes  (yyconst char * yybytes, yy_size_t  _yybytes_len )
 {
 	YY_BUFFER_STATE b;
@@ -11863,7 +10201,7 @@
 	/* Get memory for full buffer, including space for trailing EOB's. */
 	n = _yybytes_len + 2;
-	buf = (char *) fortranalloc(n  );
+	buf = (char *) fortran_alloc(n  );
 	if ( ! buf )
-		YY_FATAL_ERROR( "out of dynamic memory in fortran_scan_bytes()" );
+		YY_FATAL_ERROR( "out of dynamic memory in fortran__scan_bytes()" );
 
 	for ( i = 0; i < _yybytes_len; ++i )
@@ -11872,7 +10210,7 @@
 	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
 
-	b = fortran_scan_buffer(buf,n );
+	b = fortran__scan_buffer(buf,n );
 	if ( ! b )
-		YY_FATAL_ERROR( "bad buffer in fortran_scan_bytes()" );
+		YY_FATAL_ERROR( "bad buffer in fortran__scan_bytes()" );
 
 	/* It's okay to grow etc. this buffer, and we should throw it
@@ -11900,12 +10238,12 @@
 	do \
 		{ \
-		/* Undo effects of setting up fortrantext. */ \
+		/* Undo effects of setting up fortran_text. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-		fortrantext[fortranleng] = (yy_hold_char); \
-		(yy_c_buf_p) = fortrantext + yyless_macro_arg; \
+		fortran_text[fortran_leng] = (yy_hold_char); \
+		(yy_c_buf_p) = fortran_text + yyless_macro_arg; \
 		(yy_hold_char) = *(yy_c_buf_p); \
 		*(yy_c_buf_p) = '\0'; \
-		fortranleng = yyless_macro_arg; \
+		fortran_leng = yyless_macro_arg; \
 		} \
 	while ( 0 )
@@ -11916,8 +10254,8 @@
  * 
  */
-int fortranget_lineno  (void)
+int fortran_get_lineno  (void)
 {
         
-    return fortranlineno;
+    return fortran_lineno;
 }
 
@@ -11925,7 +10263,7 @@
  * 
  */
-FILE *fortranget_in  (void)
+FILE *fortran_get_in  (void)
 {
-        return fortranin;
+        return fortran_in;
 }
 
@@ -11933,7 +10271,7 @@
  * 
  */
-FILE *fortranget_out  (void)
+FILE *fortran_get_out  (void)
 {
-        return fortranout;
+        return fortran_out;
 }
 
@@ -11941,7 +10279,7 @@
  * 
  */
-yy_size_t fortranget_leng  (void)
+yy_size_t fortran_get_leng  (void)
 {
-        return fortranleng;
+        return fortran_leng;
 }
 
@@ -11950,7 +10288,7 @@
  */
 
-char *fortranget_text  (void)
+char *fortran_get_text  (void)
 {
-        return fortrantext;
+        return fortran_text;
 }
 
@@ -11959,8 +10297,8 @@
  * 
  */
-void fortranset_lineno (int  line_number )
+void fortran_set_lineno (int  line_number )
 {
     
-    fortranlineno = line_number;
+    fortran_lineno = line_number;
 }
 
@@ -11969,24 +10307,24 @@
  * @param in_str A readable stream.
  * 
- * @see fortran_switch_to_buffer
+ * @see fortran__switch_to_buffer
  */
-void fortranset_in (FILE *  in_str )
+void fortran_set_in (FILE *  in_str )
 {
-        fortranin = in_str ;
+        fortran_in = in_str ;
 }
 
-void fortranset_out (FILE *  out_str )
+void fortran_set_out (FILE *  out_str )
 {
-        fortranout = out_str ;
+        fortran_out = out_str ;
 }
 
-int fortranget_debug  (void)
+int fortran_get_debug  (void)
 {
-        return fortran_flex_debug;
+        return fortran__flex_debug;
 }
 
-void fortranset_debug (int  bdebug )
+void fortran_set_debug (int  bdebug )
 {
-        fortran_flex_debug = bdebug ;
+        fortran__flex_debug = bdebug ;
 }
 
@@ -11994,5 +10332,5 @@
 {
         /* Initialization is the same as for the non-reentrant scanner.
-     * This function is called from fortranlex_destroy(), so don't allocate here.
+     * This function is called from fortran_lex_destroy(), so don't allocate here.
      */
 
@@ -12006,34 +10344,34 @@
 /* Defined in main.c */
 #ifdef YY_STDINIT
-    fortranin = stdin;
-    fortranout = stdout;
+    fortran_in = stdin;
+    fortran_out = stdout;
 #else
-    fortranin = (FILE *) 0;
-    fortranout = (FILE *) 0;
+    fortran_in = (FILE *) 0;
+    fortran_out = (FILE *) 0;
 #endif
 
     /* For future reference: Set errno on error, since we are called by
-     * fortranlex_init()
+     * fortran_lex_init()
      */
     return 0;
 }
 
-/* fortranlex_destroy is for both reentrant and non-reentrant scanners. */
-int fortranlex_destroy  (void)
+/* fortran_lex_destroy is for both reentrant and non-reentrant scanners. */
+int fortran_lex_destroy  (void)
 {
     
     /* Pop the buffer stack, destroying each element. */
 	while(YY_CURRENT_BUFFER){
-		fortran_delete_buffer(YY_CURRENT_BUFFER  );
+		fortran__delete_buffer(YY_CURRENT_BUFFER  );
 		YY_CURRENT_BUFFER_LVALUE = NULL;
-		fortranpop_buffer_state();
+		fortran_pop_buffer_state();
 	}
 
 	/* Destroy the stack itself. */
-	fortranfree((yy_buffer_stack) );
+	fortran_free((yy_buffer_stack) );
 	(yy_buffer_stack) = NULL;
 
     /* Reset the globals. This is important in a non-reentrant scanner so the next time
-     * fortranlex() is called, initialization will occur. */
+     * fortran_lex() is called, initialization will occur. */
     yy_init_globals( );
 
@@ -12065,10 +10403,10 @@
 #endif
 
-void *fortranalloc (yy_size_t  size )
+void *fortran_alloc (yy_size_t  size )
 {
 	return (void *) malloc( size );
 }
 
-void *fortranrealloc  (void * ptr, yy_size_t  size )
+void *fortran_realloc  (void * ptr, yy_size_t  size )
 {
 	/* The cast to (char *) in the following accommodates both
@@ -12082,30 +10420,21 @@
 }
 
-void fortranfree (void * ptr )
+void fortran_free (void * ptr )
 {
-	free( (char *) ptr );	/* see fortranrealloc() for (char *) cast */
+	free( (char *) ptr );	/* see fortran_realloc() for (char *) cast */
 }
 
 #define YYTABLES_NAME "yytables"
 
-#line 353 "fortran.lex"
-
-
-
-fortranerror(char *s)
+#line 286 "fortran.lex"
+
+
+
+void out_of_donottreat ( void )
 {
-   if (!strcasecmp(curfile,mainfile))
-   {
-      printf("%s line %d, file %s motclef = %s\n",s,line_num_fortran,curfile,fortrantext);
-   }
-   else
-   {
-      printf("%s line %d, file %s motclef = %s curbuf = %s\n",s,line_num_fortran_common,curfile,fortrantext,curbuf);
-   }
-/*   exit(0);*/
+    BEGIN(INITIAL);
+    if (infixed) BEGIN(fortran77style) ;
+    if (infree)  BEGIN(fortran90style) ;
+    INCREMENT_LINE_NUM() ;
 }
 
-int fortranwrap()
-{
-}
-
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/main.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/main.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/main.c	(revision 9987)
@@ -1,20 +1,23 @@
-/* A Bison parser, made by GNU Bison 2.7.12-4996.  */
-
-/* Bison implementation for Yacc-like parsers in C
-   
-      Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.
-   
-   This program is free software: you can redistribute it and/or modify
+/* A Bison parser, made by GNU Bison 2.3.  */
+
+/* Skeleton implementation for Bison's Yacc-like parsers in C
+
+   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+   Free Software Foundation, Inc.
+
+   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 3 of the License, or
-   (at your option) any later version.
-   
+   the Free Software Foundation; either version 2, 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, see <http://www.gnu.org/licenses/>.  */
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.  */
 
 /* As a special exception, you may create a larger work that contains
@@ -27,5 +30,5 @@
    Bison output files to be licensed under the GNU General Public
    License without this special exception.
-   
+
    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.  */
@@ -45,5 +48,5 @@
 
 /* Bison version.  */
-#define YYBISON_VERSION "2.7.12-4996"
+#define YYBISON_VERSION "2.3"
 
 /* Skeleton name.  */
@@ -53,49 +56,16 @@
 #define YYPURE 0
 
-/* Push parsers.  */
-#define YYPUSH 0
-
-/* Pull parsers.  */
-#define YYPULL 1
-
-
-
-
-/* Copy the first part of user declarations.  */
-/* Line 371 of yacc.c  */
-#line 35 "convert.y"
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include "decl.h"
-
-/* Line 371 of yacc.c  */
-#line 75 "convert.tab.c"
-
-# ifndef YY_NULL
-#  if defined __cplusplus && 201103L <= __cplusplus
-#   define YY_NULL nullptr
-#  else
-#   define YY_NULL 0
-#  endif
-# endif
-
-/* Enabling verbose error messages.  */
-#ifdef YYERROR_VERBOSE
-# undef YYERROR_VERBOSE
-# define YYERROR_VERBOSE 1
-#else
-# define YYERROR_VERBOSE 0
-#endif
-
-
-/* Enabling traces.  */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
-#if YYDEBUG
-extern int yydebug;
-#endif
+/* Using locations.  */
+#define YYLSP_NEEDED 0
+
+/* Substitute the variable and function names.  */
+#define yyparse convert_parse
+#define yylex   convert_lex
+#define yyerror convert_error
+#define yylval  convert_lval
+#define yychar  convert_char
+#define yydebug convert_debug
+#define yynerrs convert_nerrs
+
 
 /* Tokens.  */
@@ -106,48 +76,80 @@
    enum yytokentype {
      TOK_SEP = 258,
-     TOK_USE = 259,
-     TOK_MODULEMAIN = 260,
-     TOK_NOTGRIDDEP = 261,
-     TOK_USEITEM = 262,
-     TOK_NAME = 263,
-     TOK_PROBTYPE = 264
+     TOK_KIND = 259,
+     TOK_EQUAL = 260,
+     TOK_USE = 261,
+     TOK_MODULEMAIN = 262,
+     TOK_NOTGRIDDEP = 263,
+     TOK_USEITEM = 264,
+     TOK_NAME = 265,
+     TOK_CSTINT = 266,
+     TOK_PROBTYPE = 267
    };
 #endif
-
+/* Tokens.  */
+#define TOK_SEP 258
+#define TOK_KIND 259
+#define TOK_EQUAL 260
+#define TOK_USE 261
+#define TOK_MODULEMAIN 262
+#define TOK_NOTGRIDDEP 263
+#define TOK_USEITEM 264
+#define TOK_NAME 265
+#define TOK_CSTINT 266
+#define TOK_PROBTYPE 267
+
+
+
+
+/* Copy the first part of user declarations.  */
+#line 35 "convert.y"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include "decl.h"
+
+int line_num=1;
+extern FILE * convert_in;
+
+int convert_error(const char *s)
+{
+    printf("##\n## ERROR in conv: '%s' (line %d, file: %s)\n##\n", s, line_num, config_file);
+    exit(0);
+}
+
+
+
+/* Enabling traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 1
+#endif
+
+/* Enabling verbose error messages.  */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE 0
+#endif
+
+/* Enabling the token table.  */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE 0
+#endif
 
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-{
-/* Line 387 of yacc.c  */
-#line 42 "convert.y"
-
-       int ival;
-       char na[LONG_C];
-       listnom * ln;
-       
-
-/* Line 387 of yacc.c  */
-#line 131 "convert.tab.c"
-} YYSTYPE;
-# define YYSTYPE_IS_TRIVIAL 1
+#line 52 "convert.y"
+{
+    char na[LONG_M];
+}
+/* Line 193 of yacc.c.  */
+#line 149 "convert.tab.c"
+	YYSTYPE;
 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
 # define YYSTYPE_IS_DECLARED 1
-#endif
-
-extern YYSTYPE yylval;
-
-#ifdef YYPARSE_PARAM
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void *YYPARSE_PARAM);
-#else
-int yyparse ();
-#endif
-#else /* ! YYPARSE_PARAM */
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
+# define YYSTYPE_IS_TRIVIAL 1
+#endif
 
 
@@ -155,6 +157,7 @@
 /* Copy the second part of user declarations.  */
 
-/* Line 390 of yacc.c  */
-#line 159 "convert.tab.c"
+
+/* Line 216 of yacc.c.  */
+#line 162 "convert.tab.c"
 
 #ifdef short
@@ -209,17 +212,9 @@
 #  if ENABLE_NLS
 #   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
-#   define YY_(Msgid) dgettext ("bison-runtime", Msgid)
+#   define YY_(msgid) dgettext ("bison-runtime", msgid)
 #  endif
 # endif
 # ifndef YY_
-#  define YY_(Msgid) Msgid
-# endif
-#endif
-
-#ifndef __attribute__
-/* This feature is available in gcc versions 2.5 and later.  */
-# if (! defined __GNUC__ || __GNUC__ < 2 \
-      || (__GNUC__ == 2 && __GNUC_MINOR__ < 5))
-#  define __attribute__(Spec) /* empty */
+#  define YY_(msgid) msgid
 # endif
 #endif
@@ -227,25 +222,24 @@
 /* Suppress unused-variable warnings by "using" E.  */
 #if ! defined lint || defined __GNUC__
-# define YYUSE(E) ((void) (E))
+# define YYUSE(e) ((void) (e))
 #else
-# define YYUSE(E) /* empty */
-#endif
-
+# define YYUSE(e) /* empty */
+#endif
 
 /* Identity function, used to suppress warnings about constant conditions.  */
 #ifndef lint
-# define YYID(N) (N)
+# define YYID(n) (n)
 #else
 #if (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 static int
-YYID (int yyi)
+YYID (int i)
 #else
 static int
-YYID (yyi)
-    int yyi;
-#endif
-{
-  return yyi;
+YYID (i)
+    int i;
+#endif
+{
+  return i;
 }
 #endif
@@ -268,10 +262,9 @@
 #   else
 #    define YYSTACK_ALLOC alloca
-#    if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
+#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 #     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-      /* Use EXIT_SUCCESS as a witness for stdlib.h.  */
-#     ifndef EXIT_SUCCESS
-#      define EXIT_SUCCESS 0
+#     ifndef _STDLIB_H
+#      define _STDLIB_H 1
 #     endif
 #    endif
@@ -296,15 +289,15 @@
 #   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
 #  endif
-#  if (defined __cplusplus && ! defined EXIT_SUCCESS \
+#  if (defined __cplusplus && ! defined _STDLIB_H \
        && ! ((defined YYMALLOC || defined malloc) \
 	     && (defined YYFREE || defined free)))
 #   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#   ifndef EXIT_SUCCESS
-#    define EXIT_SUCCESS 0
+#   ifndef _STDLIB_H
+#    define _STDLIB_H 1
 #   endif
 #  endif
 #  ifndef YYMALLOC
 #   define YYMALLOC malloc
-#   if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
+#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
@@ -313,5 +306,5 @@
 #  ifndef YYFREE
 #   define YYFREE free
-#   if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
+#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 void free (void *); /* INFRINGES ON USER NAME SPACE */
@@ -329,7 +322,7 @@
 union yyalloc
 {
-  yytype_int16 yyss_alloc;
-  YYSTYPE yyvs_alloc;
-};
+  yytype_int16 yyss;
+  YYSTYPE yyvs;
+  };
 
 /* The size of the maximum gap between one aligned stack and the next.  */
@@ -342,5 +335,21 @@
       + YYSTACK_GAP_MAXIMUM)
 
-# define YYCOPY_NEEDED 1
+/* Copy COUNT objects from FROM to TO.  The source and destination do
+   not overlap.  */
+# ifndef YYCOPY
+#  if defined __GNUC__ && 1 < __GNUC__
+#   define YYCOPY(To, From, Count) \
+      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
+#  else
+#   define YYCOPY(To, From, Count)		\
+      do					\
+	{					\
+	  YYSIZE_T yyi;				\
+	  for (yyi = 0; yyi < (Count); yyi++)	\
+	    (To)[yyi] = (From)[yyi];		\
+	}					\
+      while (YYID (0))
+#  endif
+# endif
 
 /* Relocate STACK from its old location to the new one.  The
@@ -349,10 +358,10 @@
    stack.  Advance YYPTR to a properly aligned location for the next
    stack.  */
-# define YYSTACK_RELOCATE(Stack_alloc, Stack)				\
+# define YYSTACK_RELOCATE(Stack)					\
     do									\
       {									\
 	YYSIZE_T yynewbytes;						\
-	YYCOPY (&yyptr->Stack_alloc, Stack, yysize);			\
-	Stack = &yyptr->Stack_alloc;					\
+	YYCOPY (&yyptr->Stack, Stack, yysize);				\
+	Stack = &yyptr->Stack;						\
 	yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
 	yyptr += yynewbytes / sizeof (*yyptr);				\
@@ -362,41 +371,21 @@
 #endif
 
-#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
-/* Copy COUNT objects from SRC to DST.  The source and destination do
-   not overlap.  */
-# ifndef YYCOPY
-#  if defined __GNUC__ && 1 < __GNUC__
-#   define YYCOPY(Dst, Src, Count) \
-      __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
-#  else
-#   define YYCOPY(Dst, Src, Count)              \
-      do                                        \
-        {                                       \
-          YYSIZE_T yyi;                         \
-          for (yyi = 0; yyi < (Count); yyi++)   \
-            (Dst)[yyi] = (Src)[yyi];            \
-        }                                       \
-      while (YYID (0))
-#  endif
-# endif
-#endif /* !YYCOPY_NEEDED */
-
 /* YYFINAL -- State number of the termination state.  */
 #define YYFINAL  2
 /* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   23
+#define YYLAST   29
 
 /* YYNTOKENS -- Number of terminals.  */
-#define YYNTOKENS  18
+#define YYNTOKENS  16
 /* YYNNTS -- Number of nonterminals.  */
 #define YYNNTS  3
 /* YYNRULES -- Number of rules.  */
-#define YYNRULES  10
+#define YYNRULES  11
 /* YYNRULES -- Number of states.  */
-#define YYNSTATES  24
+#define YYNSTATES  29
 
 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
 #define YYUNDEFTOK  2
-#define YYMAXUTOK   264
+#define YYMAXUTOK   267
 
 #define YYTRANSLATE(YYX)						\
@@ -407,13 +396,13 @@
 {
        0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-      17,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+      15,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-      13,    14,     2,     2,    10,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,    12,    11,
+       2,     2,     2,     2,    13,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,    14,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,    15,     2,    16,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
@@ -432,5 +421,5 @@
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     1,     2,     3,     4,
-       5,     6,     7,     8,     9
+       5,     6,     7,     8,     9,    10,    11,    12
 };
 
@@ -441,5 +430,5 @@
 {
        0,     0,     3,     4,     7,     9,    13,    19,    27,    31,
-      36
+      37,    42
 };
 
@@ -447,8 +436,9 @@
 static const yytype_int8 yyrhs[] =
 {
-      19,     0,    -1,    -1,    19,    20,    -1,    17,    -1,     9,
-       8,    11,    -1,     9,     8,    10,     8,    11,    -1,     9,
-       8,    10,     8,    10,     8,    11,    -1,     5,     8,    11,
-      -1,     6,     3,     8,    11,    -1,     4,     7,    11,    -1
+      17,     0,    -1,    -1,    17,    18,    -1,    15,    -1,    12,
+      10,    14,    -1,    12,    10,    13,    10,    14,    -1,    12,
+      10,    13,    10,    13,    10,    14,    -1,     7,    10,    14,
+      -1,     4,    10,     5,    11,    14,    -1,     8,     3,    10,
+      14,    -1,     6,     9,    14,    -1
 };
 
@@ -456,18 +446,18 @@
 static const yytype_uint8 yyrline[] =
 {
-       0,    63,    63,    64,    66,    67,    68,    69,    71,    74,
-      75
+       0,    71,    71,    72,    75,    76,    77,    78,    79,    84,
+     100,   104
 };
 #endif
 
-#if YYDEBUG || YYERROR_VERBOSE || 0
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
    First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
 static const char *const yytname[] =
 {
-  "$end", "error", "$undefined", "TOK_SEP", "TOK_USE", "TOK_MODULEMAIN",
-  "TOK_NOTGRIDDEP", "TOK_USEITEM", "TOK_NAME", "TOK_PROBTYPE", "','",
-  "';'", "':'", "'('", "')'", "'['", "']'", "'\\n'", "$accept", "input",
-  "line", YY_NULL
+  "$end", "error", "$undefined", "TOK_SEP", "TOK_KIND", "TOK_EQUAL",
+  "TOK_USE", "TOK_MODULEMAIN", "TOK_NOTGRIDDEP", "TOK_USEITEM", "TOK_NAME",
+  "TOK_CSTINT", "TOK_PROBTYPE", "','", "';'", "'\\n'", "$accept", "input",
+  "line", 0
 };
 #endif
@@ -479,5 +469,5 @@
 {
        0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
-      44,    59,    58,    40,    41,    91,    93,    10
+     265,   266,   267,    44,    59,    10
 };
 # endif
@@ -486,6 +476,6 @@
 static const yytype_uint8 yyr1[] =
 {
-       0,    18,    19,    19,    20,    20,    20,    20,    20,    20,
-      20
+       0,    16,    17,    17,    18,    18,    18,    18,    18,    18,
+      18,    18
 };
 
@@ -493,16 +483,16 @@
 static const yytype_uint8 yyr2[] =
 {
-       0,     2,     0,     2,     1,     3,     5,     7,     3,     4,
-       3
+       0,     2,     0,     2,     1,     3,     5,     7,     3,     5,
+       4,     3
 };
 
-/* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM.
-   Performed when YYTABLE doesn't specify something else to do.  Zero
+/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
+   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
    means the default is an error.  */
 static const yytype_uint8 yydefact[] =
 {
-       2,     0,     1,     0,     0,     0,     0,     4,     3,     0,
-       0,     0,     0,    10,     8,     0,     0,     5,     9,     0,
-       0,     6,     0,     7
+       2,     0,     1,     0,     0,     0,     0,     0,     4,     3,
+       0,     0,     0,     0,     0,     0,    11,     8,     0,     0,
+       5,     0,    10,     0,     9,     0,     6,     0,     7
 };
 
@@ -510,15 +500,15 @@
 static const yytype_int8 yydefgoto[] =
 {
-      -1,     1,     8
+      -1,     1,     9
 };
 
 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
    STATE-NUM.  */
-#define YYPACT_NINF -10
+#define YYPACT_NINF -13
 static const yytype_int8 yypact[] =
 {
-     -10,     0,   -10,    -4,     2,     8,     4,   -10,   -10,     3,
-       5,     7,    -9,   -10,   -10,     9,    10,   -10,   -10,    -3,
-      11,   -10,    12,   -10
+     -13,     0,   -13,    -7,     2,    -5,    10,     4,   -13,   -13,
+      11,     3,     5,     8,   -12,     9,   -13,   -13,     7,    12,
+     -13,    13,   -13,    -4,   -13,    14,   -13,    15,   -13
 };
 
@@ -526,29 +516,24 @@
 static const yytype_int8 yypgoto[] =
 {
-     -10,   -10,   -10
+     -13,   -13,   -13
 };
 
 /* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
    positive, shift that token.  If negative, reduce the rule which
-   number is the opposite.  If YYTABLE_NINF, syntax error.  */
+   number is the opposite.  If zero, do what YYDEFACT says.
+   If YYTABLE_NINF, syntax error.  */
 #define YYTABLE_NINF -1
 static const yytype_uint8 yytable[] =
 {
-       2,    16,    17,     9,     3,     4,     5,    20,    21,     6,
-      10,    11,    12,     0,    13,    15,    14,     7,    19,    22,
-      18,     0,     0,    23
+       2,    19,    20,    10,     3,    12,     4,     5,     6,    25,
+      26,    11,     7,    13,    14,     8,    15,    16,    18,    17,
+      21,    22,    23,     0,    27,     0,     0,    24,     0,    28
 };
 
-#define yypact_value_is_default(Yystate) \
-  (!!((Yystate) == (-10)))
-
-#define yytable_value_is_error(Yytable_value) \
-  YYID (0)
-
 static const yytype_int8 yycheck[] =
 {
-       0,    10,    11,     7,     4,     5,     6,    10,    11,     9,
-       8,     3,     8,    -1,    11,     8,    11,    17,     8,     8,
-      11,    -1,    -1,    11
+       0,    13,    14,    10,     4,    10,     6,     7,     8,    13,
+      14,     9,    12,     3,    10,    15,     5,    14,    10,    14,
+      11,    14,    10,    -1,    10,    -1,    -1,    14,    -1,    14
 };
 
@@ -557,7 +542,7 @@
 static const yytype_uint8 yystos[] =
 {
-       0,    19,     0,     4,     5,     6,     9,    17,    20,     7,
-       8,     3,     8,    11,    11,     8,    10,    11,    11,     8,
-      10,    11,     8,    11
+       0,    17,     0,     4,     6,     7,     8,    12,    15,    18,
+      10,     9,    10,     3,    10,     5,    14,    14,    10,    13,
+      14,    11,    14,    10,    14,    13,    14,    10,    14
 };
 
@@ -574,31 +559,22 @@
 /* Like YYERROR except do call yyerror.  This remains here temporarily
    to ease the transition to the new meaning of YYERROR, for GCC.
-   Once GCC version 2 has supplanted version 1, this can go.  However,
-   YYFAIL appears to be in use.  Nevertheless, it is formally deprecated
-   in Bison 2.4.2's NEWS entry, where a plan to phase it out is
-   discussed.  */
+   Once GCC version 2 has supplanted version 1, this can go.  */
 
 #define YYFAIL		goto yyerrlab
-#if defined YYFAIL
-  /* This is here to suppress warnings from the GCC cpp's
-     -Wunused-macros.  Normally we don't worry about that warning, but
-     some users do, and we want to make it easy for users to remove
-     YYFAIL uses, which will produce warnings from Bison 2.5.  */
-#endif
 
 #define YYRECOVERING()  (!!yyerrstatus)
 
-#define YYBACKUP(Token, Value)                                  \
-do                                                              \
-  if (yychar == YYEMPTY)                                        \
-    {                                                           \
-      yychar = (Token);                                         \
-      yylval = (Value);                                         \
-      YYPOPSTACK (yylen);                                       \
-      yystate = *yyssp;                                         \
-      goto yybackup;                                            \
-    }                                                           \
-  else                                                          \
-    {                                                           \
+#define YYBACKUP(Token, Value)					\
+do								\
+  if (yychar == YYEMPTY && yylen == 1)				\
+    {								\
+      yychar = (Token);						\
+      yylval = (Value);						\
+      yytoken = YYTRANSLATE (yychar);				\
+      YYPOPSTACK (1);						\
+      goto yybackup;						\
+    }								\
+  else								\
+    {								\
       yyerror (YY_("syntax error: cannot back up")); \
       YYERROR;							\
@@ -606,16 +582,53 @@
 while (YYID (0))
 
-/* Error token number */
+
 #define YYTERROR	1
 #define YYERRCODE	256
 
 
-/* This macro is provided for backward compatibility. */
+/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
+   If N is 0, then set CURRENT to the empty location which ends
+   the previous symbol: RHS[0] (always defined).  */
+
+#define YYRHSLOC(Rhs, K) ((Rhs)[K])
+#ifndef YYLLOC_DEFAULT
+# define YYLLOC_DEFAULT(Current, Rhs, N)				\
+    do									\
+      if (YYID (N))                                                    \
+	{								\
+	  (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;	\
+	  (Current).first_column = YYRHSLOC (Rhs, 1).first_column;	\
+	  (Current).last_line    = YYRHSLOC (Rhs, N).last_line;		\
+	  (Current).last_column  = YYRHSLOC (Rhs, N).last_column;	\
+	}								\
+      else								\
+	{								\
+	  (Current).first_line   = (Current).last_line   =		\
+	    YYRHSLOC (Rhs, 0).last_line;				\
+	  (Current).first_column = (Current).last_column =		\
+	    YYRHSLOC (Rhs, 0).last_column;				\
+	}								\
+    while (YYID (0))
+#endif
+
+
+/* YY_LOCATION_PRINT -- Print the location on the stream.
+   This macro was not mandated originally: define only if we know
+   we won't break user code: when these are the locations we know.  */
+
 #ifndef YY_LOCATION_PRINT
-# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
+#  define YY_LOCATION_PRINT(File, Loc)			\
+     fprintf (File, "%d.%d-%d.%d",			\
+	      (Loc).first_line, (Loc).first_column,	\
+	      (Loc).last_line,  (Loc).last_column)
+# else
+#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+# endif
 #endif
 
 
 /* YYLEX -- calling `yylex' with the right arguments.  */
+
 #ifdef YYLEX_PARAM
 # define YYLEX yylex (YYLEX_PARAM)
@@ -667,6 +680,4 @@
 #endif
 {
-  FILE *yyo = yyoutput;
-  YYUSE (yyo);
   if (!yyvaluep)
     return;
@@ -677,5 +688,9 @@
   YYUSE (yyoutput);
 # endif
-  YYUSE (yytype);
+  switch (yytype)
+    {
+      default:
+	break;
+    }
 }
 
@@ -714,18 +729,15 @@
      || defined __cplusplus || defined _MSC_VER)
 static void
-yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
+yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
 #else
 static void
-yy_stack_print (yybottom, yytop)
-    yytype_int16 *yybottom;
-    yytype_int16 *yytop;
+yy_stack_print (bottom, top)
+    yytype_int16 *bottom;
+    yytype_int16 *top;
 #endif
 {
   YYFPRINTF (stderr, "Stack now");
-  for (; yybottom <= yytop; yybottom++)
-    {
-      int yybot = *yybottom;
-      YYFPRINTF (stderr, " %d", yybot);
-    }
+  for (; bottom <= top; ++bottom)
+    YYFPRINTF (stderr, " %d", *bottom);
   YYFPRINTF (stderr, "\n");
 }
@@ -761,9 +773,9 @@
   for (yyi = 0; yyi < yynrhs; yyi++)
     {
-      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
+      fprintf (stderr, "   $%d = ", yyi + 1);
       yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
 		       &(yyvsp[(yyi + 1) - (yynrhs)])
 		       		       );
-      YYFPRINTF (stderr, "\n");
+      fprintf (stderr, "\n");
     }
 }
@@ -801,4 +813,6 @@
 # define YYMAXDEPTH 10000
 #endif
+
+
 
 
@@ -904,143 +918,114 @@
 # endif
 
-/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
-   about the unexpected token YYTOKEN for the state stack whose top is
-   YYSSP.
-
-   Return 0 if *YYMSG was successfully written.  Return 1 if *YYMSG is
-   not large enough to hold the message.  In that case, also set
-   *YYMSG_ALLOC to the required number of bytes.  Return 2 if the
-   required number of bytes is too large to store.  */
-static int
-yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
-                yytype_int16 *yyssp, int yytoken)
-{
-  YYSIZE_T yysize0 = yytnamerr (YY_NULL, yytname[yytoken]);
-  YYSIZE_T yysize = yysize0;
-  enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
-  /* Internationalized format string. */
-  const char *yyformat = YY_NULL;
-  /* Arguments of yyformat. */
-  char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
-  /* Number of reported tokens (one for the "unexpected", one per
-     "expected"). */
-  int yycount = 0;
-
-  /* There are many possibilities here to consider:
-     - Assume YYFAIL is not used.  It's too flawed to consider.  See
-       <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html>
-       for details.  YYERROR is fine as it does not invoke this
-       function.
-     - If this state is a consistent state with a default action, then
-       the only way this function was invoked is if the default action
-       is an error action.  In that case, don't check for expected
-       tokens because there are none.
-     - The only way there can be no lookahead present (in yychar) is if
-       this state is a consistent state with a default action.  Thus,
-       detecting the absence of a lookahead is sufficient to determine
-       that there is no unexpected or expected token to report.  In that
-       case, just report a simple "syntax error".
-     - Don't assume there isn't a lookahead just because this state is a
-       consistent state with a default action.  There might have been a
-       previous inconsistent state, consistent state with a non-default
-       action, or user semantic action that manipulated yychar.
-     - Of course, the expected token list depends on states to have
-       correct lookahead information, and it depends on the parser not
-       to perform extra reductions after fetching a lookahead from the
-       scanner and before detecting a syntax error.  Thus, state merging
-       (from LALR or IELR) and default reductions corrupt the expected
-       token list.  However, the list is correct for canonical LR with
-       one exception: it will still contain any token that will not be
-       accepted due to an error action in a later state.
-  */
-  if (yytoken != YYEMPTY)
+/* Copy into YYRESULT an error message about the unexpected token
+   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
+   including the terminating null byte.  If YYRESULT is null, do not
+   copy anything; just return the number of bytes that would be
+   copied.  As a special case, return 0 if an ordinary "syntax error"
+   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
+   size calculation.  */
+static YYSIZE_T
+yysyntax_error (char *yyresult, int yystate, int yychar)
+{
+  int yyn = yypact[yystate];
+
+  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
+    return 0;
+  else
     {
-      int yyn = yypact[*yyssp];
-      yyarg[yycount++] = yytname[yytoken];
-      if (!yypact_value_is_default (yyn))
-        {
-          /* Start YYX at -YYN if negative to avoid negative indexes in
-             YYCHECK.  In other words, skip the first -YYN actions for
-             this state because they are default actions.  */
-          int yyxbegin = yyn < 0 ? -yyn : 0;
-          /* Stay within bounds of both yycheck and yytname.  */
-          int yychecklim = YYLAST - yyn + 1;
-          int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
-          int yyx;
-
-          for (yyx = yyxbegin; yyx < yyxend; ++yyx)
-            if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
-                && !yytable_value_is_error (yytable[yyx + yyn]))
-              {
-                if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
-                  {
-                    yycount = 1;
-                    yysize = yysize0;
-                    break;
-                  }
-                yyarg[yycount++] = yytname[yyx];
-                {
-                  YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULL, yytname[yyx]);
-                  if (! (yysize <= yysize1
-                         && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
-                    return 2;
-                  yysize = yysize1;
-                }
-              }
-        }
+      int yytype = YYTRANSLATE (yychar);
+      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
+      YYSIZE_T yysize = yysize0;
+      YYSIZE_T yysize1;
+      int yysize_overflow = 0;
+      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+      int yyx;
+
+# if 0
+      /* This is so xgettext sees the translatable formats that are
+	 constructed on the fly.  */
+      YY_("syntax error, unexpected %s");
+      YY_("syntax error, unexpected %s, expecting %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
+# endif
+      char *yyfmt;
+      char const *yyf;
+      static char const yyunexpected[] = "syntax error, unexpected %s";
+      static char const yyexpecting[] = ", expecting %s";
+      static char const yyor[] = " or %s";
+      char yyformat[sizeof yyunexpected
+		    + sizeof yyexpecting - 1
+		    + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
+		       * (sizeof yyor - 1))];
+      char const *yyprefix = yyexpecting;
+
+      /* Start YYX at -YYN if negative to avoid negative indexes in
+	 YYCHECK.  */
+      int yyxbegin = yyn < 0 ? -yyn : 0;
+
+      /* Stay within bounds of both yycheck and yytname.  */
+      int yychecklim = YYLAST - yyn + 1;
+      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+      int yycount = 1;
+
+      yyarg[0] = yytname[yytype];
+      yyfmt = yystpcpy (yyformat, yyunexpected);
+
+      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+	if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
+	  {
+	    if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+	      {
+		yycount = 1;
+		yysize = yysize0;
+		yyformat[sizeof yyunexpected - 1] = '\0';
+		break;
+	      }
+	    yyarg[yycount++] = yytname[yyx];
+	    yysize1 = yysize + yytnamerr (0, yytname[yyx]);
+	    yysize_overflow |= (yysize1 < yysize);
+	    yysize = yysize1;
+	    yyfmt = yystpcpy (yyfmt, yyprefix);
+	    yyprefix = yyor;
+	  }
+
+      yyf = YY_(yyformat);
+      yysize1 = yysize + yystrlen (yyf);
+      yysize_overflow |= (yysize1 < yysize);
+      yysize = yysize1;
+
+      if (yysize_overflow)
+	return YYSIZE_MAXIMUM;
+
+      if (yyresult)
+	{
+	  /* Avoid sprintf, as that infringes on the user's name space.
+	     Don't have undefined behavior even if the translation
+	     produced a string with the wrong number of "%s"s.  */
+	  char *yyp = yyresult;
+	  int yyi = 0;
+	  while ((*yyp = *yyf) != '\0')
+	    {
+	      if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
+		{
+		  yyp += yytnamerr (yyp, yyarg[yyi++]);
+		  yyf += 2;
+		}
+	      else
+		{
+		  yyp++;
+		  yyf++;
+		}
+	    }
+	}
+      return yysize;
     }
-
-  switch (yycount)
-    {
-# define YYCASE_(N, S)                      \
-      case N:                               \
-        yyformat = S;                       \
-      break
-      YYCASE_(0, YY_("syntax error"));
-      YYCASE_(1, YY_("syntax error, unexpected %s"));
-      YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
-      YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
-      YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
-      YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
-# undef YYCASE_
-    }
-
-  {
-    YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
-    if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
-      return 2;
-    yysize = yysize1;
-  }
-
-  if (*yymsg_alloc < yysize)
-    {
-      *yymsg_alloc = 2 * yysize;
-      if (! (yysize <= *yymsg_alloc
-             && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
-        *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
-      return 1;
-    }
-
-  /* Avoid sprintf, as that infringes on the user's name space.
-     Don't have undefined behavior even if the translation
-     produced a string with the wrong number of "%s"s.  */
-  {
-    char *yyp = *yymsg;
-    int yyi = 0;
-    while ((*yyp = *yyformat) != '\0')
-      if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
-        {
-          yyp += yytnamerr (yyp, yyarg[yyi++]);
-          yyformat += 2;
-        }
-      else
-        {
-          yyp++;
-          yyformat++;
-        }
-  }
-  return 0;
 }
 #endif /* YYERROR_VERBOSE */
+
+
 
 /*-----------------------------------------------.
@@ -1067,27 +1052,41 @@
   YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
 
-  YYUSE (yytype);
-}
-
-
-
-
-/* The lookahead symbol.  */
+  switch (yytype)
+    {
+
+      default:
+	break;
+    }
+}
+
+
+
+/* Prevent warnings from -Wmissing-prototypes.  */
+
+#ifdef YYPARSE_PARAM
+#if defined __STDC__ || defined __cplusplus
+int yyparse (void *YYPARSE_PARAM);
+#else
+int yyparse ();
+#endif
+#else /* ! YYPARSE_PARAM */
+#if defined __STDC__ || defined __cplusplus
+int yyparse (void);
+#else
+int yyparse ();
+#endif
+#endif /* ! YYPARSE_PARAM */
+
+
+
+/* The look-ahead symbol.  */
 int yychar;
 
-
-#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
-# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
-# define YY_IGNORE_MAYBE_UNINITIALIZED_END
-#endif
-#ifndef YY_INITIAL_VALUE
-# define YY_INITIAL_VALUE(Value) /* Nothing. */
-#endif
-
-/* The semantic value of the lookahead symbol.  */
-YYSTYPE yylval YY_INITIAL_VALUE(yyval_default);
+/* The semantic value of the look-ahead symbol.  */
+YYSTYPE yylval;
 
 /* Number of syntax errors so far.  */
 int yynerrs;
+
 
 
@@ -1118,35 +1117,12 @@
 #endif
 {
-    int yystate;
-    /* Number of tokens to shift before error messages enabled.  */
-    int yyerrstatus;
-
-    /* The stacks and their tools:
-       `yyss': related to states.
-       `yyvs': related to semantic values.
-
-       Refer to the stacks through separate pointers, to allow yyoverflow
-       to reallocate them elsewhere.  */
-
-    /* The state stack.  */
-    yytype_int16 yyssa[YYINITDEPTH];
-    yytype_int16 *yyss;
-    yytype_int16 *yyssp;
-
-    /* The semantic value stack.  */
-    YYSTYPE yyvsa[YYINITDEPTH];
-    YYSTYPE *yyvs;
-    YYSTYPE *yyvsp;
-
-    YYSIZE_T yystacksize;
-
+  
+  int yystate;
   int yyn;
   int yyresult;
-  /* Lookahead token as an internal (translated) token number.  */
+  /* Number of tokens to shift before error messages enabled.  */
+  int yyerrstatus;
+  /* Look-ahead token as an internal (translated) token number.  */
   int yytoken = 0;
-  /* The variables used to return semantic value and location from the
-     action routines.  */
-  YYSTYPE yyval;
-
 #if YYERROR_VERBOSE
   /* Buffer for error messages, and its allocated size.  */
@@ -1156,5 +1132,32 @@
 #endif
 
+  /* Three stacks and their tools:
+     `yyss': related to states,
+     `yyvs': related to semantic values,
+     `yyls': related to locations.
+
+     Refer to the stacks thru separate pointers, to allow yyoverflow
+     to reallocate them elsewhere.  */
+
+  /* The state stack.  */
+  yytype_int16 yyssa[YYINITDEPTH];
+  yytype_int16 *yyss = yyssa;
+  yytype_int16 *yyssp;
+
+  /* The semantic value stack.  */
+  YYSTYPE yyvsa[YYINITDEPTH];
+  YYSTYPE *yyvs = yyvsa;
+  YYSTYPE *yyvsp;
+
+
+
 #define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
+
+  YYSIZE_T yystacksize = YYINITDEPTH;
+
+  /* The variables used to return semantic value and location from the
+     action routines.  */
+  YYSTYPE yyval;
+
 
   /* The number of symbols on the RHS of the reduced rule.
@@ -1162,8 +1165,4 @@
   int yylen = 0;
 
-  yyssp = yyss = yyssa;
-  yyvsp = yyvs = yyvsa;
-  yystacksize = YYINITDEPTH;
-
   YYDPRINTF ((stderr, "Starting parse\n"));
 
@@ -1171,5 +1170,14 @@
   yyerrstatus = 0;
   yynerrs = 0;
-  yychar = YYEMPTY; /* Cause a token to be read.  */
+  yychar = YYEMPTY;		/* Cause a token to be read.  */
+
+  /* Initialize stack pointers.
+     Waste one element of value and location stack
+     so that they stay on the same level as the state stack.
+     The wasted elements are never initialized.  */
+
+  yyssp = yyss;
+  yyvsp = yyvs;
+
   goto yysetstate;
 
@@ -1198,4 +1206,5 @@
 	yytype_int16 *yyss1 = yyss;
 
+
 	/* Each stack pointer address is followed by the size of the
 	   data in use in that stack, in bytes.  This used to be a
@@ -1205,4 +1214,5 @@
 		    &yyss1, yysize * sizeof (*yyssp),
 		    &yyvs1, yysize * sizeof (*yyvsp),
+
 		    &yystacksize);
 
@@ -1227,6 +1237,7 @@
 	if (! yyptr)
 	  goto yyexhaustedlab;
-	YYSTACK_RELOCATE (yyss_alloc, yyss);
-	YYSTACK_RELOCATE (yyvs_alloc, yyvs);
+	YYSTACK_RELOCATE (yyss);
+	YYSTACK_RELOCATE (yyvs);
+
 #  undef YYSTACK_RELOCATE
 	if (yyss1 != yyssa)
@@ -1239,4 +1250,5 @@
       yyvsp = yyvs + yysize - 1;
 
+
       YYDPRINTF ((stderr, "Stack size increased to %lu\n",
 		  (unsigned long int) yystacksize));
@@ -1247,7 +1259,4 @@
 
   YYDPRINTF ((stderr, "Entering state %d\n", yystate));
-
-  if (yystate == YYFINAL)
-    YYACCEPT;
 
   goto yybackup;
@@ -1259,14 +1268,14 @@
 
   /* Do appropriate processing given the current state.  Read a
-     lookahead token if we need one and don't already have one.  */
-
-  /* First try to decide what to do without reference to lookahead token.  */
+     look-ahead token if we need one and don't already have one.  */
+
+  /* First try to decide what to do without reference to look-ahead token.  */
   yyn = yypact[yystate];
-  if (yypact_value_is_default (yyn))
+  if (yyn == YYPACT_NINF)
     goto yydefault;
 
-  /* Not known => get a lookahead token if don't already have one.  */
-
-  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
+  /* Not known => get a look-ahead token if don't already have one.  */
+
+  /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol.  */
   if (yychar == YYEMPTY)
     {
@@ -1294,9 +1303,12 @@
   if (yyn <= 0)
     {
-      if (yytable_value_is_error (yyn))
-        goto yyerrlab;
+      if (yyn == 0 || yyn == YYTABLE_NINF)
+	goto yyerrlab;
       yyn = -yyn;
       goto yyreduce;
     }
+
+  if (yyn == YYFINAL)
+    YYACCEPT;
 
   /* Count tokens shifted since error; after three, turn off error
@@ -1305,14 +1317,13 @@
     yyerrstatus--;
 
-  /* Shift the lookahead token.  */
+  /* Shift the look-ahead token.  */
   YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
 
-  /* Discard the shifted token.  */
-  yychar = YYEMPTY;
+  /* Discard the shifted token unless it is eof.  */
+  if (yychar != YYEOF)
+    yychar = YYEMPTY;
 
   yystate = yyn;
-  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
   *++yyvsp = yylval;
-  YY_IGNORE_MAYBE_UNINITIALIZED_END
 
   goto yynewstate;
@@ -1351,61 +1362,65 @@
     {
         case 5:
-/* Line 1787 of yacc.c  */
-#line 67 "convert.y"
-    {initdimprob(1,(yyvsp[(2) - (3)].na),"0","0");}
+#line 76 "convert.y"
+    { initdimprob(1,(yyvsp[(2) - (3)].na),"0","0"); ;}
     break;
 
   case 6:
-/* Line 1787 of yacc.c  */
-#line 68 "convert.y"
-    {initdimprob(2,(yyvsp[(2) - (5)].na), (yyvsp[(4) - (5)].na),"0");}
+#line 77 "convert.y"
+    { initdimprob(2,(yyvsp[(2) - (5)].na), (yyvsp[(4) - (5)].na),"0"); ;}
     break;
 
   case 7:
-/* Line 1787 of yacc.c  */
-#line 70 "convert.y"
-    {initdimprob(3,(yyvsp[(2) - (7)].na), (yyvsp[(4) - (7)].na), (yyvsp[(6) - (7)].na));}
+#line 78 "convert.y"
+    { initdimprob(3,(yyvsp[(2) - (7)].na), (yyvsp[(4) - (7)].na), (yyvsp[(6) - (7)].na)); ;}
     break;
 
   case 8:
-/* Line 1787 of yacc.c  */
-#line 72 "convert.y"
-    {listofmodules = Addtolistnom((yyvsp[(2) - (3)].na),listofmodules,0);
-                                                        Addmoduletothelist((yyvsp[(2) - (3)].na));}
+#line 80 "convert.y"
+    {
+            listofmodules = Addtolistnom((yyvsp[(2) - (3)].na),listofmodules,0);
+            Addmoduletothelist((yyvsp[(2) - (3)].na));
+        ;}
     break;
 
   case 9:
-/* Line 1787 of yacc.c  */
-#line 74 "convert.y"
-    {Add_NotGridDepend_Var_1((yyvsp[(3) - (4)].na));}
+#line 85 "convert.y"
+    {
+            if (!strcasecmp((yyvsp[(4) - (5)].na),"4"))
+            {
+                listofkind = Addtolistnom((yyvsp[(2) - (5)].na),listofkind,4);
+            }
+            else if (!strcasecmp((yyvsp[(4) - (5)].na),"8"))
+            {
+                listofkind = Addtolistnom((yyvsp[(2) - (5)].na),listofkind,8);
+            }
+            else
+            {
+                printf("##\n## Unknown kind type : %s (must be 4 or 8)\n##",(yyvsp[(4) - (5)].na));
+                exit(0);
+            }
+        ;}
     break;
 
   case 10:
-/* Line 1787 of yacc.c  */
-#line 75 "convert.y"
+#line 101 "convert.y"
     {
-                                    if (!strcasecmp((yyvsp[(2) - (3)].na),"FIXED_GRIDS"))
-                                                                 fixedgrids=1;
-                                    if (!strcasecmp((yyvsp[(2) - (3)].na),"ONLY_FIXED_GRIDS"))
-                                                             onlyfixedgrids=1;
-                                 }
+            Add_NotGridDepend_Var_1((yyvsp[(3) - (4)].na));
+        ;}
     break;
 
-
-/* Line 1787 of yacc.c  */
-#line 1397 "convert.tab.c"
+  case 11:
+#line 105 "convert.y"
+    {
+            if (!strcasecmp((yyvsp[(2) - (3)].na),"FIXED_GRIDS"))      fixedgrids = 1;
+            if (!strcasecmp((yyvsp[(2) - (3)].na),"ONLY_FIXED_GRIDS")) onlyfixedgrids = 1;
+        ;}
+    break;
+
+
+/* Line 1267 of yacc.c.  */
+#line 1420 "convert.tab.c"
       default: break;
     }
-  /* User semantic actions sometimes alter yychar, and that requires
-     that yytoken be updated with the new translation.  We take the
-     approach of translating immediately before every use of yytoken.
-     One alternative is translating here after every semantic action,
-     but that translation would be missed if the semantic action invokes
-     YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
-     if it invokes YYBACKUP.  In the case of YYABORT or YYACCEPT, an
-     incorrect destructor might then be invoked immediately.  In the
-     case of YYERROR or YYBACKUP, subsequent parser actions might lead
-     to an incorrect destructor call or verbose syntax error message
-     before the lookahead is translated.  */
   YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
 
@@ -1415,4 +1430,5 @@
 
   *++yyvsp = yyval;
+
 
   /* Now `shift' the result of the reduction.  Determine what state
@@ -1435,8 +1451,4 @@
 `------------------------------------*/
 yyerrlab:
-  /* Make sure we have latest lookahead translation.  See comments at
-     user semantic actions for why this is necessary.  */
-  yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
-
   /* If not already recovering from an error, report this error.  */
   if (!yyerrstatus)
@@ -1446,34 +1458,35 @@
       yyerror (YY_("syntax error"));
 #else
-# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
-                                        yyssp, yytoken)
       {
-        char const *yymsgp = YY_("syntax error");
-        int yysyntax_error_status;
-        yysyntax_error_status = YYSYNTAX_ERROR;
-        if (yysyntax_error_status == 0)
-          yymsgp = yymsg;
-        else if (yysyntax_error_status == 1)
-          {
-            if (yymsg != yymsgbuf)
-              YYSTACK_FREE (yymsg);
-            yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
-            if (!yymsg)
-              {
-                yymsg = yymsgbuf;
-                yymsg_alloc = sizeof yymsgbuf;
-                yysyntax_error_status = 2;
-              }
-            else
-              {
-                yysyntax_error_status = YYSYNTAX_ERROR;
-                yymsgp = yymsg;
-              }
-          }
-        yyerror (yymsgp);
-        if (yysyntax_error_status == 2)
-          goto yyexhaustedlab;
+	YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
+	if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
+	  {
+	    YYSIZE_T yyalloc = 2 * yysize;
+	    if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
+	      yyalloc = YYSTACK_ALLOC_MAXIMUM;
+	    if (yymsg != yymsgbuf)
+	      YYSTACK_FREE (yymsg);
+	    yymsg = (char *) YYSTACK_ALLOC (yyalloc);
+	    if (yymsg)
+	      yymsg_alloc = yyalloc;
+	    else
+	      {
+		yymsg = yymsgbuf;
+		yymsg_alloc = sizeof yymsgbuf;
+	      }
+	  }
+
+	if (0 < yysize && yysize <= yymsg_alloc)
+	  {
+	    (void) yysyntax_error (yymsg, yystate, yychar);
+	    yyerror (yymsg);
+	  }
+	else
+	  {
+	    yyerror (YY_("syntax error"));
+	    if (yysize != 0)
+	      goto yyexhaustedlab;
+	  }
       }
-# undef YYSYNTAX_ERROR
 #endif
     }
@@ -1483,5 +1496,5 @@
   if (yyerrstatus == 3)
     {
-      /* If just tried and failed to reuse lookahead token after an
+      /* If just tried and failed to reuse look-ahead token after an
 	 error, discard it.  */
 
@@ -1500,5 +1513,5 @@
     }
 
-  /* Else will try to reuse lookahead token after shifting the error
+  /* Else will try to reuse look-ahead token after shifting the error
      token.  */
   goto yyerrlab1;
@@ -1534,5 +1547,5 @@
     {
       yyn = yypact[yystate];
-      if (!yypact_value_is_default (yyn))
+      if (yyn != YYPACT_NINF)
 	{
 	  yyn += YYTERROR;
@@ -1557,7 +1570,8 @@
     }
 
-  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+  if (yyn == YYFINAL)
+    YYACCEPT;
+
   *++yyvsp = yylval;
-  YY_IGNORE_MAYBE_UNINITIALIZED_END
 
 
@@ -1583,5 +1597,5 @@
   goto yyreturn;
 
-#if !defined yyoverflow || YYERROR_VERBOSE
+#ifndef yyoverflow
 /*-------------------------------------------------.
 | yyexhaustedlab -- memory exhaustion comes here.  |
@@ -1594,12 +1608,7 @@
 
 yyreturn:
-  if (yychar != YYEMPTY)
-    {
-      /* Make sure we have latest lookahead translation.  See comments at
-         user semantic actions for why this is necessary.  */
-      yytoken = YYTRANSLATE (yychar);
-      yydestruct ("Cleanup: discarding lookahead",
-                  yytoken, &yylval);
-    }
+  if (yychar != YYEOF && yychar != YYEMPTY)
+     yydestruct ("Cleanup: discarding lookahead",
+		 yytoken, &yylval);
   /* Do not reclaim the symbols of the rule which action triggered
      this YYABORT or YYACCEPT.  */
@@ -1625,375 +1634,360 @@
 
 
-/* Line 2050 of yacc.c  */
-#line 82 "convert.y"
-
+#line 110 "convert.y"
+
+
+void print_usage()
+{
+    printf("usage : conv <config_file> -convfile  <FILENAME>\n");
+    printf(" [-workdir <directory>] [-incdir <directory>]\n");
+    printf(" [-comdirin   <directory>] [-comdirout <directory>]\n");
+    printf(" [-convfile  <FILENAME>] [-SubloopScalar] [-SubloopScalar1] \n");
+    printf(" [-free|-fixed]\n");
+    exit(0);
+}
 
 int main(int argc,char *argv[])
 {
-   extern FILE * yyin ;
-   FILE *dependglobaloutput;
-   int i;
-   listnom *parcours;
-   listvar *newvar;
-   int stylegiven = 0;
-   int infreegiven ;
-   int infixedgiven ;
-   int lengthmainfile;
-
-   if (argc < 2)
-   {
-       printf("usage : conv <file> [-rm] [-incdir <directory>] \n");
-       printf(" [-comdirin   <directory>] [-comdirout <directory>]\n");
-       printf(" [-convfile  <FILENAME >] -SubloopScalar -SubloopScalar1 \n");
-       printf(" [-free|-fixed]\n");
-       exit(0);
-   }
+    extern FILE * convert_in ;
+    FILE *dependglobaloutput;
+    int i;
+    listnom *parcours;
+    listvar *newvar;
+    int stylegiven = 0;
+    int infreegiven ;
+    int infixedgiven ;
+    int lengthmainfile;
+
+    char filetoparse[LONG_FNAME];
+
 /******************************************************************************/
 /*  1-  Variables initialization                                              */
 /******************************************************************************/
-   List_Global_Var=(listvar *)NULL;
-   List_GlobalParameter_Var=(listvar *)NULL;
-   List_Allocate_Var=(listallocate *)NULL;
-   List_Common_Var=(listvar *)NULL;
-   List_SubroutineWhereAgrifUsed=(listnom *)NULL;
-   List_Subroutine_For_Alloc=(listnom *)NULL;
-   List_Include=(listusemodule *)NULL;
-   List_NameOfModuleUsed=(listusemodule *)NULL;
-   listofmoduletmp=(listusemodule *)NULL;
-   List_SubroutineDeclaration_Var=(listvar *)NULL;
-   List_UsedInSubroutine_Var=(listvar *)NULL;
-   List_NotGridDepend_Var=(listvar *)NULL;
-   Listofavailableindices=(listindice *)NULL;
-   List_CouplePointed_Var=(listvarpointtovar *)NULL;
-   List_ModuleUsed_Var = (listvar *)NULL;
-   List_ModuleUsedInModuleUsed_Var = (listvar *)NULL;
-   List_GlobParamModuleUsed_Var = (listparameter *)NULL;
-   List_GlobParamModuleUsedInModuleUsed_Var = (listparameter *)NULL;
-   List_SubroutineArgument_Var = (listvar *)NULL;
-   List_FunctionType_Var = (listvar *)NULL;
-   tmpuselocallist = (listusemodule *)NULL;
-   List_ContainsSubroutine = (listnom *)NULL;
-   oldfortranout = (FILE *)NULL;
-
-   strcpy(mainfile,argv[1]);
-   strcpy(nomdir,"AGRIF_INC");
-   strcpy(commondirin,".");
-   strcpy(commondirout,".");
-   strcpy(filetoparse," ");
-   strcpy(subofagrifinitgrids,"");
-   strcpy(meetagrifinitgrids,"");
-   strcpy(mpiinitvar,"");
-
-   length_last = 0 ;
-   length_first = 0 ;
-   length_v_typevar = 0 ;
-   length_v_nomvar = 0 ;
-   length_v_dimchar = 0 ;
-   length_v_modulename = 0 ;
-   length_v_commonname = 0 ;
-   length_v_vallengspec = 0 ;
-   length_v_nameinttypename = 0 ;
-   length_v_commoninfile = 0 ;
-   length_v_subroutinename = 0 ;
-   length_v_precision = 0 ;
-   length_v_IntentSpec = 0 ;
-   length_v_initialvalue = 0 ;
-   length_v_readedlistdimension = 0 ;
-   length_u_usemodule = 0 ;
-   length_u_charusemodule = 0 ;
-   length_u_cursubroutine = 0 ;
-   length_u_modulename = 0 ;
-   length_n_name = 0 ;
-   length_c_namevar = 0 ;
-   length_c_namepointedvar = 0 ;
-   length_o_nom = 0 ;
-   length_o_module = 0 ;
-   length_a_nomvar = 0 ;
-   length_a_subroutine = 0 ;
-   length_a_module = 0 ;
-   length_t_usemodule = 0 ;
-   length_t_cursubroutine = 0 ;
-   length_curfilename = 0 ;
-   length_nomfileoutput = 0 ;
-   length_motparse = 0 ;
-   length_mainfile = 0 ;
-   length_nomdir = 0 ;
-   length_commondirout = 0 ;
-   length_commondirin = 0 ;
-   length_filetoparse = 0 ;
-   length_curbuf = 0 ;
-   length_toprintglob = 0 ;
-   length_tmpvargridname = 0 ;
-   length_ligne_Subloop = 0 ;
-   length_lvargridname_toamr = 0 ;
-   length_toprint_utilagrif = 0 ;
-   length_toprinttmp_utilchar = 0 ;
-   length_ligne_writedecl = 0 ;
-   length_newname_toamr = 0 ;
-   length_newname_writedecl = 0 ;
-   length_ligne_toamr = 0 ;
-   length_tmpligne_writedecl = 0 ;
-   value_char_size = 0 ;
-   value_char_size1 = 0 ;
-   value_char_size2 = 0 ;
-   value_char_size3 = 0 ;
-   inallocate = 0;
-   infixed = 1;
-   infree  = 0;
-
-   checkexistcommon=1;
-   todebug=0;
-   onlyfixedgrids=0;
-   fixedgrids=0;
-   InAgrifParentDef = 0;
-   IndicenbmaillesX=0;
-   IndicenbmaillesY=0;
-   IndicenbmaillesZ=0;
-   created_dimensionlist = 1;
-   indicemaxtabvars = 0;   /* current indice in the table tabvars             */
-   SubloopScalar = 0;
-   todebug = 0;
-   todebugfree = 0;
-   retour77 = 1 ;
-   mark = 0 ;
-   shouldincludempif = 0 ;
-   Read_val_max();
+    List_Global_Var = (listvar *) NULL;
+    List_GlobalParameter_Var = (listvar *) NULL;
+    List_Common_Var = (listvar *) NULL;
+    List_Allocate_Var = (listallocate *) NULL;
+    List_SubroutineWhereAgrifUsed = (listnom *) NULL;
+    List_Subroutine_For_Alloc = (listnom *) NULL;
+    List_Include = (listusemodule *) NULL;
+    List_NameOfModuleUsed = (listusemodule *) NULL;
+    listofmoduletmp = (listusemodule *) NULL;
+    List_SubroutineDeclaration_Var = (listvar *) NULL;
+    List_UsedInSubroutine_Var = (listvar *) NULL;
+    List_NotGridDepend_Var = (listvar *) NULL;
+    Listofavailableindices = (listindice *) NULL;
+    Listofavailableindices_glob = (listindice **) calloc(NB_CAT_VARIABLES,sizeof(listindice *));
+    List_CouplePointed_Var = (listvarpointtovar *) NULL;
+    List_ModuleUsed_Var = (listvar *) NULL;
+    List_ModuleUsedInModuleUsed_Var = (listvar *) NULL;
+    List_GlobParamModuleUsed_Var = (listparameter *) NULL;
+    List_GlobParamModuleUsedInModuleUsed_Var = (listparameter *) NULL;
+    List_SubroutineArgument_Var = (listvar *) NULL;
+    List_FunctionType_Var = (listvar *) NULL;
+    tmpuselocallist = (listusemodule *) NULL;
+    List_ContainsSubroutine = (listnom *) NULL;
+    oldfortran_out = (FILE *) NULL;
+
+    if (argc < 2) print_usage();
+    
+    strcpy(config_file, argv[1]);
+    strcpy(work_dir, ".");
+    strcpy(input_dir, ".");
+    strcpy(output_dir, "AGRIF_MODELFILES");
+    strcpy(include_dir, "AGRIF_INC");
+    strcpy(filetoparse, "");
+    strcpy(subofagrifinitgrids, "");
+    strcpy(meetagrifinitgrids, "");
+    strcpy(mpiinitvar, "");
+
+    length_last = 0 ;
+    length_first = 0 ;
+    length_v_vallengspec = 0 ;
+    length_v_commoninfile = 0 ;
+    length_v_precision = 0 ;
+    length_v_IntentSpec = 0 ;
+    length_v_initialvalue = 0 ;
+    length_v_readedlistdimension = 0 ;
+    length_a_nomvar = 0 ;
+    length_toprintglob = 0 ;
+    length_tmpvargridname = 0 ;
+    length_ligne_Subloop = 0 ;
+    length_toprint_utilagrif = 0 ;
+    length_toprinttmp_utilchar = 0 ;
+    length_ligne_writedecl = 0 ;
+    length_newname_toamr = 0 ;
+    length_newname_writedecl = 0 ;
+    length_ligne_toamr = 0 ;
+    length_tmpligne_writedecl = 0 ;
+    value_char_size = 0 ;
+    value_char_size1 = 0 ;
+    value_char_size2 = 0 ;
+    value_char_size3 = 0 ;
+    inallocate = 0;
+    infixed = 1;
+    infree  = 0;
+
+    onlyfixedgrids=0;
+    fixedgrids=0;
+    InAgrifParentDef = 0;
+    IndicenbmaillesX=0;
+    IndicenbmaillesY=0;
+    IndicenbmaillesZ=0;
+    created_dimensionlist = 1;
+    /* current indice in the table tabvars             */
+    for ( i=0 ; i<NB_CAT_VARIABLES ; i++)
+    {
+        indicemaxtabvars[i] = 0;
+    }
+    SubloopScalar = 0;
+    todebug = 0;
+    retour77 = 1 ;
+    shouldincludempif = 0 ;
+
+    Read_val_max();
+
 /******************************************************************************/
 /*  2-  Program arguments                                                     */
 /******************************************************************************/
 
-   if ((yyin=fopen(argv[1],"r"))==NULL)
-   {
-      printf("the file %s doesn't exist \n",argv[1]);
-      exit(0);
-   }
-
-   i=2;
-   while (i<argc)
-   {
-      if (!strcasecmp(argv[i],"-incdir"))
-      {
-         strcpy(nomdir,argv[i+1]);
-         i++;
-      }
-      else if (!strcasecmp(argv[i],"-comdirin")) /* input directory           */
-      {
-         strcpy(commondirin,argv[i+1]);
-         i++;
-      }
-      else if (!strcasecmp(argv[i],"-comdirout")) /* output directory         */
-      {
-         strcpy(commondirout,argv[i+1]);
-         i++;
-      }
-      else if (!strcasecmp(argv[i],"-convfile")) /* file to parse             */
-      {
-         strcpy(filetoparse,argv[i+1]);
-         i++;
-         lengthmainfile = strlen(filetoparse);
-         if (!strcasecmp(&filetoparse[lengthmainfile-4],".f90"))
-         {
-         infixed = 0;
-         infree = 1;
-         }
-         else
-         {
-         infixed = 1;
-         infree = 0;
-         }
-      }
-      else if (!strcasecmp(argv[i],"-free")) /* file to parse        */
-      {
-         stylegiven = 1;
-         infreegiven  = 1 ;
-         infixedgiven = 0;
-      }   
-      else if (!strcasecmp(argv[i],"-fixed")) /* file to parse        */
-      {
-         stylegiven = 1;
-         infreegiven  = 0;
-         infixedgiven = 1;
-      }         
-      else if (!strcasecmp(argv[i],"-SubloopScalar")) /* file to parse        */
-      {
-         SubloopScalar = 1 ;
-      }
-      else if (!strcasecmp(argv[i],"-SubloopScalar1")) /* file to parse       */
-      {
-         SubloopScalar = 2 ;
-      }
-      else if (!strcasecmp(argv[i],"-todebug")) /* file to parse       */
-      {
-         todebug = 1 ;
-      }
-      else if (!strcasecmp(argv[i],"-mark")) /* file to parse       */
-      {
-         mark = 1 ;
-      }
-      else if (!strcasecmp(argv[i],"-todebugfree")) /* file to parse       */
-      {
-         todebugfree = 1 ;
-      }
-      else if (!strcasecmp(argv[i],"-rm"))
-      {
-         checkexistcommon=0;
-      }
-      else
-      {
-         printf("Unkwon option : %s\n",argv[i]);
-         exit(0);
-      }
-      i++;
-   }
-
-   if (stylegiven == 1) 
-   {
-   infree = infreegiven;
-   infixed = infixedgiven;   
-   }
-   Save_Length(nomdir,34);
-   Save_Length(commondirout,35);
-   Save_Length(commondirin,36);
-   Save_Length(filetoparse,37);
+    if ( (convert_in=fopen(config_file,"r")) == NULL )
+    {
+        printf("##\n## ERROR: the configuration file '%s' doesn't exist.\n##\n", config_file);
+        print_usage();
+    }
+
+    i=2;
+    while ( i < argc )
+    {
+        if (!strcasecmp(argv[i], "-workdir"))
+        {
+            strcpy(work_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-incdir"))
+        {
+            strcpy(include_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-comdirin")) /* input directory           */
+        {
+            strcpy(input_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-comdirout")) /* output directory         */
+        {
+            strcpy(output_dir,argv[i+1]);
+            i++;
+        }
+        else if (!strcasecmp(argv[i], "-convfile")) /* file to parse             */
+        {
+            strcpy(filetoparse, argv[i+1]);
+            i++;
+            lengthmainfile = strlen(filetoparse);
+            if (!strcasecmp(&filetoparse[lengthmainfile-4], ".f90"))
+            {
+                infixed = 0;
+                infree = 1;
+            }
+            else
+            {
+                infixed = 1;
+                infree = 0;
+            }
+        }
+        else if (!strcasecmp(argv[i], "-free"))
+        {
+            stylegiven = 1;
+            infreegiven  = 1 ;
+            infixedgiven = 0;
+        }
+        else if (!strcasecmp(argv[i], "-fixed"))
+        {
+            stylegiven = 1;
+            infreegiven  = 0;
+            infixedgiven = 1;
+        }
+        else if (!strcasecmp(argv[i], "-SubloopScalar"))
+        {
+            SubloopScalar = 1 ;
+        }
+        else if (!strcasecmp(argv[i], "-SubloopScalar1"))
+        {
+            SubloopScalar = 2 ;
+        }
+        else if (!strcasecmp(argv[i], "-todebug"))
+        {
+            todebug = 1 ;
+        }
+        else if (!strcasecmp(argv[i],"-rm")) { }
+        else
+        {
+            printf("##\n## Unkwon option : %s\n##\n", argv[i]);
+            exit(0);
+        }
+        i++;
+    }
+    // Check input file
+    if ( strlen(filetoparse) == 0 )         // -convfile has not been specified
+    {
+        printf("##\n## ERROR: please provide a file to parse with -convfile.\n##\n");
+        print_usage();
+    }
+    // Setup input & output directories
+    if ( strcasecmp(work_dir, ".") != 0 )   // -workdir has been changed...
+    {
+        if ( strcasecmp(input_dir,  ".") == 0 )                 // ...and -comdirin  has NOT been changed
+        {
+            strcpy(input_dir, work_dir);
+        }
+        if ( strcasecmp(output_dir, "AGRIF_MODELFILES") == 0 )  // ...and -comdirout has NOT been changed
+        {
+            sprintf(output_dir, "%s/%s", work_dir, "AGRIF_MODELFILES");
+        }
+        if ( strcasecmp(include_dir, "AGRIF_INC") == 0 )        // ...and -incdir    has NOT been changed
+        {
+            sprintf(include_dir, "%s/%s", work_dir, "AGRIF_INC");
+        }
+    }
+    if (stylegiven == 1)
+    {
+        infree  = infreegiven;
+        infixed = infixedgiven;
+    }
 
 /******************************************************************************/
-/*  3-  Parsing of the  conv file <name>.in                                   */
+/*  3-  Parsing of the conv file <name>.in                                    */
 /******************************************************************************/
 
-   if ((yyin=fopen(argv[1],"r"))==NULL)
-   {
-       printf("the file %s doesn't exist \n",argv[1]);
-       exit(0);
-   }
-   strcpy(mainfile,argv[1]);
-   Save_Length(mainfile,33);
-
-   if ( strstr(filetoparse,".f90") ||
-        strstr(filetoparse,".F90") ) retour77 = 0;
-
-   yyparse();
+    if ( strstr(filetoparse, ".f90") || strstr(filetoparse, ".F90") ) retour77 = 0;
+
+    convert_parse();
 
 /******************************************************************************/
 /*  4-  Preparation of the file parsing                                       */
 /******************************************************************************/
-   if ((yyin=fopen(filetoparse,"r"))==NULL) /* Is the file to parse exist ?   */
-   {
-      printf("the file %s doesn't exist \n",filetoparse);
-      exit(0);
-   }
-   /* mainfile : the name of the file to parse                                */
-   strcpy(mainfile,filetoparse);
-   /*                                                                         */
-   if ((dependglobaloutput=fopen(".dependglobal_agrif","r"))!=NULL)
-   {
-      fscanf(dependglobaloutput,"%d\n",&indicemaxtabvars);
-      fclose(dependglobaloutput);
-   }
-   Readthedependavailablefile();
-   /* Read the .dependnbxnby file which contains indices of nbmaillsX,        */
-   /*    nbmailleY and nbmailleZ                                              */
-   Readthedependnbxnbyfile();
-   Read_Subroutine_For_Alloc();
+
+    sprintf(dependfilename, "%s/.dependglobal_agrif", work_dir);
+    /*                                                                         */
+    if ( (dependglobaloutput=fopen(dependfilename, "r")) != NULL )
+    {
+        for (i=0;i<NB_CAT_VARIABLES;i++)
+        {
+            fscanf(dependglobaloutput,"%d\n",&indicemaxtabvars[i]);
+        }
+        fclose(dependglobaloutput);
+    }
+    Readthedependavailablefile();
+    /* Read the .dependnbxnby file which contains indices of nbmaillsX, nbmailleY and nbmailleZ */
+    Readthedependnbxnbyfile();
+    Read_Subroutine_For_Alloc();
+
 /******************************************************************************/
 /*  5-  Parsing of the input file (2 times)                                   */
 /******************************************************************************/
-   /* Record all variable in list                                             */
-   firstpass = 1;
-   processfortran(filetoparse);
-   /*                                                                         */
-   CompleteThelistvarindoloop();
-   /* Read list of module used                                                */
-   RecordUseModulesVariables();
-   /* Read list of module used in module used                                 */
-   RecordUseModulesUseModulesVariables();
-   /* Save variables are considered as globals ones                           */
-   Update_List_Global_Var_From_List_Save_Var();
-   /* Update all lists                                                        */
-   ListUpdate();
-   /*                                                                         */
-   Clean_List_Global_Var();
-   /* Indice tabvars identification                                           */
-   IndiceTabvarsIdentification();
-   /* Update all lists                                                        */
-   ListUpdate();
-   /* The allocation subroutine is necessary ????                             */
-   New_Allocate_Subroutine_Is_Necessary();
-   /* The allocation subroutine is necessary for common list                  */
-   New_Allocate_Subroutine_For_Common_Is_Necessary();
-   /* Sort List_SubroutineArgument_Var                                        */
-   Sort_List_SubroutineArgument_Var();
-   /* Clean all lists                                                         */
-   ListClean();
-   /* Update Indice of List_UsedInSubroutine_Var from module used             */
-   List_UsedInSubroutine_Var_Update_From_Module_Used();
-   /* Update List_SubroutineWhereAgrifUsed                                    */
-   UpdateList_SubroutineWhereAgrifUsed();
-   /* Update List_UsedInSubroutine_Var with v_readedlistdimension             */
-   UpdateList_UsedInSubroutine_With_dimension();;
-   /*                                                                         */
-   ModifyThelistvarindoloop();
-   /*                                                                         */
-   UpdateListDeclarationWithDimensionList();
-   /*                                                                         */
-   GiveTypeOfVariables();
-   Affiche();
-   /* Build new subroutines                                                   */
-   firstpass = 0;
-   processfortran(filetoparse);
-
-   newvar = (listvar *)NULL;
-/*newvar = List_Global_Var; */
-   while ( newvar )
-   {
-      printf("++++ %s %d %s %s %s\n",
-      newvar->var->v_nomvar,
-      newvar->var->v_nbdim,
-      newvar->var->v_subroutinename,
-      newvar->var->v_modulename,
-      newvar->var->v_typevar
-             );
-      newvar = newvar->suiv;
-   }
+
+    /* Record all variables in list                                            */
+    firstpass = 1;
+    process_fortran(filetoparse);
+
+    CompleteThelistvarindoloop();
+    /* Read list of module used                                                */
+    RecordUseModulesVariables();
+    /* Read list of module used in module used                                 */
+    RecordUseModulesUseModulesVariables();
+    /* Save variables are considered as globals ones                           */
+    Update_List_Global_Var_From_List_Save_Var();
+    /* Update all lists                                                        */
+    ListUpdate();
+
+    Clean_List_Global_Var();
+    /* Indice tabvars identification                                           */
+    IndiceTabvarsIdentification();
+    /* Update all lists                                                        */
+    ListUpdate();
+    /* The allocation subroutine is necessary ????                             */
+    New_Allocate_Subroutine_Is_Necessary();
+    /* The allocation subroutine is necessary for common list                  */
+    New_Allocate_Subroutine_For_Common_Is_Necessary();
+    /* Sort List_SubroutineArgument_Var                                        */
+    Sort_List_SubroutineArgument_Var();
+    /* Clean all lists                                                         */
+    ListClean();
+    /* Update Indice of List_UsedInSubroutine_Var from module used             */
+    List_UsedInSubroutine_Var_Update_From_Module_Used();
+    /* Update List_SubroutineWhereAgrifUsed                                    */
+    UpdateList_SubroutineWhereAgrifUsed();
+    /* Update List_UsedInSubroutine_Var with v_readedlistdimension             */
+    UpdateList_UsedInSubroutine_With_dimension();
+
+    ModifyThelistvarindoloop();
+    UpdateListDeclarationWithDimensionList();
+    GiveTypeOfVariables();
+
+    /* Build new subroutines                                                   */
+    firstpass = 0;
+    process_fortran(filetoparse);
+
+    newvar = (listvar *) NULL;
+
+    while ( newvar )
+    {
+        printf("++++ %s %d %s %s %s\n",
+            newvar->var->v_nomvar,
+            newvar->var->v_nbdim,
+            newvar->var->v_subroutinename,
+            newvar->var->v_modulename,
+            newvar->var->v_typevar);
+        newvar = newvar->suiv;
+    }
+
 /******************************************************************************/
 /*  6-  Write informations in output files                                    */
 /******************************************************************************/
 
-   /* Write the .dependglobal_agrif file which contain the max indice         */
-   /*    of the tabvars table                                                 */
-   dependglobaloutput = fopen(".dependglobal_agrif","w");
-   fprintf(dependglobaloutput,"%d\n",indicemaxtabvars);
-   fclose(dependglobaloutput);
-   /* Write the list of available indice                                      */
-   Writethedependavailablefile();
-   /* Write the .dependnbxnby file which contains indices of nbmaillsX,       */
-   /*    nbmailleY and nbmailleZ                                              */
-   Writethedependnbxnbyfile();
-   /* Write the .depend<namefile> file which contain general informations     */
-   /*    about variable of this file                                          */
-   parcours = List_NameOfModule;
-   while( parcours )
-   {
-      Writethedependlistofmoduleused(parcours->o_nom);
-      WritedependParameterList(parcours->o_nom);
-      Writethedependfile(parcours->o_nom,List_Global_Var);
-      parcours=parcours->suiv;
-   }
-   parcours = List_NameOfCommon;
-   while( parcours )
-   {
-      Writethedependfile(parcours->o_nom,List_Common_Var);
-      parcours=parcours->suiv;
-   }
-   Write_Subroutine_For_Alloc();
+    /* Write the .dependglobal_agrif file which contain the max indice         */
+    /*    of the tabvars table                                                 */
+    sprintf(dependfilename, "%s/.dependglobal_agrif", work_dir);
+    dependglobaloutput = fopen(dependfilename, "w");
+    for (i=0;i<NB_CAT_VARIABLES;i++)
+    {
+        fprintf(dependglobaloutput,"%d\n",indicemaxtabvars[i]);
+    }
+    fclose(dependglobaloutput);
+    /* Write the list of available indice                                      */
+    Writethedependavailablefile();
+    /* Write the .dependnbxnby file which contains indices of nbmaillsX,       */
+    /*    nbmailleY and nbmailleZ                                              */
+    Writethedependnbxnbyfile();
+    /* Write the .depend<namefile> file which contain general informations     */
+    /*    about variable of this file                                          */
+    parcours = List_NameOfModule;
+    while( parcours )
+    {
+        Writethedependlistofmoduleused(parcours->o_nom);
+        WritedependParameterList(parcours->o_nom);
+        Writethedependfile(parcours->o_nom,List_Global_Var);
+        parcours=parcours->suiv;
+    }
+    parcours = List_NameOfCommon;
+    while( parcours )
+    {
+        Writethedependfile(parcours->o_nom,List_Common_Var);
+        parcours=parcours->suiv;
+    }
+    Write_Subroutine_For_Alloc();
+
 /******************************************************************************/
 /*  7-  Create files in AGRIF_INC directory                                   */
 /******************************************************************************/
-   creefichieramr(NameTamponfile);
-
-   Write_val_max();
-
-   if ( todebug == 1 ) printf("Out of CONV \n");
-   return 0;
-}
+
+    creefichieramr();
+
+    Write_val_max();
+
+    if ( todebug == 1 ) printf("Out of CONV \n");
+    return 0;
+}
+
 #line 2 "convert.yy.c"
 
@@ -2003,9 +1997,28 @@
 
 /* A lexical scanner generated by flex */
+
+#define yy_create_buffer convert__create_buffer
+#define yy_delete_buffer convert__delete_buffer
+#define yy_flex_debug convert__flex_debug
+#define yy_init_buffer convert__init_buffer
+#define yy_flush_buffer convert__flush_buffer
+#define yy_load_buffer_state convert__load_buffer_state
+#define yy_switch_to_buffer convert__switch_to_buffer
+#define yyin convert_in
+#define yyleng convert_leng
+#define yylex convert_lex
+#define yylineno convert_lineno
+#define yyout convert_out
+#define yyrestart convert_restart
+#define yytext convert_text
+#define yywrap convert_wrap
+#define yyalloc convert_alloc
+#define yyrealloc convert_realloc
+#define yyfree convert_free
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
 #define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 37
+#define YY_FLEX_SUBMINOR_VERSION 35
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
@@ -2045,4 +2058,5 @@
 typedef int32_t flex_int32_t;
 typedef uint32_t flex_uint32_t;
+typedef uint64_t flex_uint64_t;
 #else
 typedef signed char flex_int8_t;
@@ -2052,4 +2066,5 @@
 typedef unsigned short int flex_uint16_t;
 typedef unsigned int flex_uint32_t;
+#endif /* ! C99 */
 
 /* Limits of integral types. */
@@ -2081,6 +2096,4 @@
 #define UINT32_MAX             (4294967295U)
 #endif
-
-#endif /* ! C99 */
 
 #endif /* ! FLEXINT_H */
@@ -2134,5 +2147,5 @@
 
 /* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE yyrestart(yyin  )
+#define YY_NEW_FILE convert_restart(convert_in  )
 
 #define YY_END_OF_BUFFER_CHAR 0
@@ -2157,7 +2170,7 @@
 #endif
 
-extern yy_size_t yyleng;
-
-extern FILE *yyin, *yyout;
+extern yy_size_t convert_leng;
+
+extern FILE *convert_in, *convert_out;
 
 #define EOB_ACT_CONTINUE_SCAN 0
@@ -2171,5 +2184,5 @@
 	do \
 		{ \
-		/* Undo effects of setting up yytext. */ \
+		/* Undo effects of setting up convert_text. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
@@ -2177,5 +2190,5 @@
 		YY_RESTORE_YY_MORE_OFFSET \
 		(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
-		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		YY_DO_BEFORE_ACTION; /* set up convert_text again */ \
 		} \
 	while ( 0 )
@@ -2240,6 +2253,6 @@
 	 *
 	 * When we actually see the EOF, we change the status to "new"
-	 * (via yyrestart()), so that the user can continue scanning by
-	 * just pointing yyin at a new input file.
+	 * (via convert_restart()), so that the user can continue scanning by
+	 * just pointing convert_in at a new input file.
 	 */
 #define YY_BUFFER_EOF_PENDING 2
@@ -2268,8 +2281,8 @@
 #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
 
-/* yy_hold_char holds the character lost when yytext is formed. */
+/* yy_hold_char holds the character lost when convert_text is formed. */
 static char yy_hold_char;
 static yy_size_t yy_n_chars;		/* number of characters read into yy_ch_buf */
-yy_size_t yyleng;
+yy_size_t convert_leng;
 
 /* Points to current character in buffer. */
@@ -2278,39 +2291,39 @@
 static int yy_start = 0;	/* start state number */
 
-/* Flag which is used to allow yywrap()'s to do buffer switches
- * instead of setting up a fresh yyin.  A bit of a hack ...
+/* Flag which is used to allow convert_wrap()'s to do buffer switches
+ * instead of setting up a fresh convert_in.  A bit of a hack ...
  */
 static int yy_did_buffer_switch_on_eof;
 
-void yyrestart (FILE *input_file  );
-void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
-YY_BUFFER_STATE yy_create_buffer (FILE *file,int size  );
-void yy_delete_buffer (YY_BUFFER_STATE b  );
-void yy_flush_buffer (YY_BUFFER_STATE b  );
-void yypush_buffer_state (YY_BUFFER_STATE new_buffer  );
-void yypop_buffer_state (void );
-
-static void yyensure_buffer_stack (void );
-static void yy_load_buffer_state (void );
-static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file  );
-
-#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
-
-YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
-YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
-YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len  );
-
-void *yyalloc (yy_size_t  );
-void *yyrealloc (void *,yy_size_t  );
-void yyfree (void *  );
-
-#define yy_new_buffer yy_create_buffer
+void convert_restart (FILE *input_file  );
+void convert__switch_to_buffer (YY_BUFFER_STATE new_buffer  );
+YY_BUFFER_STATE convert__create_buffer (FILE *file,int size  );
+void convert__delete_buffer (YY_BUFFER_STATE b  );
+void convert__flush_buffer (YY_BUFFER_STATE b  );
+void convert_push_buffer_state (YY_BUFFER_STATE new_buffer  );
+void convert_pop_buffer_state (void );
+
+static void convert_ensure_buffer_stack (void );
+static void convert__load_buffer_state (void );
+static void convert__init_buffer (YY_BUFFER_STATE b,FILE *file  );
+
+#define YY_FLUSH_BUFFER convert__flush_buffer(YY_CURRENT_BUFFER )
+
+YY_BUFFER_STATE convert__scan_buffer (char *base,yy_size_t size  );
+YY_BUFFER_STATE convert__scan_string (yyconst char *yy_str  );
+YY_BUFFER_STATE convert__scan_bytes (yyconst char *bytes,yy_size_t len  );
+
+void *convert_alloc (yy_size_t  );
+void *convert_realloc (void *,yy_size_t  );
+void convert_free (void *  );
+
+#define yy_new_buffer convert__create_buffer
 
 #define yy_set_interactive(is_interactive) \
 	{ \
 	if ( ! YY_CURRENT_BUFFER ){ \
-        yyensure_buffer_stack (); \
+        convert_ensure_buffer_stack (); \
 		YY_CURRENT_BUFFER_LVALUE =    \
-            yy_create_buffer(yyin,YY_BUF_SIZE ); \
+            convert__create_buffer(convert_in,YY_BUF_SIZE ); \
 	} \
 	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
@@ -2320,7 +2333,7 @@
 	{ \
 	if ( ! YY_CURRENT_BUFFER ){\
-        yyensure_buffer_stack (); \
+        convert_ensure_buffer_stack (); \
 		YY_CURRENT_BUFFER_LVALUE =    \
-            yy_create_buffer(yyin,YY_BUF_SIZE ); \
+            convert__create_buffer(convert_in,YY_BUF_SIZE ); \
 	} \
 	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
@@ -2331,16 +2344,19 @@
 /* Begin user sect3 */
 
+#define convert_wrap(n) 1
+#define YY_SKIP_YYWRAP
+
 typedef unsigned char YY_CHAR;
 
-FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
+FILE *convert_in = (FILE *) 0, *convert_out = (FILE *) 0;
 
 typedef int yy_state_type;
 
-extern int yylineno;
-
-int yylineno = 1;
-
-extern char *yytext;
-#define yytext_ptr yytext
+extern int convert_lineno;
+
+int convert_lineno = 1;
+
+extern char *convert_text;
+#define yytext_ptr convert_text
 
 static yy_state_type yy_get_previous_state (void );
@@ -2350,15 +2366,15 @@
 
 /* Done after the current pattern has been matched and before the
- * corresponding action - sets up yytext.
+ * corresponding action - sets up convert_text.
  */
 #define YY_DO_BEFORE_ACTION \
 	(yytext_ptr) = yy_bp; \
-	yyleng = (size_t) (yy_cp - yy_bp); \
+	convert_leng = (yy_size_t) (yy_cp - yy_bp); \
 	(yy_hold_char) = *yy_cp; \
 	*yy_cp = '\0'; \
 	(yy_c_buf_p) = yy_cp;
 
-#define YY_NUM_RULES 12
-#define YY_END_OF_BUFFER 13
+#define YY_NUM_RULES 15
+#define YY_END_OF_BUFFER 16
 /* This struct is not used in this scanner,
    but its presence is necessary. */
@@ -2368,14 +2384,15 @@
 	flex_int32_t yy_nxt;
 	};
-static yyconst flex_int16_t yy_accept[77] =
+static yyconst flex_int16_t yy_accept[84] =
     {   0,
-        0,    0,    0,    0,   13,   12,   11,   10,   12,    9,
-       12,   12,   12,    9,    8,    8,    8,    8,    8,    8,
-       11,    0,    4,    7,    7,    7,    5,    8,    8,    8,
-        8,    8,    8,    8,    6,    8,    8,    8,    8,    3,
-        8,    8,    8,    8,    8,    8,    8,    8,    8,    8,
-        8,    8,    8,    8,    8,    8,    8,    8,    8,    8,
-        8,    8,    8,    8,    8,    2,    8,    8,    8,    1,
-        8,    8,    8,    8,    6,    0
+        0,    0,    0,    0,   16,   15,   14,   13,   15,   12,
+       11,   11,   11,   11,   12,    7,   10,   10,   10,   10,
+       10,   10,   10,   14,    0,    4,   11,    9,    9,    9,
+        5,   10,   10,   10,   10,   10,   10,   10,   10,    8,
+       10,   10,   10,   10,   10,    3,   10,    6,   10,   10,
+       10,   10,   10,   10,   10,   10,   10,   10,   10,   10,
+       10,   10,   10,   10,   10,   10,   10,   10,   10,   10,
+       10,   10,    2,   10,   10,   10,    1,   10,   10,   10,
+       10,    8,    0
     } ;
 
@@ -2388,12 +2405,12 @@
         6,    1,    1,    7,    1,    1,    1,    8,    9,   10,
        11,    8,    8,    8,   12,    8,    8,   13,   14,    1,
-        1,    1,    1,    1,   15,   16,   16,   17,   18,   19,
-       20,   16,   21,   16,   16,   22,   23,   24,   25,   26,
-       16,   27,   28,   29,   30,   16,   16,   31,   32,   16,
-       33,    1,   34,    1,   35,    1,   36,   16,   16,   37,
-
-       38,   39,   40,   16,   41,   16,   16,   42,   43,   44,
-       45,   46,   16,   47,   48,   49,   50,   16,   16,   51,
-       52,   16,    1,    1,    1,    1,    1,    1,    1,    1,
+       15,    1,    1,    1,   16,   17,   17,   18,   19,   20,
+       21,   17,   22,   17,   23,   24,   25,   26,   27,   28,
+       17,   29,   30,   31,   32,   17,   17,   33,   34,   17,
+       35,    1,   36,    1,   37,    1,   38,   17,   17,   39,
+
+       40,   41,   42,   17,   43,   17,   44,   45,   46,   47,
+       48,   49,   17,   50,   51,   52,   53,   17,   17,   54,
+       55,   17,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -2412,67 +2429,72 @@
     } ;
 
-static yyconst flex_int32_t yy_meta[53] =
+static yyconst flex_int32_t yy_meta[56] =
     {   0,
         1,    1,    2,    1,    1,    1,    1,    3,    3,    3,
-        3,    3,    1,    1,    3,    3,    3,    3,    3,    3,
+        3,    3,    1,    1,    1,    3,    3,    3,    3,    3,
         3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    1,    1,    3,    3,    3,    3,    3,    3,
+        3,    3,    3,    3,    1,    1,    3,    3,    3,    3,
         3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3
+        3,    3,    3,    3,    3
     } ;
 
-static yyconst flex_int16_t yy_base[79] =
+static yyconst flex_int16_t yy_base[86] =
     {   0,
-        0,    0,    0,    0,  150,  164,  147,  164,  144,  164,
-       36,   37,   38,  134,    0,   44,   32,   34,   44,   33,
-      144,  141,  140,  164,  164,  164,  164,    0,  131,   31,
-       34,   42,   39,   49,    0,   50,   49,   38,   56,    0,
-       59,   52,  107,   68,  106,   72,   75,   72,   77,   81,
-       79,   76,   75,   86,   73,   88,   85,   89,   90,   79,
-       93,   86,   99,   97,  103,    0,   37,  115,  114,    0,
-      108,  116,  121,  112,    0,  164,  160,   57
+        0,    0,    0,    0,  192,  194,  186,  194,  176,  194,
+       48,   53,   58,   69,  164,  194,    0,   60,   51,   47,
+       49,   67,   55,  173,  170,  169,   90,  194,  194,  194,
+      194,    0,  160,   53,   62,   58,   66,   62,   74,    0,
+       85,   95,   94,   82,  101,    0,  101,    0,   91,  134,
+       96,  133,  100,  103,   99,  105,  109,  106,  102,  101,
+      113,   99,  115,  113,  119,  127,  123,  139,  130,  142,
+      137,  132,    0,   81,  144,  143,    0,  136,  144,  150,
+      139,    0,  194,  190,   81
     } ;
 
-static yyconst flex_int16_t yy_def[79] =
+static yyconst flex_int16_t yy_def[86] =
     {   0,
-       76,    1,    1,    1,   76,   76,   76,   76,   77,   76,
-       76,   76,   76,   76,   78,   78,   78,   78,   78,   78,
-       76,   77,   77,   76,   76,   76,   76,   78,   78,   78,
-       78,   78,   78,   78,   78,   78,   78,   78,   78,   78,
-       78,   78,   78,   78,   78,   78,   78,   78,   78,   78,
-       78,   78,   78,   78,   78,   78,   78,   78,   78,   78,
-       78,   78,   78,   78,   78,   78,   78,   78,   78,   78,
-       78,   78,   78,   78,   78,    0,   76,   76
+       83,    1,    1,    1,   83,   83,   83,   83,   84,   83,
+       83,   83,   83,   83,   83,   83,   85,   85,   85,   85,
+       85,   85,   85,   83,   84,   84,   83,   83,   83,   83,
+       83,   85,   85,   85,   85,   85,   85,   85,   85,   85,
+       85,   85,   85,   85,   85,   85,   85,   85,   85,   85,
+       85,   85,   85,   85,   85,   85,   85,   85,   85,   85,
+       85,   85,   85,   85,   85,   85,   85,   85,   85,   85,
+       85,   85,   85,   85,   85,   85,   85,   85,   85,   85,
+       85,   85,    0,   83,   83
     } ;
 
-static yyconst flex_int16_t yy_nxt[217] =
+static yyconst flex_int16_t yy_nxt[250] =
     {   0,
-        6,    7,    8,    9,   10,   10,   10,    6,   11,   12,
-       13,    6,   14,   10,   15,   15,   15,   15,   16,   15,
-       15,   15,   15,   17,   18,   19,   15,   15,   15,   20,
-       15,   15,   10,   10,   15,   15,   15,   15,   16,   15,
-       15,   15,   15,   17,   18,   19,   15,   15,   15,   20,
-       15,   15,   24,   25,   26,   29,   31,   32,   33,   28,
-       34,   36,   37,   38,   30,   39,   40,   41,   42,   43,
-       44,   69,   24,   25,   26,   45,   31,   32,   46,   33,
-       34,   36,   37,   38,   30,   39,   40,   41,   42,   43,
-       48,   44,   50,   51,   52,   45,   53,   54,   46,   55,
-
-       56,   57,   58,   59,   60,   61,   62,   63,   64,   65,
-       48,   66,   50,   51,   52,   67,   53,   54,   68,   55,
-       56,   57,   58,   59,   60,   61,   62,   63,   64,   65,
-       35,   66,   70,   71,   72,   67,   73,   74,   68,   75,
-       49,   47,   35,   23,   23,   21,   27,   23,   21,   76,
-       35,   76,   70,   71,   72,   76,   73,   74,   76,   75,
-       22,   76,   22,    5,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76
+        6,    7,    8,    9,   10,   10,   10,   11,   12,   13,
+       14,   11,   15,   10,   16,   17,   17,   17,   17,   18,
+       17,   17,   19,   17,   17,   20,   21,   22,   17,   17,
+       17,   23,   17,   17,   10,   10,   17,   17,   17,   17,
+       18,   17,   17,   19,   17,   17,   20,   21,   22,   17,
+       17,   17,   23,   17,   17,   27,   27,   27,   27,   27,
+       27,   27,   27,   27,   27,   27,   27,   27,   27,   27,
+       28,   33,   35,   36,   37,   29,   27,   27,   27,   27,
+       27,   34,   38,   32,   39,   41,   30,   42,   43,   44,
+       45,   28,   46,   35,   36,   37,   29,   27,   27,   27,
+
+       27,   27,   34,   47,   38,   39,   41,   30,   42,   43,
+       44,   45,   48,   46,   49,   50,   51,   76,   52,   53,
+       55,   57,   58,   59,   47,   60,   61,   62,   63,   64,
+       65,   66,   67,   48,   68,   49,   50,   69,   51,   52,
+       53,   55,   57,   58,   59,   70,   60,   61,   62,   63,
+       64,   65,   66,   67,   71,   68,   72,   73,   69,   74,
+       75,   40,   77,   78,   79,   80,   70,   81,   82,   56,
+       54,   40,   26,   26,   24,   71,   31,   72,   73,   26,
+       74,   75,   40,   77,   78,   79,   80,   24,   81,   82,
+       25,   83,   25,    5,   83,   83,   83,   83,   83,   83,
+
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83
     } ;
 
-static yyconst flex_int16_t yy_chk[217] =
+static yyconst flex_int16_t yy_chk[250] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -2481,23 +2503,26 @@
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,   11,   12,   13,   16,   17,   18,   19,   78,
-       20,   30,   31,   32,   16,   33,   34,   36,   37,   38,
-       39,   67,   11,   12,   13,   41,   17,   18,   42,   19,
-       20,   30,   31,   32,   16,   33,   34,   36,   37,   38,
-       44,   39,   46,   47,   48,   41,   49,   50,   42,   51,
-
-       52,   53,   54,   55,   56,   57,   58,   59,   60,   61,
-       44,   62,   46,   47,   48,   63,   49,   50,   64,   51,
-       52,   53,   54,   55,   56,   57,   58,   59,   60,   61,
-       65,   62,   68,   69,   71,   63,   72,   73,   64,   74,
-       45,   43,   29,   23,   22,   21,   14,    9,    7,    5,
-       65,    0,   68,   69,   71,    0,   72,   73,    0,   74,
-       77,    0,   77,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-
-       76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
-       76,   76,   76,   76,   76,   76
+        1,    1,    1,    1,    1,   11,   11,   11,   11,   11,
+       12,   12,   12,   12,   12,   13,   13,   13,   13,   13,
+       12,   18,   19,   20,   21,   13,   14,   14,   14,   14,
+       14,   18,   22,   85,   23,   34,   14,   35,   36,   37,
+       38,   12,   39,   19,   20,   21,   13,   27,   27,   27,
+
+       27,   27,   18,   41,   22,   23,   34,   14,   35,   36,
+       37,   38,   42,   39,   43,   44,   45,   74,   47,   49,
+       51,   53,   54,   55,   41,   56,   57,   58,   59,   60,
+       61,   62,   63,   42,   64,   43,   44,   65,   45,   47,
+       49,   51,   53,   54,   55,   66,   56,   57,   58,   59,
+       60,   61,   62,   63,   67,   64,   68,   69,   65,   70,
+       71,   72,   75,   76,   78,   79,   66,   80,   81,   52,
+       50,   33,   26,   25,   24,   67,   15,   68,   69,    9,
+       70,   71,   72,   75,   76,   78,   79,    7,   80,   81,
+       84,    5,   84,   83,   83,   83,   83,   83,   83,   83,
+
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83,   83,
+       83,   83,   83,   83,   83,   83,   83,   83,   83
     } ;
 
@@ -2505,6 +2530,6 @@
 static char *yy_last_accepting_cpos;
 
-extern int yy_flex_debug;
-int yy_flex_debug = 0;
+extern int convert__flex_debug;
+int convert__flex_debug = 0;
 
 /* The intent behind this definition is that it'll catch
@@ -2515,5 +2540,5 @@
 #define YY_MORE_ADJ 0
 #define YY_RESTORE_YY_MORE_OFFSET
-char *yytext;
+char *convert_text;
 #line 1 "convert.lex"
 /******************************************************************************/
@@ -2552,13 +2577,11 @@
 /******************************************************************************/
 
-#line 37 "convert.lex"
+#line 40 "convert.lex"
 #include <math.h>
 #include <stdlib.h>
 #include <string.h>
-int line_num=1;
-extern FILE * yyin;
-#define MAX_INCLUDE_DEPTH 30
-YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
-#line 566 "convert.yy.c"
+
+#define YY_NO_INPUT
+#line 595 "convert.yy.c"
 
 #define INITIAL 0
@@ -2582,29 +2605,29 @@
    These are made visible to non-reentrant scanners for convenience. */
 
-int yylex_destroy (void );
-
-int yyget_debug (void );
-
-void yyset_debug (int debug_flag  );
-
-YY_EXTRA_TYPE yyget_extra (void );
-
-void yyset_extra (YY_EXTRA_TYPE user_defined  );
-
-FILE *yyget_in (void );
-
-void yyset_in  (FILE * in_str  );
-
-FILE *yyget_out (void );
-
-void yyset_out  (FILE * out_str  );
-
-yy_size_t yyget_leng (void );
-
-char *yyget_text (void );
-
-int yyget_lineno (void );
-
-void yyset_lineno (int line_number  );
+int convert_lex_destroy (void );
+
+int convert_get_debug (void );
+
+void convert_set_debug (int debug_flag  );
+
+YY_EXTRA_TYPE convert_get_extra (void );
+
+void convert_set_extra (YY_EXTRA_TYPE user_defined  );
+
+FILE *convert_get_in (void );
+
+void convert_set_in  (FILE * in_str  );
+
+FILE *convert_get_out (void );
+
+void convert_set_out  (FILE * out_str  );
+
+yy_size_t convert_get_leng (void );
+
+char *convert_get_text (void );
+
+int convert_get_lineno (void );
+
+void convert_set_lineno (int line_number  );
 
 /* Macros after this point can all be overridden by user definitions in
@@ -2614,7 +2637,7 @@
 #ifndef YY_SKIP_YYWRAP
 #ifdef __cplusplus
-extern "C" int yywrap (void );
+extern "C" int convert_wrap (void );
 #else
-extern int yywrap (void );
+extern int convert_wrap (void );
 #endif
 #endif
@@ -2650,5 +2673,5 @@
  * we now use fwrite().
  */
-#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
+#define ECHO fwrite( convert_text, convert_leng, 1, convert_out )
 #endif
 
@@ -2661,11 +2684,11 @@
 		{ \
 		int c = '*'; \
-		size_t n; \
+		yy_size_t n; \
 		for ( n = 0; n < max_size && \
-			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			     (c = getc( convert_in )) != EOF && c != '\n'; ++n ) \
 			buf[n] = (char) c; \
 		if ( c == '\n' ) \
 			buf[n++] = (char) c; \
-		if ( c == EOF && ferror( yyin ) ) \
+		if ( c == EOF && ferror( convert_in ) ) \
 			YY_FATAL_ERROR( "input in flex scanner failed" ); \
 		result = n; \
@@ -2674,5 +2697,5 @@
 		{ \
 		errno=0; \
-		while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+		while ( (result = fread(buf, 1, max_size, convert_in))==0 && ferror(convert_in)) \
 			{ \
 			if( errno != EINTR) \
@@ -2682,5 +2705,5 @@
 				} \
 			errno=0; \
-			clearerr(yyin); \
+			clearerr(convert_in); \
 			} \
 		}\
@@ -2715,10 +2738,10 @@
 #define YY_DECL_IS_OURS 1
 
-extern int yylex (void);
-
-#define YY_DECL int yylex (void)
+extern int convert_lex (void);
+
+#define YY_DECL int convert_lex (void)
 #endif /* !YY_DECL */
 
-/* Code executed at the beginning of each rule, after yytext and yyleng
+/* Code executed at the beginning of each rule, after convert_text and convert_leng
  * have been set up.
  */
@@ -2743,7 +2766,7 @@
 	register int yy_act;
     
-#line 55 "convert.lex"
-
-#line 751 "convert.yy.c"
+#line 54 "convert.lex"
+
+#line 780 "convert.yy.c"
 
 	if ( !(yy_init) )
@@ -2758,17 +2781,17 @@
 			(yy_start) = 1;	/* first start state */
 
-		if ( ! yyin )
-			yyin = stdin;
-
-		if ( ! yyout )
-			yyout = stdout;
+		if ( ! convert_in )
+			convert_in = stdin;
+
+		if ( ! convert_out )
+			convert_out = stdout;
 
 		if ( ! YY_CURRENT_BUFFER ) {
-			yyensure_buffer_stack ();
+			convert_ensure_buffer_stack ();
 			YY_CURRENT_BUFFER_LVALUE =
-				yy_create_buffer(yyin,YY_BUF_SIZE );
+				convert__create_buffer(convert_in,YY_BUF_SIZE );
 		}
 
-		yy_load_buffer_state( );
+		convert__load_buffer_state( );
 		}
 
@@ -2777,5 +2800,5 @@
 		yy_cp = (yy_c_buf_p);
 
-		/* Support of yytext. */
+		/* Support of convert_text. */
 		*yy_cp = (yy_hold_char);
 
@@ -2798,5 +2821,5 @@
 				{
 				yy_current_state = (int) yy_def[yy_current_state];
-				if ( yy_current_state >= 77 )
+				if ( yy_current_state >= 84 )
 					yy_c = yy_meta[(unsigned int) yy_c];
 				}
@@ -2804,5 +2827,5 @@
 			++yy_cp;
 			}
-		while ( yy_base[yy_current_state] != 164 );
+		while ( yy_base[yy_current_state] != 194 );
 
 yy_find_action:
@@ -2830,65 +2853,79 @@
 case 1:
 YY_RULE_SETUP
-#line 56 "convert.lex"
-return TOK_MODULEMAIN; /* name of the module                      */
+#line 55 "convert.lex"
+{ return TOK_MODULEMAIN; } /* name of the module                      */
 	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 57 "convert.lex"
-return TOK_NOTGRIDDEP; /* variable which are not grid dependent   */
+#line 56 "convert.lex"
+{ return TOK_NOTGRIDDEP; } /* variable which are not grid dependent   */
 	YY_BREAK
 case 3:
 YY_RULE_SETUP
-#line 58 "convert.lex"
-return TOK_USE;
+#line 57 "convert.lex"
+{ return TOK_USE; }
 	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 59 "convert.lex"
-{}
+#line 58 "convert.lex"
+{ }
 	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 60 "convert.lex"
-return TOK_SEP;
+#line 59 "convert.lex"
+{ return TOK_SEP; }
 	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 61 "convert.lex"
-{strcpy(yylval.na,yytext); return TOK_USEITEM;}
+#line 60 "convert.lex"
+{ return TOK_KIND; }
 	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 62 "convert.lex"
-{strcpy(yylval.na,yytext); return TOK_PROBTYPE;}
+#line 61 "convert.lex"
+{ return TOK_EQUAL; }
 	YY_BREAK
-/* dimension of the problem                */
 case 8:
 YY_RULE_SETUP
-#line 64 "convert.lex"
-{strcpy(yylval.na,yytext); return TOK_NAME;}
+#line 62 "convert.lex"
+{ strcpy(yylval.na,convert_text); return TOK_USEITEM;  }
 	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 65 "convert.lex"
-{return (int) *yytext;}
+#line 63 "convert.lex"
+{ strcpy(yylval.na,convert_text); return TOK_PROBTYPE; }  /* dimension of the problem */
 	YY_BREAK
 case 10:
-/* rule 10 can match eol */
 YY_RULE_SETUP
-#line 66 "convert.lex"
-{line_num++;return (int) *yytext;}
+#line 64 "convert.lex"
+{ strcpy(yylval.na,convert_text); return TOK_NAME; }
 	YY_BREAK
 case 11:
 YY_RULE_SETUP
-#line 67 "convert.lex"
-;
+#line 65 "convert.lex"
+{ strcpy(yylval.na,convert_text); return TOK_CSTINT; }
 	YY_BREAK
 case 12:
 YY_RULE_SETUP
+#line 66 "convert.lex"
+{ return (int) *convert_text; }
+	YY_BREAK
+case 13:
+/* rule 13 can match eol */
+YY_RULE_SETUP
+#line 67 "convert.lex"
+{ line_num++; return (int) *convert_text; }
+	YY_BREAK
+case 14:
+YY_RULE_SETUP
 #line 68 "convert.lex"
+;
+	YY_BREAK
+case 15:
+YY_RULE_SETUP
+#line 69 "convert.lex"
 ECHO;
 	YY_BREAK
-#line 896 "convert.yy.c"
+#line 939 "convert.yy.c"
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(character):
@@ -2908,6 +2945,6 @@
 			/* We're scanning a new file or input source.  It's
 			 * possible that this happened because the user
-			 * just pointed yyin at a new source and called
-			 * yylex().  If so, then we have to assure
+			 * just pointed convert_in at a new source and called
+			 * convert_lex().  If so, then we have to assure
 			 * consistency between YY_CURRENT_BUFFER and our
 			 * globals.  Here is the right place to do so, because
@@ -2916,5 +2953,5 @@
 			 */
 			(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-			YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = convert_in;
 			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
 			}
@@ -2969,9 +3006,9 @@
 				(yy_did_buffer_switch_on_eof) = 0;
 
-				if ( yywrap( ) )
+				if ( convert_wrap( ) )
 					{
 					/* Note: because we've taken care in
 					 * yy_get_next_buffer() to have set up
-					 * yytext, we can now set up
+					 * convert_text, we can now set up
 					 * yy_c_buf_p so that if some total
 					 * hoser (like flex itself) wants to
@@ -3022,5 +3059,5 @@
 	} /* end of action switch */
 		} /* end of scanning one token */
-} /* end of yylex */
+} /* end of convert_lex */
 
 /* yy_get_next_buffer - try to read in a new buffer
@@ -3084,5 +3121,5 @@
 
 			/* just a shorter name for the current buffer */
-			YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
+			YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
 
 			int yy_c_buf_p_offset =
@@ -3100,5 +3137,5 @@
 				b->yy_ch_buf = (char *)
 					/* Include room in for 2 EOB chars. */
-					yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
+					convert_realloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
 				}
 			else
@@ -3132,5 +3169,5 @@
 			{
 			ret_val = EOB_ACT_END_OF_FILE;
-			yyrestart(yyin  );
+			convert_restart(convert_in  );
 			}
 
@@ -3149,5 +3186,5 @@
 		/* Extend the array by 50%, plus the number we really need. */
 		yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
-		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) convert_realloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
 		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
 			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
@@ -3183,5 +3220,5 @@
 			{
 			yy_current_state = (int) yy_def[yy_current_state];
-			if ( yy_current_state >= 77 )
+			if ( yy_current_state >= 84 )
 				yy_c = yy_meta[(unsigned int) yy_c];
 			}
@@ -3211,11 +3248,11 @@
 		{
 		yy_current_state = (int) yy_def[yy_current_state];
-		if ( yy_current_state >= 77 )
+		if ( yy_current_state >= 84 )
 			yy_c = yy_meta[(unsigned int) yy_c];
 		}
 	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-	yy_is_jam = (yy_current_state == 76);
-
-		return yy_is_jam ? 0 : yy_current_state;
+	yy_is_jam = (yy_current_state == 83);
+
+	return yy_is_jam ? 0 : yy_current_state;
 }
 
@@ -3226,5 +3263,5 @@
     yy_cp = (yy_c_buf_p);
 
-	/* undo effects of setting up yytext */
+	/* undo effects of setting up convert_text */
 	*yy_cp = (yy_hold_char);
 
@@ -3298,5 +3335,5 @@
 
 					/* Reset buffer status. */
-					yyrestart(yyin );
+					convert_restart(convert_in );
 
 					/*FALLTHROUGH*/
@@ -3304,6 +3341,6 @@
 				case EOB_ACT_END_OF_FILE:
 					{
-					if ( yywrap( ) )
-						return EOF;
+					if ( convert_wrap( ) )
+						return 0;
 
 					if ( ! (yy_did_buffer_switch_on_eof) )
@@ -3324,5 +3361,5 @@
 
 	c = *(unsigned char *) (yy_c_buf_p);	/* cast for 8-bit char's */
-	*(yy_c_buf_p) = '\0';	/* preserve yytext */
+	*(yy_c_buf_p) = '\0';	/* preserve convert_text */
 	(yy_hold_char) = *++(yy_c_buf_p);
 
@@ -3336,15 +3373,15 @@
  * @note This function does not reset the start condition to @c INITIAL .
  */
-    void yyrestart  (FILE * input_file )
+    void convert_restart  (FILE * input_file )
 {
     
 	if ( ! YY_CURRENT_BUFFER ){
-        yyensure_buffer_stack ();
+        convert_ensure_buffer_stack ();
 		YY_CURRENT_BUFFER_LVALUE =
-            yy_create_buffer(yyin,YY_BUF_SIZE );
+            convert__create_buffer(convert_in,YY_BUF_SIZE );
 	}
 
-	yy_init_buffer(YY_CURRENT_BUFFER,input_file );
-	yy_load_buffer_state( );
+	convert__init_buffer(YY_CURRENT_BUFFER,input_file );
+	convert__load_buffer_state( );
 }
 
@@ -3353,13 +3390,13 @@
  * 
  */
-    void yy_switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
+    void convert__switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
 {
     
 	/* TODO. We should be able to replace this entire function body
 	 * with
-	 *		yypop_buffer_state();
-	 *		yypush_buffer_state(new_buffer);
+	 *		convert_pop_buffer_state();
+	 *		convert_push_buffer_state(new_buffer);
      */
-	yyensure_buffer_stack ();
+	convert_ensure_buffer_stack ();
 	if ( YY_CURRENT_BUFFER == new_buffer )
 		return;
@@ -3374,9 +3411,9 @@
 
 	YY_CURRENT_BUFFER_LVALUE = new_buffer;
-	yy_load_buffer_state( );
+	convert__load_buffer_state( );
 
 	/* We don't actually know whether we did this switch during
-	 * EOF (yywrap()) processing, but the only time this flag
-	 * is looked at is after yywrap() is called, so it's safe
+	 * EOF (convert_wrap()) processing, but the only time this flag
+	 * is looked at is after convert_wrap() is called, so it's safe
 	 * to go ahead and always set it.
 	 */
@@ -3384,9 +3421,9 @@
 }
 
-static void yy_load_buffer_state  (void)
+static void convert__load_buffer_state  (void)
 {
     	(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
 	(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
-	yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	convert_in = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
 	(yy_hold_char) = *(yy_c_buf_p);
 }
@@ -3398,11 +3435,11 @@
  * @return the allocated buffer state.
  */
-    YY_BUFFER_STATE yy_create_buffer  (FILE * file, int  size )
+    YY_BUFFER_STATE convert__create_buffer  (FILE * file, int  size )
 {
 	YY_BUFFER_STATE b;
     
-	b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state )  );
+	b = (YY_BUFFER_STATE) convert_alloc(sizeof( struct yy_buffer_state )  );
 	if ( ! b )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+		YY_FATAL_ERROR( "out of dynamic memory in convert__create_buffer()" );
 
 	b->yy_buf_size = size;
@@ -3411,11 +3448,11 @@
 	 * we need to put in 2 end-of-buffer characters.
 	 */
-	b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2  );
+	b->yy_ch_buf = (char *) convert_alloc(b->yy_buf_size + 2  );
 	if ( ! b->yy_ch_buf )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+		YY_FATAL_ERROR( "out of dynamic memory in convert__create_buffer()" );
 
 	b->yy_is_our_buffer = 1;
 
-	yy_init_buffer(b,file );
+	convert__init_buffer(b,file );
 
 	return b;
@@ -3423,8 +3460,8 @@
 
 /** Destroy the buffer.
- * @param b a buffer created with yy_create_buffer()
+ * @param b a buffer created with convert__create_buffer()
  * 
  */
-    void yy_delete_buffer (YY_BUFFER_STATE  b )
+    void convert__delete_buffer (YY_BUFFER_STATE  b )
 {
     
@@ -3436,25 +3473,29 @@
 
 	if ( b->yy_is_our_buffer )
-		yyfree((void *) b->yy_ch_buf  );
-
-	yyfree((void *) b  );
-}
-
+		convert_free((void *) b->yy_ch_buf  );
+
+	convert_free((void *) b  );
+}
+
+#ifndef __cplusplus
+extern int isatty (int );
+#endif /* __cplusplus */
+    
 /* Initializes or reinitializes a buffer.
  * This function is sometimes called more than once on the same buffer,
- * such as during a yyrestart() or at EOF.
+ * such as during a convert_restart() or at EOF.
  */
-    static void yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file )
+    static void convert__init_buffer  (YY_BUFFER_STATE  b, FILE * file )
 
 {
 	int oerrno = errno;
     
-	yy_flush_buffer(b );
+	convert__flush_buffer(b );
 
 	b->yy_input_file = file;
 	b->yy_fill_buffer = 1;
 
-    /* If b is the current buffer, then yy_init_buffer was _probably_
-     * called from yyrestart() or through yy_get_next_buffer.
+    /* If b is the current buffer, then convert__init_buffer was _probably_
+     * called from convert_restart() or through yy_get_next_buffer.
      * In that case, we don't want to reset the lineno or column.
      */
@@ -3473,5 +3514,5 @@
  * 
  */
-    void yy_flush_buffer (YY_BUFFER_STATE  b )
+    void convert__flush_buffer (YY_BUFFER_STATE  b )
 {
     	if ( ! b )
@@ -3493,5 +3534,5 @@
 
 	if ( b == YY_CURRENT_BUFFER )
-		yy_load_buffer_state( );
+		convert__load_buffer_state( );
 }
 
@@ -3502,12 +3543,12 @@
  *  
  */
-void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
+void convert_push_buffer_state (YY_BUFFER_STATE new_buffer )
 {
     	if (new_buffer == NULL)
 		return;
 
-	yyensure_buffer_stack();
-
-	/* This block is copied from yy_switch_to_buffer. */
+	convert_ensure_buffer_stack();
+
+	/* This block is copied from convert__switch_to_buffer. */
 	if ( YY_CURRENT_BUFFER )
 		{
@@ -3523,6 +3564,6 @@
 	YY_CURRENT_BUFFER_LVALUE = new_buffer;
 
-	/* copied from yy_switch_to_buffer. */
-	yy_load_buffer_state( );
+	/* copied from convert__switch_to_buffer. */
+	convert__load_buffer_state( );
 	(yy_did_buffer_switch_on_eof) = 1;
 }
@@ -3532,10 +3573,10 @@
  *  
  */
-void yypop_buffer_state (void)
+void convert_pop_buffer_state (void)
 {
     	if (!YY_CURRENT_BUFFER)
 		return;
 
-	yy_delete_buffer(YY_CURRENT_BUFFER );
+	convert__delete_buffer(YY_CURRENT_BUFFER );
 	YY_CURRENT_BUFFER_LVALUE = NULL;
 	if ((yy_buffer_stack_top) > 0)
@@ -3543,5 +3584,5 @@
 
 	if (YY_CURRENT_BUFFER) {
-		yy_load_buffer_state( );
+		convert__load_buffer_state( );
 		(yy_did_buffer_switch_on_eof) = 1;
 	}
@@ -3551,5 +3592,5 @@
  *  Guarantees space for at least one push.
  */
-static void yyensure_buffer_stack (void)
+static void convert_ensure_buffer_stack (void)
 {
 	yy_size_t num_to_alloc;
@@ -3562,9 +3603,9 @@
          */
 		num_to_alloc = 1;
-		(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
+		(yy_buffer_stack) = (struct yy_buffer_state**)convert_alloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
 		if ( ! (yy_buffer_stack) )
-			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+			YY_FATAL_ERROR( "out of dynamic memory in convert_ensure_buffer_stack()" );
 								  
 		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -3581,10 +3622,10 @@
 
 		num_to_alloc = (yy_buffer_stack_max) + grow_size;
-		(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
+		(yy_buffer_stack) = (struct yy_buffer_state**)convert_realloc
 								((yy_buffer_stack),
 								num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
 		if ( ! (yy_buffer_stack) )
-			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+			YY_FATAL_ERROR( "out of dynamic memory in convert_ensure_buffer_stack()" );
 
 		/* zero only the new slots.*/
@@ -3600,5 +3641,5 @@
  * @return the newly allocated buffer state object. 
  */
-YY_BUFFER_STATE yy_scan_buffer  (char * base, yy_size_t  size )
+YY_BUFFER_STATE convert__scan_buffer  (char * base, yy_size_t  size )
 {
 	YY_BUFFER_STATE b;
@@ -3610,7 +3651,7 @@
 		return 0;
 
-	b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state )  );
+	b = (YY_BUFFER_STATE) convert_alloc(sizeof( struct yy_buffer_state )  );
 	if ( ! b )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
+		YY_FATAL_ERROR( "out of dynamic memory in convert__scan_buffer()" );
 
 	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
@@ -3624,10 +3665,10 @@
 	b->yy_buffer_status = YY_BUFFER_NEW;
 
-	yy_switch_to_buffer(b  );
+	convert__switch_to_buffer(b  );
 
 	return b;
 }
 
-/** Setup the input buffer state to scan a string. The next call to yylex() will
+/** Setup the input buffer state to scan a string. The next call to convert_lex() will
  * scan from a @e copy of @a str.
  * @param yystr a NUL-terminated string to scan
@@ -3635,31 +3676,30 @@
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
- *       yy_scan_bytes() instead.
+ *       convert__scan_bytes() instead.
  */
-YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
+YY_BUFFER_STATE convert__scan_string (yyconst char * yystr )
 {
     
-	return yy_scan_bytes(yystr,strlen(yystr) );
-}
-
-/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
+	return convert__scan_bytes(yystr,strlen(yystr) );
+}
+
+/** Setup the input buffer state to scan the given bytes. The next call to convert_lex() will
  * scan from a @e copy of @a bytes.
- * @param yybytes the byte buffer to scan
- * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
+ * @param bytes the byte buffer to scan
+ * @param len the number of bytes in the buffer pointed to by @a bytes.
  * 
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybytes_len )
+YY_BUFFER_STATE convert__scan_bytes  (yyconst char * yybytes, yy_size_t  _yybytes_len )
 {
 	YY_BUFFER_STATE b;
 	char *buf;
-	yy_size_t n;
-	int i;
+	yy_size_t n, i;
     
 	/* Get memory for full buffer, including space for trailing EOB's. */
 	n = _yybytes_len + 2;
-	buf = (char *) yyalloc(n  );
+	buf = (char *) convert_alloc(n  );
 	if ( ! buf )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
+		YY_FATAL_ERROR( "out of dynamic memory in convert__scan_bytes()" );
 
 	for ( i = 0; i < _yybytes_len; ++i )
@@ -3668,7 +3708,7 @@
 	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
 
-	b = yy_scan_buffer(buf,n );
+	b = convert__scan_buffer(buf,n );
 	if ( ! b )
-		YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
+		YY_FATAL_ERROR( "bad buffer in convert__scan_bytes()" );
 
 	/* It's okay to grow etc. this buffer, and we should throw it
@@ -3696,12 +3736,12 @@
 	do \
 		{ \
-		/* Undo effects of setting up yytext. */ \
+		/* Undo effects of setting up convert_text. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-		yytext[yyleng] = (yy_hold_char); \
-		(yy_c_buf_p) = yytext + yyless_macro_arg; \
+		convert_text[convert_leng] = (yy_hold_char); \
+		(yy_c_buf_p) = convert_text + yyless_macro_arg; \
 		(yy_hold_char) = *(yy_c_buf_p); \
 		*(yy_c_buf_p) = '\0'; \
-		yyleng = yyless_macro_arg; \
+		convert_leng = yyless_macro_arg; \
 		} \
 	while ( 0 )
@@ -3712,8 +3752,8 @@
  * 
  */
-int yyget_lineno  (void)
+int convert_get_lineno  (void)
 {
         
-    return yylineno;
+    return convert_lineno;
 }
 
@@ -3721,7 +3761,7 @@
  * 
  */
-FILE *yyget_in  (void)
-{
-        return yyin;
+FILE *convert_get_in  (void)
+{
+        return convert_in;
 }
 
@@ -3729,7 +3769,7 @@
  * 
  */
-FILE *yyget_out  (void)
-{
-        return yyout;
+FILE *convert_get_out  (void)
+{
+        return convert_out;
 }
 
@@ -3737,7 +3777,7 @@
  * 
  */
-yy_size_t yyget_leng  (void)
-{
-        return yyleng;
+yy_size_t convert_get_leng  (void)
+{
+        return convert_leng;
 }
 
@@ -3746,7 +3786,7 @@
  */
 
-char *yyget_text  (void)
-{
-        return yytext;
+char *convert_get_text  (void)
+{
+        return convert_text;
 }
 
@@ -3755,8 +3795,8 @@
  * 
  */
-void yyset_lineno (int  line_number )
+void convert_set_lineno (int  line_number )
 {
     
-    yylineno = line_number;
+    convert_lineno = line_number;
 }
 
@@ -3765,24 +3805,24 @@
  * @param in_str A readable stream.
  * 
- * @see yy_switch_to_buffer
+ * @see convert__switch_to_buffer
  */
-void yyset_in (FILE *  in_str )
-{
-        yyin = in_str ;
-}
-
-void yyset_out (FILE *  out_str )
-{
-        yyout = out_str ;
-}
-
-int yyget_debug  (void)
-{
-        return yy_flex_debug;
-}
-
-void yyset_debug (int  bdebug )
-{
-        yy_flex_debug = bdebug ;
+void convert_set_in (FILE *  in_str )
+{
+        convert_in = in_str ;
+}
+
+void convert_set_out (FILE *  out_str )
+{
+        convert_out = out_str ;
+}
+
+int convert_get_debug  (void)
+{
+        return convert__flex_debug;
+}
+
+void convert_set_debug (int  bdebug )
+{
+        convert__flex_debug = bdebug ;
 }
 
@@ -3790,5 +3830,5 @@
 {
         /* Initialization is the same as for the non-reentrant scanner.
-     * This function is called from yylex_destroy(), so don't allocate here.
+     * This function is called from convert_lex_destroy(), so don't allocate here.
      */
 
@@ -3802,34 +3842,34 @@
 /* Defined in main.c */
 #ifdef YY_STDINIT
-    yyin = stdin;
-    yyout = stdout;
+    convert_in = stdin;
+    convert_out = stdout;
 #else
-    yyin = (FILE *) 0;
-    yyout = (FILE *) 0;
+    convert_in = (FILE *) 0;
+    convert_out = (FILE *) 0;
 #endif
 
     /* For future reference: Set errno on error, since we are called by
-     * yylex_init()
+     * convert_lex_init()
      */
     return 0;
 }
 
-/* yylex_destroy is for both reentrant and non-reentrant scanners. */
-int yylex_destroy  (void)
+/* convert_lex_destroy is for both reentrant and non-reentrant scanners. */
+int convert_lex_destroy  (void)
 {
     
     /* Pop the buffer stack, destroying each element. */
 	while(YY_CURRENT_BUFFER){
-		yy_delete_buffer(YY_CURRENT_BUFFER  );
+		convert__delete_buffer(YY_CURRENT_BUFFER  );
 		YY_CURRENT_BUFFER_LVALUE = NULL;
-		yypop_buffer_state();
+		convert_pop_buffer_state();
 	}
 
 	/* Destroy the stack itself. */
-	yyfree((yy_buffer_stack) );
+	convert_free((yy_buffer_stack) );
 	(yy_buffer_stack) = NULL;
 
     /* Reset the globals. This is important in a non-reentrant scanner so the next time
-     * yylex() is called, initialization will occur. */
+     * convert_lex() is called, initialization will occur. */
     yy_init_globals( );
 
@@ -3861,10 +3901,10 @@
 #endif
 
-void *yyalloc (yy_size_t  size )
+void *convert_alloc (yy_size_t  size )
 {
 	return (void *) malloc( size );
 }
 
-void *yyrealloc  (void * ptr, yy_size_t  size )
+void *convert_realloc  (void * ptr, yy_size_t  size )
 {
 	/* The cast to (char *) in the following accommodates both
@@ -3878,32 +3918,13 @@
 }
 
-void yyfree (void * ptr )
-{
-	free( (char *) ptr );	/* see yyrealloc() for (char *) cast */
+void convert_free (void * ptr )
+{
+	free( (char *) ptr );	/* see convert_realloc() for (char *) cast */
 }
 
 #define YYTABLES_NAME "yytables"
 
-#line 68 "convert.lex"
-
-
-
-
-int yywrap()
-{
-}
-
-
-yyerror(char *s)
-{
-if (!strcasecmp(curfile,mainfile))
-{
-   printf("Dans convert %s line %d, fichier %s\n",s,line_num,curfile);
-}
-else
-{
-   printf("Dans convert %s line %d, fichier %s\n",s,line_num,curfile);
-}
-exit(0);
-}
-
+#line 69 "convert.lex"
+
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/run
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/run	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/run	(revision 9987)
@@ -1,2 +1,2 @@
-gmake -f Makefile.lex clean
-gmake -f Makefile.lex
+make -f Makefile.lex clean
+make -f Makefile.lex
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/toamr.c
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/toamr.c	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/LIB/toamr.c	(revision 9987)
@@ -37,288 +37,224 @@
 #include <string.h>
 #include "decl.h"
-char lvargridname[LONG_4C];
-char lvargridname2[LONG_4C];
-
-
-/******************************************************************************/
-/*                       variablenameroottabvars                              */
+
+const char * tabvarsname(const variable *var)
+{
+    static char * tname[5] = {
+        "tabvars",      // v_catvar == 0
+        "tabvars_c",    // v_catvar == 1
+        "tabvars_r",    // v_catvar == 2
+        "tabvars_l",    // v_catvar == 3
+        "tabvars_i"     // v_catvar == 4
+    };
+    return tname[var->v_catvar];    // v_catvar should never be ouside the range [0:4].
+}
+
+/******************************************************************************/
+/*                        variablecurgridtabvars                              */
 /******************************************************************************/
 /* This subroutine is used to create the string                               */
 /******************************************************************************/
 /*                                                                            */
-/*  ----------->  Agrif_Mygrid % tabvars (i) % var                            */
-/*                                                                            */
-/******************************************************************************/
-char *variablenameroottabvars (variable * var)
-{
-  char *ligne;
-
-  ligne = (char *) malloc (LONG_C * sizeof (char));
-  sprintf (ligne, "Agrif_Mygrid %% tabvars(%d) %% var ", var->v_indicetabvars);
-  return ligne;
-}
-
-
-/******************************************************************************/
-/*                        variablenametabvars                                 */
+/*  ----------->  Agrif_Curgrid % tabvars (i)                                 */
+/*                                                                            */
+/******************************************************************************/
+const char * variablecurgridtabvars(int which_grid)
+{
+    static char * varname[4] = {
+        " Agrif_%s(%d)",                // which_grid == 0
+        " Agrif_%s(%d) %% parent_var",  // which_grid == 1
+        " Agrif_Mygrid %% %s(%d)",      // which_grid == 2
+        " Agrif_Curgrid %% %s(%d)",     // which_grid == 3
+    };
+
+    return varname[which_grid];
+}
+
+void WARNING_CharSize(const variable *var)
+{
+    if ( var->v_nbdim == 0 )
+    {
+        if ( convert2int(var->v_dimchar) > 2400 )
+        {
+            printf("WARNING : The dimension of the character  %s   \n", var->v_nomvar);
+            printf("   is upper than 2400. You must change         \n");
+            printf("   the dimension of carray0                    \n");
+            printf("   in the file AGRIF/AGRIF_FILES/modtypes.F90  \n");
+            printf("   line 161. Replace 2400 with %d.              \n", convert2int(var->v_dimchar)+100);
+        }
+        Save_Length_int(convert2int(var->v_dimchar),1);
+    }
+    else if ( var->v_nbdim == 1 )
+    {
+        if ( convert2int(var->v_dimchar) > 200 )
+        {
+            printf("WARNING : The dimension of the character  %s   \n", var->v_nomvar);
+            printf("   is upper than 200. You must change          \n");
+            printf("   the dimension of carray1                    \n");
+            printf("   in the file AGRIF/AGRIF_FILES/modtypes.F90  \n");
+            printf("   line 162. Replace 200 with %d.              \n", convert2int(var->v_dimchar)+100);
+        }
+        Save_Length_int(convert2int(var->v_dimchar),2);
+    }
+    else if ( var->v_nbdim == 2 )
+    {
+        if ( convert2int(var->v_dimchar) > 200 )
+        {
+            printf("WARNING : The dimension of the character  %s   \n", var->v_nomvar);
+            printf("   is upper than 200. You must change          \n");
+            printf("   the dimension of carray2                    \n");
+            printf("   in the file AGRIF/AGRIF_FILES/modtypes.F90  \n");
+            printf("   line 163. Replace 200 with %d.              \n", convert2int(var->v_dimchar)+100);
+        }
+        Save_Length_int(convert2int(var->v_dimchar),3);
+    }
+    else if ( var->v_nbdim == 3 )
+    {
+        if ( convert2int(var->v_dimchar) > 200 )
+        {
+            printf("WARNING : The dimension of the character  %s   \n", var->v_nomvar);
+            printf("   is upper than 200. You must change          \n");
+            printf("   the dimension of carray3                    \n");
+            printf("   in the file AGRIF/AGRIF_FILES/modtypes.F90  \n");
+            printf("   line 164. Replace 200 with %d.              \n", convert2int(var->v_dimchar)+100);
+        }
+        Save_Length_int(convert2int(var->v_dimchar),4);
+    }
+}
+/******************************************************************************/
+/*                           vargridnametabvars                               */
 /******************************************************************************/
 /* This subroutine is used to create the string                               */
 /******************************************************************************/
 /*                                                                            */
-/*  if iorindice = 0 ---------->  Agrif_Gr % tabvars (i) % var                */
-/*                                                                            */
-/*  if iorindice = 1 ---------->  Agrif_Gr % tabvars (12) % var               */
-/*                                                                            */
-/******************************************************************************/
-char *variablenametabvars (variable * var, int iorindice)
-{
-  char *ligne;
-
-  ligne = (char *) malloc (LONG_C * sizeof (char));
-  if ( iorindice == 0 ) sprintf (ligne, " Agrif_Gr %% tabvars(%d)%% var",
-                                 var->v_indicetabvars);
-  else sprintf (ligne, " Agrif_Gr %% tabvars(i)%% var");
-  return ligne;
-}
-
-/******************************************************************************/
-/*                        variablecurgridtabvars                              */
+/*  if iorindice == 0 ----------->  Agrif_Gr % tabvars (i) % array1           */
+/*                                                                            */
+/*  if iorindice == 1 ----------->  Agrif_Gr % tabvars (12) % array1          */
+/*                                                                            */
+/******************************************************************************/
+const char *vargridnametabvars (const variable * var, int iorindice)
+{
+    static char tname_1[LONG_C];
+    static char tname_2[LONG_C];
+
+    if ( iorindice == 0 ) sprintf(tname_1, "Agrif_Gr %% %s(%d)", tabvarsname(var), var->v_indicetabvars);
+    else                  sprintf(tname_1, "Agrif_Gr %% %s(i)",  tabvarsname(var));
+
+    if (!strcasecmp(var->v_typevar, "REAL"))
+    {
+        if      ( !strcasecmp(var->v_nameinttypename,"8") ) sprintf(tname_2, "%% darray%d", var->v_nbdim);
+        else if ( !strcasecmp(var->v_nameinttypename,"4") ) sprintf(tname_2, "%% sarray%d", var->v_nbdim);
+        else                                                sprintf(tname_2, "%% array%d",  var->v_nbdim);
+    }
+    else if (!strcasecmp(var->v_typevar, "integer"))
+    {
+        sprintf(tname_2, "%% iarray%d", var->v_nbdim);
+    }
+    else if (!strcasecmp(var->v_typevar, "logical"))
+    {
+        sprintf(tname_2, "%% larray%d", var->v_nbdim);
+    }
+    else if (!strcasecmp(var->v_typevar, "character"))
+    {
+        WARNING_CharSize(var);
+        sprintf (tname_2, "%% carray%d", var->v_nbdim);
+    }
+
+    strcat(tname_1, tname_2);
+    Save_Length(tname_1, 46);
+
+    return tname_1;
+}
+
+/******************************************************************************/
+/*                           vargridcurgridtabvars                            */
 /******************************************************************************/
 /* This subroutine is used to create the string                               */
 /******************************************************************************/
 /*                                                                            */
-/*  ----------->  Agrif_Curgrid % tabvars (i) % var                           */
-/*                                                                            */
-/******************************************************************************/
-char *variablecurgridtabvars (variable * var,int ParentOrCurgrid)
-{
-  char *ligne;
-
-  ligne = (char *) malloc (LONG_C * sizeof (char));
-  if ( ParentOrCurgrid == 0 ) sprintf (ligne, " Agrif_tabvars(%d) %% var",
-                              var->v_indicetabvars);
-  else if ( ParentOrCurgrid == 1 ) sprintf (ligne,
-                              " Agrif_tabvars(%d) %% parent_var %% var",
-                               var->v_indicetabvars);
-  else if ( ParentOrCurgrid == 2 ) sprintf (ligne,
-                              " Agrif_Mygrid %% tabvars(%d) %% var",
-                               var->v_indicetabvars);
-  else if ( ParentOrCurgrid == 3 ) sprintf (ligne,
-                              " Agrif_Curgrid %% tabvars(%d) %% var",
-                               var->v_indicetabvars);
-  else sprintf (ligne, " AGRIF_Mygrid %% tabvars(%d) %% var",
-                               var->v_indicetabvars);
-  return ligne;
-}
-
-void WARNING_CharSize(variable *var)
-{
-   if ( var->v_nbdim == 0 )
-   {
-      if ( convert2int(var->v_dimchar) > 2050 )
-      {
-         printf("WARNING : The dimension of the character  %s   \n",
-                                                              var->v_nomvar);
-         printf("   is upper than 2050. You must change         \n");
-         printf("   the dimension of carray0                    \n");
-         printf("   in the file AGRIF/AGRIF_FILES/modtypes.F    \n");
-         printf("   line 247. Replace 300 with %d.              \n",
-                                            convert2int(var->v_dimchar)+100);
-      }
-      Save_Length_int(convert2int(var->v_dimchar),1);
-   }
-   else if ( var->v_nbdim == 1 )
-   {
-      if ( convert2int(var->v_dimchar) > 300 )
-      {
-         printf("WARNING : The dimension of the character  %s   \n",
-                                                              var->v_nomvar);
-         printf("   is upper than 300. You must change          \n");
-         printf("   the dimension of carray1                    \n");
-         printf("   in the file AGRIF/AGRIF_FILES/modtypes.F    \n");
-         printf("   line 247. Replace 300 with %d.              \n",
-                                            convert2int(var->v_dimchar)+100);
-      }
-      Save_Length_int(convert2int(var->v_dimchar),2);
-   }
-   else if ( var->v_nbdim == 2 )
-   {
-      if ( convert2int(var->v_dimchar) > 300 )
-      {
-         printf("WARNING : The dimension of the character  %s   \n",
-                                                              var->v_nomvar);
-         printf("   is upper than 300. You must change          \n");
-         printf("   the dimension of carray2                    \n");
-         printf("   in the file AGRIF/AGRIF_FILES/modtypes.F    \n");
-         printf("   line 247. Replace 300 with %d.              \n",
-                                            convert2int(var->v_dimchar)+100);
-      }
-      Save_Length_int(convert2int(var->v_dimchar),3);
-   }
-   else if ( var->v_nbdim == 3 )
-   {
-      if ( convert2int(var->v_dimchar) > 300 )
-      {
-         printf("WARNING : The dimension of the character  %s   \n",
-                                                              var->v_nomvar);
-         printf("   is upper than 300. You must change          \n");
-         printf("   the dimension of carray3                    \n");
-         printf("   in the file AGRIF/AGRIF_FILES/modtypes.F    \n");
-         printf("   line 247. Replace 300 with %d.              \n",
-                                            convert2int(var->v_dimchar)+100);
-      }
-      Save_Length_int(convert2int(var->v_dimchar),4);
-   }
-}
-/******************************************************************************/
-/*                           vargridnametabvars                               */
+/* if which_grid == 0 -->  Agrif_Curgrid % tabvars (i) % array1               */
+/*                                                                            */
+/* if which_grid == 1 -->  Agrif_tabvars (i) % parent_var % array1            */
+/*                                                                            */
+/* if which_grid == 2 -->  Agrif_Gr % tabvars (i) % array1                    */
+/*                                                                            */
+/******************************************************************************/
+const char *vargridcurgridtabvars(const variable *var, int which_grid)
+{
+    static char tname_1[LONG_C];
+    static char tname_2[LONG_C];
+
+    if (!strcasecmp(var->v_typevar,"type"))
+    {
+        sprintf(tname_1, "Agrif_%s_var(Agrif_Curgrid%%fixedrank)%%%s", var->v_modulename, var->v_nomvar);
+    }
+    else
+    {
+        sprintf(tname_1, variablecurgridtabvars(which_grid), tabvarsname(var), var->v_indicetabvars);
+
+        if (!strcasecmp(var->v_typevar, "REAL"))
+        {
+            if      ( !strcasecmp(var->v_nameinttypename,"8") ) sprintf(tname_2, "%% darray%d", var->v_nbdim);
+            else if ( !strcasecmp(var->v_nameinttypename,"4") ) sprintf(tname_2, "%% sarray%d", var->v_nbdim);
+            else                                                sprintf(tname_2, "%% array%d", var->v_nbdim);
+        }
+        else if (!strcasecmp(var->v_typevar, "INTEGER"))
+        {
+            sprintf(tname_2, "%% iarray%d", var->v_nbdim);
+        }
+        else if (!strcasecmp(var->v_typevar, "LOGICAL"))
+        {
+            sprintf(tname_2, "%% larray%d", var->v_nbdim);
+        }
+        else if (!strcasecmp(var->v_typevar, "CHARACTER"))
+        {
+            WARNING_CharSize(var);
+            sprintf(tname_2, "%% carray%d", var->v_nbdim);
+        }
+        strcat(tname_1, tname_2);
+    }
+    Save_Length(tname_1, 46);
+
+    return tname_1;
+}
+
+/******************************************************************************/
+/*                  vargridcurgridtabvarswithoutAgrif_Gr                      */
 /******************************************************************************/
 /* This subroutine is used to create the string                               */
 /******************************************************************************/
 /*                                                                            */
-/*  if iorindice == 0 ----------->  Agrif_Gr % tabvars (i) % var % array1     */
-/*                                                                            */
-/*  if iorindice == 1 ----------->  Agrif_Gr % tabvars (12) % var % array1    */
-/*                                                                            */
-/******************************************************************************/
-char *vargridnametabvars (variable * var,int iorindice)
-{
-  char *tmp;
-  char tmp1[LONG_C];
-
-  tmp = variablenametabvars (var,iorindice);
-  strcpy(tmp1,tmp);
-  if ( todebugfree == 1 ) free(tmp);
-
-  sprintf (lvargridname, "%s", tmp1);
-  if (!strcasecmp (var->v_typevar, "REAL"))
-    {
-      if ( !strcasecmp(var->v_nameinttypename,"8") )
-                           sprintf (lvargridname2, "%% darray%d", var->v_nbdim);
-      else if ( !strcasecmp(var->v_nameinttypename,"4") )
-                           sprintf (lvargridname2, "%% sarray%d", var->v_nbdim);
-      else sprintf (lvargridname2, "%% array%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "INTEGER"))
-    {
-      sprintf (lvargridname2, "%% iarray%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "LOGICAL"))
-    {
-      sprintf (lvargridname2, "%% larray%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "CHARACTER"))
-    {
-      WARNING_CharSize(var);
-      sprintf (lvargridname2, "%% carray%d", var->v_nbdim);
-    }
-
-  strcat (lvargridname, lvargridname2);
-
-  Save_Length(lvargridname,42);
-  Save_Length(lvargridname2,42);
-  return lvargridname;
-}
-
-/******************************************************************************/
-/*                           vargridcurgridtabvars                            */
-/******************************************************************************/
-/* This subroutine is used to create the string                               */
-/******************************************************************************/
-/*                                                                            */
-/* if ParentOrCurgrid == 0 -->  Agrif_Curgrid % tabvars (i) % var % array1    */
-/*                                                                            */
-/* if ParentOrCurgrid == 1 -->  Agrif_tabvars (i) % parent_var %var % array1  */
-/*                                                                            */
-/* if ParentOrCurgrid == 2 -->  Agrif_Gr % tabvars (i) % var % array1         */
-/*                                                                            */
-/******************************************************************************/
-char *vargridcurgridtabvars (variable * var,int ParentOrCurgrid)
-{
-  char *tmp;
-  char tmp1[LONG_C];
-
- if (!strcasecmp(var->v_typevar,"type"))
-  {
-  strcpy(lvargridname2,"");
-  sprintf(lvargridname,"Agrif_%s_var(Agrif_Curgrid%%fixedrank)%%%s",var->v_modulename,var->v_nomvar);
-  printf("modulename = %s %s\n",var->v_nomvar, var->v_modulename);
-  }
-  else
-  {
-  tmp = variablecurgridtabvars (var,ParentOrCurgrid);
-  strcpy(tmp1,tmp);
-  if ( todebugfree == 1 ) free(tmp);
-
-  sprintf (lvargridname, "%s", tmp1);
-  if (!strcasecmp (var->v_typevar, "REAL"))
-    {
-      if ( !strcasecmp(var->v_nameinttypename,"8") )
-                           sprintf (lvargridname2, "%% darray%d", var->v_nbdim);
-      else if ( !strcasecmp(var->v_nameinttypename,"4") )
-                           sprintf (lvargridname2, "%% sarray%d", var->v_nbdim);
-      else sprintf (lvargridname2, "%% array%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "INTEGER"))
-    {
-      sprintf (lvargridname2, "%% iarray%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "LOGICAL"))
-    {
-      sprintf (lvargridname2, "%% larray%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "CHARACTER"))
-    {
-      WARNING_CharSize(var);
-      sprintf (lvargridname2, "%% carray%d", var->v_nbdim);
-    }
-  }
-
-  strcat (lvargridname, lvargridname2);
-
-  Save_Length(lvargridname,42);
-  Save_Length(lvargridname2,42);
-  return lvargridname;
-}
-
-/******************************************************************************/
-/*                  vargridcurgridtabvarswithoutAgrif_Gr                      */
-/******************************************************************************/
-/* This subroutine is used to create the string                               */
-/******************************************************************************/
-/*                                                                            */
-/******************************************************************************/
-char *vargridcurgridtabvarswithoutAgrif_Gr (variable * var)
-{
-
-  sprintf (lvargridname, "(%d) %% var", var->v_indicetabvars);
-
-  if (!strcasecmp (var->v_typevar, "REAL"))
-    {
-      if ( !strcasecmp(var->v_nameinttypename,"8") )
-                           sprintf (lvargridname2, "%% darray%d", var->v_nbdim);
-      else if ( !strcasecmp(var->v_nameinttypename,"4") )
-                           sprintf (lvargridname2, "%% sarray%d", var->v_nbdim);
-      else sprintf (lvargridname2, "%% array%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "INTEGER"))
-    {
-      sprintf (lvargridname2, "%% iarray%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "LOGICAL"))
-    {
-      sprintf (lvargridname2, "%% larray%d", var->v_nbdim);
-    }
-  else if (!strcasecmp (var->v_typevar, "CHARACTER"))
-    {
-      WARNING_CharSize(var);
-      sprintf (lvargridname2, "%% carray%d", var->v_nbdim);
-    }
-
-  strcat (lvargridname, lvargridname2);
-
-  Save_Length(lvargridname,42);
-  Save_Length(lvargridname2,42);
-  return lvargridname;
+/******************************************************************************/
+const char *vargridcurgridtabvarswithoutAgrif_Gr(const variable *var)
+{
+    static char tname_1[LONG_C];
+    static char tname_2[LONG_C];
+
+    sprintf(tname_1, "(%d)", var->v_indicetabvars);
+
+    if (!strcasecmp (var->v_typevar, "REAL"))
+    {
+        if      ( !strcasecmp(var->v_nameinttypename,"8") ) sprintf(tname_2, "%% darray%d", var->v_nbdim);
+        else if ( !strcasecmp(var->v_nameinttypename,"4") ) sprintf(tname_2, "%% sarray%d", var->v_nbdim);
+        else                                                sprintf(tname_2, "%% array%d", var->v_nbdim);
+    }
+    else if (!strcasecmp(var->v_typevar, "INTEGER"))
+    {
+        sprintf(tname_2, "%% iarray%d", var->v_nbdim);
+    }
+    else if (!strcasecmp(var->v_typevar, "LOGICAL"))
+    {
+        sprintf(tname_2, "%% larray%d", var->v_nbdim);
+    }
+    else if (!strcasecmp(var->v_typevar, "CHARACTER"))
+    {
+        WARNING_CharSize(var);
+        sprintf(tname_2, "%% carray%d", var->v_nbdim);
+    }
+
+    strcat(tname_1, tname_2);
+    Save_Length(tname_1, 46);
+
+    return tname_1;
 }
 
@@ -333,51 +269,32 @@
 /*                                                                            */
 /******************************************************************************/
-char *vargridparam (variable * v, int whichone)
-{
-  typedim dim;
-  listdim *newdim;
-  char newname[LONG_4C];
-
-  newdim = v->v_dimension;
-  if (!newdim) return "";
-
-  strcpy (tmpvargridname, "(");
-  while (newdim)
-  {
-     dim = newdim->dim;
-
-     strcpy(newname,"");
-     strcpy(newname,
-            ChangeTheInitalvaluebyTabvarsName(dim.first,List_Global_Var,
-                                                                     whichone));
-                                                                     
-        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname,
-                       List_Common_Var,whichone));
-
-        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname,
-                       List_ModuleUsed_Var,whichone));
-
-     strcat (tmpvargridname, newname);
-     strcat (tmpvargridname, " : ");
-
-     strcpy(newname,"");
-     strcpy(newname,ChangeTheInitalvaluebyTabvarsName
-                        (dim.last,List_Global_Var,whichone));
-                        
-        strcpy(newname,ChangeTheInitalvaluebyTabvarsName
-                       (newname, List_Common_Var,whichone));   
-                       
-        strcpy(newname,ChangeTheInitalvaluebyTabvarsName
-                       (newname, List_ModuleUsed_Var,whichone));                                            
-                        
-     Save_Length(tmpvargridname,46);
-     strcat (tmpvargridname, newname);
-     newdim = newdim->suiv;
-     if (newdim) strcat (tmpvargridname, ",");
-  }
-  strcat (tmpvargridname, ")");
-  strcat (tmpvargridname, "\0");
-  Save_Length(tmpvargridname,40);
-  return tmpvargridname;
+const char * vargridparam(const variable *var)
+{
+    typedim dim;
+    listdim *newdim;
+    char newname[LONG_M];
+
+    newdim = var->v_dimension;
+    if (!newdim) return "";
+
+    strcpy (tmpvargridname, "(");
+    while (newdim)
+    {
+        dim = newdim->dim;
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(dim.first,List_Global_Var));
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname,List_Common_Var));
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname,List_ModuleUsed_Var));
+        strcat(tmpvargridname, newname);
+        strcat(tmpvargridname, " : ");
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(dim.last,List_Global_Var));
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname, List_Common_Var));
+        strcpy(newname,ChangeTheInitalvaluebyTabvarsName(newname, List_ModuleUsed_Var));
+        strcat(tmpvargridname, newname);
+        newdim = newdim->suiv;
+        if (newdim) strcat(tmpvargridname, ",");
+    }
+    strcat(tmpvargridname, ")\0");
+    Save_Length(tmpvargridname,40);
+    return tmpvargridname;
 }
 
@@ -396,7 +313,7 @@
 {
   FILE *probdim;
-  char ligne[LONG_C];
-
-  probdim = associate("probdim_agrif.h");
+  char ligne[LONG_M];
+
+  probdim = open_for_write("probdim_agrif.h");
   sprintf (ligne, "Agrif_Probdim = %d", dimprob);
   tofich (probdim, ligne,1);
@@ -421,11 +338,7 @@
   FILE *keys;
 
-  keys = associate ("keys_agrif.h");
-  fprintf(keys,"      AGRIF_USE_FIXED_GRIDS = 0\n");
-  fprintf(keys,"      AGRIF_USE_ONLY_FIXED_GRIDS = 0\n");
-  if (fixedgrids     == 1) fprintf(keys,"      AGRIF_USE_FIXED_GRIDS = 1\n");
-  if (onlyfixedgrids == 1)
-                         fprintf(keys,"      AGRIF_USE_ONLY_FIXED_GRIDS = 1\n");
-
+  keys = open_for_write("keys_agrif.h");
+  fprintf(keys,"      AGRIF_USE_FIXED_GRIDS = %d\n", fixedgrids);
+  fprintf(keys,"      AGRIF_USE_ONLY_FIXED_GRIDS = %d\n", onlyfixedgrids);
   fclose(keys);
 }
@@ -444,11 +357,15 @@
 void write_modtypeagrif_file()
 {
-  char ligne[LONG_C];
+  char ligne[LONG_M];
   FILE *typedata;
-
-  typedata = associate ("modtype_agrif.h");
+  int i;
+
+  typedata = open_for_write("modtype_agrif.h");
   /* AGRIF_NbVariables : number of variables                                  */
-  sprintf (ligne, "AGRIF_NbVariables = %d",indicemaxtabvars);
-  tofich(typedata,ligne,1);
+  for (i=0;i<NB_CAT_VARIABLES;i++)
+   {
+    sprintf (ligne, "Agrif_NbVariables(%d) = %d",i,indicemaxtabvars[i]);
+    tofich(typedata,ligne,1);
+   }
   fclose (typedata);
 }
@@ -460,21 +377,14 @@
 /******************************************************************************/
 /*                                                                            */
-/*    Agrif_Gr % tabvars (i) % var % namevar = "variable"                     */
-/*                                                                            */
-/******************************************************************************/
-void write_createvarnameagrif_file(variable *v,FILE *createvarname,
-                                                       int *InitEmpty)
-{
-  char ligne[LONG_C];
-  char *tmp;
-  char temp1[LONG_C];
-
-  tmp =  variablenametabvars(v,0);
-  strcpy (temp1, tmp);
-  if ( todebugfree == 1 ) free(tmp);
-
-  *InitEmpty = 0 ;
-  sprintf(ligne, "%s %% namevar = \"%s\"",temp1,v->v_nomvar);
-  tofich(createvarname,ligne,1);
+/*    Agrif_Gr % tabvars (i) % namevar = "variable"                           */
+/*                                                                            */
+/******************************************************************************/
+void write_createvarnameagrif_file(variable *v,FILE *createvarname, int *InitEmpty)
+{
+    char ligne[LONG_M];
+
+    *InitEmpty = 0 ;
+    sprintf(ligne, "Agrif_Gr %% %s(%d) %% namevar = \"%s\"",tabvarsname(v),v->v_indicetabvars,v->v_nomvar);
+    tofich(createvarname,ligne,1);
 }
 
@@ -488,62 +398,33 @@
 /*                                                                            */
 /******************************************************************************/
-void write_Setnumberofcells_file(char *name)
-{
-  char ligne[LONG_C];
-  FILE *setnumberofcells;
-
-  if ( IndicenbmaillesX != 0 )
-  {
-  setnumberofcells=associate(name);
-
-  if (onlyfixedgrids != 1 )
-  {
-  sprintf (ligne,
-           "Agrif_Gr %% nb(1) = Agrif_Gr %% tabvars(%d) %% var %% iarray0",
-           IndicenbmaillesX);
-  }
-  else
-  {
-  sprintf (ligne,
-           "Agrif_Gr %% nb(1) = Agrif_Curgrid %% tabvars(%d) %% var %% iarray0",
-           IndicenbmaillesX);
-  }
-  tofich (setnumberofcells, ligne,1);
-  if (dimprob > 1)
-  {
-     if (onlyfixedgrids != 1 )
-     {
-     sprintf (ligne,
-           "Agrif_Gr %% nb(2) = Agrif_Gr %% tabvars(%d) %% var %% iarray0",
-           IndicenbmaillesY);
-     }
-     else
-     {
-     sprintf (ligne,
-           "Agrif_Gr %% nb(2) = Agrif_Curgrid %% tabvars(%d) %% var %% iarray0",
-           IndicenbmaillesY);
-     }
-
-     tofich (setnumberofcells, ligne,1);
-  }
-  if (dimprob > 2)
-  {
-     if (onlyfixedgrids != 1 )
-     {
-     sprintf (ligne,
-           "Agrif_Gr %% nb(3) = Agrif_Gr %% tabvars(%d) %% var %% iarray0",
-           IndicenbmaillesZ);
-     }
-     else
-     {
-     sprintf (ligne,
-           "Agrif_Gr %% nb(3) = Agrif_Curgrid %% tabvars(%d) %% var %% iarray0",
-           IndicenbmaillesZ);
-     }
-     tofich (setnumberofcells, ligne,1);
-  }
-
-  fclose (setnumberofcells);
-  }
+void write_Setnumberofcells_file()
+{
+    char ligne[LONG_VNAME];
+    char cformat[LONG_VNAME];
+    FILE *setnumberofcells;
+
+    if ( IndicenbmaillesX == 0 )  return;
+
+    setnumberofcells = open_for_write("SetNumberofcells.h");
+
+    if ( onlyfixedgrids == 1 )
+        strcpy(cformat, "Agrif_Gr %% nb(%d) = Agrif_Curgrid %% tabvars_i(%d) %% iarray0");
+    else
+        strcpy(cformat, "Agrif_Gr %% nb(%d) = Agrif_Gr %% tabvars_i(%d) %% iarray0");
+
+    sprintf(ligne, cformat, 1, IndicenbmaillesX);
+    tofich(setnumberofcells, ligne, 1);
+
+    if ( dimprob > 1 )
+    {
+        sprintf(ligne, cformat, 2, IndicenbmaillesY);
+        tofich(setnumberofcells, ligne, 1);
+    }
+    if ( dimprob > 2 )
+    {
+        sprintf(ligne, cformat, 3, IndicenbmaillesZ);
+        tofich(setnumberofcells, ligne, 1);
+    }
+    fclose(setnumberofcells);
 }
 
@@ -557,32 +438,30 @@
 /*                                                                            */
 /******************************************************************************/
-void write_Getnumberofcells_file(char *name)
-{
-  char ligne[LONG_C];
-  FILE *getnumberofcells;
-
-  if ( IndicenbmaillesX != 0 )
-  {
-  getnumberofcells=associate(name);
-  sprintf (ligne,
-           "Agrif_Curgrid %% tabvars(%d) %% var %% iarray0 = Agrif_Gr %% nb(1)",
-           IndicenbmaillesX);
-  tofich (getnumberofcells, ligne,1);
-  if (dimprob > 1)
-    {
-      sprintf (ligne,
-           "Agrif_Curgrid %% tabvars(%d) %% var %% iarray0 = Agrif_Gr %% nb(2)",
-           IndicenbmaillesY);
-      tofich (getnumberofcells, ligne,1);
-    }
-  if (dimprob > 2)
-    {
-      sprintf (ligne,
-           "Agrif_Curgrid %% tabvars(%d) %% var %% iarray0 = Agrif_Gr %% nb(3)",
-           IndicenbmaillesZ);
-      tofich (getnumberofcells, ligne,1);
-    }
-  fclose (getnumberofcells);
-  }
+void write_Getnumberofcells_file()
+{
+    char ligne[LONG_VNAME];
+    char cformat[LONG_VNAME];
+    FILE *getnumberofcells;
+
+    if ( IndicenbmaillesX == 0 )    return;
+
+    strcpy(cformat, "Agrif_Curgrid %% tabvars_i(%d) %% iarray0 = Agrif_Gr %% nb(%d)");
+
+    getnumberofcells = open_for_write("GetNumberofcells.h");
+
+    sprintf(ligne, cformat, IndicenbmaillesX, 1);
+    tofich(getnumberofcells, ligne, 1);
+
+    if (dimprob > 1)
+    {
+        sprintf(ligne, cformat, IndicenbmaillesY, 2);
+        tofich(getnumberofcells, ligne,1);
+    }
+    if (dimprob > 2)
+    {
+        sprintf(ligne, cformat, IndicenbmaillesZ, 3);
+        tofich(getnumberofcells, ligne,1);
+    }
+    fclose(getnumberofcells);
 }
 
@@ -595,24 +474,17 @@
 /*                                                                            */
 /*              ! variable                                                    */
-/*              Agrif_Gr % tabvars(i) % var % nbdim = 1                       */
-/*                                                                            */
-/******************************************************************************/
-void write_initialisationsagrif_file(variable *v,FILE *initproc,
-                                     int *VarnameEmpty)
-{
-  char ligne[LONG_C];
-  char temp1[LONG_C];
-  char *tmp;
-
-  tmp = variablenameroottabvars (v);
-  strcpy (temp1, tmp);
-  if ( todebugfree == 1 ) free(tmp);
-
-  if ( v->v_nbdim != 0 )
-  {
-     *VarnameEmpty = 0 ;
-     sprintf (ligne, "%s %% nbdim = %d", temp1, v->v_nbdim);
-     tofich (initproc, ligne,1);
-  }
+/*              Agrif_Gr % tabvars(i) % nbdim = 1                             */
+/*                                                                            */
+/******************************************************************************/
+void write_initialisationsagrif_file(variable *v,FILE *initproc,int *VarnameEmpty)
+{
+    char ligne[LONG_M];
+
+    if ( v->v_nbdim != 0 )
+    {
+        *VarnameEmpty = 0 ;
+        sprintf(ligne,"Agrif_Mygrid %% %s(%d) %% nbdim = %d", tabvarsname(v), v->v_indicetabvars, v->v_nbdim);
+        tofich (initproc, ligne,1);
+    }
 }
 
@@ -624,13 +496,12 @@
    FILE *AllocUSE;
 
-   AllocUSE= associate("include_use_Alloc_agrif.h");
-   alloccalls = associate("allocations_calls_agrif.h");
+   AllocUSE= open_for_write("include_use_Alloc_agrif.h");
+   alloccalls = open_for_write("allocations_calls_agrif.h");
 
    parcours = List_Subroutine_For_Alloc;
    while ( parcours )
    {
-      fprintf(AllocUSE,"      USE %s\n", parcours -> o_nom );
-      fprintf (alloccalls,"      Call Alloc_agrif_%s(Agrif_Gr)\n",
-                                                            parcours -> o_nom );
+      fprintf(AllocUSE,"      use %s, only: Alloc_agrif_%s\n", parcours -> o_nom, parcours -> o_nom );
+      fprintf (alloccalls,"      call Alloc_agrif_%s(Agrif_Gr)\n", parcours -> o_nom );
       parcours = parcours -> suiv;
    }
@@ -656,421 +527,338 @@
    return out;
 }
+
 void write_allocation_Common_0()
 {
-   listnom *parcours_nom;
-   listnom *neededparameter;
-   listvar *parcours;
-   listvar *parcoursprec;
-   listvar *parcours1;
-   FILE *allocationagrif;
-   FILE *paramtoamr;
-   char ligne[LONGNOM];
-   char ligne2[LONGNOM];   
-   variable *v;
-   int IndiceMax;
-   int IndiceMin;
-   int compteur;
-   int out;
-   int indiceprec;
-   int ValeurMax;
-   char initialvalue[LONG_4C];
-   listindice *list_indic;
-   listindice *parcoursindic;
-   int i;
-
-   parcoursprec = (listvar *)NULL;
-   parcours_nom = List_NameOfCommon;
-   ValeurMax = 2;
-   while ( parcours_nom  )
-   {
-      /*                                                                      */
-      if ( parcours_nom->o_val == 1 )
-      {
-         /* Open the file to create the Alloc_agrif subroutine                */
-         sprintf(ligne,"alloc_agrif_%s.h",parcours_nom->o_nom);
-         allocationagrif = associate (ligne);
-         /*                                                                   */
-         fprintf(allocationagrif,"#include \"Param_toamr_%s.h\" \n",
-                                                           parcours_nom->o_nom);
-         /*                                                                   */
-         sprintf(ligne,"Param_toamr_%s.h",parcours_nom->o_nom);
-         paramtoamr = associate (ligne);
-         neededparameter = (listnom * )NULL;
-         /*                                                                   */
-         list_indic = (listindice *)NULL;
-         /*                                                                   */
-         shouldincludempif = 1 ;
-         parcours = List_Common_Var;
-         while ( parcours )
-         {
-            if ( !strcasecmp(parcours->var->v_commonname,parcours_nom->o_nom) &&
-                  IndiceInlist(parcours->var->v_indicetabvars,list_indic) == 0
-               )
+    listnom *parcours_nom;
+    listnom *neededparameter;
+    listvar *parcours;
+    listvar *parcoursprec;
+    listvar *parcours1;
+    FILE *allocationagrif;
+    FILE *paramtoamr;
+    char ligne[LONG_M];
+    char ligne2[LONG_M];
+    variable *v;
+    int IndiceMax;
+    int IndiceMin;
+    int compteur;
+    int out;
+    int indiceprec;
+    int ValeurMax;
+    char initialvalue[LONG_M];
+    listindice **list_indic;
+    listindice *parcoursindic;
+    int i;
+
+    parcoursprec = (listvar *) NULL;
+    parcours_nom = List_NameOfCommon;
+    ValeurMax = 2;
+    while ( parcours_nom  )
+    {
+        if ( parcours_nom->o_val == 1 )
+        {
+            /* Open the file to create the Alloc_agrif subroutine                */
+            sprintf(ligne,"alloc_agrif_%s.h",parcours_nom->o_nom);
+            allocationagrif = open_for_write(ligne);
+            fprintf(allocationagrif,"#include \"Param_toamr_%s.h\" \n", parcours_nom->o_nom);
+
+            sprintf(ligne,"Param_toamr_%s.h",parcours_nom->o_nom);
+            paramtoamr = open_for_write(ligne);
+            neededparameter = (listnom *) NULL;
+            list_indic = (listindice **) calloc(NB_CAT_VARIABLES,sizeof(listindice *));
+
+//             shouldincludempif = 1 ;
+            parcours = List_Common_Var;
+            while ( parcours )
             {
-               /***************************************************************/
-               /***************************************************************/
-               /***************************************************************/
-               v = parcours->var;
-               IndiceMax = 0;
-               IndiceMin = indicemaxtabvars;
-  /* body of the file                                                         */
-  if ( !strcasecmp(v->v_commoninfile,mainfile) )
-  {
-     if (onlyfixedgrids != 1 && v->v_nbdim!=0)
-     {
-        strcpy (ligne, "If (.not. associated(");
-        strcat (ligne, vargridnametabvars(v,0));
-        strcat (ligne, "))                       then");
-        Save_Length(ligne,48);
-        tofich (allocationagrif, ligne,1);
-     }
-     if ( v->v_allocatable != 1 && ( v->v_dimsempty != 1) )
-     {
-        /*                ALLOCATION                                          */
-        if ( v->v_dimension != 0  )
-        {
-           if ( v->v_indicetabvars < IndiceMin ||
-                v->v_indicetabvars > IndiceMax )
-           {
-              parcours1 = parcours;
-              compteur = -1;
-              out = 0;
-              indiceprec = parcours->var->v_indicetabvars -1 ;
-              while ( parcours1 && out == 0 &&
-                      !strcasecmp(  parcours->var->v_readedlistdimension,
-                                  parcours1->var->v_readedlistdimension) &&
-                      !strcasecmp(  parcours->var->v_typevar,
-                                  parcours1->var->v_typevar) &&
-                            ( parcours1->var->v_indicetabvars == indiceprec+1 )
-                     )
-              {
-
-               if ( !strcasecmp(parcours1->var->v_modulename,
-                                parcours_nom->o_nom) ||
-                    !strcasecmp(parcours1->var->v_commonname,
-                                parcours_nom->o_nom) )
-                 {
-                      compteur = compteur +1 ;
-                      indiceprec = parcours1->var->v_indicetabvars;
-                      parcoursprec = parcours1;
-                      parcours1 = parcours1->suiv;
-                 }
-                 else out = 1;
-              }
-
-              if ( compteur > ValeurMax )
-              {
-                 fprintf(allocationagrif,"      DO i = %d , %d\n",
-                                         parcours->var->v_indicetabvars,
-                                       parcours->var->v_indicetabvars+compteur);
-                 IndiceMin = parcours->var->v_indicetabvars;
-                 IndiceMax = parcours->var->v_indicetabvars+compteur;
-                 strcpy (ligne, "allocate ");
-                 strcat (ligne, "(");
-                 strcat (ligne, vargridnametabvars(v,1));
-                 strcat (ligne, vargridparam(v,0));
-                 strcat (ligne, ")");
-                 Save_Length(ligne,48);
-                 tofich (allocationagrif, ligne,1);
-                 fprintf(allocationagrif,"      end do\n");
-                 i=parcours->var->v_indicetabvars;
-                 do
-                 {
-                    parcoursindic =  (listindice *)malloc(sizeof(listindice));
-                    parcoursindic -> i_indice = i;
-                    parcoursindic -> suiv = list_indic;
-                    list_indic = parcoursindic;
-                    i = i + 1;
-                 } while ( i <= parcours->var->v_indicetabvars+compteur );
-                 parcours = parcoursprec;
-                 /*                                                           */
-              }
-              else
-              {
-                 strcpy (ligne, "allocate ");
-                 strcat (ligne, "(");
-                 strcat (ligne, vargridnametabvars(v,0));
-                 strcat (ligne, vargridparam(v,0));
-                 strcat (ligne, ")");
-                 Save_Length(ligne,48);
-                 tofich (allocationagrif, ligne,1);
-                 /*                                                           */
-                 parcoursindic =  (listindice *)malloc(sizeof(listindice));
-                 parcoursindic -> i_indice = parcours->var->v_indicetabvars;
-                 parcoursindic -> suiv = list_indic;
-                 list_indic = parcoursindic;
-              }
-                neededparameter = writedeclarationintoamr(List_Parameter_Var,
-                              paramtoamr,v,parcours_nom->o_nom,neededparameter,
-                                                               v->v_commonname);
-              /*                                                              */
-           }
-        } /* end of the allocation part                                       */
-        /*                INITIALISATION                                      */
-        if ( strcasecmp(v->v_initialvalue,"") )
-        {
-           strcpy (ligne, "");
-           strcat (ligne, vargridnametabvars(v,0));
-           /* We should modify the initialvalue in the case of variable has   */
-           /*    been defined with others variables                           */
-                      
-           strcpy(initialvalue,
-                  ChangeTheInitalvaluebyTabvarsName
-                                      (v->v_initialvalue,List_Global_Var,0));
-           if ( !strcasecmp(initialvalue,v->v_initialvalue) )
-           {
-              strcpy(initialvalue,"");
-              strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName
-                                      (v->v_initialvalue,List_Common_Var,0));
-           }
-           if ( !strcasecmp(initialvalue,v->v_initialvalue) )
-           {
-              strcpy(initialvalue,"");
-              strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName
-                                     (v->v_initialvalue,List_ModuleUsed_Var,0));
-           }
-           strcat (ligne," = ");
-
-           if (v->v_nbdim == 0)
-           {
-           strcpy(ligne2,initialvalue);
-           }
-           else
-           {
-           sprintf(ligne2,"RESHAPE(%s,SHAPE(%s))",initialvalue,vargridnametabvars(v,0));
-           }
-           strcat (ligne,ligne2);
-           /*                                                                 */
-           Save_Length(ligne,48);
-           tofich (allocationagrif, ligne,1);
-        }
-     }
-     if (onlyfixedgrids != 1 && v->v_nbdim!=0)
-     {
-        strcpy (ligne, "   End if");
-        tofich (allocationagrif, ligne,1);
-     }
-  }
-               /***************************************************************/
-               /***************************************************************/
-               /***************************************************************/
+                if ( !strcasecmp(parcours->var->v_commonname,parcours_nom->o_nom) &&
+                    IndiceInlist(parcours->var->v_indicetabvars,list_indic[parcours->var->v_catvar]) == 0 )
+                {
+                    v = parcours->var;
+                    IndiceMax = 0;
+                    IndiceMin = indicemaxtabvars[v->v_catvar];
+                    /* body of the file */
+                    if ( !strcasecmp(v->v_commoninfile,cur_filename) )
+                    {
+                        if ( (onlyfixedgrids != 1) && (v->v_nbdim != 0) )
+                        {
+                            sprintf(ligne,"if (.not. allocated(%s)) then", vargridnametabvars(v,0));
+                            tofich(allocationagrif,ligne,1);
+                        }
+                        if ( (v->v_allocatable != 1) && (v->v_dimsempty != 1) )
+                        {
+                            /*                ALLOCATION                                          */
+                            if ( v->v_dimension != 0 )
+                            {
+                                if ( v->v_indicetabvars < IndiceMin || v->v_indicetabvars > IndiceMax )
+                                {
+                                    parcours1 = parcours;
+                                    compteur = -1;
+                                    out = 0;
+                                    indiceprec = parcours->var->v_indicetabvars -1 ;
+                                    while ( parcours1 && out == 0
+                                        && !strcasecmp(parcours->var->v_readedlistdimension,parcours1->var->v_readedlistdimension)
+                                        && !strcasecmp(parcours->var->v_typevar,            parcours1->var->v_typevar)
+                                        && (parcours1->var->v_indicetabvars == indiceprec+1) )
+                                    {
+                                        if ( !strcasecmp(parcours1->var->v_modulename,parcours_nom->o_nom) ||
+                                             !strcasecmp(parcours1->var->v_commonname,parcours_nom->o_nom) )
+                                        {
+                                            compteur = compteur +1 ;
+                                            indiceprec = parcours1->var->v_indicetabvars;
+                                            parcoursprec = parcours1;
+                                            parcours1 = parcours1->suiv;
+                                        }
+                                        else out = 1;
+                                    }
+                                    sprintf(ligne,"!! ALLOCATION OF VARIABLE : %s",v->v_nomvar);
+                                    tofich(allocationagrif,ligne,1);
+                                    if ( compteur > ValeurMax )
+                                    {
+                                        sprintf(ligne,"do i = %d,%d", parcours->var->v_indicetabvars,
+                                                                      parcours->var->v_indicetabvars+compteur);
+                                        tofich(allocationagrif,ligne,1);
+                                        IndiceMin = parcours->var->v_indicetabvars;
+                                        IndiceMax = parcours->var->v_indicetabvars+compteur;
+                                        sprintf(ligne,"    allocate(%s", vargridnametabvars(v,1));
+                                        sprintf(ligne2,"%s)", vargridparam(v));
+                                        strcat(ligne,ligne2);
+                                        tofich(allocationagrif,ligne,1);
+                                        tofich(allocationagrif,"enddo",1);
+                                        i = parcours->var->v_indicetabvars;
+                                        do
+                                        {
+                                            parcoursindic =  (listindice *)calloc(1,sizeof(listindice));
+                                            parcoursindic -> i_indice = i;
+                                            parcoursindic -> suiv = list_indic[parcours->var->v_catvar];
+                                            list_indic[parcours->var->v_catvar] = parcoursindic;
+                                            i = i + 1;
+                                        } while ( i <= parcours->var->v_indicetabvars+compteur );
+                                        parcours = parcoursprec;
+                                    }
+                                    else
+                                    {
+                                        sprintf(ligne,"allocate(%s", vargridnametabvars(v,0));
+                                        sprintf(ligne2,"%s)", vargridparam(v));
+                                        strcat(ligne,ligne2);
+                                        tofich(allocationagrif,ligne,1);
+                                        parcoursindic =  (listindice *) calloc(1,sizeof(listindice));
+                                        parcoursindic -> i_indice = parcours->var->v_indicetabvars;
+                                        parcoursindic -> suiv = list_indic[parcours->var->v_catvar];
+                                        list_indic[parcours->var->v_catvar] = parcoursindic;
+                                    }
+                                    neededparameter = writedeclarationintoamr(List_Parameter_Var,
+                                                        paramtoamr,v,parcours_nom->o_nom,neededparameter,v->v_commonname);
+                                }
+                            } /* end of the allocation part                                       */
+                            /*                INITIALISATION                                      */
+                            if ( strcasecmp(v->v_initialvalue,"") )
+                            {
+                                strcpy(ligne, vargridnametabvars(v,0));
+                                /* We should modify the initialvalue in the case of variable has been defined with others variables */
+                                strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName(v->v_initialvalue,List_Global_Var));
+                                if ( !strcasecmp(initialvalue,v->v_initialvalue) )
+                                {
+                                    strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName(v->v_initialvalue,List_Common_Var));
+                                }
+                                if ( !strcasecmp(initialvalue,v->v_initialvalue) )
+                                {
+                                    strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName(v->v_initialvalue,List_ModuleUsed_Var));
+                                }
+                                strcat (ligne," = ");
+
+                                if (v->v_nbdim == 0)
+                                {
+                                    strcpy(ligne2,initialvalue);
+                                }
+                                else
+                                {
+                                    sprintf(ligne2,"reshape(%s,shape(%s))",initialvalue,vargridnametabvars(v,0));
+                                }
+                                strcat(ligne,ligne2);
+                                tofich(allocationagrif,ligne,1);
+                            }
+                        }
+                        if ( (onlyfixedgrids != 1) && (v->v_nbdim != 0) )
+                        {
+                            tofich(allocationagrif,"endif",1);
+                        }
+                    }
+                }
+                parcours = parcours -> suiv;
             }
-            parcours = parcours -> suiv;
-         }
-         /* Close the file Alloc_agrif                                        */
-         fclose(allocationagrif);
-         fclose(paramtoamr);
-      }
-      /*                                                                      */
-      parcours_nom = parcours_nom -> suiv;
-   }
-
-}
-
-
+            /* Close the file Alloc_agrif                                        */
+            fclose(allocationagrif);
+            fclose(paramtoamr);
+        }
+        parcours_nom = parcours_nom -> suiv;
+    }
+}
 
 void write_allocation_Global_0()
 {
-   listnom *parcours_nom;
-   listvar *parcours;
-   listvar *parcoursprec;
-   listvar *parcours1;
-   FILE *allocationagrif;
-   char ligne[LONGNOM];
-   variable *v;
-   int IndiceMax;
-   int IndiceMin;
-   int compteur;
-   int out;
-   int indiceprec;
-   int ValeurMax;
-   char initialvalue[LONG_4C];
-   int typeiswritten ;
-
-   parcoursprec = (listvar *)NULL;
-   parcours_nom = List_NameOfModule;
-   ValeurMax = 2;
-   while ( parcours_nom  )
-   {
-      /*                                                                      */
-      if ( parcours_nom->o_val == 1 )
-      {
-         IndiceMax = 0;
-         IndiceMin = indicemaxtabvars;
-         /* Open the file to create the Alloc_agrif subroutine                */
-         sprintf(ligne,"alloc_agrif_%s.h",parcours_nom->o_nom);
-         allocationagrif = associate (ligne);
-         /*                                                                   */
-         if ( ModuleIsDefineInInputFile(parcours_nom->o_nom) == 1 )
-         {
-             /* add the call to initworkspace                                 */
-            tofich(allocationagrif,"if ( .NOT. Agrif_Root() ) then ",1);
-            fprintf(allocationagrif,"#include \"GetNumberofcells.h\" \n");
-            tofich(allocationagrif,"else ",1);
-            fprintf(allocationagrif,"#include \"SetNumberofcells.h\" \n");
-            tofich(allocationagrif,"endif ",1);
-            tofich(allocationagrif,"Call Agrif_InitWorkspace ",1);
-         }
-
-         typeiswritten = 0;
-
-         parcours = List_Global_Var;
-         while ( parcours )
-         {
-            if ( !strcasecmp(parcours->var->v_modulename,parcours_nom->o_nom) &&
-                 parcours->var->v_VariableIsParameter == 0                  &&
-                 parcours->var->v_notgrid == 0                              &&
-                 !strcasecmp(parcours->var->v_modulename,parcours_nom->o_nom)  )
+    listnom *parcours_nom;
+    listvar *parcours;
+    listvar *parcoursprec;
+    listvar *parcours1;
+    FILE *allocationagrif;
+    char ligne[LONG_M];
+    char ligne2[LONG_M];
+    variable *v;
+    int IndiceMax;
+    int IndiceMin;
+    int compteur;
+    int out;
+    int indiceprec;
+    int ValeurMax;
+    char initialvalue[LONG_M];
+    int typeiswritten ;
+
+    parcoursprec = (listvar *) NULL;
+    parcours_nom = List_NameOfModule;
+    ValeurMax = 2;
+
+    while ( parcours_nom  )
+    {
+        if ( parcours_nom->o_val == 1 )
+        {
+            IndiceMax = 0;
+            IndiceMin = indicemaxtabvars[0];
+            /* Open the file to create the Alloc_agrif subroutine                */
+            sprintf(ligne,"alloc_agrif_%s.h",parcours_nom->o_nom);
+            allocationagrif = open_for_write(ligne);
+
+//             if ( ModuleIsDefineInInputFile(parcours_nom->o_nom) == 1 )
+//             {
+//                 /* add the call to initworkspace         */
+//                 tofich(allocationagrif,"if (.not. Agrif_Root() ) then",1);
+//                 tofich(allocationagrif,"#include \"GetNumberofcells.h\"\n",0);
+//                 tofich(allocationagrif,"else",1);
+//                 tofich(allocationagrif,"#include \"SetNumberofcells.h\"\n",0);
+//                 tofich(allocationagrif,"endif",1);
+//                 tofich(allocationagrif,"call Agrif_InitWorkspace",1);
+//             }
+
+            typeiswritten = 0;
+            parcours = List_Global_Var;
+            while ( parcours )
             {
-               /***************************************************************/
-               /***************************************************************/
-               /***************************************************************/
-               v = parcours->var;
-               IndiceMax = 0;
-               IndiceMin = indicemaxtabvars;
-  /* body of the file                                                         */
-  if ( !strcasecmp(v->v_commoninfile,mainfile) )
-  {
-     if (onlyfixedgrids != 1 && v->v_nbdim!=0)
-     {
-        strcpy (ligne, "If (.not. associated(");
-        strcat (ligne, vargridnametabvars(v,0));
-        strcat (ligne, "))                       then");
-        Save_Length(ligne,48);
-        tofich (allocationagrif, ligne,1);
-     }
-     if ( v->v_allocatable != 1 && ( v->v_dimsempty != 1) )
-     {
-        /*                ALLOCATION                                          */
-        if ( v->v_dimension != 0  )
-        {
-           if ( v->v_indicetabvars < IndiceMin ||
-                v->v_indicetabvars > IndiceMax )
-           {
-              parcours1 = parcours;
-              compteur = -1;
-              out = 0;
-              indiceprec = parcours->var->v_indicetabvars -1 ;
-              while ( parcours1 && out == 0 &&
-                      !strcasecmp(  parcours->var->v_readedlistdimension,
-                                  parcours1->var->v_readedlistdimension) &&
-                      !strcasecmp(  parcours->var->v_typevar,
-                                  parcours1->var->v_typevar) &&
-                             ( parcours1->var->v_indicetabvars == indiceprec+1 )
-                     )
-              {
-
-               if ( !strcasecmp(parcours1->var->v_modulename,
-                                parcours_nom->o_nom) ||
-                    !strcasecmp(parcours1->var->v_commonname,
-                                parcours_nom->o_nom) )
-                 {
-                      compteur = compteur +1 ;
-                      indiceprec = parcours1->var->v_indicetabvars;
-                      parcoursprec = parcours1;
-                      parcours1 = parcours1->suiv;
-                 }
-                 else out = 1;
-              }
-              if ( compteur > ValeurMax )
-              {
-                 fprintf(allocationagrif,"      DO i = %d , %d\n",
-                                          parcours->var->v_indicetabvars,
-                                       parcours->var->v_indicetabvars+compteur);
-                 IndiceMin = parcours->var->v_indicetabvars;
-                 IndiceMax = parcours->var->v_indicetabvars+compteur;
-                 strcpy (ligne, "allocate ");
-                 strcat (ligne, "(");
-                 strcat (ligne, vargridnametabvars(v,1));
-                 strcat (ligne, vargridparam(v,0));
-                 strcat (ligne, ")");
-                 Save_Length(ligne,48);
-                 tofich (allocationagrif, ligne,1);
-                 fprintf(allocationagrif,"      end do\n");
-                 parcours = parcoursprec;
-              }
-              else
-              {
-                 strcpy (ligne, "allocate ");
-                 strcat (ligne, "(");
-                 strcat (ligne, vargridnametabvars(v,0));
-                 strcat (ligne, vargridparam(v,0));
-                 strcat (ligne, ")");
-                 Save_Length(ligne,48);
-                 tofich (allocationagrif, ligne,1);
-              }
-           }
-        } /* end of the allocation part                                       */
-
-        /*                INITIALISATION                                      */
-        if ( strcasecmp(v->v_initialvalue,"") )
-        {
-           strcpy (ligne, "");
-           strcat (ligne, vargridnametabvars(v,0));
-           /* We should modify the initialvalue in the case of variable has   */
-           /*    been defined with others variables                           */
-
-           strcpy(initialvalue,
-                  ChangeTheInitalvaluebyTabvarsName
-                                      (v->v_initialvalue,List_Global_Var,0));
-           if ( !strcasecmp(initialvalue,v->v_initialvalue) )
-           {
-              strcpy(initialvalue,"");
-              strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName
-                                      (v->v_initialvalue,List_Common_Var,0));
-           }
-           if ( !strcasecmp(initialvalue,v->v_initialvalue) )
-           {
-              strcpy(initialvalue,"");
-              strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName
-                                     (v->v_initialvalue,List_ModuleUsed_Var,0));
-           }
-           strcat (ligne," = ");
-           strcat (ligne,initialvalue);
-           /*                                                                 */
-           Save_Length(ligne,48);
-           tofich (allocationagrif, ligne,1);
-        }
-     }
-/* Case of structure types */
-        if ((typeiswritten == 0) && !strcasecmp(v->v_typevar,"type"))
-        {
-        sprintf(ligne,"If (.Not.Allocated(Agrif_%s_var)) Then",v->v_modulename);
-        tofich(allocationagrif, ligne, 1);
-        sprintf(ligne,"Allocate(Agrif_%s_var(0:Agrif_NbMaxGrids))",v->v_modulename);
-        tofich(allocationagrif, ligne, 1);
-        strcpy(ligne,"End If");
-        tofich(allocationagrif, ligne, 1);
-        typeiswritten = 1;
-        }
-     if (onlyfixedgrids != 1 && v->v_nbdim!=0)
-     {
-        strcpy (ligne, "   End if");
-        tofich (allocationagrif, ligne,1);
-     }
-  }
-               /***************************************************************/
-               /***************************************************************/
-               /***************************************************************/
+                if ( !strcasecmp(parcours->var->v_modulename,parcours_nom->o_nom) &&
+                       parcours->var->v_VariableIsParameter == 0                  &&
+                       parcours->var->v_notgrid == 0  )
+                {
+                    v = parcours->var;
+                    IndiceMax = 0;
+                    IndiceMin = indicemaxtabvars[v->v_catvar];
+                    /* body of the file */
+                    if ( !strcasecmp(v->v_commoninfile,cur_filename) )
+                    {
+                        if ( (onlyfixedgrids != 1) && (v->v_nbdim != 0) )
+                        {
+                            sprintf(ligne,"if (.not. allocated(%s)) then", vargridnametabvars(v,0));
+                            tofich(allocationagrif,ligne,1);
+                        }
+                        if ( (v->v_allocatable != 1) && (v->v_dimsempty != 1) )
+                        {
+                            /*                ALLOCATION                                          */
+                            if ( v->v_dimension != 0 )
+                            {
+                                if ( v->v_indicetabvars < IndiceMin || v->v_indicetabvars > IndiceMax )
+                                {
+                                    parcours1 = parcours;
+                                    compteur = -1;
+                                    out = 0;
+                                    indiceprec = parcours->var->v_indicetabvars -1 ;
+                                    while ( parcours1 && out == 0
+                                        && !strcasecmp(parcours->var->v_readedlistdimension,parcours1->var->v_readedlistdimension)
+                                        && !strcasecmp(parcours->var->v_typevar,            parcours1->var->v_typevar)
+                                        && (parcours1->var->v_indicetabvars == indiceprec+1) )
+                                    {
+                                        if ( !strcasecmp(parcours1->var->v_modulename, parcours_nom->o_nom) ||
+                                             !strcasecmp(parcours1->var->v_commonname, parcours_nom->o_nom) )
+                                        {
+                                            compteur = compteur +1 ;
+                                            indiceprec = parcours1->var->v_indicetabvars;
+                                            parcoursprec = parcours1;
+                                            parcours1 = parcours1->suiv;
+                                        }
+                                        else out = 1;
+                                    }
+                                    sprintf(ligne,"!! ALLOCATION OF VARIABLE : %s",v->v_nomvar);
+                                    tofich(allocationagrif,ligne,1);
+                                    if ( compteur > ValeurMax )
+                                    {
+                                        sprintf(ligne,"do i = %d,%d", parcours->var->v_indicetabvars,
+                                                                      parcours->var->v_indicetabvars+compteur);
+                                        tofich(allocationagrif,ligne,1);
+                                        IndiceMin = parcours->var->v_indicetabvars;
+                                        IndiceMax = parcours->var->v_indicetabvars+compteur;
+                                        sprintf(ligne,"    allocate(%s", vargridnametabvars(v,1));
+                                        sprintf(ligne2,"%s)", vargridparam(v));
+                                        strcat(ligne,ligne2);
+                                        tofich(allocationagrif,ligne,1);
+                                        tofich(allocationagrif,"enddo",1);
+                                        parcours = parcoursprec;
+                                    }
+                                    else
+                                    {
+                                        sprintf(ligne,"allocate(%s", vargridnametabvars(v,0));
+                                        sprintf(ligne2,"%s)", vargridparam(v));
+                                        strcat(ligne,ligne2);
+                                        tofich(allocationagrif,ligne,1);
+                                    }
+                                }
+                            } /* end of the allocation part                                       */
+                            /*                INITIALISATION                                      */
+                            if ( strcasecmp(v->v_initialvalue,"") )
+                            {
+                                strcpy(ligne, vargridnametabvars(v,0));
+                                /* We should modify the initialvalue in the case of variable has been defined with others variables */
+                                strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName(v->v_initialvalue,List_Global_Var));
+                                if ( !strcasecmp(initialvalue,v->v_initialvalue) )
+                                {
+                                    strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName(v->v_initialvalue,List_Common_Var));
+                                }
+                                if ( !strcasecmp(initialvalue,v->v_initialvalue) )
+                                {
+                                    strcpy(initialvalue,ChangeTheInitalvaluebyTabvarsName(v->v_initialvalue,List_ModuleUsed_Var));
+                                }
+                                strcat (ligne," = ");
+                                strcat (ligne,initialvalue);
+                                Save_Length(ligne,48);
+                                tofich(allocationagrif,ligne,1);
+                            }
+                        }
+                        /* Case of structure types */
+                        if ( (typeiswritten == 0) && !strcasecmp(v->v_typevar,"type") )
+                        {
+                            sprintf(ligne,"if (.not. allocated(Agrif_%s_var)) then",v->v_modulename);
+                            tofich(allocationagrif, ligne, 1);
+                            sprintf(ligne,"    allocate(Agrif_%s_var(0:Agrif_NbMaxGrids))",v->v_modulename);
+                            tofich(allocationagrif, ligne, 1);
+                            tofich(allocationagrif, "endif", 1);
+                            typeiswritten = 1;
+                        }
+                        if ( (onlyfixedgrids != 1) && (v->v_nbdim != 0) )
+                        {
+                            tofich(allocationagrif,"endif",1);
+                        }
+                    }
+                }
+                parcours = parcours -> suiv;
             }
-            parcours = parcours -> suiv;
-         }
-         /*                                                                   */
-         if ( ModuleIsDefineInInputFile(parcours_nom->o_nom) == 1 )
-         {
-            /* add the call to initworkspace                                  */
-            tofich(allocationagrif,"if ( .NOT. Agrif_Root() ) then ",1);
-            fprintf(allocationagrif,"#include \"GetNumberofcells.h\" \n");
-            tofich(allocationagrif,"else ",1);
-            fprintf(allocationagrif,"#include \"SetNumberofcells.h\" \n");
-            tofich(allocationagrif,"endif ",1);
-            tofich(allocationagrif,"Call Agrif_InitWorkspace ",1);
-         }
-         /* Close the file Alloc_agrif                                        */
-         fclose(allocationagrif);
-      } /* end parcours_nom == 1                                              */
-      /*                                                                      */
-      parcours_nom = parcours_nom -> suiv;
-   }
+            if ( ModuleIsDefineInInputFile(parcours_nom->o_nom) == 1 )
+            {
+                fprintf(allocationagrif, "      if ( .not.Agrif_Root() ) then\n");
+                fprintf(allocationagrif, "#include \"GetNumberofcells.h\"\n");
+                fprintf(allocationagrif, "      else\n");
+                fprintf(allocationagrif, "#include \"SetNumberofcells.h\"\n");
+                fprintf(allocationagrif, "      endif\n");
+                fprintf(allocationagrif, "      call Agrif_InitWorkspace\n");
+            }
+            fclose(allocationagrif);
+        }
+        parcours_nom = parcours_nom -> suiv;
+    }
 }
 
@@ -1082,33 +870,30 @@
 /*                                                                            */
 /******************************************************************************/
-void creefichieramr (char *NameTampon)
-{
-  listvar *newvar;
-  variable *v;
-  int erreur;
-  char filefich[LONG_C];
-  char ligne[LONG_C];
-  int IndiceMax;
-  int IndiceMin;
-  int InitEmpty;
-  int VarnameEmpty;
-  int donotwrite;
-
-  FILE *initproc;
-  FILE *initglobal;
-  FILE *createvarname;
-  FILE *createvarnameglobal;
-
-  if ( todebug == 1 ) printf("Enter in creefichieramr\n");
-  strcpy (filefich, "cd ");
-  strcat (filefich, nomdir);
-  erreur = system (filefich);
-  if (erreur)
-  {
-     strcpy (filefich, "mkdir ");
-     strcat (filefich, nomdir);
-     system (filefich);
-     printf ("%s: Directory created\n", nomdir);
-  }
+void creefichieramr ()
+{
+    listvar *newvar;
+    variable *v;
+    int erreur;
+    char filefich[LONG_M];
+
+    int InitEmpty;
+    int VarnameEmpty;
+    int donotwrite;
+
+    FILE *initproc;
+    FILE *initglobal;
+    FILE *createvarname;
+    FILE *createvarnameglobal;
+
+    if ( todebug == 1 ) printf("Enter in creefichieramr\n");
+
+    sprintf(filefich, "cd %s", include_dir);
+    erreur = system (filefich);
+    if (erreur)
+    {
+        sprintf(filefich, "mkdir -p %s", include_dir);
+        system(filefich);
+        printf("%s: Directory created\n", include_dir);
+    }
 
 /******************************************************************************/
@@ -1116,89 +901,62 @@
 /******************************************************************************/
 
-/*----------------------------------------------------------------------------*/
-  if ( todebug == 1 )
-  {
-     strcpy(ligne,"initialisations_agrif_");
-     strcat(ligne,NameTampon);
-     strcat(ligne,".h");
-     initproc = associate (ligne);
-/*----------------------------------------------------------------------------*/
-     strcpy(ligne,"createvarname_agrif_");
-     strcat(ligne,NameTampon);
-     strcat(ligne,".h");
-     createvarname = associate (ligne);
-/*----------------------------------------------------------------------------*/
-     InitEmpty = 1 ;
-     VarnameEmpty = 1 ;
-
-     newvar = List_Global_Var;
-     while ( newvar && todebug == 1 )
-     {
-        donotwrite = 0;
-        v = newvar->var;
-
-        if ( ( v->v_common == 1 || v->v_module == 1 ) && donotwrite == 0 )
-        {
-          write_createvarnameagrif_file(v,createvarname,&VarnameEmpty);
-          write_initialisationsagrif_file(v,initproc,&InitEmpty);
-        }
-        newvar = newvar->suiv;
-     }
-  /*                                                                          */
-     fclose (createvarname);
-     fclose (initproc);
-  /*--------------------------------------------------------------------------*/
-     if ( Did_filetoparse_readed(curmodulename) == 0 )
-     {
-        if ( InitEmpty != 1  )
-        {
-           initglobal = associateaplus("initialisations_agrif.h");
-           strcpy(ligne,"#include \"initialisations_agrif_");
-           strcat(ligne,NameTampon);
-           strcat(ligne,".h\"\n");
-           fprintf(initglobal,ligne);
-           fclose(initglobal);
-        }
-  /*--------------------------------------------------------------------------*/
-        if ( VarnameEmpty != 1 )
-        {
-           createvarnameglobal= associateaplus("createvarname_agrif.h");
-           strcpy(ligne,"#include \"createvarname_agrif_");
-           strcat(ligne,NameTampon);
-           strcat(ligne,".h\"\n");
-           fprintf(createvarnameglobal,ligne);
-           fclose(createvarnameglobal);
-        }
-     }
-  }
-/*----------------------------------------------------------------------------*/
-/*----------------------------------------------------------------------------*/
-/*----------------------------------------------------------------------------*/
-/*----------------------------------------------------------------------------*/
-/*----------------------------------------------------------------------------*/
-  IndiceMax = 0;
-  IndiceMin = 0;
-
-  write_allocation_Common_0();
-  write_allocation_Global_0();
-
-  Write_Alloc_Agrif_Files();
-  write_probdimagrif_file();
-  write_keysagrif_file();
-  write_modtypeagrif_file();
-  if ( NbMailleXDefined == 1 )
-                             write_Setnumberofcells_file("SetNumberofcells.h");
-  if ( NbMailleXDefined == 1 )
-                             write_Getnumberofcells_file("GetNumberofcells.h");
-  retour77 = 0;
-  if ( NbMailleXDefined == 1 )
-                          write_Setnumberofcells_file("SetNumberofcellsFree.h");
-  if ( NbMailleXDefined == 1 )
-                          write_Getnumberofcells_file("GetNumberofcellsFree.h");
-  retour77 = 1;
-  if ( NbMailleXDefined == 1 )
-                         write_Setnumberofcells_file("SetNumberofcellsFixed.h");
-  if ( NbMailleXDefined == 1 )
-                         write_Getnumberofcells_file("GetNumberofcellsFixed.h");
-  if ( todebug == 1 ) printf("Out of creefichieramr\n");
-}
+    if ( todebug == 1 )
+    {
+        const char *NameTampon = "toto";
+        sprintf(filefich,"initialisations_agrif_%s.h", NameTampon);
+        initproc = open_for_write(filefich);
+
+        sprintf(filefich,"createvarname_agrif_%s.h", NameTampon);
+        createvarname = open_for_write(filefich);
+
+        InitEmpty = 1 ;
+        VarnameEmpty = 1 ;
+
+        newvar = List_Global_Var;
+        while ( newvar )
+        {
+            donotwrite = 0;
+            v = newvar->var;
+
+            if ( ( v->v_common == 1 || v->v_module == 1 ) && donotwrite == 0 )
+            {
+                write_createvarnameagrif_file(v,createvarname,&VarnameEmpty);
+                write_initialisationsagrif_file(v,initproc,&InitEmpty);
+            }
+            newvar = newvar->suiv;
+        }
+        fclose (createvarname);
+        fclose (initproc);
+
+        if ( is_dependfile_created(curmodulename) == 0 )
+        {
+            if ( InitEmpty != 1  )
+            {
+                initglobal = open_for_append("initialisations_agrif.h");
+                fprintf(initglobal,"#include \"initialisations_agrif_%s.h\"\n", NameTampon);
+                fclose(initglobal);
+            }
+            if ( VarnameEmpty != 1 )
+            {
+                createvarnameglobal= open_for_append("createvarname_agrif.h");
+                fprintf(createvarnameglobal,"#include \"createvarname_agrif_%s.h\"\n", NameTampon);
+                fclose(createvarnameglobal);
+            }
+        }
+    }
+    write_allocation_Common_0();
+    write_allocation_Global_0();
+
+    Write_Alloc_Agrif_Files();
+    write_probdimagrif_file();
+    write_keysagrif_file();
+    write_modtypeagrif_file();
+
+    if ( NbMailleXDefined == 1 )
+    {
+        write_Setnumberofcells_file();
+        write_Getnumberofcells_file();
+    }
+
+    if ( todebug == 1 ) printf("Out of creefichieramr\n");
+}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/nemo_mpi.h
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/nemo_mpi.h	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/EXTERNAL/AGRIF/nemo_mpi.h	(revision 9987)
@@ -0,0 +1,3 @@
+#if defined key_mpp_mpi
+#define AGRIF_MPI
+#endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_2/limistate_2.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_2/limistate_2.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_2/limistate_2.F90	(revision 9987)
@@ -69,5 +69,6 @@
       IF( .NOT. ln_limini ) THEN  
          
-         tfu(:,:) = eos_fzp( tsn(:,:,1,jp_sal) ) * tmask(:,:,1)       ! freezing/melting point of sea water [Celcius]
+         CALL eos_fzp( tsn(:,:,1,jp_sal), tfu(:,:) )       ! freezing/melting point of sea water [Celcius]
+         tfu(:,:) = tfu(:,:) *  tmask(:,:,1)
 
          DO jj = 1, jpj
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/ice.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/ice.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/ice.F90	(revision 9987)
@@ -234,5 +234,4 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   u_oce, v_oce   !: surface ocean velocity used in ice dynamics
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ahiu , ahiv    !: hor. diffusivity coeff. at U- and V-points [m2/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   pahu , pahv    !: ice hor. eddy diffusivity coef. at U- and V-points
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ust2s, hicol   !: friction velocity, ice collection thickness accreted in leads
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   strp1, strp2   !: strength at previous time steps
@@ -253,20 +252,20 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fhld        !: heat flux from the lead used for bottom melting
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_snw    !: snow-ocean mass exchange over 1 time step [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_spr    !: snow precipitation on ice over 1 time step [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sub    !: snow sublimation over 1 time step [kg/m2]
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_ice    !: ice-ocean mass exchange over 1 time step [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sni    !: snow ice growth component of wfx_ice [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_opw    !: lateral ice growth component of wfx_ice [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_bog    !: bottom ice growth component of wfx_ice [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_dyn    !: dynamical ice growth component of wfx_ice [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_bom    !: bottom melt component of wfx_ice [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sum    !: surface melt component of wfx_ice [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_res    !: residual component of wfx_ice [kg/m2]
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   afx_tot     !: ice concentration tendency (total) [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_snw    !: snow-ocean mass exchange   [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_spr    !: snow precipitation on ice  [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sub    !: snow/ice sublimation       [kg.m-2.s-1]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_ice    !: ice-ocean mass exchange                   [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sni    !: snow ice growth component of wfx_ice      [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_opw    !: lateral ice growth component of wfx_ice   [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_bog    !: bottom ice growth component of wfx_ice    [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_dyn    !: dynamical ice growth component of wfx_ice [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_bom    !: bottom melt component of wfx_ice          [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sum    !: surface melt component of wfx_ice         [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_res    !: residual component of wfx_ice             [kg.m-2.s-1]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   afx_tot     !: ice concentration tendency (total)          [s-1]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   afx_thd     !: ice concentration tendency (thermodynamics) [s-1]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   afx_dyn     !: ice concentration tendency (dynamics) [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   afx_dyn     !: ice concentration tendency (dynamics)       [s-1]
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_bog     !: salt flux due to ice growth/melt                      [PSU/m2/s]
@@ -279,26 +278,31 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_res     !: residual salt flux due to correction of ice thickness [PSU/m2/s]
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_bog     !: total heat flux causing bottom ice growth 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_bom     !: total heat flux causing bottom ice melt 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_sum     !: total heat flux causing surface ice melt 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_opw     !: total heat flux causing open water ice formation
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_dif     !: total heat flux causing Temp change in the ice 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_snw     !: heat flux for snow melt 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err     !: heat flux error after heat diffusion 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err_dif !: heat flux remaining due to change in non-solar flux
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err_rem !: heat flux error after heat remapping 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_in      !: heat flux available for thermo transformations 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_out     !: heat flux remaining at the end of thermo transformations 
-
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_sub     !: salt flux due to ice sublimation
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_bog     !: total heat flux causing bottom ice growth        [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_bom     !: total heat flux causing bottom ice melt          [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_sum     !: total heat flux causing surface ice melt         [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_opw     !: total heat flux causing open water ice formation [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_dif     !: total heat flux causing Temp change in the ice   [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_snw     !: heat flux for snow melt                          [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err     !: heat flux error after heat diffusion             [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err_dif !: heat flux remaining due to change in non-solar flux [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err_rem !: heat flux error after heat remapping             [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_in      !: heat flux available for thermo transformations   [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_out     !: heat flux remaining at the end of thermo transformations  [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_err_sub !: mass flux error after sublimation [kg.m-2.s-1]
+   
    ! heat flux associated with ice-atmosphere mass exchange
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_sub     !: heat flux for sublimation 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_spr     !: heat flux of the snow precipitation 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_sub     !: heat flux for sublimation  [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_spr     !: heat flux of the snow precipitation  [W.m-2]
 
    ! heat flux associated with ice-ocean mass exchange
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_thd     !: ice-ocean heat flux from thermo processes (limthd_dh) 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_dyn     !: ice-ocean heat flux from mecanical processes (limitd_me) 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_res     !: residual heat flux due to correction of ice thickness
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ftr_ice   !: transmitted solar radiation under ice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_thd     !: ice-ocean heat flux from thermo processes (limthd_dh)  [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_dyn     !: ice-ocean heat flux from mecanical processes (limitd_me)  [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_res     !: residual heat flux due to correction of ice thickness [W.m-2]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ftr_ice   !: transmitted solar radiation under ice   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   pahu3D , pahv3D
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rn_amax_2d  !: maximum ice concentration 2d array
 
    !!--------------------------------------------------------------------------
@@ -372,11 +376,12 @@
    INTEGER          , PUBLIC ::   nlay_i          !: number of ice  layers 
    INTEGER          , PUBLIC ::   nlay_s          !: number of snow layers 
-   CHARACTER(len=32), PUBLIC ::   cn_icerst_in    !: suffix of ice restart name (input)
+   CHARACTER(len=80), PUBLIC ::   cn_icerst_in    !: suffix of ice restart name (input)
    CHARACTER(len=256), PUBLIC ::   cn_icerst_indir !: ice restart input directory
-   CHARACTER(len=32), PUBLIC ::   cn_icerst_out   !: suffix of ice restart name (output)
+   CHARACTER(len=80), PUBLIC ::   cn_icerst_out   !: suffix of ice restart name (output)
    CHARACTER(len=256), PUBLIC ::   cn_icerst_outdir!: ice restart output directory
    LOGICAL          , PUBLIC ::   ln_limdyn       !: flag for ice dynamics (T) or not (F)
    LOGICAL          , PUBLIC ::   ln_icectl       !: flag for sea-ice points output (T) or not (F)
-   REAL(wp)         , PUBLIC ::   rn_amax         !: maximum ice concentration
+   REAL(wp)         , PUBLIC ::   rn_amax_n       !: maximum ice concentration Northern hemisphere
+   REAL(wp)         , PUBLIC ::   rn_amax_s       !: maximum ice concentration Southern hemisphere
    INTEGER          , PUBLIC ::   iiceprt         !: debug i-point
    INTEGER          , PUBLIC ::   jiceprt         !: debug j-point
@@ -424,5 +429,4 @@
       ALLOCATE( u_oce    (jpi,jpj) , v_oce    (jpi,jpj) ,                           &
          &      ahiu     (jpi,jpj) , ahiv     (jpi,jpj) ,                           &
-         &      pahu     (jpi,jpj) , pahv     (jpi,jpj) ,                           &
          &      ust2s    (jpi,jpj) , hicol    (jpi,jpj) ,                           &
          &      strp1    (jpi,jpj) , strp2    (jpi,jpj) , strength  (jpi,jpj) ,     &
@@ -437,9 +441,10 @@
          &      wfx_res(jpi,jpj) , wfx_sni(jpi,jpj) , wfx_opw(jpi,jpj) , wfx_spr(jpi,jpj) ,     &
          &      afx_tot(jpi,jpj) , afx_thd(jpi,jpj),  afx_dyn(jpi,jpj) ,                        &
-         &      fhtur  (jpi,jpj) , ftr_ice(jpi,jpj,jpl), qlead  (jpi,jpj) ,                     &
-         &      sfx_res(jpi,jpj) , sfx_bri(jpi,jpj) , sfx_dyn(jpi,jpj) ,                        &
+         &      fhtur  (jpi,jpj) , ftr_ice(jpi,jpj,jpl), pahu3D(jpi,jpj,jpl+1), pahv3D(jpi,jpj,jpl+1),            &
+         &      qlead  (jpi,jpj) , rn_amax_2d(jpi,jpj),                                         &
+         &      sfx_res(jpi,jpj) , sfx_bri(jpi,jpj) , sfx_dyn(jpi,jpj) , sfx_sub(jpi,jpj),      &
          &      sfx_bog(jpi,jpj) , sfx_bom(jpi,jpj) , sfx_sum(jpi,jpj) , sfx_sni(jpi,jpj) , sfx_opw(jpi,jpj) ,    &
          &      hfx_res(jpi,jpj) , hfx_snw(jpi,jpj) , hfx_sub(jpi,jpj) , hfx_err(jpi,jpj) ,     & 
-         &      hfx_err_dif(jpi,jpj) , hfx_err_rem(jpi,jpj) ,                                   &
+         &      hfx_err_dif(jpi,jpj) , hfx_err_rem(jpi,jpj) , wfx_err_sub(jpi,jpj) ,       &
          &      hfx_in (jpi,jpj) , hfx_out(jpi,jpj) , fhld(jpi,jpj) ,                           &
          &      hfx_sum(jpi,jpj) , hfx_bom(jpi,jpj) , hfx_bog(jpi,jpj) , hfx_dif(jpi,jpj) , hfx_opw(jpi,jpj) ,    &
@@ -508,2 +513,3 @@
    !!======================================================================
 END MODULE ice
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limcons.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limcons.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limcons.F90	(revision 9987)
@@ -24,5 +24,6 @@
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
    USE sbc_oce , ONLY : sfx  ! Surface boundary condition: ocean fields
-
+   USE sbc_ice , ONLY : qevap_ice
+   
    IMPLICIT NONE
    PRIVATE
@@ -184,5 +185,5 @@
          ! salt flux
          zfs_b  = glob_sum(  ( sfx_bri(:,:) + sfx_bog(:,:) + sfx_bom(:,:) + sfx_sum(:,:) + sfx_sni(:,:) +  &
-            &                  sfx_opw(:,:) + sfx_res(:,:) + sfx_dyn(:,:)                                  &
+            &                  sfx_opw(:,:) + sfx_res(:,:) + sfx_dyn(:,:) + sfx_sub(:,:)                   &
             &                ) *  e12t(:,:) * tmask(:,:,1) * zconv )
 
@@ -209,5 +210,5 @@
          ! salt flux
          zfs  = glob_sum(  ( sfx_bri(:,:) + sfx_bog(:,:) + sfx_bom(:,:) + sfx_sum(:,:) + sfx_sni(:,:) +  &
-            &                sfx_opw(:,:) + sfx_res(:,:) + sfx_dyn(:,:)                                  & 
+            &                sfx_opw(:,:) + sfx_res(:,:) + sfx_dyn(:,:) + sfx_sub(:,:)                   & 
             &              ) * e12t(:,:) * tmask(:,:,1) * zconv ) - zfs_b
 
@@ -256,5 +257,6 @@
             ENDIF
             IF (     zvmin   < -epsi10 ) WRITE(numout,*) 'violation v_i<0  [m]          (',cd_routine,') = ',zvmin
-            IF (     zamax   > rn_amax+epsi10 .AND. cd_routine /= 'limtrp' .AND. cd_routine /= 'limitd_me' ) THEN
+            IF (     zamax   > MAX( rn_amax_n, rn_amax_s ) + epsi10 .AND. &
+               &                         cd_routine /= 'limtrp' .AND. cd_routine /= 'limitd_me' ) THEN
                                          WRITE(numout,*) 'violation a_i>amax            (',cd_routine,') = ',zamax
             ENDIF
@@ -286,5 +288,6 @@
 #if ! defined key_bdy
       ! heat flux
-      zhfx  = glob_sum( ( hfx_in - hfx_out - diag_heat - diag_trp_ei - diag_trp_es - hfx_sub ) * e12t * tmask(:,:,1) * zconv ) 
+      zhfx  = glob_sum( ( hfx_in - hfx_out - diag_heat - diag_trp_ei - diag_trp_es - SUM( qevap_ice * a_i_b, dim=3 ) )  &
+         &              * e12t * tmask(:,:,1) * zconv ) 
       ! salt flux
       zsfx  = glob_sum( ( sfx + diag_smvi ) * e12t * tmask(:,:,1) * zconv ) * rday
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limdiahsb.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limdiahsb.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limdiahsb.F90	(revision 9987)
@@ -56,5 +56,5 @@
       real(wp)   ::   zbg_ivo, zbg_svo, zbg_are, zbg_sal ,zbg_tem ,zbg_ihc ,zbg_shc
       real(wp)   ::   zbg_sfx, zbg_sfx_bri, zbg_sfx_bog, zbg_sfx_bom, zbg_sfx_sum, zbg_sfx_sni,   &
-      &               zbg_sfx_opw, zbg_sfx_res, zbg_sfx_dyn 
+      &               zbg_sfx_opw, zbg_sfx_res, zbg_sfx_dyn, zbg_sfx_sub 
       real(wp)   ::   zbg_vfx, zbg_vfx_bog, zbg_vfx_opw, zbg_vfx_sni, zbg_vfx_dyn
       real(wp)   ::   zbg_vfx_bom, zbg_vfx_sum, zbg_vfx_res, zbg_vfx_spr, zbg_vfx_snw, zbg_vfx_sub  
@@ -111,4 +111,5 @@
       zbg_sfx_bom = ztmp * glob_sum( sfx_bom(:,:) * e12t(:,:) * tmask(:,:,1) )
       zbg_sfx_sum = ztmp * glob_sum( sfx_sum(:,:) * e12t(:,:) * tmask(:,:,1) )
+      zbg_sfx_sub = ztmp * glob_sum( sfx_sub(:,:) * e12t(:,:) * tmask(:,:,1) )
 
       ! Heat budget
@@ -189,4 +190,5 @@
       CALL iom_put( 'ibgsfxbom' , zbg_sfx_bom                              )   ! salt flux bottom melt       -
       CALL iom_put( 'ibgsfxsum' , zbg_sfx_sum                              )   ! salt flux surface melt      -
+      CALL iom_put( 'ibgsfxsub' , zbg_sfx_sub                              )   ! salt flux sublimation      -
 
       CALL iom_put( 'ibghfxdhc' , zbg_hfx_dhc                              )   ! Heat content variation in snow and ice [W]
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limhdf.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limhdf.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limhdf.F90	(revision 9987)
@@ -7,4 +7,5 @@
    !!             -   !  2001-05 (G. Madec, R. Hordoir) opa norm
    !!            1.0  !  2002-08 (C. Ethe)  F90, free form
+   !!            3.0  !  2015-08 (O. Tintó and M. Castrillo)  added lim_hdf (multiple)
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -27,5 +28,5 @@
    PRIVATE
 
-   PUBLIC   lim_hdf         ! called by lim_trp
+   PUBLIC   lim_hdf ! called by lim_trp
    PUBLIC   lim_hdf_init    ! called by sbc_lim_init
 
@@ -43,5 +44,5 @@
 CONTAINS
 
-   SUBROUTINE lim_hdf( ptab )
+   SUBROUTINE lim_hdf( ptab , ihdf_vars , jpl , nlay_i )
       !!-------------------------------------------------------------------
       !!                  ***  ROUTINE lim_hdf  ***
@@ -54,10 +55,13 @@
       !! ** Action  :    update ptab with the diffusive contribution
       !!-------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT( inout ) ::   ptab    ! Field on which the diffusion is applied
-      !
-      INTEGER                           ::  ji, jj                    ! dummy loop indices
+      INTEGER                           :: jpl, nlay_i, isize, ihdf_vars
+      REAL(wp),  DIMENSION(:,:,:), INTENT( inout ),TARGET ::   ptab    ! Field on which the diffusion is applied
+      !
+      INTEGER                           ::  ji, jj, jk, jl , jm               ! dummy loop indices
       INTEGER                           ::  iter, ierr           ! local integers
-      REAL(wp)                          ::  zrlxint, zconv     ! local scalars
-      REAL(wp), POINTER, DIMENSION(:,:) ::  zrlx, zflu, zflv, zdiv0, zdiv, ztab0
+      REAL(wp)                          ::  zrlxint     ! local scalars
+      REAL(wp), POINTER , DIMENSION ( : )        :: zconv     ! local scalars
+      REAL(wp), POINTER , DIMENSION(:,:,:) ::  zrlx,zdiv0, ztab0
+      REAL(wp), POINTER , DIMENSION(:,:) ::  zflu, zflv, zdiv
       CHARACTER(lc)                     ::  charout                   ! local character
       REAL(wp), PARAMETER               ::  zrelax = 0.5_wp           ! relaxation constant for iterative procedure
@@ -65,8 +69,29 @@
       INTEGER , PARAMETER               ::  its    = 100              ! Maximum number of iteration
       !!-------------------------------------------------------------------
+      TYPE(arrayptr)   , ALLOCATABLE, DIMENSION(:) ::   pt2d_array, zrlx_array
+      CHARACTER(len=1) , ALLOCATABLE, DIMENSION(:) ::   type_array ! define the nature of ptab array grid-points
+      !                                                            ! = T , U , V , F , W and I points
+      REAL(wp)        , ALLOCATABLE, DIMENSION(:)  ::   psgn_array    ! =-1 the sign change across the north fold boundary
+
+     !!--------------------------------------------------------------------- 
+
+      !                       !==  Initialisation  ==!
+      ! +1 open water diffusion
+      isize = jpl*(ihdf_vars+nlay_i)+1
+      ALLOCATE( zconv (isize) )
+      ALLOCATE( pt2d_array(isize) , zrlx_array(isize) )
+      ALLOCATE( type_array(isize) )
+      ALLOCATE( psgn_array(isize) )
       
-      CALL wrk_alloc( jpi, jpj, zrlx, zflu, zflv, zdiv0, zdiv, ztab0 )
-
-      !                       !==  Initialisation  ==!
+      CALL wrk_alloc( jpi, jpj, isize, zrlx, zdiv0, ztab0 )
+      CALL wrk_alloc( jpi, jpj, zflu, zflv, zdiv )
+
+      DO jk= 1 , isize
+         pt2d_array(jk)%pt2d=>ptab(:,:,jk)
+         zrlx_array(jk)%pt2d=>zrlx(:,:,jk)
+         type_array(jk)='T'
+         psgn_array(jk)=1.
+      END DO
+
       !
       IF( linit ) THEN              ! Metric coefficient (compute at the first call and saved in efact)
@@ -74,5 +99,5 @@
          IF( lk_mpp    )   CALL mpp_sum( ierr )
          IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'lim_hdf : unable to allocate arrays' )
-         DO jj = 2, jpjm1  
+         DO jj = 2, jpjm1
             DO ji = fs_2 , fs_jpim1   ! vector opt.
                efact(ji,jj) = ( e2u(ji,jj) + e2u(ji-1,jj) + e1v(ji,jj) + e1v(ji,jj-1) ) * r1_e12t(ji,jj)
@@ -83,23 +108,82 @@
       !                             ! Time integration parameters
       !
-      ztab0(:, : ) = ptab(:,:)      ! Arrays initialization
-      zdiv0(:, 1 ) = 0._wp
-      zdiv0(:,jpj) = 0._wp
-      zflu (jpi,:) = 0._wp   
-      zflv (jpi,:) = 0._wp
-      zdiv0(1,  :) = 0._wp
-      zdiv0(jpi,:) = 0._wp
+      zflu (jpi,: ) = 0._wp
+      zflv (jpi,: ) = 0._wp
+
+      DO jk=1 , isize
+         ztab0(:, : , jk ) = ptab(:,:,jk)      ! Arrays initialization
+         zdiv0(:, 1 , jk ) = 0._wp
+         zdiv0(:,jpj, jk ) = 0._wp
+         zdiv0(1,  :, jk ) = 0._wp
+         zdiv0(jpi,:, jk ) = 0._wp
+      END DO
 
       zconv = 1._wp           !==  horizontal diffusion using a Crant-Nicholson scheme  ==!
       iter  = 0
       !
-      DO WHILE( zconv > ( 2._wp * 1.e-04 ) .AND. iter <= its )   ! Sub-time step loop
+      DO WHILE( MAXVAL(zconv(:)) > ( 2._wp * 1.e-04 ) .AND. iter <= its )   ! Sub-time step loop
          !
          iter = iter + 1                                 ! incrementation of the sub-time step number
          !
+         DO jk = 1 , isize
+            jl = (jk-1) /( ihdf_vars+nlay_i)+1
+            IF (zconv(jk) > ( 2._wp * 1.e-04 )) THEN
+               DO jj = 1, jpjm1                                ! diffusive fluxes in U- and V- direction
+                  DO ji = 1 , fs_jpim1   ! vector opt.
+                     zflu(ji,jj) = pahu3D(ji,jj,jl) * e2u(ji,jj) * r1_e1u(ji,jj) * ( ptab(ji+1,jj,jk) - ptab(ji,jj,jk) )
+                     zflv(ji,jj) = pahv3D(ji,jj,jl) * e1v(ji,jj) * r1_e2v(ji,jj) * ( ptab(ji,jj+1,jk) - ptab(ji,jj,jk) )
+                  END DO
+               END DO
+               !
+               DO jj= 2, jpjm1                                 ! diffusive trend : divergence of the fluxes
+                  DO ji = fs_2 , fs_jpim1   ! vector opt. 
+                     zdiv(ji,jj) = ( zflu(ji,jj) - zflu(ji-1,jj) + zflv(ji,jj) - zflv(ji,jj-1) ) * r1_e12t(ji,jj)
+                  END DO
+               END DO
+               !
+               IF( iter == 1 )   zdiv0(:,:,jk) = zdiv(:,:)        ! save the 1st evaluation of the diffusive trend in zdiv0
+               !
+               DO jj = 2, jpjm1                                ! iterative evaluation
+                  DO ji = fs_2 , fs_jpim1   ! vector opt.
+                     zrlxint = (   ztab0(ji,jj,jk)    &
+                        &       +  rdt_ice * (           zalfa   * ( zdiv(ji,jj) + efact(ji,jj) * ptab(ji,jj,jk) )   &
+                        &                      + ( 1.0 - zalfa ) *   zdiv0(ji,jj,jk) )                               &
+                        &      ) / ( 1.0 + zalfa * rdt_ice * efact(ji,jj) )
+                     zrlx(ji,jj,jk) = ptab(ji,jj,jk) + zrelax * ( zrlxint - ptab(ji,jj,jk) )
+                  END DO
+               END DO
+            END IF
+
+         END DO
+
+         CALL lbc_lnk_multi( zrlx_array, type_array , psgn_array , isize ) ! Multiple interchange of all the variables
+         !
+         
+         IF ( MOD( iter-1 , nn_convfrq ) == 0 )  THEN   !Convergence test every nn_convfrq iterations (perf. optimization ) 
+            DO jk=1,isize
+               zconv(jk) = 0._wp                                   ! convergence test
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zconv(jk) = MAX( zconv(jk), ABS( zrlx(ji,jj,jk) - ptab(ji,jj,jk) )  )
+                  END DO
+               END DO
+            END DO
+            IF( lk_mpp ) CALL mpp_max_multiple( zconv , isize )            ! max over the global domain for all the variables
+         ENDIF
+         !
+         DO jk=1,isize
+            ptab(:,:,jk) = zrlx(:,:,jk)
+         END DO
+         !
+      END DO                                       ! end of sub-time step loop
+
+     ! -----------------------
+      !!! final step (clem) !!!
+      DO jk = 1, isize
+         jl = (jk-1) /( ihdf_vars+nlay_i)+1
          DO jj = 1, jpjm1                                ! diffusive fluxes in U- and V- direction
             DO ji = 1 , fs_jpim1   ! vector opt.
-               zflu(ji,jj) = pahu(ji,jj) * e2u(ji,jj) * r1_e1u(ji,jj) * ( ptab(ji+1,jj) - ptab(ji,jj) )
-               zflv(ji,jj) = pahv(ji,jj) * e1v(ji,jj) * r1_e2v(ji,jj) * ( ptab(ji,jj+1) - ptab(ji,jj) )
+               zflu(ji,jj) = pahu3D(ji,jj,jl) * e2u(ji,jj) * r1_e1u(ji,jj) * ( ptab(ji+1,jj,jk) - ptab(ji,jj,jk) )
+               zflv(ji,jj) = pahv3D(ji,jj,jl) * e1v(ji,jj) * r1_e2v(ji,jj) * ( ptab(ji,jj+1,jk) - ptab(ji,jj,jk) )
             END DO
          END DO
@@ -108,62 +192,32 @@
             DO ji = fs_2 , fs_jpim1   ! vector opt. 
                zdiv(ji,jj) = ( zflu(ji,jj) - zflu(ji-1,jj) + zflv(ji,jj) - zflv(ji,jj-1) ) * r1_e12t(ji,jj)
-            END DO
-         END DO
-         !
-         IF( iter == 1 )   zdiv0(:,:) = zdiv(:,:)        ! save the 1st evaluation of the diffusive trend in zdiv0
-         !
-         DO jj = 2, jpjm1                                ! iterative evaluation
-            DO ji = fs_2 , fs_jpim1   ! vector opt.
-               zrlxint = (   ztab0(ji,jj)    &
-                  &       +  rdt_ice * (           zalfa   * ( zdiv(ji,jj) + efact(ji,jj) * ptab(ji,jj) )   &
-                  &                      + ( 1.0 - zalfa ) *   zdiv0(ji,jj) )                               & 
-                  &      ) / ( 1.0 + zalfa * rdt_ice * efact(ji,jj) )
-               zrlx(ji,jj) = ptab(ji,jj) + zrelax * ( zrlxint - ptab(ji,jj) )
-            END DO
-         END DO
-         CALL lbc_lnk( zrlx, 'T', 1. )                   ! lateral boundary condition
-         !
-         IF ( MOD( iter, nn_convfrq ) == 0 )  THEN    ! convergence test every nn_convfrq iterations (perf. optimization)
-            zconv = 0._wp
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1
-                  zconv = MAX( zconv, ABS( zrlx(ji,jj) - ptab(ji,jj) )  )
-               END DO
-            END DO
-            IF( lk_mpp )   CALL mpp_max( zconv )      ! max over the global domain
-         ENDIF
-         !
-         ptab(:,:) = zrlx(:,:)
-         !
-      END DO                                       ! end of sub-time step loop
-
-      ! -----------------------
-      !!! final step (clem) !!!
-      DO jj = 1, jpjm1                                ! diffusive fluxes in U- and V- direction
-         DO ji = 1 , fs_jpim1   ! vector opt.
-            zflu(ji,jj) = pahu(ji,jj) * e2u(ji,jj) * r1_e1u(ji,jj) * ( ptab(ji+1,jj) - ptab(ji,jj) )
-            zflv(ji,jj) = pahv(ji,jj) * e1v(ji,jj) * r1_e2v(ji,jj) * ( ptab(ji,jj+1) - ptab(ji,jj) )
+               ptab(ji,jj,jk) = ztab0(ji,jj,jk) + 0.5 * ( zdiv(ji,jj) + zdiv0(ji,jj,jk) )
+            END DO
          END DO
       END DO
-      !
-      DO jj= 2, jpjm1                                 ! diffusive trend : divergence of the fluxes
-         DO ji = fs_2 , fs_jpim1   ! vector opt. 
-            zdiv(ji,jj) = ( zflu(ji,jj) - zflu(ji-1,jj) + zflv(ji,jj) - zflv(ji,jj-1) ) * r1_e12t(ji,jj)
-            ptab(ji,jj) = ztab0(ji,jj) + 0.5 * ( zdiv(ji,jj) + zdiv0(ji,jj) )
-         END DO
-      END DO
-      CALL lbc_lnk( ptab, 'T', 1. )                   ! lateral boundary condition
+
+      CALL lbc_lnk_multi( pt2d_array, type_array , psgn_array , isize ) ! Multiple interchange of all the variables
+
       !!! final step (clem) !!!
       ! -----------------------
 
       IF(ln_ctl)   THEN
-         zrlx(:,:) = ptab(:,:) - ztab0(:,:)
-         WRITE(charout,FMT="(' lim_hdf  : zconv =',D23.16, ' iter =',I4,2X)") zconv, iter
-         CALL prt_ctl( tab2d_1=zrlx, clinfo1=charout )
-      ENDIF
-      !
-      CALL wrk_dealloc( jpi, jpj, zrlx, zflu, zflv, zdiv0, zdiv, ztab0 )
+         DO jk = 1 , isize
+            zrlx(:,:,jk) = ptab(:,:,jk) - ztab0(:,:,jk)
+            WRITE(charout,FMT="(' lim_hdf  : zconv =',D23.16, ' iter =',I4,2X)") zconv, iter
+            CALL prt_ctl( tab2d_1=zrlx(:,:,jk), clinfo1=charout )
+         END DO
+      ENDIF
+      !
+      CALL wrk_dealloc( jpi, jpj, isize, zrlx, zdiv0, ztab0 )
+      CALL wrk_dealloc( jpi, jpj, zflu, zflv, zdiv )
+
+      DEALLOCATE( zconv )
+      DEALLOCATE( pt2d_array , zrlx_array )
+      DEALLOCATE( type_array )
+      DEALLOCATE( psgn_array )
       !
    END SUBROUTINE lim_hdf
+
 
    
@@ -179,5 +233,5 @@
       !!-------------------------------------------------------------------
       INTEGER  ::   ios                 ! Local integer output status for namelist read
-      NAMELIST/namicehdf/ nn_convfrq
+      NAMELIST/namicehdf/ nn_convfrq 
       !!-------------------------------------------------------------------
       !
@@ -212,2 +266,3 @@
    !!======================================================================
 END MODULE limhdf
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limistate.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limistate.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limistate.F90	(revision 9987)
@@ -24,4 +24,5 @@
    USE par_oce          ! ocean parameters
    USE dom_ice          ! sea-ice domain
+   USE limvar           ! lim_var_salprof
    USE in_out_manager   ! I/O manager
    USE lib_mpp          ! MPP library
@@ -117,5 +118,6 @@
 
       ! basal temperature (considered at freezing point)
-      t_bo(:,:) = ( eos_fzp( sss_m(:,:) ) + rt0 ) * tmask(:,:,1) 
+      CALL eos_fzp( sss_m(:,:), t_bo(:,:) )
+      t_bo(:,:) = ( t_bo(:,:) + rt0 ) * tmask(:,:,1) 
 
       IF( ln_iceini ) THEN
@@ -245,6 +247,4 @@
                ztest_1 = 1
             ELSE 
-              ! this write is useful
-              IF(lwp)  WRITE(numout,*) ' * TEST1 AREA NOT CONSERVED *** zA_cons = ', zA_cons,' zat_i_ini = ',zat_i_ini(i_hemis) 
                ztest_1 = 0
             ENDIF
@@ -257,7 +257,4 @@
                ztest_2 = 1
             ELSE
-              ! this write is useful
-              IF(lwp)  WRITE(numout,*) ' * TEST2 VOLUME NOT CONSERVED *** zV_cons = ', zV_cons, &
-                            ' zvt_i_ini = ', zvt_i_ini(i_hemis)
                ztest_2 = 0
             ENDIF
@@ -267,7 +264,4 @@
                ztest_3 = 1
             ELSE
-               ! this write is useful
-               IF(lwp) WRITE(numout,*) ' * TEST 3 THICKNESS OF THE LAST CATEGORY OUT OF BOUNDS *** zh_i_ini(i_fill,i_hemis) = ', &
-               zh_i_ini(i_fill,i_hemis), ' hi_max(jpl-1) = ', hi_max(i_fill-1)
                ztest_3 = 0
             ENDIF
@@ -277,6 +271,4 @@
             DO jl = 1, jpl
                IF ( za_i_ini(jl,i_hemis) .LT. 0._wp ) THEN 
-                  ! this write is useful
-                  IF(lwp) WRITE(numout,*) ' * TEST 4 POSITIVITY NOT OK FOR CAT ', jl, ' WITH A = ', za_i_ini(jl,i_hemis)
                   ztest_4 = 0
                ENDIF
@@ -336,4 +328,10 @@
          END DO
       END DO
+
+      ! for constant salinity in time
+      IF( nn_icesal == 1 .OR. nn_icesal == 3 )  THEN
+         CALL lim_var_salprof
+         smv_i = sm_i * v_i
+      ENDIF
 
       ! Snow temperature and heat content
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limitd_me.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limitd_me.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limitd_me.F90	(revision 9987)
@@ -45,26 +45,17 @@
    REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   asum     ! sum of total ice and open water area
    REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   aksum    ! ratio of area removed to area ridged
-   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   athorn   ! participation function; fraction of ridging/
-   !                                                     ! closing associated w/ category n
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   athorn   ! participation function; fraction of ridging/closing associated w/ category n
    REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   hrmin    ! minimum ridge thickness
    REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   hrmax    ! maximum ridge thickness
    REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   hraft    ! thickness of rafted ice
-   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   krdg     ! mean ridge thickness/thickness of ridging ice 
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   krdg     ! thickness of ridging ice / mean ridge thickness
    REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   aridge   ! participating ice ridging
    REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   araft    ! participating ice rafting
 
    REAL(wp), PARAMETER ::   krdgmin = 1.1_wp    ! min ridge thickness multiplier
-   REAL(wp), PARAMETER ::   kraft   = 2.0_wp    ! rafting multipliyer
-   REAL(wp), PARAMETER ::   kamax   = 1.0_wp    ! max of ice area authorized (clem: scheme is not stable if kamax <= 0.99)
+   REAL(wp), PARAMETER ::   kraft   = 0.5_wp    ! rafting multipliyer
 
    REAL(wp) ::   Cp                             ! 
    !
-   !-----------------------------------------------------------------------
-   ! Ridging diagnostic arrays for history files
-   !-----------------------------------------------------------------------
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dardg1dt   ! rate of fractional area loss by ridging ice (1/s)
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dardg2dt   ! rate of fractional area gain by new ridges (1/s)
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dvirdgdt   ! rate of ice volume ridged (m/s)
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   opening    ! rate of opening due to divergence/shear (1/s)
    !
    !!----------------------------------------------------------------------
@@ -83,11 +74,6 @@
          &      asum (jpi,jpj)     , athorn(jpi,jpj,0:jpl)                    ,     &
          &      aksum(jpi,jpj)                                                ,     &
-         !
          &      hrmin(jpi,jpj,jpl) , hraft(jpi,jpj,jpl) , aridge(jpi,jpj,jpl) ,     &
-         &      hrmax(jpi,jpj,jpl) , krdg (jpi,jpj,jpl) , araft (jpi,jpj,jpl) ,     &
-         !
-         !* Ridging diagnostic arrays for history files
-         &      dardg1dt(jpi,jpj)  , dardg2dt(jpi,jpj)                        ,     & 
-         &      dvirdgdt(jpi,jpj)  , opening(jpi,jpj)                         , STAT=lim_itd_me_alloc )
+         &      hrmax(jpi,jpj,jpl) , krdg (jpi,jpj,jpl) , araft (jpi,jpj,jpl) , STAT=lim_itd_me_alloc )
          !
       IF( lim_itd_me_alloc /= 0 )   CALL ctl_warn( 'lim_itd_me_alloc: failed to allocate arrays' )
@@ -132,7 +118,4 @@
       REAL(wp), POINTER, DIMENSION(:,:)   ::   opning          ! rate of opening due to divergence/shear
       REAL(wp), POINTER, DIMENSION(:,:)   ::   closing_gross   ! rate at which area removed, not counting area of new ridges
-      REAL(wp), POINTER, DIMENSION(:,:)   ::   msnow_mlt       ! mass of snow added to ocean (kg m-2)
-      REAL(wp), POINTER, DIMENSION(:,:)   ::   esnow_mlt       ! energy needed to melt snow in ocean (J m-2)
-      REAL(wp), POINTER, DIMENSION(:,:)   ::   vt_i_init, vt_i_final  !  ice volume summed over categories
       !
       INTEGER, PARAMETER ::   nitermax = 20    
@@ -142,5 +125,5 @@
       IF( nn_timing == 1 )  CALL timing_start('limitd_me')
 
-      CALL wrk_alloc( jpi,jpj, closing_net, divu_adv, opning, closing_gross, msnow_mlt, esnow_mlt, vt_i_init, vt_i_final )
+      CALL wrk_alloc( jpi,jpj, closing_net, divu_adv, opning, closing_gross )
 
       IF(ln_ctl) THEN
@@ -154,7 +137,4 @@
       IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limitd_me', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
-      CALL lim_var_zapsmall
-      CALL lim_var_glo2eqv            ! equivalent variables, requested for rafting
-
       !-----------------------------------------------------------------------------!
       ! 1) Thickness categories boundaries, ice / o.w. concentrations, init_ons
@@ -164,14 +144,7 @@
       CALL lim_itd_me_ridgeprep                                    ! prepare ridging
       !
-      IF( con_i)   CALL lim_column_sum( jpl, v_i, vt_i_init )      ! conservation check
 
       DO jj = 1, jpj                                     ! Initialize arrays.
          DO ji = 1, jpi
-            msnow_mlt(ji,jj) = 0._wp
-            esnow_mlt(ji,jj) = 0._wp
-            dardg1dt (ji,jj) = 0._wp
-            dardg2dt (ji,jj) = 0._wp
-            dvirdgdt (ji,jj) = 0._wp
-            opening  (ji,jj) = 0._wp
 
             !-----------------------------------------------------------------------------!
@@ -204,6 +177,6 @@
             ! If divu_adv < 0, make sure the closing rate is large enough
             ! to give asum = 1.0 after ridging.
-
-            divu_adv(ji,jj) = ( kamax - asum(ji,jj) ) * r1_rdtice  ! asum found in ridgeprep
+            
+            divu_adv(ji,jj) = ( 1._wp - asum(ji,jj) ) * r1_rdtice  ! asum found in ridgeprep
 
             IF( divu_adv(ji,jj) < 0._wp )   closing_net(ji,jj) = MAX( closing_net(ji,jj), -divu_adv(ji,jj) )
@@ -224,25 +197,25 @@
       DO WHILE ( iterate_ridging > 0 .AND. niter < nitermax )
 
+         ! 3.2 closing_gross
+         !-----------------------------------------------------------------------------!
+         ! Based on the ITD of ridging and ridged ice, convert the net
+         !  closing rate to a gross closing rate.  
+         ! NOTE: 0 < aksum <= 1
+         closing_gross(:,:) = closing_net(:,:) / aksum(:,:)
+
+         ! correction to closing rate and opening if closing rate is excessive
+         !---------------------------------------------------------------------
+         ! Reduce the closing rate if more than 100% of the open water 
+         ! would be removed.  Reduce the opening rate proportionately.
          DO jj = 1, jpj
             DO ji = 1, jpi
-
-               ! 3.2 closing_gross
-               !-----------------------------------------------------------------------------!
-               ! Based on the ITD of ridging and ridged ice, convert the net
-               !  closing rate to a gross closing rate.  
-               ! NOTE: 0 < aksum <= 1
-               closing_gross(ji,jj) = closing_net(ji,jj) / aksum(ji,jj)
-
-               ! correction to closing rate and opening if closing rate is excessive
-               !---------------------------------------------------------------------
-               ! Reduce the closing rate if more than 100% of the open water 
-               ! would be removed.  Reduce the opening rate proportionately.
-               za   = athorn(ji,jj,0) * closing_gross(ji,jj) * rdt_ice
-               IF( za > epsi20 ) THEN
-                  zfac = MIN( 1._wp, ato_i(ji,jj) / za )
-                  closing_gross(ji,jj) = closing_gross(ji,jj) * zfac
-                  opning       (ji,jj) = opning       (ji,jj) * zfac
+               za   = ( opning(ji,jj) - athorn(ji,jj,0) * closing_gross(ji,jj) ) * rdt_ice
+               IF( za < 0._wp .AND. za > - ato_i(ji,jj) ) THEN  ! would lead to negative ato_i
+                  zfac = - ato_i(ji,jj) / za
+                  opning(ji,jj) = athorn(ji,jj,0) * closing_gross(ji,jj) - ato_i(ji,jj) * r1_rdtice 
+               ELSEIF( za > 0._wp .AND. za > ( asum(ji,jj) - ato_i(ji,jj) ) ) THEN  ! would lead to ato_i > asum
+                  zfac = ( asum(ji,jj) - ato_i(ji,jj) ) / za
+                  opning(ji,jj) = athorn(ji,jj,0) * closing_gross(ji,jj) + ( asum(ji,jj) - ato_i(ji,jj) ) * r1_rdtice 
                ENDIF
-
             END DO
          END DO
@@ -256,8 +229,7 @@
                DO ji = 1, jpi
                   za = athorn(ji,jj,jl) * closing_gross(ji,jj) * rdt_ice
-                  IF( za  >  epsi20 ) THEN
-                     zfac = MIN( 1._wp, a_i(ji,jj,jl) / za )
+                  IF( za  >  a_i(ji,jj,jl) ) THEN
+                     zfac = a_i(ji,jj,jl) / za
                      closing_gross(ji,jj) = closing_gross(ji,jj) * zfac
-                     opning       (ji,jj) = opning       (ji,jj) * zfac
                   ENDIF
                END DO
@@ -268,13 +240,11 @@
          !-----------------------------------------------------------------------------!
 
-         CALL lim_itd_me_ridgeshift( opning, closing_gross, msnow_mlt, esnow_mlt )
-
+         CALL lim_itd_me_ridgeshift( opning, closing_gross )
+
+         
          ! 3.4 Compute total area of ice plus open water after ridging.
          !-----------------------------------------------------------------------------!
          ! This is in general not equal to one because of divergence during transport
-         asum(:,:) = ato_i(:,:)
-         DO jl = 1, jpl
-            asum(:,:) = asum(:,:) + a_i(:,:,jl)
-         END DO
+         asum(:,:) = ato_i(:,:) + SUM( a_i, dim=3 )
 
          ! 3.5 Do we keep on iterating ???
@@ -284,13 +254,12 @@
 
          iterate_ridging = 0
-
          DO jj = 1, jpj
             DO ji = 1, jpi
-               IF (ABS(asum(ji,jj) - kamax ) < epsi10) THEN
+               IF( ABS( asum(ji,jj) - 1._wp ) < epsi10 ) THEN
                   closing_net(ji,jj) = 0._wp
                   opning     (ji,jj) = 0._wp
                ELSE
                   iterate_ridging    = 1
-                  divu_adv   (ji,jj) = ( kamax - asum(ji,jj) ) * r1_rdtice
+                  divu_adv   (ji,jj) = ( 1._wp - asum(ji,jj) ) * r1_rdtice
                   closing_net(ji,jj) = MAX( 0._wp, -divu_adv(ji,jj) )
                   opning     (ji,jj) = MAX( 0._wp,  divu_adv(ji,jj) )
@@ -309,60 +278,12 @@
 
          IF( iterate_ridging == 1 ) THEN
+            CALL lim_itd_me_ridgeprep
             IF( niter  >  nitermax ) THEN
                WRITE(numout,*) ' ALERTE : non-converging ridging scheme '
                WRITE(numout,*) ' niter, iterate_ridging ', niter, iterate_ridging
             ENDIF
-            CALL lim_itd_me_ridgeprep
          ENDIF
 
       END DO !! on the do while over iter
-
-      !-----------------------------------------------------------------------------!
-      ! 4) Ridging diagnostics
-      !-----------------------------------------------------------------------------!
-      ! Convert ridging rate diagnostics to correct units.
-      ! Update fresh water and heat fluxes due to snow melt.
-      DO jj = 1, jpj
-         DO ji = 1, jpi
-
-            dardg1dt(ji,jj) = dardg1dt(ji,jj) * r1_rdtice
-            dardg2dt(ji,jj) = dardg2dt(ji,jj) * r1_rdtice
-            dvirdgdt(ji,jj) = dvirdgdt(ji,jj) * r1_rdtice
-            opening (ji,jj) = opening (ji,jj) * r1_rdtice
-
-            !-----------------------------------------------------------------------------!
-            ! 5) Heat, salt and freshwater fluxes
-            !-----------------------------------------------------------------------------!
-            wfx_snw(ji,jj) = wfx_snw(ji,jj) + msnow_mlt(ji,jj) * r1_rdtice     ! fresh water source for ocean
-            hfx_dyn(ji,jj) = hfx_dyn(ji,jj) + esnow_mlt(ji,jj) * r1_rdtice     ! heat sink for ocean (<0, W.m-2)
-
-         END DO
-      END DO
-
-      ! Check if there is a ridging error
-      IF( lwp ) THEN
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               IF( ABS( asum(ji,jj) - kamax)  >  epsi10 ) THEN   ! there is a bug
-                  WRITE(numout,*) ' '
-                  WRITE(numout,*) ' ALERTE : Ridging error: total area = ', asum(ji,jj)
-                  WRITE(numout,*) ' limitd_me '
-                  WRITE(numout,*) ' POINT : ', ji, jj
-                  WRITE(numout,*) ' jpl, a_i, athorn '
-                  WRITE(numout,*) 0, ato_i(ji,jj), athorn(ji,jj,0)
-                  DO jl = 1, jpl
-                     WRITE(numout,*) jl, a_i(ji,jj,jl), athorn(ji,jj,jl)
-                  END DO
-               ENDIF
-            END DO
-         END DO
-      END IF
-
-      ! Conservation check
-      IF ( con_i ) THEN
-         CALL lim_column_sum (jpl,   v_i, vt_i_final)
-         fieldid = ' v_i : limitd_me '
-         CALL lim_cons_check (vt_i_init, vt_i_final, 1.0e-6, fieldid) 
-      ENDIF
 
       CALL lim_var_agg( 1 ) 
@@ -410,9 +331,448 @@
       ENDIF  ! ln_limdyn=.true.
       !
-      CALL wrk_dealloc( jpi, jpj, closing_net, divu_adv, opning, closing_gross, msnow_mlt, esnow_mlt, vt_i_init, vt_i_final )
+      CALL wrk_dealloc( jpi, jpj, closing_net, divu_adv, opning, closing_gross )
       !
       IF( nn_timing == 1 )  CALL timing_stop('limitd_me')
    END SUBROUTINE lim_itd_me
 
+   SUBROUTINE lim_itd_me_ridgeprep
+      !!---------------------------------------------------------------------!
+      !!                ***  ROUTINE lim_itd_me_ridgeprep ***
+      !!
+      !! ** Purpose :   preparation for ridging and strength calculations
+      !!
+      !! ** Method  :   Compute the thickness distribution of the ice and open water 
+      !!              participating in ridging and of the resulting ridges.
+      !!---------------------------------------------------------------------!
+      INTEGER ::   ji,jj, jl    ! dummy loop indices
+      REAL(wp) ::   Gstari, astari, hrmean, zdummy   ! local scalar
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   Gsum      ! Gsum(n) = sum of areas in categories 0 to n
+      !------------------------------------------------------------------------------!
+
+      CALL wrk_alloc( jpi,jpj,jpl+2, Gsum, kkstart = -1 )
+
+      Gstari     = 1.0/rn_gstar    
+      astari     = 1.0/rn_astar    
+      aksum(:,:)    = 0.0
+      athorn(:,:,:) = 0.0
+      aridge(:,:,:) = 0.0
+      araft (:,:,:) = 0.0
+
+      ! Zero out categories with very small areas
+      CALL lim_var_zapsmall
+
+      ! Ice thickness needed for rafting
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               rswitch = MAX( 0._wp , SIGN( 1._wp, a_i(ji,jj,jl) - epsi20 ) )
+               ht_i(ji,jj,jl) = v_i (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi20 ) * rswitch
+            END DO
+         END DO
+      END DO
+
+      !------------------------------------------------------------------------------!
+      ! 1) Participation function 
+      !------------------------------------------------------------------------------!
+
+      ! Compute total area of ice plus open water.
+      ! This is in general not equal to one because of divergence during transport
+      asum(:,:) = ato_i(:,:) + SUM( a_i, dim=3 )
+
+      ! Compute cumulative thickness distribution function
+      ! Compute the cumulative thickness distribution function Gsum,
+      ! where Gsum(n) is the fractional area in categories 0 to n.
+      ! initial value (in h = 0) equals open water area
+      Gsum(:,:,-1) = 0._wp
+      Gsum(:,:,0 ) = ato_i(:,:)
+      ! for each value of h, you have to add ice concentration then
+      DO jl = 1, jpl
+         Gsum(:,:,jl) = Gsum(:,:,jl-1) + a_i(:,:,jl)
+      END DO
+
+      ! Normalize the cumulative distribution to 1
+      DO jl = 0, jpl
+         Gsum(:,:,jl) = Gsum(:,:,jl) / asum(:,:)
+      END DO
+
+      ! 1.3 Compute participation function a(h) = b(h).g(h) (athorn)
+      !--------------------------------------------------------------------------------------------------
+      ! Compute the participation function athorn; this is analogous to
+      ! a(h) = b(h)g(h) as defined in Thorndike et al. (1975).
+      ! area lost from category n due to ridging/closing
+      ! athorn(n)   = total area lost due to ridging/closing
+      ! assume b(h) = (2/Gstar) * (1 - G(h)/Gstar). 
+      !
+      ! The expressions for athorn are found by integrating b(h)g(h) between
+      ! the category boundaries.
+      ! athorn is always >= 0 and SUM(athorn(0:jpl))=1
+      !-----------------------------------------------------------------
+
+      IF( nn_partfun == 0 ) THEN       !--- Linear formulation (Thorndike et al., 1975)
+         DO jl = 0, jpl    
+            DO jj = 1, jpj 
+               DO ji = 1, jpi
+                  IF    ( Gsum(ji,jj,jl)   < rn_gstar ) THEN
+                     athorn(ji,jj,jl) = Gstari * ( Gsum(ji,jj,jl) - Gsum(ji,jj,jl-1) ) * &
+                        &                        ( 2._wp - ( Gsum(ji,jj,jl-1) + Gsum(ji,jj,jl) ) * Gstari )
+                  ELSEIF( Gsum(ji,jj,jl-1) < rn_gstar ) THEN
+                     athorn(ji,jj,jl) = Gstari * ( rn_gstar       - Gsum(ji,jj,jl-1) ) *  &
+                        &                        ( 2._wp - ( Gsum(ji,jj,jl-1) + rn_gstar       ) * Gstari )
+                  ELSE
+                     athorn(ji,jj,jl) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         END DO
+
+      ELSE                             !--- Exponential, more stable formulation (Lipscomb et al, 2007)
+         !                        
+         zdummy = 1._wp / ( 1._wp - EXP(-astari) )        ! precompute exponential terms using Gsum as a work array
+         DO jl = -1, jpl
+            Gsum(:,:,jl) = EXP( -Gsum(:,:,jl) * astari ) * zdummy
+         END DO
+         DO jl = 0, jpl
+             athorn(:,:,jl) = Gsum(:,:,jl-1) - Gsum(:,:,jl)
+         END DO
+         !
+      ENDIF
+
+      IF( ln_rafting ) THEN      ! Ridging and rafting ice participation functions
+         !
+         DO jl = 1, jpl
+            DO jj = 1, jpj 
+               DO ji = 1, jpi
+                  zdummy           = TANH ( rn_craft * ( ht_i(ji,jj,jl) - rn_hraft ) )
+                  aridge(ji,jj,jl) = ( 1._wp + zdummy ) * 0.5_wp * athorn(ji,jj,jl)
+                  araft (ji,jj,jl) = ( 1._wp - zdummy ) * 0.5_wp * athorn(ji,jj,jl)
+               END DO
+            END DO
+         END DO
+
+      ELSE
+         !
+         DO jl = 1, jpl
+            aridge(:,:,jl) = athorn(:,:,jl)
+         END DO
+         !
+      ENDIF
+
+      !-----------------------------------------------------------------
+      ! 2) Transfer function
+      !-----------------------------------------------------------------
+      ! Compute max and min ridged ice thickness for each ridging category.
+      ! Assume ridged ice is uniformly distributed between hrmin and hrmax.
+      ! 
+      ! This parameterization is a modified version of Hibler (1980).
+      ! The mean ridging thickness, hrmean, is proportional to hi^(0.5)
+      !  and for very thick ridging ice must be >= krdgmin*hi
+      !
+      ! The minimum ridging thickness, hrmin, is equal to 2*hi 
+      !  (i.e., rafting) and for very thick ridging ice is
+      !  constrained by hrmin <= (hrmean + hi)/2.
+      ! 
+      ! The maximum ridging thickness, hrmax, is determined by
+      !  hrmean and hrmin.
+      !
+      ! These modifications have the effect of reducing the ice strength
+      ! (relative to the Hibler formulation) when very thick ice is
+      ! ridging.
+      !
+      ! aksum = net area removed/ total area removed
+      ! where total area removed = area of ice that ridges
+      !         net area removed = total area removed - area of new ridges
+      !-----------------------------------------------------------------
+
+      aksum(:,:) = athorn(:,:,0)
+      ! Transfer function
+      DO jl = 1, jpl !all categories have a specific transfer function
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               
+               IF( athorn(ji,jj,jl) > 0._wp ) THEN
+                  hrmean          = MAX( SQRT( rn_hstar * ht_i(ji,jj,jl) ), ht_i(ji,jj,jl) * krdgmin )
+                  hrmin(ji,jj,jl) = MIN( 2._wp * ht_i(ji,jj,jl), 0.5_wp * ( hrmean + ht_i(ji,jj,jl) ) )
+                  hrmax(ji,jj,jl) = 2._wp * hrmean - hrmin(ji,jj,jl)
+                  hraft(ji,jj,jl) = ht_i(ji,jj,jl) / kraft
+                  krdg(ji,jj,jl)  = ht_i(ji,jj,jl) / MAX( hrmean, epsi20 )
+
+                  ! Normalization factor : aksum, ensures mass conservation
+                  aksum(ji,jj) = aksum(ji,jj) + aridge(ji,jj,jl) * ( 1._wp - krdg(ji,jj,jl) )    &
+                     &                        + araft (ji,jj,jl) * ( 1._wp - kraft          )
+
+               ELSE
+                  hrmin(ji,jj,jl)  = 0._wp 
+                  hrmax(ji,jj,jl)  = 0._wp 
+                  hraft(ji,jj,jl)  = 0._wp 
+                  krdg (ji,jj,jl)  = 1._wp
+               ENDIF
+
+            END DO
+         END DO
+      END DO
+      !
+      CALL wrk_dealloc( jpi,jpj,jpl+2, Gsum, kkstart = -1 )
+      !
+   END SUBROUTINE lim_itd_me_ridgeprep
+
+
+   SUBROUTINE lim_itd_me_ridgeshift( opning, closing_gross )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE lim_itd_me_icestrength ***
+      !!
+      !! ** Purpose :   shift ridging ice among thickness categories of ice thickness
+      !!
+      !! ** Method  :   Remove area, volume, and energy from each ridging category
+      !!              and add to thicker ice categories.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   opning         ! rate of opening due to divergence/shear
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   closing_gross  ! rate at which area removed, excluding area of new ridges
+      !
+      CHARACTER (len=80) ::   fieldid   ! field identifier
+      !
+      INTEGER ::   ji, jj, jl, jl1, jl2, jk   ! dummy loop indices
+      INTEGER ::   ij                ! horizontal index, combines i and j loops
+      INTEGER ::   icells            ! number of cells with a_i > puny
+      REAL(wp) ::   hL, hR, farea    ! left and right limits of integration
+
+      INTEGER , POINTER, DIMENSION(:) ::   indxi, indxj   ! compressed indices
+      REAL(wp), POINTER, DIMENSION(:) ::   zswitch, fvol   ! new ridge volume going to n2
+
+      REAL(wp), POINTER, DIMENSION(:) ::   afrac            ! fraction of category area ridged 
+      REAL(wp), POINTER, DIMENSION(:) ::   ardg1 , ardg2    ! area of ice ridged & new ridges
+      REAL(wp), POINTER, DIMENSION(:) ::   vsrdg , esrdg    ! snow volume & energy of ridging ice
+      REAL(wp), POINTER, DIMENSION(:) ::   dhr   , dhr2     ! hrmax - hrmin  &  hrmax^2 - hrmin^2
+
+      REAL(wp), POINTER, DIMENSION(:) ::   vrdg1   ! volume of ice ridged
+      REAL(wp), POINTER, DIMENSION(:) ::   vrdg2   ! volume of new ridges
+      REAL(wp), POINTER, DIMENSION(:) ::   vsw     ! volume of seawater trapped into ridges
+      REAL(wp), POINTER, DIMENSION(:) ::   srdg1   ! sal*volume of ice ridged
+      REAL(wp), POINTER, DIMENSION(:) ::   srdg2   ! sal*volume of new ridges
+      REAL(wp), POINTER, DIMENSION(:) ::   smsw    ! sal*volume of water trapped into ridges
+      REAL(wp), POINTER, DIMENSION(:) ::   oirdg1, oirdg2   ! ice age of ice ridged
+
+      REAL(wp), POINTER, DIMENSION(:) ::   afrft            ! fraction of category area rafted
+      REAL(wp), POINTER, DIMENSION(:) ::   arft1 , arft2    ! area of ice rafted and new rafted zone
+      REAL(wp), POINTER, DIMENSION(:) ::   virft , vsrft    ! ice & snow volume of rafting ice
+      REAL(wp), POINTER, DIMENSION(:) ::   esrft , smrft    ! snow energy & salinity of rafting ice
+      REAL(wp), POINTER, DIMENSION(:) ::   oirft1, oirft2   ! ice age of ice rafted
+
+      REAL(wp), POINTER, DIMENSION(:,:) ::   eirft      ! ice energy of rafting ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   erdg1      ! enth*volume of ice ridged
+      REAL(wp), POINTER, DIMENSION(:,:) ::   erdg2      ! enth*volume of new ridges
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ersw       ! enth of water trapped into ridges
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpij,        indxi, indxj )
+      CALL wrk_alloc( jpij,        zswitch, fvol )
+      CALL wrk_alloc( jpij,        afrac, ardg1, ardg2, vsrdg, esrdg, dhr, dhr2 )
+      CALL wrk_alloc( jpij,        vrdg1, vrdg2, vsw  , srdg1, srdg2, smsw, oirdg1, oirdg2 )
+      CALL wrk_alloc( jpij,        afrft, arft1, arft2, virft, vsrft, esrft, smrft, oirft1, oirft2 )
+      CALL wrk_alloc( jpij,nlay_i, eirft, erdg1, erdg2, ersw )
+
+      !-------------------------------------------------------------------------------
+      ! 1) Compute change in open water area due to closing and opening.
+      !-------------------------------------------------------------------------------
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ato_i(ji,jj) = MAX( 0._wp, ato_i(ji,jj) +  &
+               &                     ( opning(ji,jj) - athorn(ji,jj,0) * closing_gross(ji,jj) ) * rdt_ice )
+         END DO
+      END DO
+
+      !-----------------------------------------------------------------
+      ! 3) Pump everything from ice which is being ridged / rafted
+      !-----------------------------------------------------------------
+      ! Compute the area, volume, and energy of ice ridging in each
+      ! category, along with the area of the resulting ridge.
+
+      DO jl1 = 1, jpl !jl1 describes the ridging category
+
+         !------------------------------------------------
+         ! 3.1) Identify grid cells with nonzero ridging
+         !------------------------------------------------
+         icells = 0
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( athorn(ji,jj,jl1) > 0._wp .AND. closing_gross(ji,jj) > 0._wp ) THEN
+                  icells = icells + 1
+                  indxi(icells) = ji
+                  indxj(icells) = jj
+               ENDIF
+            END DO
+         END DO
+
+         DO ij = 1, icells
+            ji = indxi(ij) ; jj = indxj(ij)
+
+            !--------------------------------------------------------------------
+            ! 3.2) Compute area of ridging ice (ardg1) and of new ridge (ardg2)
+            !--------------------------------------------------------------------
+            ardg1(ij) = aridge(ji,jj,jl1) * closing_gross(ji,jj) * rdt_ice
+            arft1(ij) = araft (ji,jj,jl1) * closing_gross(ji,jj) * rdt_ice
+
+            !---------------------------------------------------------------
+            ! 3.3) Compute ridging /rafting fractions, make sure afrac <=1 
+            !---------------------------------------------------------------
+            afrac(ij) = ardg1(ij) / a_i(ji,jj,jl1) !ridging
+            afrft(ij) = arft1(ij) / a_i(ji,jj,jl1) !rafting
+            ardg2(ij) = ardg1(ij) * krdg(ji,jj,jl1)
+            arft2(ij) = arft1(ij) * kraft
+
+            !--------------------------------------------------------------------------
+            ! 3.4) Subtract area, volume, and energy from ridging 
+            !     / rafting category n1.
+            !--------------------------------------------------------------------------
+            vrdg1(ij) = v_i(ji,jj,jl1) * afrac(ij)
+            vrdg2(ij) = vrdg1(ij) * ( 1. + rn_por_rdg )
+            vsw  (ij) = vrdg1(ij) * rn_por_rdg
+
+            vsrdg (ij) = v_s  (ji,jj,  jl1) * afrac(ij)
+            esrdg (ij) = e_s  (ji,jj,1,jl1) * afrac(ij)
+            srdg1 (ij) = smv_i(ji,jj,  jl1) * afrac(ij)
+            oirdg1(ij) = oa_i (ji,jj,  jl1) * afrac(ij)
+            oirdg2(ij) = oa_i (ji,jj,  jl1) * afrac(ij) * krdg(ji,jj,jl1) 
+
+            ! rafting volumes, heat contents ...
+            virft (ij) = v_i  (ji,jj,  jl1) * afrft(ij)
+            vsrft (ij) = v_s  (ji,jj,  jl1) * afrft(ij)
+            esrft (ij) = e_s  (ji,jj,1,jl1) * afrft(ij)
+            smrft (ij) = smv_i(ji,jj,  jl1) * afrft(ij) 
+            oirft1(ij) = oa_i (ji,jj,  jl1) * afrft(ij) 
+            oirft2(ij) = oa_i (ji,jj,  jl1) * afrft(ij) * kraft 
+
+            !-----------------------------------------------------------------
+            ! 3.5) Compute properties of new ridges
+            !-----------------------------------------------------------------
+            smsw(ij)  = vsw(ij) * sss_m(ji,jj)                   ! salt content of seawater frozen in voids
+            srdg2(ij) = srdg1(ij) + smsw(ij)                     ! salt content of new ridge
+            
+            sfx_dyn(ji,jj) = sfx_dyn(ji,jj) - smsw(ij) * rhoic * r1_rdtice
+            wfx_dyn(ji,jj) = wfx_dyn(ji,jj) - vsw (ij) * rhoic * r1_rdtice   ! increase in ice volume due to seawater frozen in voids
+            
+             ! virtual salt flux to keep salinity constant
+            IF( nn_icesal == 1 .OR. nn_icesal == 3 )  THEN
+               srdg2(ij)      = srdg2(ij) - vsw(ij) * ( sss_m(ji,jj) - sm_i(ji,jj,jl1) )           ! ridge salinity = sm_i
+               sfx_bri(ji,jj) = sfx_bri(ji,jj) + sss_m(ji,jj)    * vsw(ij) * rhoic * r1_rdtice  &  ! put back sss_m into the ocean
+                  &                            - sm_i(ji,jj,jl1) * vsw(ij) * rhoic * r1_rdtice     ! and get  sm_i  from the ocean 
+            ENDIF
+
+            !------------------------------------------            
+            ! 3.7 Put the snow somewhere in the ocean
+            !------------------------------------------            
+            !  Place part of the snow lost by ridging into the ocean. 
+            !  Note that esrdg > 0; the ocean must cool to melt snow.
+            !  If the ocean temp = Tf already, new ice must grow.
+            !  During the next time step, thermo_rates will determine whether
+            !  the ocean cools or new ice grows.
+            wfx_snw(ji,jj) = wfx_snw(ji,jj) + ( rhosn * vsrdg(ij) * ( 1._wp - rn_fsnowrdg )   & 
+               &                              + rhosn * vsrft(ij) * ( 1._wp - rn_fsnowrft ) ) * r1_rdtice  ! fresh water source for ocean
+
+            hfx_dyn(ji,jj) = hfx_dyn(ji,jj) + ( - esrdg(ij) * ( 1._wp - rn_fsnowrdg )         & 
+               &                                - esrft(ij) * ( 1._wp - rn_fsnowrft ) ) * r1_rdtice        ! heat sink for ocean (<0, W.m-2)
+               
+            !-----------------------------------------------------------------
+            ! 3.8 Compute quantities used to apportion ice among categories
+            ! in the n2 loop below
+            !-----------------------------------------------------------------
+            dhr (ij) = 1._wp / ( hrmax(ji,jj,jl1)                    - hrmin(ji,jj,jl1)                    )
+            dhr2(ij) = 1._wp / ( hrmax(ji,jj,jl1) * hrmax(ji,jj,jl1) - hrmin(ji,jj,jl1) * hrmin(ji,jj,jl1) )
+
+
+            ! update jl1 (removing ridged/rafted area)
+            a_i  (ji,jj,  jl1) = a_i  (ji,jj,  jl1) - ardg1 (ij) - arft1 (ij)
+            v_i  (ji,jj,  jl1) = v_i  (ji,jj,  jl1) - vrdg1 (ij) - virft (ij)
+            v_s  (ji,jj,  jl1) = v_s  (ji,jj,  jl1) - vsrdg (ij) - vsrft (ij)
+            e_s  (ji,jj,1,jl1) = e_s  (ji,jj,1,jl1) - esrdg (ij) - esrft (ij)
+            smv_i(ji,jj,  jl1) = smv_i(ji,jj,  jl1) - srdg1 (ij) - smrft (ij)
+            oa_i (ji,jj,  jl1) = oa_i (ji,jj,  jl1) - oirdg1(ij) - oirft1(ij)
+
+         END DO
+
+         !--------------------------------------------------------------------
+         ! 3.9 Compute ridging ice enthalpy, remove it from ridging ice and
+         !      compute ridged ice enthalpy 
+         !--------------------------------------------------------------------
+         DO jk = 1, nlay_i
+            DO ij = 1, icells
+               ji = indxi(ij) ; jj = indxj(ij)
+               ! heat content of ridged ice
+               erdg1(ij,jk) = e_i(ji,jj,jk,jl1) * afrac(ij) 
+               eirft(ij,jk) = e_i(ji,jj,jk,jl1) * afrft(ij)               
+               
+               ! enthalpy of the trapped seawater (J/m2, >0)
+               ! clem: if sst>0, then ersw <0 (is that possible?)
+               ersw(ij,jk)  = - rhoic * vsw(ij) * rcp * sst_m(ji,jj) * r1_nlay_i
+
+               ! heat flux to the ocean
+               hfx_dyn(ji,jj) = hfx_dyn(ji,jj) + ersw(ij,jk) * r1_rdtice  ! > 0 [W.m-2] ocean->ice flux 
+
+               ! it is added to sea ice because the sign convention is the opposite of the sign convention for the ocean
+               erdg2(ij,jk) = erdg1(ij,jk) + ersw(ij,jk)
+
+               ! update jl1
+               e_i  (ji,jj,jk,jl1) = e_i(ji,jj,jk,jl1) - erdg1(ij,jk) - eirft(ij,jk)
+
+            END DO
+         END DO
+
+         !-------------------------------------------------------------------------------
+         ! 4) Add area, volume, and energy of new ridge to each category jl2
+         !-------------------------------------------------------------------------------
+         DO jl2  = 1, jpl 
+            ! over categories to which ridged/rafted ice is transferred
+            DO ij = 1, icells
+               ji = indxi(ij) ; jj = indxj(ij)
+
+               ! Compute the fraction of ridged ice area and volume going to thickness category jl2.
+               IF( hrmin(ji,jj,jl1) <= hi_max(jl2) .AND. hrmax(ji,jj,jl1) > hi_max(jl2-1) ) THEN
+                  hL = MAX( hrmin(ji,jj,jl1), hi_max(jl2-1) )
+                  hR = MIN( hrmax(ji,jj,jl1), hi_max(jl2)   )
+                  farea    = ( hR      - hL      ) * dhr(ij) 
+                  fvol(ij) = ( hR * hR - hL * hL ) * dhr2(ij)
+               ELSE
+                  farea    = 0._wp 
+                  fvol(ij) = 0._wp                  
+               ENDIF
+
+               ! Compute the fraction of rafted ice area and volume going to thickness category jl2
+               IF( hraft(ji,jj,jl1) <= hi_max(jl2) .AND. hraft(ji,jj,jl1) >  hi_max(jl2-1) ) THEN
+                  zswitch(ij) = 1._wp
+               ELSE
+                  zswitch(ij) = 0._wp                  
+               ENDIF
+
+               a_i  (ji,jj  ,jl2) = a_i  (ji,jj  ,jl2) + ( ardg2 (ij) * farea    + arft2 (ij) * zswitch(ij) )
+               oa_i (ji,jj  ,jl2) = oa_i (ji,jj  ,jl2) + ( oirdg2(ij) * farea    + oirft2(ij) * zswitch(ij) )
+               v_i  (ji,jj  ,jl2) = v_i  (ji,jj  ,jl2) + ( vrdg2 (ij) * fvol(ij) + virft (ij) * zswitch(ij) )
+               smv_i(ji,jj  ,jl2) = smv_i(ji,jj  ,jl2) + ( srdg2 (ij) * fvol(ij) + smrft (ij) * zswitch(ij) )
+               v_s  (ji,jj  ,jl2) = v_s  (ji,jj  ,jl2) + ( vsrdg (ij) * rn_fsnowrdg * fvol(ij)  +  &
+                  &                                        vsrft (ij) * rn_fsnowrft * zswitch(ij) )
+               e_s  (ji,jj,1,jl2) = e_s  (ji,jj,1,jl2) + ( esrdg (ij) * rn_fsnowrdg * fvol(ij)  +  &
+                  &                                        esrft (ij) * rn_fsnowrft * zswitch(ij) )
+
+            END DO
+
+            ! Transfer ice energy to category jl2 by ridging
+            DO jk = 1, nlay_i
+               DO ij = 1, icells
+                  ji = indxi(ij) ; jj = indxj(ij)
+                  e_i(ji,jj,jk,jl2) = e_i(ji,jj,jk,jl2) + erdg2(ij,jk) * fvol(ij) + eirft(ij,jk) * zswitch(ij)                  
+               END DO
+            END DO
+            !
+         END DO ! jl2
+         
+      END DO ! jl1 (deforming categories)
+
+      !
+      CALL wrk_dealloc( jpij,        indxi, indxj )
+      CALL wrk_dealloc( jpij,        zswitch, fvol )
+      CALL wrk_dealloc( jpij,        afrac, ardg1, ardg2, vsrdg, esrdg, dhr, dhr2 )
+      CALL wrk_dealloc( jpij,        vrdg1, vrdg2, vsw  , srdg1, srdg2, smsw, oirdg1, oirdg2 )
+      CALL wrk_dealloc( jpij,        afrft, arft1, arft2, virft, vsrft, esrft, smrft, oirft1, oirft2 )
+      CALL wrk_dealloc( jpij,nlay_i, eirft, erdg1, erdg2, ersw )
+      !
+   END SUBROUTINE lim_itd_me_ridgeshift
 
    SUBROUTINE lim_itd_me_icestrength( kstrngth )
@@ -434,5 +794,5 @@
       INTEGER             ::   ksmooth     ! smoothing the resistance to deformation
       INTEGER             ::   numts_rm    ! number of time steps for the P smoothing
-      REAL(wp)            ::   zhi, zp, z1_3  ! local scalars
+      REAL(wp)            ::   zp, z1_3    ! local scalars
       REAL(wp), POINTER, DIMENSION(:,:) ::   zworka   ! temporary array used here
       !!----------------------------------------------------------------------
@@ -459,21 +819,22 @@
                DO ji = 1, jpi
                   !
-                  IF( a_i(ji,jj,jl) > epsi10 .AND. athorn(ji,jj,jl) > 0._wp ) THEN
-                     zhi = v_i(ji,jj,jl) / a_i(ji,jj,jl)
+                  IF( athorn(ji,jj,jl) > 0._wp ) THEN
                      !----------------------------
                      ! PE loss from deforming ice
                      !----------------------------
-                     strength(ji,jj) = strength(ji,jj) - athorn(ji,jj,jl) * zhi * zhi
+                     strength(ji,jj) = strength(ji,jj) - athorn(ji,jj,jl) * ht_i(ji,jj,jl) * ht_i(ji,jj,jl)
 
                      !--------------------------
                      ! PE gain from rafting ice
                      !--------------------------
-                     strength(ji,jj) = strength(ji,jj) + 2._wp * araft(ji,jj,jl) * zhi * zhi
+                     strength(ji,jj) = strength(ji,jj) + 2._wp * araft(ji,jj,jl) * ht_i(ji,jj,jl) * ht_i(ji,jj,jl)
 
                      !----------------------------
                      ! PE gain from ridging ice
                      !----------------------------
-                     strength(ji,jj) = strength(ji,jj) + aridge(ji,jj,jl) / krdg(ji,jj,jl)     &
-                        * z1_3 * ( hrmax(ji,jj,jl)**2 + hrmin(ji,jj,jl)**2 +  hrmax(ji,jj,jl) * hrmin(ji,jj,jl) )  
+                     strength(ji,jj) = strength(ji,jj) + aridge(ji,jj,jl) * krdg(ji,jj,jl) * z1_3 *  &
+                        &                              ( hrmax(ji,jj,jl) * hrmax(ji,jj,jl) +         &
+                        &                                hrmin(ji,jj,jl) * hrmin(ji,jj,jl) +         &
+                        &                                hrmax(ji,jj,jl) * hrmin(ji,jj,jl) )  
                         !!(a**3-b**3)/(a-b) = a*a+ab+b*b                      
                   ENDIF
@@ -497,5 +858,4 @@
          !
       ENDIF                     ! kstrngth
-
       !
       !------------------------------------------------------------------------------!
@@ -503,7 +863,5 @@
       !------------------------------------------------------------------------------!
       ! CAN BE REMOVED
-      !
       IF( ln_icestr_bvf ) THEN
-
          DO jj = 1, jpj
             DO ji = 1, jpi
@@ -511,7 +869,5 @@
             END DO
          END DO
-
       ENDIF
-
       !
       !------------------------------------------------------------------------------!
@@ -558,5 +914,4 @@
       IF ( ksmooth == 2 ) THEN
 
-
          CALL lbc_lnk( strength, 'T', 1. )
 
@@ -565,6 +920,6 @@
                IF ( ( asum(ji,jj) - ato_i(ji,jj) ) > 0._wp) THEN 
                   numts_rm = 1 ! number of time steps for the running mean
-                  IF ( strp1(ji,jj) > 0.0 ) numts_rm = numts_rm + 1
-                  IF ( strp2(ji,jj) > 0.0 ) numts_rm = numts_rm + 1
+                  IF ( strp1(ji,jj) > 0._wp ) numts_rm = numts_rm + 1
+                  IF ( strp2(ji,jj) > 0._wp ) numts_rm = numts_rm + 1
                   zp = ( strength(ji,jj) + strp1(ji,jj) + strp2(ji,jj) ) / numts_rm
                   strp2(ji,jj) = strp1(ji,jj)
@@ -583,616 +938,4 @@
       !
    END SUBROUTINE lim_itd_me_icestrength
-
-
-   SUBROUTINE lim_itd_me_ridgeprep
-      !!---------------------------------------------------------------------!
-      !!                ***  ROUTINE lim_itd_me_ridgeprep ***
-      !!
-      !! ** Purpose :   preparation for ridging and strength calculations
-      !!
-      !! ** Method  :   Compute the thickness distribution of the ice and open water 
-      !!              participating in ridging and of the resulting ridges.
-      !!---------------------------------------------------------------------!
-      INTEGER ::   ji,jj, jl    ! dummy loop indices
-      REAL(wp) ::   Gstari, astari, zhi, hrmean, zdummy   ! local scalar
-      REAL(wp), POINTER, DIMENSION(:,:)   ::   zworka    ! temporary array used here
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   Gsum      ! Gsum(n) = sum of areas in categories 0 to n
-      !------------------------------------------------------------------------------!
-
-      CALL wrk_alloc( jpi,jpj, zworka )
-      CALL wrk_alloc( jpi,jpj,jpl+2, Gsum, kkstart = -1 )
-
-      Gstari     = 1.0/rn_gstar    
-      astari     = 1.0/rn_astar    
-      aksum(:,:)    = 0.0
-      athorn(:,:,:) = 0.0
-      aridge(:,:,:) = 0.0
-      araft (:,:,:) = 0.0
-      hrmin(:,:,:)  = 0.0 
-      hrmax(:,:,:)  = 0.0 
-      hraft(:,:,:)  = 0.0 
-      krdg (:,:,:)  = 1.0
-
-      !     ! Zero out categories with very small areas
-      CALL lim_var_zapsmall
-
-      !------------------------------------------------------------------------------!
-      ! 1) Participation function 
-      !------------------------------------------------------------------------------!
-
-      ! Compute total area of ice plus open water.
-      ! This is in general not equal to one because of divergence during transport
-      asum(:,:) = ato_i(:,:)
-      DO jl = 1, jpl
-         asum(:,:) = asum(:,:) + a_i(:,:,jl)
-      END DO
-
-      ! Compute cumulative thickness distribution function
-      ! Compute the cumulative thickness distribution function Gsum,
-      ! where Gsum(n) is the fractional area in categories 0 to n.
-      ! initial value (in h = 0) equals open water area
-
-      Gsum(:,:,-1) = 0._wp
-      Gsum(:,:,0 ) = ato_i(:,:)
-
-      ! for each value of h, you have to add ice concentration then
-      DO jl = 1, jpl
-         Gsum(:,:,jl) = Gsum(:,:,jl-1) + a_i(:,:,jl)
-      END DO
-
-      ! Normalize the cumulative distribution to 1
-      zworka(:,:) = 1._wp / Gsum(:,:,jpl)
-      DO jl = 0, jpl
-         Gsum(:,:,jl) = Gsum(:,:,jl) * zworka(:,:)
-      END DO
-
-      ! 1.3 Compute participation function a(h) = b(h).g(h) (athorn)
-      !--------------------------------------------------------------------------------------------------
-      ! Compute the participation function athorn; this is analogous to
-      ! a(h) = b(h)g(h) as defined in Thorndike et al. (1975).
-      ! area lost from category n due to ridging/closing
-      ! athorn(n)   = total area lost due to ridging/closing
-      ! assume b(h) = (2/Gstar) * (1 - G(h)/Gstar). 
-      !
-      ! The expressions for athorn are found by integrating b(h)g(h) between
-      ! the category boundaries.
-      !-----------------------------------------------------------------
-
-      IF( nn_partfun == 0 ) THEN       !--- Linear formulation (Thorndike et al., 1975)
-         DO jl = 0, jpl    
-            DO jj = 1, jpj 
-               DO ji = 1, jpi
-                  IF( Gsum(ji,jj,jl) < rn_gstar) THEN
-                     athorn(ji,jj,jl) = Gstari * ( Gsum(ji,jj,jl) - Gsum(ji,jj,jl-1) ) * &
-                        &                        ( 2.0 - (Gsum(ji,jj,jl-1) + Gsum(ji,jj,jl) ) * Gstari )
-                  ELSEIF (Gsum(ji,jj,jl-1) < rn_gstar) THEN
-                     athorn(ji,jj,jl) = Gstari * ( rn_gstar - Gsum(ji,jj,jl-1) ) *  &
-                        &                        ( 2.0 - ( Gsum(ji,jj,jl-1) + rn_gstar ) * Gstari )
-                  ELSE
-                     athorn(ji,jj,jl) = 0.0
-                  ENDIF
-               END DO
-            END DO
-         END DO
-
-      ELSE                             !--- Exponential, more stable formulation (Lipscomb et al, 2007)
-         !                        
-         zdummy = 1._wp / ( 1._wp - EXP(-astari) )        ! precompute exponential terms using Gsum as a work array
-         DO jl = -1, jpl
-            Gsum(:,:,jl) = EXP( -Gsum(:,:,jl) * astari ) * zdummy
-         END DO
-         DO jl = 0, jpl
-             athorn(:,:,jl) = Gsum(:,:,jl-1) - Gsum(:,:,jl)
-         END DO
-         !
-      ENDIF
-
-      IF( ln_rafting ) THEN      ! Ridging and rafting ice participation functions
-         !
-         DO jl = 1, jpl
-            DO jj = 1, jpj 
-               DO ji = 1, jpi
-                  IF ( athorn(ji,jj,jl) > 0._wp ) THEN
-!!gm  TANH( -X ) = - TANH( X )  so can be computed only 1 time....
-                     aridge(ji,jj,jl) = ( TANH (  rn_craft * ( ht_i(ji,jj,jl) - rn_hraft ) ) + 1.0 ) * 0.5 * athorn(ji,jj,jl)
-                     araft (ji,jj,jl) = ( TANH ( -rn_craft * ( ht_i(ji,jj,jl) - rn_hraft ) ) + 1.0 ) * 0.5 * athorn(ji,jj,jl)
-                     IF ( araft(ji,jj,jl) < epsi06 )   araft(ji,jj,jl)  = 0._wp
-                     aridge(ji,jj,jl) = MAX( athorn(ji,jj,jl) - araft(ji,jj,jl), 0.0 )
-                  ENDIF
-               END DO
-            END DO
-         END DO
-
-      ELSE
-         !
-         DO jl = 1, jpl
-            aridge(:,:,jl) = athorn(:,:,jl)
-         END DO
-         !
-      ENDIF
-
-      IF( ln_rafting ) THEN
-
-         IF( MAXVAL(aridge + araft - athorn(:,:,1:jpl)) > epsi10 .AND. lwp ) THEN
-            DO jl = 1, jpl
-               DO jj = 1, jpj
-                  DO ji = 1, jpi
-                     IF ( aridge(ji,jj,jl) + araft(ji,jj,jl) - athorn(ji,jj,jl) > epsi10 ) THEN
-                        WRITE(numout,*) ' ALERTE 96 : wrong participation function ... '
-                        WRITE(numout,*) ' ji, jj, jl : ', ji, jj, jl
-                        WRITE(numout,*) ' lat, lon   : ', gphit(ji,jj), glamt(ji,jj)
-                        WRITE(numout,*) ' aridge     : ', aridge(ji,jj,1:jpl)
-                        WRITE(numout,*) ' araft      : ', araft(ji,jj,1:jpl)
-                        WRITE(numout,*) ' athorn     : ', athorn(ji,jj,1:jpl)
-                     ENDIF
-                  END DO
-               END DO
-            END DO
-         ENDIF
-
-      ENDIF
-
-      !-----------------------------------------------------------------
-      ! 2) Transfer function
-      !-----------------------------------------------------------------
-      ! Compute max and min ridged ice thickness for each ridging category.
-      ! Assume ridged ice is uniformly distributed between hrmin and hrmax.
-      ! 
-      ! This parameterization is a modified version of Hibler (1980).
-      ! The mean ridging thickness, hrmean, is proportional to hi^(0.5)
-      !  and for very thick ridging ice must be >= krdgmin*hi
-      !
-      ! The minimum ridging thickness, hrmin, is equal to 2*hi 
-      !  (i.e., rafting) and for very thick ridging ice is
-      !  constrained by hrmin <= (hrmean + hi)/2.
-      ! 
-      ! The maximum ridging thickness, hrmax, is determined by
-      !  hrmean and hrmin.
-      !
-      ! These modifications have the effect of reducing the ice strength
-      ! (relative to the Hibler formulation) when very thick ice is
-      ! ridging.
-      !
-      ! aksum = net area removed/ total area removed
-      ! where total area removed = area of ice that ridges
-      !         net area removed = total area removed - area of new ridges
-      !-----------------------------------------------------------------
-
-      ! Transfer function
-      DO jl = 1, jpl !all categories have a specific transfer function
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-
-               IF (a_i(ji,jj,jl) > epsi10 .AND. athorn(ji,jj,jl) > 0.0 ) THEN
-                  zhi = v_i(ji,jj,jl) / a_i(ji,jj,jl)
-                  hrmean          = MAX(SQRT(rn_hstar*zhi), zhi*krdgmin)
-                  hrmin(ji,jj,jl) = MIN(2.0*zhi, 0.5*(hrmean + zhi))
-                  hrmax(ji,jj,jl) = 2.0*hrmean - hrmin(ji,jj,jl)
-                  hraft(ji,jj,jl) = kraft*zhi
-                  krdg(ji,jj,jl)  = hrmean / zhi
-               ELSE
-                  hraft(ji,jj,jl) = 0.0
-                  hrmin(ji,jj,jl) = 0.0 
-                  hrmax(ji,jj,jl) = 0.0 
-                  krdg (ji,jj,jl) = 1.0
-               ENDIF
-
-            END DO
-         END DO
-      END DO
-
-      ! Normalization factor : aksum, ensures mass conservation
-      aksum(:,:) = athorn(:,:,0)
-      DO jl = 1, jpl 
-         aksum(:,:)    = aksum(:,:) + aridge(:,:,jl) * ( 1._wp - 1._wp / krdg(:,:,jl) )    &
-            &                       + araft (:,:,jl) * ( 1._wp - 1._wp / kraft        )
-      END DO
-      !
-      CALL wrk_dealloc( jpi,jpj, zworka )
-      CALL wrk_dealloc( jpi,jpj,jpl+2, Gsum, kkstart = -1 )
-      !
-   END SUBROUTINE lim_itd_me_ridgeprep
-
-
-   SUBROUTINE lim_itd_me_ridgeshift( opning, closing_gross, msnow_mlt, esnow_mlt )
-      !!----------------------------------------------------------------------
-      !!                ***  ROUTINE lim_itd_me_icestrength ***
-      !!
-      !! ** Purpose :   shift ridging ice among thickness categories of ice thickness
-      !!
-      !! ** Method  :   Remove area, volume, and energy from each ridging category
-      !!              and add to thicker ice categories.
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   opning         ! rate of opening due to divergence/shear
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   closing_gross  ! rate at which area removed, excluding area of new ridges
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   msnow_mlt      ! mass of snow added to ocean (kg m-2)
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   esnow_mlt      ! energy needed to melt snow in ocean (J m-2)
-      !
-      CHARACTER (len=80) ::   fieldid   ! field identifier
-      LOGICAL, PARAMETER ::   l_conservation_check = .true.  ! if true, check conservation (useful for debugging)
-      !
-      INTEGER ::   ji, jj, jl, jl1, jl2, jk   ! dummy loop indices
-      INTEGER ::   ij                ! horizontal index, combines i and j loops
-      INTEGER ::   icells            ! number of cells with aicen > puny
-      REAL(wp) ::   hL, hR, farea, ztmelts    ! left and right limits of integration
-
-      INTEGER , POINTER, DIMENSION(:) ::   indxi, indxj   ! compressed indices
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vice_init, vice_final   ! ice volume summed over categories
-      REAL(wp), POINTER, DIMENSION(:,:) ::   eice_init, eice_final   ! ice energy summed over layers
-
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   aicen_init, vicen_init   ! ice  area    & volume before ridging
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   vsnwn_init, esnwn_init   ! snow volume  & energy before ridging
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   smv_i_init, oa_i_init    ! ice salinity & age    before ridging
-
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   eicen_init        ! ice energy before ridging
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   afrac , fvol     ! fraction of category area ridged & new ridge volume going to n2
-      REAL(wp), POINTER, DIMENSION(:,:) ::   ardg1 , ardg2    ! area of ice ridged & new ridges
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vsrdg , esrdg    ! snow volume & energy of ridging ice
-      REAL(wp), POINTER, DIMENSION(:,:) ::   dhr   , dhr2     ! hrmax - hrmin  &  hrmax^2 - hrmin^2
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vrdg1   ! volume of ice ridged
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vrdg2   ! volume of new ridges
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vsw     ! volume of seawater trapped into ridges
-      REAL(wp), POINTER, DIMENSION(:,:) ::   srdg1   ! sal*volume of ice ridged
-      REAL(wp), POINTER, DIMENSION(:,:) ::   srdg2   ! sal*volume of new ridges
-      REAL(wp), POINTER, DIMENSION(:,:) ::   smsw    ! sal*volume of water trapped into ridges
-      REAL(wp), POINTER, DIMENSION(:,:) ::   oirdg1, oirdg2   ! ice age of ice ridged
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   afrft            ! fraction of category area rafted
-      REAL(wp), POINTER, DIMENSION(:,:) ::   arft1 , arft2    ! area of ice rafted and new rafted zone
-      REAL(wp), POINTER, DIMENSION(:,:) ::   virft , vsrft    ! ice & snow volume of rafting ice
-      REAL(wp), POINTER, DIMENSION(:,:) ::   esrft , smrft    ! snow energy & salinity of rafting ice
-      REAL(wp), POINTER, DIMENSION(:,:) ::   oirft1, oirft2   ! ice age of ice rafted
-
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   eirft      ! ice energy of rafting ice
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   erdg1      ! enth*volume of ice ridged
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   erdg2      ! enth*volume of new ridges
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ersw       ! enth of water trapped into ridges
-      !!----------------------------------------------------------------------
-
-      CALL wrk_alloc( (jpi+1)*(jpj+1),       indxi, indxj )
-      CALL wrk_alloc( jpi, jpj,              vice_init, vice_final, eice_init, eice_final )
-      CALL wrk_alloc( jpi, jpj,              afrac, fvol , ardg1, ardg2, vsrdg, esrdg, dhr, dhr2 )
-      CALL wrk_alloc( jpi, jpj,              vrdg1, vrdg2, vsw  , srdg1, srdg2, smsw, oirdg1, oirdg2 )
-      CALL wrk_alloc( jpi, jpj,              afrft, arft1, arft2, virft, vsrft, esrft, smrft, oirft1, oirft2 )
-      CALL wrk_alloc( jpi, jpj, jpl,         aicen_init, vicen_init, vsnwn_init, esnwn_init, smv_i_init, oa_i_init )
-      CALL wrk_alloc( jpi, jpj, nlay_i,      eirft, erdg1, erdg2, ersw )
-      CALL wrk_alloc( jpi, jpj, nlay_i, jpl, eicen_init )
-
-      ! Conservation check
-      eice_init(:,:) = 0._wp
-
-      IF( con_i ) THEN
-         CALL lim_column_sum        (jpl,    v_i,       vice_init )
-         CALL lim_column_sum_energy (jpl, nlay_i,  e_i, eice_init )
-         DO ji = mi0(iiceprt), mi1(iiceprt)
-            DO jj = mj0(jiceprt), mj1(jiceprt)
-               WRITE(numout,*) ' vice_init  : ', vice_init(ji,jj)
-               WRITE(numout,*) ' eice_init  : ', eice_init(ji,jj)
-            END DO
-         END DO
-      ENDIF
-
-      !-------------------------------------------------------------------------------
-      ! 1) Compute change in open water area due to closing and opening.
-      !-------------------------------------------------------------------------------
-      DO jj = 1, jpj
-         DO ji = 1, jpi
-            ato_i(ji,jj) = ato_i(ji,jj) - athorn(ji,jj,0) * closing_gross(ji,jj) * rdt_ice        &
-               &                        + opning(ji,jj)                          * rdt_ice
-            IF    ( ato_i(ji,jj) < -epsi10 ) THEN    ! there is a bug
-               IF(lwp)   WRITE(numout,*) 'Ridging error: ato_i < 0 -- ato_i : ',ato_i(ji,jj)
-            ELSEIF( ato_i(ji,jj) < 0._wp   ) THEN    ! roundoff error
-               ato_i(ji,jj) = 0._wp
-            ENDIF
-         END DO
-      END DO
-
-      !-----------------------------------------------------------------
-      ! 2) Save initial state variables
-      !-----------------------------------------------------------------
-      aicen_init(:,:,:)   = a_i  (:,:,:)
-      vicen_init(:,:,:)   = v_i  (:,:,:)
-      vsnwn_init(:,:,:)   = v_s  (:,:,:)
-      smv_i_init(:,:,:)   = smv_i(:,:,:)
-      esnwn_init(:,:,:)   = e_s  (:,:,1,:)
-      eicen_init(:,:,:,:) = e_i  (:,:,:,:)
-      oa_i_init (:,:,:)   = oa_i (:,:,:)
-
-      !
-      !-----------------------------------------------------------------
-      ! 3) Pump everything from ice which is being ridged / rafted
-      !-----------------------------------------------------------------
-      ! Compute the area, volume, and energy of ice ridging in each
-      ! category, along with the area of the resulting ridge.
-
-      DO jl1 = 1, jpl !jl1 describes the ridging category
-
-         !------------------------------------------------
-         ! 3.1) Identify grid cells with nonzero ridging
-         !------------------------------------------------
-
-         icells = 0
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               IF( aicen_init(ji,jj,jl1) > epsi10 .AND. athorn(ji,jj,jl1) > 0._wp  &
-                  &   .AND. closing_gross(ji,jj) > 0._wp ) THEN
-                  icells = icells + 1
-                  indxi(icells) = ji
-                  indxj(icells) = jj
-               ENDIF
-            END DO
-         END DO
-
-         DO ij = 1, icells
-            ji = indxi(ij)
-            jj = indxj(ij)
-
-            !--------------------------------------------------------------------
-            ! 3.2) Compute area of ridging ice (ardg1) and of new ridge (ardg2)
-            !--------------------------------------------------------------------
-
-            ardg1(ji,jj) = aridge(ji,jj,jl1)*closing_gross(ji,jj)*rdt_ice
-            arft1(ji,jj) = araft (ji,jj,jl1)*closing_gross(ji,jj)*rdt_ice
-            ardg2(ji,jj) = ardg1(ji,jj) / krdg(ji,jj,jl1)
-            arft2(ji,jj) = arft1(ji,jj) / kraft
-
-            !---------------------------------------------------------------
-            ! 3.3) Compute ridging /rafting fractions, make sure afrac <=1 
-            !---------------------------------------------------------------
-
-            afrac(ji,jj) = ardg1(ji,jj) / aicen_init(ji,jj,jl1) !ridging
-            afrft(ji,jj) = arft1(ji,jj) / aicen_init(ji,jj,jl1) !rafting
-
-            IF( afrac(ji,jj) > kamax + epsi10 ) THEN  ! there is a bug
-               IF(lwp)   WRITE(numout,*) ' ardg > a_i -- ardg, aicen_init : ', ardg1(ji,jj), aicen_init(ji,jj,jl1)
-            ELSEIF( afrac(ji,jj) > kamax ) THEN       ! roundoff error
-               afrac(ji,jj) = kamax
-            ENDIF
-
-            IF( afrft(ji,jj) > kamax + epsi10 ) THEN ! there is a bug
-               IF(lwp)   WRITE(numout,*) ' arft > a_i -- arft, aicen_init : ', arft1(ji,jj), aicen_init(ji,jj,jl1) 
-            ELSEIF( afrft(ji,jj) > kamax) THEN       ! roundoff error
-               afrft(ji,jj) = kamax
-            ENDIF
-
-            !--------------------------------------------------------------------------
-            ! 3.4) Subtract area, volume, and energy from ridging 
-            !     / rafting category n1.
-            !--------------------------------------------------------------------------
-            vrdg1(ji,jj) = vicen_init(ji,jj,jl1) * afrac(ji,jj)
-            vrdg2(ji,jj) = vrdg1(ji,jj) * ( 1. + rn_por_rdg )
-            vsw  (ji,jj) = vrdg1(ji,jj) * rn_por_rdg
-
-            vsrdg (ji,jj) = vsnwn_init(ji,jj,jl1) * afrac(ji,jj)
-            esrdg (ji,jj) = esnwn_init(ji,jj,jl1) * afrac(ji,jj)
-            srdg1 (ji,jj) = smv_i_init(ji,jj,jl1) * afrac(ji,jj)
-            oirdg1(ji,jj) = oa_i_init (ji,jj,jl1) * afrac(ji,jj)
-            oirdg2(ji,jj) = oa_i_init (ji,jj,jl1) * afrac(ji,jj) / krdg(ji,jj,jl1) 
-
-            ! rafting volumes, heat contents ...
-            virft (ji,jj) = vicen_init(ji,jj,jl1) * afrft(ji,jj)
-            vsrft (ji,jj) = vsnwn_init(ji,jj,jl1) * afrft(ji,jj)
-            esrft (ji,jj) = esnwn_init(ji,jj,jl1) * afrft(ji,jj)
-            smrft (ji,jj) = smv_i_init(ji,jj,jl1) * afrft(ji,jj) 
-            oirft1(ji,jj) = oa_i_init (ji,jj,jl1) * afrft(ji,jj) 
-            oirft2(ji,jj) = oa_i_init (ji,jj,jl1) * afrft(ji,jj) / kraft 
-
-            ! substract everything
-            a_i(ji,jj,jl1)   = a_i(ji,jj,jl1)   - ardg1 (ji,jj) - arft1 (ji,jj)
-            v_i(ji,jj,jl1)   = v_i(ji,jj,jl1)   - vrdg1 (ji,jj) - virft (ji,jj)
-            v_s(ji,jj,jl1)   = v_s(ji,jj,jl1)   - vsrdg (ji,jj) - vsrft (ji,jj)
-            e_s(ji,jj,1,jl1) = e_s(ji,jj,1,jl1) - esrdg (ji,jj) - esrft (ji,jj)
-            smv_i(ji,jj,jl1) = smv_i(ji,jj,jl1) - srdg1 (ji,jj) - smrft (ji,jj)
-            oa_i(ji,jj,jl1)  = oa_i(ji,jj,jl1)  - oirdg1(ji,jj) - oirft1(ji,jj)
-
-            !-----------------------------------------------------------------
-            ! 3.5) Compute properties of new ridges
-            !-----------------------------------------------------------------
-            !---------
-            ! Salinity
-            !---------
-            smsw(ji,jj)  = vsw(ji,jj) * sss_m(ji,jj)                      ! salt content of seawater frozen in voids !! MV HC2014
-            srdg2(ji,jj) = srdg1(ji,jj) + smsw(ji,jj)                     ! salt content of new ridge
-
-            !srdg2(ji,jj) = MIN( rn_simax * vrdg2(ji,jj) , zsrdg2 )         ! impose a maximum salinity
-            
-            sfx_dyn(ji,jj) = sfx_dyn(ji,jj) - smsw(ji,jj) * rhoic * r1_rdtice
-            wfx_dyn(ji,jj) = wfx_dyn(ji,jj) - vsw (ji,jj) * rhoic * r1_rdtice   ! increase in ice volume du to seawater frozen in voids             
-
-            !------------------------------------            
-            ! 3.6 Increment ridging diagnostics
-            !------------------------------------            
-
-            !        jl1 looping 1-jpl
-            !           ij looping 1-icells
-
-            dardg1dt   (ji,jj) = dardg1dt(ji,jj) + ardg1(ji,jj) + arft1(ji,jj)
-            dardg2dt   (ji,jj) = dardg2dt(ji,jj) + ardg2(ji,jj) + arft2(ji,jj)
-            opening    (ji,jj) = opening (ji,jj) + opning(ji,jj) * rdt_ice
-
-            IF( con_i )   vice_init(ji,jj) = vice_init(ji,jj) + vrdg2(ji,jj) - vrdg1(ji,jj)
-
-            !------------------------------------------            
-            ! 3.7 Put the snow somewhere in the ocean
-            !------------------------------------------            
-            !  Place part of the snow lost by ridging into the ocean. 
-            !  Note that esnow_mlt < 0; the ocean must cool to melt snow.
-            !  If the ocean temp = Tf already, new ice must grow.
-            !  During the next time step, thermo_rates will determine whether
-            !  the ocean cools or new ice grows.
-            !        jl1 looping 1-jpl
-            !           ij looping 1-icells
-
-            msnow_mlt(ji,jj) = msnow_mlt(ji,jj) + rhosn*vsrdg(ji,jj)*(1.0-rn_fsnowrdg)   &   ! rafting included
-               &                                + rhosn*vsrft(ji,jj)*(1.0-rn_fsnowrft)
-
-            ! in J/m2 (same as e_s)
-            esnow_mlt(ji,jj) = esnow_mlt(ji,jj) - esrdg(ji,jj)*(1.0-rn_fsnowrdg)         &   !rafting included
-               &                                - esrft(ji,jj)*(1.0-rn_fsnowrft)          
-
-            !-----------------------------------------------------------------
-            ! 3.8 Compute quantities used to apportion ice among categories
-            ! in the n2 loop below
-            !-----------------------------------------------------------------
-
-            !        jl1 looping 1-jpl
-            !           ij looping 1-icells
-
-            dhr (ji,jj) = hrmax(ji,jj,jl1) - hrmin(ji,jj,jl1)
-            dhr2(ji,jj) = hrmax(ji,jj,jl1) * hrmax(ji,jj,jl1) - hrmin(ji,jj,jl1) * hrmin(ji,jj,jl1)
-
-         END DO
-
-         !--------------------------------------------------------------------
-         ! 3.9 Compute ridging ice enthalpy, remove it from ridging ice and
-         !      compute ridged ice enthalpy 
-         !--------------------------------------------------------------------
-         DO jk = 1, nlay_i
-            DO ij = 1, icells
-               ji = indxi(ij)
-               jj = indxj(ij)
-               ! heat content of ridged ice
-               erdg1(ji,jj,jk)      = eicen_init(ji,jj,jk,jl1) * afrac(ji,jj) 
-               eirft(ji,jj,jk)      = eicen_init(ji,jj,jk,jl1) * afrft(ji,jj)
-               e_i  (ji,jj,jk,jl1)  = e_i(ji,jj,jk,jl1) - erdg1(ji,jj,jk) - eirft(ji,jj,jk)
-               
-               
-               ! enthalpy of the trapped seawater (J/m2, >0)
-               ! clem: if sst>0, then ersw <0 (is that possible?)
-               ersw(ji,jj,jk)   = - rhoic * vsw(ji,jj) * rcp * sst_m(ji,jj) * r1_nlay_i
-
-               ! heat flux to the ocean
-               hfx_dyn(ji,jj) = hfx_dyn(ji,jj) + ersw(ji,jj,jk) * r1_rdtice  ! > 0 [W.m-2] ocean->ice flux 
-
-               ! it is added to sea ice because the sign convention is the opposite of the sign convention for the ocean
-               erdg2(ji,jj,jk)  = erdg1(ji,jj,jk) + ersw(ji,jj,jk)
-
-            END DO
-         END DO
-
-
-         IF( con_i ) THEN
-            DO jk = 1, nlay_i
-               DO ij = 1, icells
-                  ji = indxi(ij)
-                  jj = indxj(ij)
-                  eice_init(ji,jj) = eice_init(ji,jj) + erdg2(ji,jj,jk) - erdg1(ji,jj,jk)
-               END DO
-            END DO
-         ENDIF
-
-         !-------------------------------------------------------------------------------
-         ! 4) Add area, volume, and energy of new ridge to each category jl2
-         !-------------------------------------------------------------------------------
-         !        jl1 looping 1-jpl
-         DO jl2  = 1, jpl 
-            ! over categories to which ridged ice is transferred
-            DO ij = 1, icells
-               ji = indxi(ij)
-               jj = indxj(ij)
-
-               ! Compute the fraction of ridged ice area and volume going to 
-               ! thickness category jl2.
-               ! Transfer area, volume, and energy accordingly.
-
-               IF( hrmin(ji,jj,jl1) >= hi_max(jl2) .OR. hrmax(ji,jj,jl1) <= hi_max(jl2-1) ) THEN
-                  hL = 0._wp
-                  hR = 0._wp
-               ELSE
-                  hL = MAX( hrmin(ji,jj,jl1), hi_max(jl2-1) )
-                  hR = MIN( hrmax(ji,jj,jl1), hi_max(jl2)   )
-               ENDIF
-
-               ! fraction of ridged ice area and volume going to n2
-               farea = ( hR - hL ) / dhr(ji,jj) 
-               fvol(ji,jj) = ( hR*hR - hL*hL ) / dhr2(ji,jj)
-
-               a_i  (ji,jj  ,jl2) = a_i  (ji,jj  ,jl2) + ardg2 (ji,jj) * farea
-               v_i  (ji,jj  ,jl2) = v_i  (ji,jj  ,jl2) + vrdg2 (ji,jj) * fvol(ji,jj)
-               v_s  (ji,jj  ,jl2) = v_s  (ji,jj  ,jl2) + vsrdg (ji,jj) * fvol(ji,jj) * rn_fsnowrdg
-               e_s  (ji,jj,1,jl2) = e_s  (ji,jj,1,jl2) + esrdg (ji,jj) * fvol(ji,jj) * rn_fsnowrdg
-               smv_i(ji,jj  ,jl2) = smv_i(ji,jj  ,jl2) + srdg2 (ji,jj) * fvol(ji,jj)
-               oa_i (ji,jj  ,jl2) = oa_i (ji,jj  ,jl2) + oirdg2(ji,jj) * farea
-
-            END DO
-
-            ! Transfer ice energy to category jl2 by ridging
-            DO jk = 1, nlay_i
-               DO ij = 1, icells
-                  ji = indxi(ij)
-                  jj = indxj(ij)
-                  e_i(ji,jj,jk,jl2) = e_i(ji,jj,jk,jl2) + fvol(ji,jj) * erdg2(ji,jj,jk)
-               END DO
-            END DO
-            !
-         END DO                 ! jl2 (new ridges)            
-
-         DO jl2 = 1, jpl 
-
-            DO ij = 1, icells
-               ji = indxi(ij)
-               jj = indxj(ij)
-               ! Compute the fraction of rafted ice area and volume going to 
-               ! thickness category jl2, transfer area, volume, and energy accordingly.
-               !
-               IF( hraft(ji,jj,jl1) <= hi_max(jl2) .AND. hraft(ji,jj,jl1) >  hi_max(jl2-1) ) THEN
-                  a_i  (ji,jj  ,jl2) = a_i  (ji,jj  ,jl2) + arft2 (ji,jj)
-                  v_i  (ji,jj  ,jl2) = v_i  (ji,jj  ,jl2) + virft (ji,jj)
-                  v_s  (ji,jj  ,jl2) = v_s  (ji,jj  ,jl2) + vsrft (ji,jj) * rn_fsnowrft
-                  e_s  (ji,jj,1,jl2) = e_s  (ji,jj,1,jl2) + esrft (ji,jj) * rn_fsnowrft
-                  smv_i(ji,jj  ,jl2) = smv_i(ji,jj  ,jl2) + smrft (ji,jj)    
-                  oa_i (ji,jj  ,jl2) = oa_i (ji,jj  ,jl2) + oirft2(ji,jj)
-               ENDIF
-               !
-            END DO
-
-            ! Transfer rafted ice energy to category jl2 
-            DO jk = 1, nlay_i
-               DO ij = 1, icells
-                  ji = indxi(ij)
-                  jj = indxj(ij)
-                  IF( hraft(ji,jj,jl1) <= hi_max(jl2) .AND. hraft(ji,jj,jl1) > hi_max(jl2-1)  ) THEN
-                     e_i(ji,jj,jk,jl2) = e_i(ji,jj,jk,jl2) + eirft(ji,jj,jk)
-                  ENDIF
-               END DO
-            END DO
-
-         END DO
-
-      END DO ! jl1 (deforming categories)
-
-      ! Conservation check
-      IF ( con_i ) THEN
-         CALL lim_column_sum (jpl,   v_i, vice_final)
-         fieldid = ' v_i : limitd_me '
-         CALL lim_cons_check (vice_init, vice_final, 1.0e-6, fieldid) 
-
-         CALL lim_column_sum_energy (jpl, nlay_i,  e_i, eice_final )
-         fieldid = ' e_i : limitd_me '
-         CALL lim_cons_check (eice_init, eice_final, 1.0e-2, fieldid) 
-
-         DO ji = mi0(iiceprt), mi1(iiceprt)
-            DO jj = mj0(jiceprt), mj1(jiceprt)
-               WRITE(numout,*) ' vice_init  : ', vice_init (ji,jj)
-               WRITE(numout,*) ' vice_final : ', vice_final(ji,jj)
-               WRITE(numout,*) ' eice_init  : ', eice_init (ji,jj)
-               WRITE(numout,*) ' eice_final : ', eice_final(ji,jj)
-            END DO
-         END DO
-      ENDIF
-      !
-      CALL wrk_dealloc( (jpi+1)*(jpj+1),        indxi, indxj )
-      CALL wrk_dealloc( jpi, jpj,               vice_init, vice_final, eice_init, eice_final )
-      CALL wrk_dealloc( jpi, jpj,               afrac, fvol , ardg1, ardg2, vsrdg, esrdg, dhr, dhr2 )
-      CALL wrk_dealloc( jpi, jpj,               vrdg1, vrdg2, vsw  , srdg1, srdg2, smsw, oirdg1, oirdg2 )
-      CALL wrk_dealloc( jpi, jpj,               afrft, arft1, arft2, virft, vsrft, esrft, smrft, oirft1, oirft2 )
-      CALL wrk_dealloc( jpi, jpj, jpl,          aicen_init, vicen_init, vsnwn_init, esnwn_init, smv_i_init, oa_i_init )
-      CALL wrk_dealloc( jpi, jpj, nlay_i,       eirft, erdg1, erdg2, ersw )
-      CALL wrk_dealloc( jpi, jpj, nlay_i, jpl,  eicen_init )
-      !
-   END SUBROUTINE lim_itd_me_ridgeshift
 
    SUBROUTINE lim_itd_me_init
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limrhg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limrhg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limrhg.F90	(revision 9987)
@@ -159,5 +159,5 @@
       CALL wrk_alloc( jpi,jpj, u_oce2, u_ice2, v_oce1 , v_ice1 , zmask               )
       CALL wrk_alloc( jpi,jpj, zf1   , zu_ice, zf2   , zv_ice , zdt    , zds  )
-      CALL wrk_alloc( jpi,jpj, zdt   , zds   , zs1   , zs2   , zs12   , zresr , zpice                 )
+      CALL wrk_alloc( jpi,jpj, zs1   , zs2   , zs12   , zresr , zpice                 )
 
 #if  defined key_lim2 && ! defined key_lim2_vp
@@ -690,5 +690,5 @@
       CALL wrk_dealloc( jpi,jpj, u_oce2, u_ice2, v_oce1 , v_ice1 , zmask               )
       CALL wrk_dealloc( jpi,jpj, zf1   , zu_ice, zf2   , zv_ice , zdt    , zds  )
-      CALL wrk_dealloc( jpi,jpj, zdt   , zds   , zs1   , zs2   , zs12   , zresr , zpice                 )
+      CALL wrk_dealloc( jpi,jpj, zs1   , zs2   , zs12   , zresr , zpice                 )
 
    END SUBROUTINE lim_rhg
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limsbc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limsbc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limsbc.F90	(revision 9987)
@@ -94,5 +94,5 @@
       !!              - fr_i    : ice fraction
       !!              - tn_ice  : sea-ice surface temperature
-      !!              - alb_ice : sea-ice albedo (only useful in coupled mode)
+      !!              - alb_ice : sea-ice albedo (recomputed only for coupled mode)
       !!
       !! References : Goosse, H. et al. 1996, Bul. Soc. Roy. Sc. Liege, 65, 87-90.
@@ -106,8 +106,10 @@
       REAL(wp) ::   zqsr                                           ! New solar flux received by the ocean
       !
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zalb_cs, zalb_os     ! 2D/3D workspace
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zalb_cs, zalb_os     ! 3D workspace
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   zalb                 ! 2D workspace
       !!---------------------------------------------------------------------
 
       ! make calls for heat fluxes before it is modified
+      ! pfrld is the lead fraction at the previous time step (actually between TRP and THD)
       IF( iom_use('qsr_oce') )   CALL iom_put( "qsr_oce" , qsr_oce(:,:) * pfrld(:,:) )                                   !     solar flux at ocean surface
       IF( iom_use('qns_oce') )   CALL iom_put( "qns_oce" , qns_oce(:,:) * pfrld(:,:) + qemp_oce(:,:) )                   ! non-solar flux at ocean surface
@@ -118,8 +120,24 @@
       IF( iom_use('qt_ice' ) )   CALL iom_put( "qt_ice"  , SUM( ( qns_ice(:,:,:) + qsr_ice(:,:,:) )   &
          &                                                      * a_i_b(:,:,:), dim=3 ) + qemp_ice(:,:) )
-      IF( iom_use('qemp_oce' ) )   CALL iom_put( "qemp_oce"  , qemp_oce(:,:) )  
-      IF( iom_use('qemp_ice' ) )   CALL iom_put( "qemp_ice"  , qemp_ice(:,:) )  
-
-      ! pfrld is the lead fraction at the previous time step (actually between TRP and THD)
+      IF( iom_use('qemp_oce') )  CALL iom_put( "qemp_oce" , qemp_oce(:,:) )  
+      IF( iom_use('qemp_ice') )  CALL iom_put( "qemp_ice" , qemp_ice(:,:) )  
+      IF( iom_use('emp_oce' ) )  CALL iom_put( "emp_oce"  , emp_oce(:,:) )   ! emp over ocean (taking into account the snow blown away from the ice)
+      IF( iom_use('emp_ice' ) )  CALL iom_put( "emp_ice"  , emp_ice(:,:) )   ! emp over ice   (taking into account the snow blown away from the ice)
+
+      ! albedo output
+      CALL wrk_alloc( jpi,jpj, zalb )    
+
+      zalb(:,:) = 0._wp
+      WHERE     ( SUM( a_i_b, dim=3 ) <= epsi06 )  ;  zalb(:,:) = 0.066_wp
+      ELSEWHERE                                    ;  zalb(:,:) = SUM( alb_ice * a_i_b, dim=3 ) / SUM( a_i_b, dim=3 )
+      END WHERE
+      IF( iom_use('alb_ice' ) )  CALL iom_put( "alb_ice"  , zalb(:,:) )           ! ice albedo output
+
+      zalb(:,:) = SUM( alb_ice * a_i_b, dim=3 ) + 0.066_wp * ( 1._wp - SUM( a_i_b, dim=3 ) )      
+      IF( iom_use('albedo'  ) )  CALL iom_put( "albedo"  , zalb(:,:) )           ! ice albedo output
+
+      CALL wrk_dealloc( jpi,jpj, zalb )    
+      !
+      
       DO jj = 1, jpj
          DO ji = 1, jpi
@@ -140,10 +158,11 @@
             hfx_out(ji,jj) = hfx_out(ji,jj) + zqmass + zqsr
 
-            ! Add the residual from heat diffusion equation (W.m-2)
-            !-------------------------------------------------------
-            hfx_out(ji,jj) = hfx_out(ji,jj) + hfx_err_dif(ji,jj)
+            ! Add the residual from heat diffusion equation and sublimation (W.m-2)
+            !----------------------------------------------------------------------
+            hfx_out(ji,jj) = hfx_out(ji,jj) + hfx_err_dif(ji,jj) +   &
+               &           ( hfx_sub(ji,jj) - SUM( qevap_ice(ji,jj,:) * a_i_b(ji,jj,:) ) )
 
             ! New qsr and qns used to compute the oceanic heat flux at the next time step
-            !---------------------------------------------------
+            !----------------------------------------------------------------------------
             qsr(ji,jj) = zqsr                                      
             qns(ji,jj) = hfx_out(ji,jj) - zqsr              
@@ -165,7 +184,6 @@
 
             ! mass flux at the ocean/ice interface
-            fmmflx(ji,jj) = - ( wfx_ice(ji,jj) + wfx_snw(ji,jj) ) * r1_rdtice  ! F/M mass flux save at least for biogeochemical model
-            emp(ji,jj)    = emp_oce(ji,jj) - wfx_ice(ji,jj) - wfx_snw(ji,jj)   ! mass flux + F/M mass flux (always ice/ocean mass exchange)
-            
+            fmmflx(ji,jj) = - ( wfx_ice(ji,jj) + wfx_snw(ji,jj) + wfx_err_sub(ji,jj) )              ! F/M mass flux save at least for biogeochemical model
+            emp(ji,jj)    = emp_oce(ji,jj) - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_err_sub(ji,jj)   ! mass flux + F/M mass flux (always ice/ocean mass exchange)
          END DO
       END DO
@@ -175,5 +193,5 @@
       !------------------------------------------!
       sfx(:,:) = sfx_bog(:,:) + sfx_bom(:,:) + sfx_sum(:,:) + sfx_sni(:,:) + sfx_opw(:,:)   &
-         &     + sfx_res(:,:) + sfx_dyn(:,:) + sfx_bri(:,:)
+         &     + sfx_res(:,:) + sfx_dyn(:,:) + sfx_bri(:,:) + sfx_sub(:,:)
 
       !-------------------------------------------------------------!
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd.F90	(revision 9987)
@@ -461,5 +461,5 @@
 
       DO ji = kideb, kiut
-         zdh_mel = MIN( 0._wp, dh_i_surf(ji) + dh_i_bott(ji) + dh_snowice(ji) )
+         zdh_mel = MIN( 0._wp, dh_i_surf(ji) + dh_i_bott(ji) + dh_snowice(ji) + dh_i_sub(ji) )
          IF( zdh_mel < 0._wp .AND. a_i_1d(ji) > 0._wp )  THEN
             zvi          = a_i_1d(ji) * ht_i_1d(ji)
@@ -470,5 +470,5 @@
             zda_mel     = rswitch * a_i_1d(ji) * zdh_mel / ( 2._wp * MAX( zhi_bef, epsi20 ) )
             a_i_1d(ji)  = MAX( epsi20, a_i_1d(ji) + zda_mel ) 
-             ! adjust thickness
+            ! adjust thickness
             ht_i_1d(ji) = zvi / a_i_1d(ji)            
             ht_s_1d(ji) = zvs / a_i_1d(ji)            
@@ -514,4 +514,5 @@
          
          CALL tab_2d_1d( nbpb, qprec_ice_1d(1:nbpb), qprec_ice(:,:) , jpi, jpj, npb(1:nbpb) )
+         CALL tab_2d_1d( nbpb, qevap_ice_1d(1:nbpb), qevap_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
          CALL tab_2d_1d( nbpb, qsr_ice_1d (1:nbpb), qsr_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
          CALL tab_2d_1d( nbpb, fr1_i0_1d  (1:nbpb), fr1_i0          , jpi, jpj, npb(1:nbpb) )
@@ -543,5 +544,6 @@
          CALL tab_2d_1d( nbpb, sfx_bri_1d (1:nbpb), sfx_bri         , jpi, jpj, npb(1:nbpb) )
          CALL tab_2d_1d( nbpb, sfx_res_1d (1:nbpb), sfx_res         , jpi, jpj, npb(1:nbpb) )
-         
+         CALL tab_2d_1d( nbpb, sfx_sub_1d (1:nbpb), sfx_sub         , jpi, jpj,npb(1:nbpb) )
+ 
          CALL tab_2d_1d( nbpb, hfx_thd_1d (1:nbpb), hfx_thd         , jpi, jpj, npb(1:nbpb) )
          CALL tab_2d_1d( nbpb, hfx_spr_1d (1:nbpb), hfx_spr         , jpi, jpj, npb(1:nbpb) )
@@ -593,5 +595,6 @@
          CALL tab_1d_2d( nbpb, sfx_res       , npb, sfx_res_1d(1:nbpb)   , jpi, jpj )
          CALL tab_1d_2d( nbpb, sfx_bri       , npb, sfx_bri_1d(1:nbpb)   , jpi, jpj )
-         
+         CALL tab_1d_2d( nbpb, sfx_sub       , npb, sfx_sub_1d(1:nbpb)   , jpi, jpj )        
+ 
          CALL tab_1d_2d( nbpb, hfx_thd       , npb, hfx_thd_1d(1:nbpb)   , jpi, jpj )
          CALL tab_1d_2d( nbpb, hfx_spr       , npb, hfx_spr_1d(1:nbpb)   , jpi, jpj )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_dh.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_dh.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_dh.F90	(revision 9987)
@@ -74,5 +74,5 @@
 
       REAL(wp) ::   ztmelts             ! local scalar
-      REAL(wp) ::   zfdum       
+      REAL(wp) ::   zdum       
       REAL(wp) ::   zfracs       ! fractionation coefficient for bottom salt entrapment
       REAL(wp) ::   zs_snic      ! snow-ice salinity
@@ -95,4 +95,5 @@
       REAL(wp), POINTER, DIMENSION(:) ::   zq_rema     ! remaining heat at the end of the routine    (J.m-2)
       REAL(wp), POINTER, DIMENSION(:) ::   zf_tt       ! Heat budget to determine melting or freezing(W.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zevap_rema  ! remaining mass flux from sublimation        (kg.m-2)
 
       REAL(wp), POINTER, DIMENSION(:) ::   zdh_s_mel   ! snow melt 
@@ -105,6 +106,4 @@
 
       REAL(wp), POINTER, DIMENSION(:) ::   zqh_i       ! total ice heat content  (J.m-2)
-      REAL(wp), POINTER, DIMENSION(:) ::   zqh_s       ! total snow heat content (J.m-2)
-      REAL(wp), POINTER, DIMENSION(:) ::   zq_s        ! total snow enthalpy     (J.m-3)
       REAL(wp), POINTER, DIMENSION(:) ::   zsnw        ! distribution of snow after wind blowing
 
@@ -117,21 +116,20 @@
 
       ! Discriminate between varying salinity (nn_icesal=2) and prescribed cases (other values)
-      SELECT CASE( nn_icesal )                       ! varying salinity or not
-         CASE( 1, 3, 4 ) ;   zswitch_sal = 0       ! prescribed salinity profile
-         CASE( 2 )       ;   zswitch_sal = 1       ! varying salinity profile
+      SELECT CASE( nn_icesal )                  ! varying salinity or not
+         CASE( 1, 3 ) ;   zswitch_sal = 0       ! prescribed salinity profile
+         CASE( 2 )    ;   zswitch_sal = 1       ! varying salinity profile
       END SELECT
 
-      CALL wrk_alloc( jpij, zqprec, zq_su, zq_bo, zf_tt, zq_rema, zsnw )
-      CALL wrk_alloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zqh_i, zqh_s, zq_s )
+      CALL wrk_alloc( jpij, zqprec, zq_su, zq_bo, zf_tt, zq_rema, zsnw, zevap_rema )
+      CALL wrk_alloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zqh_i )
       CALL wrk_alloc( jpij, nlay_i, zdeltah, zh_i )
       CALL wrk_alloc( jpij, nlay_i, icount )
        
-      dh_i_surf  (:) = 0._wp ; dh_i_bott  (:) = 0._wp ; dh_snowice(:) = 0._wp
+      dh_i_surf  (:) = 0._wp ; dh_i_bott  (:) = 0._wp ; dh_snowice(:) = 0._wp ; dh_i_sub(:) = 0._wp
       dsm_i_se_1d(:) = 0._wp ; dsm_i_si_1d(:) = 0._wp   
 
       zqprec   (:) = 0._wp ; zq_su    (:) = 0._wp ; zq_bo    (:) = 0._wp ; zf_tt(:) = 0._wp
-      zq_rema  (:) = 0._wp ; zsnw     (:) = 0._wp
+      zq_rema  (:) = 0._wp ; zsnw     (:) = 0._wp ; zevap_rema(:) = 0._wp ;
       zdh_s_mel(:) = 0._wp ; zdh_s_pre(:) = 0._wp ; zdh_s_sub(:) = 0._wp ; zqh_i(:) = 0._wp
-      zqh_s    (:) = 0._wp ; zq_s     (:) = 0._wp     
 
       zdeltah(:,:) = 0._wp ; zh_i(:,:) = 0._wp       
@@ -159,8 +157,8 @@
       !
       DO ji = kideb, kiut
-         zfdum      = qns_ice_1d(ji) + ( 1._wp - i0(ji) ) * qsr_ice_1d(ji) - fc_su(ji) 
+         zdum       = qns_ice_1d(ji) + ( 1._wp - i0(ji) ) * qsr_ice_1d(ji) - fc_su(ji) 
          zf_tt(ji)  = fc_bo_i(ji) + fhtur_1d(ji) + fhld_1d(ji) 
 
-         zq_su (ji) = MAX( 0._wp, zfdum     * rdt_ice ) * MAX( 0._wp , SIGN( 1._wp, t_su_1d(ji) - rt0 ) )
+         zq_su (ji) = MAX( 0._wp, zdum      * rdt_ice ) * MAX( 0._wp , SIGN( 1._wp, t_su_1d(ji) - rt0 ) )
          zq_bo (ji) = MAX( 0._wp, zf_tt(ji) * rdt_ice )
       END DO
@@ -187,10 +185,4 @@
       !  2) Computing layer thicknesses and enthalpies.            !
       !------------------------------------------------------------!
-      !
-      DO jk = 1, nlay_s
-         DO ji = kideb, kiut
-            zqh_s(ji) =  zqh_s(ji) + q_s_1d(ji,jk) * ht_s_1d(ji) * r1_nlay_s
-         END DO
-      END DO
       !
       DO jk = 1, nlay_i
@@ -275,17 +267,15 @@
       END DO
 
-      !----------------------
-      ! 3.2 Snow sublimation 
-      !----------------------
+      !------------------------------
+      ! 3.2 Sublimation (part1: snow) 
+      !------------------------------
       ! qla_ice is always >=0 (upwards), heat goes to the atmosphere, therefore snow sublimates
       ! clem comment: not counted in mass/heat exchange in limsbc since this is an exchange with atm. (not ocean)
-      ! clem comment: ice should also sublimate
       zdeltah(:,:) = 0._wp
-      ! coupled mode: sublimation is set to 0 (evap_ice = 0) until further notice
-      ! forced  mode: snow thickness change due to sublimation
-      DO ji = kideb, kiut
-         zdh_s_sub(ji)  =  MAX( - ht_s_1d(ji) , - evap_ice_1d(ji) * r1_rhosn * rdt_ice )
-         ! Heat flux by sublimation [W.m-2], < 0
-         !      sublimate first snow that had fallen, then pre-existing snow
+      DO ji = kideb, kiut
+         zdh_s_sub(ji)  = MAX( - ht_s_1d(ji) , - evap_ice_1d(ji) * r1_rhosn * rdt_ice )
+         ! remaining evap in kg.m-2 (used for ice melting later on)
+         zevap_rema(ji)  = evap_ice_1d(ji) * rdt_ice + zdh_s_sub(ji) * rhosn
+         ! Heat flux by sublimation [W.m-2], < 0 (sublimate first snow that had fallen, then pre-existing snow)
          zdeltah(ji,1)  = MAX( zdh_s_sub(ji), - zdh_s_pre(ji) )
          hfx_sub_1d(ji) = hfx_sub_1d(ji) + ( zdeltah(ji,1) * zqprec(ji) + ( zdh_s_sub(ji) - zdeltah(ji,1) ) * q_s_1d(ji,1)  &
@@ -309,12 +299,10 @@
       !-------------------------------------------
       ! new temp and enthalpy of the snow (remaining snow precip + remaining pre-existing snow)
-      zq_s(:) = 0._wp 
       DO jk = 1, nlay_s
          DO ji = kideb,kiut
-            rswitch       = MAX(  0._wp , SIGN( 1._wp, ht_s_1d(ji) - epsi20 )  )
-            q_s_1d(ji,jk) = rswitch / MAX( ht_s_1d(ji), epsi20 ) *                          &
-              &            ( (   zdh_s_pre(ji)             ) * zqprec(ji) +  &
-              &              (   ht_s_1d(ji) - zdh_s_pre(ji) ) * rhosn * ( cpic * ( rt0 - t_s_1d(ji,jk) ) + lfus ) )
-            zq_s(ji)     =  zq_s(ji) + q_s_1d(ji,jk)
+            rswitch       = MAX( 0._wp , SIGN( 1._wp, ht_s_1d(ji) - epsi20 ) )
+            q_s_1d(ji,jk) = rswitch / MAX( ht_s_1d(ji), epsi20 ) *           &
+              &            ( ( zdh_s_pre(ji)               ) * zqprec(ji) +  &
+              &              ( ht_s_1d(ji) - zdh_s_pre(ji) ) * rhosn * ( cpic * ( rt0 - t_s_1d(ji,jk) ) + lfus ) )
          END DO
       END DO
@@ -370,5 +358,5 @@
                zQm            = zfmdt * zEw                           ! Energy of the melt water sent to the ocean [J/m2, <0]
                
-               ! Contribution to salt flux (clem: using sm_i_1d and not s_i_1d(jk) is ok)
+               ! Contribution to salt flux >0 (clem: using sm_i_1d and not s_i_1d(jk) is ok)
                sfx_sum_1d(ji) = sfx_sum_1d(ji) - rhoic * a_i_1d(ji) * zdeltah(ji,jk) * sm_i_1d(ji) * r1_rdtice
                
@@ -383,4 +371,20 @@
                
             END IF
+            ! ----------------------
+            ! Sublimation part2: ice
+            ! ----------------------
+            zdum      = MAX( - ( zh_i(ji,jk) + zdeltah(ji,jk) ) , - zevap_rema(ji) * r1_rhoic )
+            zdeltah(ji,jk) = zdeltah(ji,jk) + zdum
+            dh_i_sub(ji)  = dh_i_sub(ji) + zdum
+            ! Salt flux > 0 (clem2016: flux is sent to the ocean for simplicity but salt should remain in the ice except if all ice is melted.
+            !                          It must be corrected at some point)
+            sfx_sub_1d(ji) = sfx_sub_1d(ji) - rhoic * a_i_1d(ji) * zdum * sm_i_1d(ji) * r1_rdtice
+            ! Heat flux [W.m-2], < 0
+            hfx_sub_1d(ji) = hfx_sub_1d(ji) + zdum * q_i_1d(ji,jk) * a_i_1d(ji) * r1_rdtice
+            ! Mass flux > 0
+            wfx_sub_1d(ji) =  wfx_sub_1d(ji) - rhoic * a_i_1d(ji) * zdum * r1_rdtice
+            ! update remaining mass flux
+            zevap_rema(ji)  = zevap_rema(ji) + zdum * rhoic
+            
             ! record which layers have disappeared (for bottom melting) 
             !    => icount=0 : no layer has vanished
@@ -389,5 +393,5 @@
             icount(ji,jk) = NINT( rswitch )
             zh_i(ji,jk)   = MAX( 0._wp , zh_i(ji,jk) + zdeltah(ji,jk) )
-
+                        
             ! update heat content (J.m-2) and layer thickness
             qh_i_old(ji,jk) = qh_i_old(ji,jk) + zdeltah(ji,jk) * q_i_1d(ji,jk)
@@ -397,5 +401,11 @@
       ! update ice thickness
       DO ji = kideb, kiut
-         ht_i_1d(ji) =  MAX( 0._wp , ht_i_1d(ji) + dh_i_surf(ji) )
+         ht_i_1d(ji) =  MAX( 0._wp , ht_i_1d(ji) + dh_i_surf(ji) + dh_i_sub(ji) )
+      END DO
+
+      ! remaining "potential" evap is sent to ocean
+      DO ji = kideb, kiut
+         ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
+         wfx_err_sub(ii,ij) = wfx_err_sub(ii,ij) - zevap_rema(ji) * a_i_1d(ji) * r1_rdtice  ! <=0 (net evap for the ocean in kg.m-2.s-1)
       END DO
 
@@ -641,5 +651,4 @@
 
          ! Contribution to energy flux to the ocean [J/m2], >0 (if sst<0)
-         ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
          zfmdt          = ( rhosn - rhoic ) * MAX( dh_snowice(ji), 0._wp )    ! <0
          zsstK          = sst_m(ii,ij) + rt0                                
@@ -652,4 +661,10 @@
          ! Contribution to salt flux
          sfx_sni_1d(ji) = sfx_sni_1d(ji) + sss_m(ii,ij) * a_i_1d(ji) * zfmdt * r1_rdtice 
+
+         ! virtual salt flux to keep salinity constant
+         IF( nn_icesal == 1 .OR. nn_icesal == 3 )  THEN
+            sfx_bri_1d(ji) = sfx_bri_1d(ji) - sss_m(ii,ij) * a_i_1d(ji) * zfmdt                  * r1_rdtice  & ! put back sss_m into the ocean
+               &                            - sm_i_1d(ji)  * a_i_1d(ji) * dh_snowice(ji) * rhoic * r1_rdtice    ! and get  sm_i  from the ocean 
+         ENDIF
           
          ! Contribution to mass flux
@@ -686,6 +701,6 @@
       WHERE( ht_i_1d == 0._wp ) a_i_1d = 0._wp
       
-      CALL wrk_dealloc( jpij, zqprec, zq_su, zq_bo, zf_tt, zq_rema, zsnw )
-      CALL wrk_dealloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zqh_i, zqh_s, zq_s )
+      CALL wrk_dealloc( jpij, zqprec, zq_su, zq_bo, zf_tt, zq_rema, zsnw, zevap_rema )
+      CALL wrk_dealloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zqh_i )
       CALL wrk_dealloc( jpij, nlay_i, zdeltah, zh_i )
       CALL wrk_dealloc( jpij, nlay_i, icount )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_lac.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_lac.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_lac.F90	(revision 9987)
@@ -75,7 +75,6 @@
       INTEGER ::   ii, ij, iter     !   -       -
       REAL(wp)  ::   ztmelts, zdv, zfrazb, zweight, zde                         ! local scalars
-      REAL(wp) ::   zgamafr, zvfrx, zvgx, ztaux, ztwogp, zf , zhicol_new        !   -      -
+      REAL(wp) ::   zgamafr, zvfrx, zvgx, ztaux, ztwogp, zf                     !   -      -
       REAL(wp) ::   ztenagm, zvfry, zvgy, ztauy, zvrel2, zfp, zsqcd , zhicrit   !   -      -
-      LOGICAL  ::   iterate_frazil   ! iterate frazil ice collection thickness
       CHARACTER (len = 15) :: fieldid
 
@@ -108,9 +107,9 @@
       REAL(wp), POINTER, DIMENSION(:,:) ::   zsmv_i_1d ! 1-D version of smv_i
 
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ze_i_1d   !: 1-D version of e_i
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zvrel                   ! relative ice / frazil velocity
-
-      REAL(wp) :: zcai = 1.4e-3_wp
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ze_i_1d !: 1-D version of e_i
+
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zvrel     ! relative ice / frazil velocity
+
+      REAL(wp) :: zcai = 1.4e-3_wp                     ! ice-air drag (clem: should be dependent on coupling/forcing used)
       !!-----------------------------------------------------------------------!
 
@@ -143,6 +142,5 @@
       !------------------------------------------------------------------------------!    
       ! hicol is the thickness of new ice formed in open water
-      ! hicol can be either prescribed (frazswi = 0)
-      ! or computed (frazswi = 1)
+      ! hicol can be either prescribed (frazswi = 0) or computed (frazswi = 1)
       ! Frazil ice forms in open water, is transported by wind
       ! accumulates at the edge of the consolidated ice edge
@@ -155,6 +153,8 @@
       zvrel(:,:) = 0._wp
 
-      ! Default new ice thickness 
-      hicol(:,:) = rn_hnewice
+      ! Default new ice thickness
+      WHERE( qlead(:,:) < 0._wp ) ; hicol = rn_hnewice
+      ELSEWHERE                   ; hicol = 0._wp
+      END WHERE
 
       IF( ln_frazil ) THEN
@@ -182,5 +182,5 @@
                      &          +   vtau_ice(ji  ,jj  ) * vmask(ji  ,jj  ,1) ) * 0.5_wp
                   ! Square root of wind stress
-                  ztenagm       =  SQRT( SQRT( ztaux**2 + ztauy**2 ) )
+                  ztenagm       =  SQRT( SQRT( ztaux * ztaux + ztauy * ztauy ) )
 
                   !---------------------
@@ -205,41 +205,29 @@
                   zvrel2 = MAX(  ( zvfrx - zvgx ) * ( zvfrx - zvgx )   &
                      &         + ( zvfry - zvgy ) * ( zvfry - zvgy ) , 0.15 * 0.15 )
-                  zvrel(ji,jj)  = SQRT( zvrel2 )
+                  zvrel(ji,jj) = SQRT( zvrel2 )
 
                   !---------------------
                   ! Iterative procedure
                   !---------------------
-                  hicol(ji,jj) = zhicrit + 0.1 
-                  hicol(ji,jj) = zhicrit +   hicol(ji,jj)    &
-                     &                   / ( hicol(ji,jj) * hicol(ji,jj) -  zhicrit * zhicrit ) * ztwogp * zvrel2
-
-!!gm better coding: above: hicol(ji,jj) * hicol(ji,jj) = (zhicrit + 0.1)*(zhicrit + 0.1)
-!!gm                                                   = zhicrit**2 + 0.2*zhicrit +0.01
-!!gm                therefore the 2 lines with hicol can be replaced by 1 line:
-!!gm              hicol(ji,jj) = zhicrit + (zhicrit + 0.1) / ( 0.2 * zhicrit + 0.01 ) * ztwogp * zvrel2
-!!gm further more (zhicrit + 0.1)/(0.2 * zhicrit + 0.01 )*ztwogp can be computed one for all outside the DO loop
+                  hicol(ji,jj) = zhicrit +   ( zhicrit + 0.1 )    &
+                     &                   / ( ( zhicrit + 0.1 ) * ( zhicrit + 0.1 ) -  zhicrit * zhicrit ) * ztwogp * zvrel2
 
                   iter = 1
-                  iterate_frazil = .true.
-
-                  DO WHILE ( iter < 100 .AND. iterate_frazil ) 
-                     zf = ( hicol(ji,jj) - zhicrit ) * ( hicol(ji,jj)**2 - zhicrit**2 ) &
-                        - hicol(ji,jj) * zhicrit * ztwogp * zvrel2
-                     zfp = ( hicol(ji,jj) - zhicrit ) * ( 3.0*hicol(ji,jj) + zhicrit ) &
-                        - zhicrit * ztwogp * zvrel2
-                     zhicol_new = hicol(ji,jj) - zf/zfp
-                     hicol(ji,jj)   = zhicol_new
-
+                  DO WHILE ( iter < 20 ) 
+                     zf  = ( hicol(ji,jj) - zhicrit ) * ( hicol(ji,jj) * hicol(ji,jj) - zhicrit * zhicrit ) -   &
+                        &    hicol(ji,jj) * zhicrit * ztwogp * zvrel2
+                     zfp = ( hicol(ji,jj) - zhicrit ) * ( 3.0 * hicol(ji,jj) + zhicrit ) - zhicrit * ztwogp * zvrel2
+
+                     hicol(ji,jj) = hicol(ji,jj) - zf/zfp
                      iter = iter + 1
-
-                  END DO ! do while
+                  END DO
 
                ENDIF ! end of selection of pixels where ice forms
 
-            END DO ! loop on ji ends
-         END DO ! loop on jj ends
-      ! 
-      CALL lbc_lnk( zvrel(:,:), 'T', 1. )
-      CALL lbc_lnk( hicol(:,:), 'T', 1. )
+            END DO 
+         END DO 
+         ! 
+         CALL lbc_lnk( zvrel(:,:), 'T', 1. )
+         CALL lbc_lnk( hicol(:,:), 'T', 1. )
 
       ENDIF ! End of computation of frazil ice collection thickness
@@ -282,6 +270,5 @@
       ! Move from 2-D to 1-D vectors
       !------------------------------
-      ! If ocean gains heat do nothing 
-      ! 0therwise compute new ice formation
+      ! If ocean gains heat do nothing. Otherwise compute new ice formation
 
       IF ( nbpac > 0 ) THEN
@@ -297,13 +284,14 @@
          END DO
 
-         CALL tab_2d_1d( nbpac, qlead_1d  (1:nbpac)     , qlead  , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, t_bo_1d   (1:nbpac)     , t_bo   , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, sfx_opw_1d(1:nbpac)     , sfx_opw, jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, wfx_opw_1d(1:nbpac)     , wfx_opw, jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, hicol_1d  (1:nbpac)     , hicol  , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, zvrel_1d  (1:nbpac)     , zvrel  , jpi, jpj, npac(1:nbpac) )
-
-         CALL tab_2d_1d( nbpac, hfx_thd_1d(1:nbpac)     , hfx_thd, jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, hfx_opw_1d(1:nbpac)     , hfx_opw, jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, qlead_1d  (1:nbpac)     , qlead     , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, t_bo_1d   (1:nbpac)     , t_bo      , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, sfx_opw_1d(1:nbpac)     , sfx_opw   , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, wfx_opw_1d(1:nbpac)     , wfx_opw   , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, hicol_1d  (1:nbpac)     , hicol     , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, zvrel_1d  (1:nbpac)     , zvrel     , jpi, jpj, npac(1:nbpac) )
+
+         CALL tab_2d_1d( nbpac, hfx_thd_1d(1:nbpac)     , hfx_thd   , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, hfx_opw_1d(1:nbpac)     , hfx_opw   , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, rn_amax_1d(1:nbpac)     , rn_amax_2d, jpi, jpj, npac(1:nbpac) )
 
          !------------------------------------------------------------------------------!
@@ -316,11 +304,9 @@
          zv_b(1:nbpac,:) = zv_i_1d(1:nbpac,:) 
          za_b(1:nbpac,:) = za_i_1d(1:nbpac,:)
+
          !----------------------
          ! Thickness of new ice
          !----------------------
-         DO ji = 1, nbpac
-            zh_newice(ji) = rn_hnewice
-         END DO
-         IF( ln_frazil ) zh_newice(1:nbpac) = hicol_1d(1:nbpac)
+         zh_newice(1:nbpac) = hicol_1d(1:nbpac)
 
          !----------------------
@@ -384,12 +370,17 @@
             ! salt flux
             sfx_opw_1d(ji) = sfx_opw_1d(ji) - zv_newice(ji) * rhoic * zs_newice(ji) * r1_rdtice
-
+         END DO
+         
+         zv_frazb(:) = 0._wp
+         IF( ln_frazil ) THEN
             ! A fraction zfrazb of frazil ice is accreted at the ice bottom
-            rswitch       = 1._wp - MAX( 0._wp, SIGN( 1._wp , - zat_i_1d(ji) ) )
-            zfrazb        = rswitch * ( TANH ( rn_Cfrazb * ( zvrel_1d(ji) - rn_vfrazb ) ) + 1.0 ) * 0.5 * rn_maxfrazb
-            zv_frazb(ji)  =         zfrazb   * zv_newice(ji)
-            zv_newice(ji) = ( 1.0 - zfrazb ) * zv_newice(ji)
-         END DO
-
+            DO ji = 1, nbpac
+               rswitch       = 1._wp - MAX( 0._wp, SIGN( 1._wp , - zat_i_1d(ji) ) )
+               zfrazb        = rswitch * ( TANH( rn_Cfrazb * ( zvrel_1d(ji) - rn_vfrazb ) ) + 1.0 ) * 0.5 * rn_maxfrazb
+               zv_frazb(ji)  =         zfrazb   * zv_newice(ji)
+               zv_newice(ji) = ( 1.0 - zfrazb ) * zv_newice(ji)
+            END DO
+         END IF
+         
          !-----------------
          ! Area of new ice
@@ -409,6 +400,6 @@
          ! we keep the excessive volume in memory and attribute it later to bottom accretion
          DO ji = 1, nbpac
-            IF ( za_newice(ji) >  ( rn_amax - zat_i_1d(ji) ) ) THEN
-               zda_res(ji)   = za_newice(ji) - ( rn_amax - zat_i_1d(ji) )
+            IF ( za_newice(ji) >  ( rn_amax_1d(ji) - zat_i_1d(ji) ) ) THEN
+               zda_res(ji)   = za_newice(ji) - ( rn_amax_1d(ji) - zat_i_1d(ji) )
                zdv_res(ji)   = zda_res  (ji) * zh_newice(ji) 
                za_newice(ji) = za_newice(ji) - zda_res  (ji)
@@ -443,5 +434,5 @@
                jl = jcat(ji)
                rswitch = MAX( 0._wp, SIGN( 1._wp , zv_i_1d(ji,jl) - epsi20 ) )
-               ze_i_1d(ji,jk,jl) = zswinew(ji)   *   ze_newice(ji) +                                                      &
+               ze_i_1d(ji,jk,jl) = zswinew(ji)   *   ze_newice(ji) +                                                    &
                   &        ( 1.0 - zswinew(ji) ) * ( ze_newice(ji) * zv_newice(ji) + ze_i_1d(ji,jk,jl) * zv_b(ji,jl) )  &
                   &        * rswitch / MAX( zv_i_1d(ji,jl), epsi20 )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_sal.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_sal.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limthd_sal.F90	(revision 9987)
@@ -62,18 +62,12 @@
       END DO
  
-      !------------------------------------------------------------------------------|
-      ! 1) Constant salinity, constant in time                                       |
-      !------------------------------------------------------------------------------|
-!!gm comment: if nn_icesal = 1 s_i_new, s_i_1d and sm_i_1d can be set to rn_icesal one for all in the initialisation phase !!
-!!gm           ===>>>   simplification of almost all test on nn_icesal value
-      IF(  nn_icesal == 1  ) THEN
-            s_i_1d (kideb:kiut,1:nlay_i) =  rn_icesal
-            sm_i_1d(kideb:kiut)          =  rn_icesal 
-            s_i_new(kideb:kiut)          =  rn_icesal
-      ENDIF
+      !--------------------------------------------------------------------|
+      ! 1) salinity constant in time                                       |
+      !--------------------------------------------------------------------|
+      ! do nothing
 
-      !------------------------------------------------------------------------------|
-      !  Module 2 : Constant salinity varying in time                                |
-      !------------------------------------------------------------------------------|
+      !----------------------------------------------------------------------|
+      !  2) salinity varying in time                                         |
+      !----------------------------------------------------------------------|
       IF(  nn_icesal == 2  ) THEN
 
@@ -113,5 +107,5 @@
 
       !------------------------------------------------------------------------------|
-      !  Module 3 : Profile of salinity, constant in time                            |
+      !  3) vertical profile of salinity, constant in time                           |
       !------------------------------------------------------------------------------|
       IF(  nn_icesal == 3  )   CALL lim_var_salprof1d( kideb, kiut )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limtrp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limtrp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limtrp.F90	(revision 9987)
@@ -63,5 +63,5 @@
       INTEGER, INTENT(in) ::   kt           ! number of iteration
       !
-      INTEGER  ::   ji, jj, jk, jl, jt      ! dummy loop indices
+      INTEGER  ::   ji, jj, jk, jm , jl, jt      ! dummy loop indices
       INTEGER  ::   initad                  ! number of sub-timestep for the advection
       REAL(wp) ::   zcfl , zusnit           !   -      -
@@ -75,6 +75,11 @@
       REAL(wp), POINTER, DIMENSION(:,:,:)    ::   zhimax                   ! old ice thickness
       REAL(wp), POINTER, DIMENSION(:,:)      ::   zatold, zeiold, zesold   ! old concentration, enthalpies
+      REAL(wp), POINTER, DIMENSION(:,:,:)             ::   zhdfptab
       REAL(wp) ::    zdv, zvi, zvs, zsmv, zes, zei
       REAL(wp) ::    zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b
+      !!---------------------------------------------------------------------
+      INTEGER                                ::  ihdf_vars  = 6  !!Number of variables in which we apply horizontal diffusion
+                                                                   !!  inside limtrp for each ice category , not counting the 
+                                                                   !!  variables corresponding to ice_layers 
       !!---------------------------------------------------------------------
       IF( nn_timing == 1 )  CALL timing_start('limtrp')
@@ -85,4 +90,5 @@
       CALL wrk_alloc( jpi,jpj,nlay_i,jpl, z0ei )
       CALL wrk_alloc( jpi,jpj,jpl,        zhimax, zviold, zvsold, zsmvold )
+      CALL wrk_alloc( jpi,jpj,jpl*(ihdf_vars + nlay_i)+1,zhdfptab)
 
       IF( numit == nstart .AND. lwp ) THEN
@@ -170,5 +176,5 @@
             z0oi (:,:,jl)   = oa_i (:,:,jl) * e12t(:,:)    ! Age content
             z0es (:,:,jl)   = e_s  (:,:,1,jl) * e12t(:,:)  ! Snow heat content
-            DO jk = 1, nlay_i
+           DO jk = 1, nlay_i
                z0ei  (:,:,jk,jl) = e_i  (:,:,jk,jl) * e12t(:,:) ! Ice  heat content
             END DO
@@ -284,5 +290,43 @@
          ! Diffusion of Ice fields                  
          !------------------------------------------------------------------------------!
-
+         !------------------------------------
+         !  Diffusion of other ice variables
+         !------------------------------------
+         jm=1
+         DO jl = 1, jpl
+         !                             ! Masked eddy diffusivity coefficient at ocean U- and V-points
+         !   DO jj = 1, jpjm1                 ! NB: has not to be defined on jpj line and jpi row
+         !      DO ji = 1 , fs_jpim1   ! vector opt.
+         !         pahu(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji  ,jj,jl) ) ) )   &
+         !            &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji+1,jj,jl) ) ) ) * ahiu(ji,jj)
+         !         pahv(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji,jj  ,jl) ) ) )   &
+         !            &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- a_i(ji,jj+1,jl) ) ) ) * ahiv(ji,jj)
+         !      END DO
+         !   END DO
+            DO jj = 1, jpjm1                 ! NB: has not to be defined on jpj line and jpi row
+               DO ji = 1 , fs_jpim1   ! vector opt.
+                  pahu3D(ji,jj,jl) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji  ,jj,  jl ) ) ) )   &
+                  &                * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji+1,jj,  jl ) ) ) ) * ahiu(ji,jj)
+                  pahv3D(ji,jj,jl) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji,  jj,  jl ) ) ) )   &
+                  &                * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- a_i(ji,  jj+1,jl ) ) ) ) * ahiv(ji,jj)
+               END DO
+            END DO
+
+            zhdfptab(:,:,jm)= a_i  (:,:,  jl); jm = jm + 1    
+            zhdfptab(:,:,jm)= v_i  (:,:,  jl); jm = jm + 1
+            zhdfptab(:,:,jm)= v_s  (:,:,  jl); jm = jm + 1 
+            zhdfptab(:,:,jm)= smv_i(:,:,  jl); jm = jm + 1
+            zhdfptab(:,:,jm)= oa_i (:,:,  jl); jm = jm + 1
+            zhdfptab(:,:,jm)= e_s  (:,:,1,jl); jm = jm + 1
+         ! Sample of adding more variables to apply lim_hdf using lim_hdf optimization---
+         !   zhdfptab(:,:,jm) = variable_1 (:,:,1,jl); jm = jm + 1  
+         !   zhdfptab(:,:,jm) = variable_2 (:,:,1,jl); jm = jm + 1 
+         !
+         ! and in this example the parameter ihdf_vars musb be changed to 8 (necessary for allocation)
+         !----------------------------------------------------------------------------------------
+            DO jk = 1, nlay_i
+              zhdfptab(:,:,jm)=e_i(:,:,jk,jl); jm= jm+1
+            END DO
+         END DO
          !
          !--------------------------------
@@ -290,39 +334,43 @@
          !--------------------------------
          !                             ! Masked eddy diffusivity coefficient at ocean U- and V-points
+         !DO jj = 1, jpjm1                    ! NB: has not to be defined on jpj line and jpi row
+         !   DO ji = 1 , fs_jpim1   ! vector opt.
+         !      pahu(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji  ,jj) ) ) )   &
+         !         &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji+1,jj) ) ) ) * ahiu(ji,jj)
+         !      pahv(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji,jj  ) ) ) )   &
+         !         &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- at_i(ji,jj+1) ) ) ) * ahiv(ji,jj)
+         !   END DO
+         !END DO
+         
          DO jj = 1, jpjm1                    ! NB: has not to be defined on jpj line and jpi row
             DO ji = 1 , fs_jpim1   ! vector opt.
-               pahu(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji  ,jj) ) ) )   &
-                  &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji+1,jj) ) ) ) * ahiu(ji,jj)
-               pahv(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji,jj  ) ) ) )   &
-                  &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- at_i(ji,jj+1) ) ) ) * ahiv(ji,jj)
+               pahu3D(ji,jj,jpl+1) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji  ,jj) ) ) )   &
+                  &                * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji+1,jj) ) ) ) * ahiu(ji,jj)
+               pahv3D(ji,jj,jpl+1) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -at_i(ji,jj  ) ) ) )   &
+                  &                * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- at_i(ji,jj+1) ) ) ) * ahiv(ji,jj)
             END DO
          END DO
          !
-         CALL lim_hdf( ato_i (:,:) )
-
-         !------------------------------------
-         !  Diffusion of other ice variables
-         !------------------------------------
-         DO jl = 1, jpl
-         !                             ! Masked eddy diffusivity coefficient at ocean U- and V-points
-            DO jj = 1, jpjm1                 ! NB: has not to be defined on jpj line and jpi row
-               DO ji = 1 , fs_jpim1   ! vector opt.
-                  pahu(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji  ,jj,jl) ) ) )   &
-                     &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji+1,jj,jl) ) ) ) * ahiu(ji,jj)
-                  pahv(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -a_i(ji,jj  ,jl) ) ) )   &
-                     &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- a_i(ji,jj+1,jl) ) ) ) * ahiv(ji,jj)
-               END DO
-            END DO
-
-            CALL lim_hdf( v_i  (:,:,  jl) )
-            CALL lim_hdf( v_s  (:,:,  jl) )
-            CALL lim_hdf( smv_i(:,:,  jl) )
-            CALL lim_hdf( oa_i (:,:,  jl) )
-            CALL lim_hdf( a_i  (:,:,  jl) )
-            CALL lim_hdf( e_s  (:,:,1,jl) )
+         zhdfptab(:,:,jm)= ato_i  (:,:);
+         CALL lim_hdf( zhdfptab, ihdf_vars, jpl, nlay_i) 
+
+         jm=1
+         DO jl = 1, jpl
+            a_i  (:,:,  jl) = zhdfptab(:,:,jm); jm = jm + 1      
+            v_i  (:,:,  jl) = zhdfptab(:,:,jm); jm = jm + 1 
+            v_s  (:,:,  jl) = zhdfptab(:,:,jm); jm = jm + 1 
+            smv_i(:,:,  jl) = zhdfptab(:,:,jm); jm = jm + 1 
+            oa_i (:,:,  jl) = zhdfptab(:,:,jm); jm = jm + 1 
+            e_s  (:,:,1,jl) = zhdfptab(:,:,jm); jm = jm + 1 
+         ! Sample of adding more variables to apply lim_hdf---------
+         !   variable_1  (:,:,1,jl) = zhdfptab(:,:, jm  ) ; jm + 1 
+         !   variable_2  (:,:,1,jl) = zhdfptab(:,:, jm  ) ; jm + 1
+         !-----------------------------------------------------------
             DO jk = 1, nlay_i
-               CALL lim_hdf( e_i(:,:,jk,jl) )
-            END DO
-         END DO
+               e_i(:,:,jk,jl) = zhdfptab(:,:,jm);jm= jm + 1 
+            END DO
+         END DO
+
+         ato_i  (:,:) = zhdfptab(:,:,jm)
 
          !------------------------------------------------------------------------------!
@@ -422,5 +470,5 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  a_i(ji,jj,1)  = MIN( a_i(ji,jj,1), rn_amax )
+                  a_i(ji,jj,1)  = MIN( a_i(ji,jj,1), rn_amax_2d(ji,jj) )
                END DO
             END DO
@@ -464,4 +512,5 @@
       CALL wrk_dealloc( jpi,jpj,nlay_i,jpl, z0ei )
       CALL wrk_dealloc( jpi,jpj,jpl,        zviold, zvsold, zhimax, zsmvold )
+      CALL wrk_dealloc( jpi,jpj,jpl*(ihdf_vars+nlay_i)+1,zhdfptab)
       !
       IF( nn_timing == 1 )  CALL timing_stop('limtrp')
@@ -479,2 +528,3 @@
    !!======================================================================
 END MODULE limtrp
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limupdate1.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limupdate1.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limupdate1.F90	(revision 9987)
@@ -80,7 +80,7 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               IF( at_i(ji,jj) > rn_amax .AND. a_i(ji,jj,jl) > 0._wp ) THEN
-                  a_i (ji,jj,jl) = a_i (ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax / at_i(ji,jj) ) )
-                  oa_i(ji,jj,jl) = oa_i(ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax / at_i(ji,jj) ) )
+               IF( at_i(ji,jj) > rn_amax_2d(ji,jj) .AND. a_i(ji,jj,jl) > 0._wp ) THEN
+                  a_i (ji,jj,jl) = a_i (ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax_2d(ji,jj) / at_i(ji,jj) ) )
+                  oa_i(ji,jj,jl) = oa_i(ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax_2d(ji,jj) / at_i(ji,jj) ) )
                ENDIF
             END DO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limupdate2.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limupdate2.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limupdate2.F90	(revision 9987)
@@ -94,7 +94,7 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               IF( at_i(ji,jj) > rn_amax .AND. a_i(ji,jj,jl) > 0._wp ) THEN
-                  a_i (ji,jj,jl) = a_i (ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax / at_i(ji,jj) ) )
-                  oa_i(ji,jj,jl) = oa_i(ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax / at_i(ji,jj) ) )
+               IF( at_i(ji,jj) > rn_amax_2d(ji,jj) .AND. a_i(ji,jj,jl) > 0._wp ) THEN
+                  a_i (ji,jj,jl) = a_i (ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax_2d(ji,jj) / at_i(ji,jj) ) )
+                  oa_i(ji,jj,jl) = oa_i(ji,jj,jl) * ( 1._wp - ( 1._wp - rn_amax_2d(ji,jj) / at_i(ji,jj) ) )
                ENDIF
             END DO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limvar.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limvar.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limvar.F90	(revision 9987)
@@ -163,4 +163,20 @@
                rswitch = MAX( 0._wp , SIGN( 1._wp, a_i(ji,jj,jl) - epsi20 ) )   !0 if no ice and 1 if yes
                ht_i(ji,jj,jl) = v_i (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi20 ) * rswitch
+            END DO
+         END DO
+      END DO
+      ! Force the upper limit of ht_i to always be < hi_max (99 m).
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            rswitch = MAX( 0._wp , SIGN( 1._wp, ht_i(ji,jj,jpl) - epsi20 ) )
+            ht_i(ji,jj,jpl) = MIN( ht_i(ji,jj,jpl) , hi_max(jpl) )
+            a_i (ji,jj,jpl) = v_i(ji,jj,jpl) / MAX( ht_i(ji,jj,jpl) , epsi20 ) * rswitch
+         END DO
+      END DO
+
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               rswitch = MAX( 0._wp , SIGN( 1._wp, a_i(ji,jj,jl) - epsi20 ) )   !0 if no ice and 1 if yes
                ht_s(ji,jj,jl) = v_s (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi20 ) * rswitch
                o_i(ji,jj,jl)  = oa_i(ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi20 ) * rswitch
@@ -168,5 +184,5 @@
          END DO
       END DO
-
+      
       IF(  nn_icesal == 2  )THEN
          DO jl = 1, jpl
@@ -298,5 +314,8 @@
       ! Vertically constant, constant in time
       !---------------------------------------
-      IF(  nn_icesal == 1  )   s_i(:,:,:,:) = rn_icesal
+      IF(  nn_icesal == 1  )  THEN
+         s_i (:,:,:,:) = rn_icesal
+         sm_i(:,:,:)   = rn_icesal
+      ENDIF
 
       !-----------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limwri.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limwri.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/limwri.F90	(revision 9987)
@@ -157,13 +157,5 @@
       ENDIF
 
-      IF ( iom_use( "icecolf" ) ) THEN 
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               rswitch  = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) ) )
-               z2d(ji,jj) = hicol(ji,jj) * rswitch
-            END DO
-         END DO
-         CALL iom_put( "icecolf"     , z2d              )        ! frazil ice collection thickness
-      ENDIF
+      IF ( iom_use( "icecolf" ) )   CALL iom_put( "icecolf", hicol )  ! frazil ice collection thickness
 
       CALL iom_put( "isst"        , sst_m               )        ! sea surface temperature
@@ -190,12 +182,13 @@
       CALL iom_put( "destrp"      , diag_trp_es         )        ! advected snw enthalpy (W/m2)
 
-      CALL iom_put( "sfxbog"      , sfx_bog * rday      )        ! salt flux from brines
-      CALL iom_put( "sfxbom"      , sfx_bom * rday      )        ! salt flux from brines
-      CALL iom_put( "sfxsum"      , sfx_sum * rday      )        ! salt flux from brines
-      CALL iom_put( "sfxsni"      , sfx_sni * rday      )        ! salt flux from brines
-      CALL iom_put( "sfxopw"      , sfx_opw * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxbog"      , sfx_bog * rday      )        ! salt flux from bottom growth
+      CALL iom_put( "sfxbom"      , sfx_bom * rday      )        ! salt flux from bottom melt
+      CALL iom_put( "sfxsum"      , sfx_sum * rday      )        ! salt flux from surface melt
+      CALL iom_put( "sfxsni"      , sfx_sni * rday      )        ! salt flux from snow ice formation
+      CALL iom_put( "sfxopw"      , sfx_opw * rday      )        ! salt flux from open water formation
       CALL iom_put( "sfxdyn"      , sfx_dyn * rday      )        ! salt flux from ridging rafting
-      CALL iom_put( "sfxres"      , sfx_res * rday      )        ! salt flux from limupdate (resultant)
+      CALL iom_put( "sfxres"      , sfx_res * rday      )        ! salt flux from residual
       CALL iom_put( "sfxbri"      , sfx_bri * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxsub"      , sfx_sub * rday      )        ! salt flux from sublimation
       CALL iom_put( "sfx"         , sfx     * rday      )        ! total salt flux
 
@@ -235,4 +228,17 @@
       CALL iom_put ('hfxdhc'     , diag_heat(:,:)       )   ! Heat content variation in snow and ice 
       CALL iom_put ('hfxspr'     , hfx_spr(:,:)         )   ! Heat content of snow precip 
+
+
+      IF ( iom_use( "vfxthin" ) ) THEN   ! ice production for open water + thin ice (<20cm) => comparable to observations  
+         DO jj = 1, jpj 
+            DO ji = 1, jpi
+               z2d(ji,jj)  = vt_i(ji,jj) / MAX( at_i(ji,jj), epsi06 ) * zswi(ji,jj) ! mean ice thickness
+            END DO
+         END DO
+         WHERE( z2d(:,:) < 0.2 .AND. z2d(:,:) > 0. ) ; z2da = wfx_bog
+         ELSEWHERE                                   ; z2da = 0._wp
+         END WHERE
+         CALL iom_put( "vfxthin", ( wfx_opw + z2da ) * ztmp )
+      ENDIF
       
       !--------------------------------
@@ -311,5 +317,5 @@
       !!
       !! History :
-      !!   4.1  !  2013-06  (C. Rousset)
+      !!   4.0  !  2013-06  (C. Rousset)
       !!----------------------------------------------------------------------
       INTEGER, INTENT( in ) ::   kt               ! ocean time-step index)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/thd_ice.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/thd_ice.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/LIM_SRC_3/thd_ice.F90	(revision 9987)
@@ -45,4 +45,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qns_ice_1d  
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_bo_1d     
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   rn_amax_1d
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_sum_1d
@@ -83,4 +84,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_res_1d  
 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_sub_1d
+
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sprecip_1d    !: <==> the 2D  sprecip
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   frld_1d       !: <==> the 2D  frld
@@ -91,4 +94,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   evap_ice_1d   !: <==> the 2D  evap_ice
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qprec_ice_1d  !: <==> the 2D  qprec_ice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qevap_ice_1d  !: <==> the 3D  qevap_ice
    !                                                     ! to reintegrate longwave flux inside the ice thermodynamics
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   i0            !: fraction of radiation transmitted to the ice
@@ -107,4 +111,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_s_tot      !: Snow accretion/ablation        [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_surf     !: Ice surface accretion/ablation [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_sub      !: Ice surface sublimation [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_bott     !: Ice bottom accretion/ablation  [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_snowice    !: Snow ice formation             [m of ice]
@@ -144,4 +149,5 @@
          &      hfx_sum_1d(jpij) , hfx_bom_1d(jpij) ,hfx_bog_1d(jpij) ,    & 
          &      hfx_dif_1d(jpij) , hfx_opw_1d(jpij) ,                      &
+         &      rn_amax_1d(jpij) ,                                         &
          &      hfx_thd_1d(jpij) , hfx_spr_1d(jpij) ,                      &
          &      hfx_snw_1d(jpij) , hfx_sub_1d(jpij) , hfx_err_1d(jpij) ,   &
@@ -153,7 +159,7 @@
          &      wfx_sum_1d(jpij)  , wfx_sni_1d (jpij) , wfx_opw_1d (jpij) , wfx_res_1d(jpij) ,  &
          &      dqns_ice_1d(jpij) , evap_ice_1d (jpij),                                         &
-         &      qprec_ice_1d(jpij), i0         (jpij) ,                                         &  
+         &      qprec_ice_1d(jpij), qevap_ice_1d(jpij), i0         (jpij) ,                     &  
          &      sfx_bri_1d (jpij) , sfx_bog_1d (jpij) , sfx_bom_1d (jpij) , sfx_sum_1d (jpij),  &
-         &      sfx_sni_1d (jpij) , sfx_opw_1d (jpij) , sfx_res_1d (jpij) ,                     &
+         &      sfx_sni_1d (jpij) , sfx_opw_1d (jpij) , sfx_res_1d (jpij) , sfx_sub_1d (jpij),  &
          &      dsm_i_fl_1d(jpij) , dsm_i_gd_1d(jpij) , dsm_i_se_1d(jpij) ,                     &     
          &      dsm_i_si_1d(jpij) , hicol_1d    (jpij)                     , STAT=ierr(2) )
@@ -161,6 +167,6 @@
       ALLOCATE( t_su_1d   (jpij) , a_i_1d   (jpij) , ht_i_1d  (jpij) ,    &   
          &      ht_s_1d   (jpij) , fc_su    (jpij) , fc_bo_i  (jpij) ,    &    
-         &      dh_s_tot  (jpij) , dh_i_surf(jpij) , dh_i_bott(jpij) ,    &    
-         &      dh_snowice(jpij) , sm_i_1d  (jpij) , s_i_new  (jpij) ,    &
+         &      dh_s_tot  (jpij) , dh_i_surf(jpij) , dh_i_sub (jpij) ,    &    
+         &      dh_i_bott (jpij) ,dh_snowice(jpij) , sm_i_1d  (jpij) , s_i_new  (jpij) ,    &
          &      t_s_1d(jpij,nlay_s) , t_i_1d(jpij,nlay_i) , s_i_1d(jpij,nlay_i) ,  &            
          &      q_i_1d(jpij,nlay_i+1) , q_s_1d(jpij,nlay_s) ,                        &
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif2model.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif2model.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif2model.F90	(revision 9987)
@@ -1,62 +1,64 @@
 #if defined key_agrif
-   !!----------------------------------------------------------------------
-   !! NEMO/NST 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-   SUBROUTINE Agrif2Model
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif2Model ***
-      !!--------------------------------------------- 
-   END SUBROUTINE Agrif2model
+!!----------------------------------------------------------------------
+!! NEMO/NST 3.6 , NEMO Consortium (2010)
+!! $Id$
+!! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+!!----------------------------------------------------------------------
+SUBROUTINE Agrif2Model
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif2Model ***
+   !!--------------------------------------------- 
+END SUBROUTINE Agrif2model
 
-   SUBROUTINE Agrif_Set_numberofcells(Agrif_Gr)
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif_Set_numberofcells ***
-      !!--------------------------------------------- 
-      USE Agrif_Types
-      IMPLICIT NONE
+SUBROUTINE Agrif_Set_numberofcells(Agrif_Gr)
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif_Set_numberofcells ***
+   !!--------------------------------------------- 
+   USE Agrif_Grids
+   IMPLICIT NONE
 
-      Type(Agrif_Grid), Pointer :: Agrif_Gr
+   TYPE(Agrif_Grid), POINTER :: Agrif_Gr
 
-      IF ( associated(Agrif_Curgrid) )THEN
+   IF ( ASSOCIATED(Agrif_Curgrid) )THEN
 #include "SetNumberofcells.h"
-      ENDIF
+   ENDIF
 
-   END SUBROUTINE Agrif_Set_numberofcells
+END SUBROUTINE Agrif_Set_numberofcells
 
-   SUBROUTINE Agrif_Get_numberofcells(Agrif_Gr)
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif_Get_numberofcells ***
-      !!--------------------------------------------- 
-      USE Agrif_Types
-      IMPLICIT NONE
+SUBROUTINE Agrif_Get_numberofcells(Agrif_Gr)
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif_Get_numberofcells ***
+   !!--------------------------------------------- 
+   USE Agrif_Grids
+   IMPLICIT NONE
 
-      Type(Agrif_Grid), Pointer :: Agrif_Gr
+   TYPE(Agrif_Grid), POINTER :: Agrif_Gr
 
+   IF ( ASSOCIATED(Agrif_Curgrid) ) THEN
 #include "GetNumberofcells.h"
+   ENDIF
 
-   END SUBROUTINE Agrif_Get_numberofcells
+END SUBROUTINE Agrif_Get_numberofcells
 
-   SUBROUTINE Agrif_Allocationcalls(Agrif_Gr)
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif_Allocationscalls ***
-      !!--------------------------------------------- 
-      USE Agrif_Types 
+SUBROUTINE Agrif_Allocationcalls(Agrif_Gr)
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif_Allocationscalls ***
+   !!--------------------------------------------- 
+   USE Agrif_Grids 
 #include "include_use_Alloc_agrif.h"
-      IMPLICIT NONE
+   IMPLICIT NONE
 
-      Type(Agrif_Grid), Pointer :: Agrif_Gr
+   TYPE(Agrif_Grid), POINTER :: Agrif_Gr
 
 #include "allocations_calls_agrif.h"
 
-   END SUBROUTINE Agrif_Allocationcalls
+END SUBROUTINE Agrif_Allocationcalls
 
-   SUBROUTINE Agrif_probdim_modtype_def()
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif_probdim_modtype_def ***
-      !!--------------------------------------------- 
-      USE Agrif_Types
-      IMPLICIT NONE
+SUBROUTINE Agrif_probdim_modtype_def()
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif_probdim_modtype_def ***
+   !!--------------------------------------------- 
+   USE Agrif_Types
+   IMPLICIT NONE
 
 #include "modtype_agrif.h"
@@ -64,43 +66,24 @@
 #include "keys_agrif.h"
 
-      Return
+   RETURN
 
-   END SUBROUTINE Agrif_probdim_modtype_def
+END SUBROUTINE Agrif_probdim_modtype_def
 
-   SUBROUTINE Agrif_clustering_def()
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif_clustering_def ***
-      !!--------------------------------------------- 
-      Use Agrif_Types
-      IMPLICIT NONE
+SUBROUTINE Agrif_clustering_def()
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif_clustering_def ***
+   !!--------------------------------------------- 
+   IMPLICIT NONE
 
-      Return
+   RETURN
 
-   END SUBROUTINE Agrif_clustering_def
+END SUBROUTINE Agrif_clustering_def
 
-   SUBROUTINE Agrif_comm_def(modelcomm)
-
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif_clustering_def ***
-      !!--------------------------------------------- 
-      Use Agrif_Types
-      Use lib_mpp
-
-      IMPLICIT NONE
-
-      INTEGER :: modelcomm
-
-#if defined key_mpp_mpi
-      modelcomm = mpi_comm_opa
+#else
+SUBROUTINE Agrif2Model
+   !!---------------------------------------------
+   !!   *** ROUTINE Agrif2Model ***
+   !!--------------------------------------------- 
+   WRITE(*,*) 'Impossible to bet here'
+END SUBROUTINE Agrif2model
 #endif
-      Return
-
-   END SUBROUTINE Agrif_comm_def
-#else
-   SUBROUTINE Agrif2Model
-      !!---------------------------------------------
-      !!   *** ROUTINE Agrif2Model ***
-      !!--------------------------------------------- 
-      WRITE(*,*) 'Impossible to bet here'
-   END SUBROUTINE Agrif2model
-#endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_lim2_interp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_lim2_interp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_lim2_interp.F90	(revision 9987)
@@ -9,5 +9,5 @@
    !!            3.4   !  09-2012  (R. Benshila, C. Herbaut) update and EVP
    !!----------------------------------------------------------------------
-#if defined key_agrif && defined key_lim2
+#if defined key_agrif && defined key_lim2 
    !!----------------------------------------------------------------------
    !!   'key_lim2'  :                                 LIM 2.0 sea-ice model
@@ -41,4 +41,8 @@
    PUBLIC interp_adv_ice
 
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PRIVATE :: uice_agr, vice_agr
+   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE, PRIVATE :: tabice_agr 
+
+
    !!----------------------------------------------------------------------
    !! NEMO/NST 3.4 , NEMO Consortium (2012)
@@ -65,6 +69,6 @@
       u_ice_nst(:,:) = 0.
       v_ice_nst(:,:) = 0.
-      CALL Agrif_Bc_variable( u_ice_nst, u_ice_id ,procname=interp_u_ice, calledweight=1. )
-      CALL Agrif_Bc_variable( v_ice_nst, v_ice_id ,procname=interp_v_ice, calledweight=1. )
+      CALL Agrif_Bc_variable( u_ice_id ,procname=interp_u_ice, calledweight=1. )
+      CALL Agrif_Bc_variable( v_ice_id ,procname=interp_v_ice, calledweight=1. )
       Agrif_SpecialValue=0.
       Agrif_UseSpecialValue = .FALSE.
@@ -138,5 +142,4 @@
       !!  we are in inside a new parent ice time step
       !!-----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj) :: zuice, zvice
       INTEGER :: ji,jj
       REAL(wp) :: zrhox, zrhoy
@@ -155,33 +158,36 @@
          Agrif_SpecialValue=-9999.
          Agrif_UseSpecialValue = .TRUE.
-         zuice = 0.
-         zvice = 0.
-         CALL Agrif_Bc_variable(zuice,u_ice_id,procname=interp_u_ice, calledweight=1.)
-         CALL Agrif_Bc_variable(zvice,v_ice_id,procname=interp_v_ice, calledweight=1.)
+         IF( .NOT. ALLOCATED(uice_agr) )THEN
+            ALLOCATE(uice_agr(jpi,jpj), vice_agr(jpi,jpj))
+         ENDIF
+         uice_agr = 0.
+         vice_agr = 0.
+         CALL Agrif_Bc_variable(u_ice_id,procname=interp_u_ice, calledweight=1.)
+         CALL Agrif_Bc_variable(v_ice_id,procname=interp_v_ice, calledweight=1.)
          Agrif_SpecialValue=0.
          Agrif_UseSpecialValue = .FALSE.
          !  
          zrhox = agrif_rhox() ;    zrhoy = agrif_rhoy()      
-         zuice(:,:) =  zuice(:,:)/(zrhoy*e2u(:,:))*umask(:,:,1)
-         zvice(:,:) =  zvice(:,:)/(zrhox*e1v(:,:))*vmask(:,:,1)
+         uice_agr(:,:) =  uice_agr(:,:)/(zrhoy*e2u(:,:))*umask(:,:,1)
+         vice_agr(:,:) =  vice_agr(:,:)/(zrhox*e1v(:,:))*vmask(:,:,1)
          ! fill  boundaries
          DO jj = 1, jpj
             DO ji = 1, 2
-               u_ice_oe(ji,  jj,2) = zuice(ji       ,jj) 
-               u_ice_oe(ji+2,jj,2) = zuice(nlci+ji-3,jj)
+               u_ice_oe(ji,  jj,2) = uice_agr(ji       ,jj) 
+               u_ice_oe(ji+2,jj,2) = uice_agr(nlci+ji-3,jj)
             END DO
          END DO
          DO jj = 1, jpj
-            v_ice_oe(2,jj,2) = zvice(2     ,jj) 
-            v_ice_oe(4,jj,2) = zvice(nlci-1,jj)
+            v_ice_oe(2,jj,2) = vice_agr(2     ,jj) 
+            v_ice_oe(4,jj,2) = vice_agr(nlci-1,jj)
          END DO
          DO ji = 1, jpi
-            u_ice_sn(ji,2,2) = zuice(ji,2     ) 
-            u_ice_sn(ji,4,2) = zuice(ji,nlcj-1)
+            u_ice_sn(ji,2,2) = uice_agr(ji,2     ) 
+            u_ice_sn(ji,4,2) = uice_agr(ji,nlcj-1)
          END DO
          DO jj = 1, 2
             DO ji = 1, jpi
-               v_ice_sn(ji,jj  ,2) = zvice(ji,jj       ) 
-               v_ice_sn(ji,jj+2,2) = zvice(ji,nlcj+jj-3)
+               v_ice_sn(ji,jj  ,2) = vice_agr(ji,jj       ) 
+               v_ice_sn(ji,jj+2,2) = vice_agr(ji,nlcj+jj-3)
             END DO
          END DO
@@ -334,5 +340,4 @@
       !!  we are in inside a new parent ice time step
      !!-----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,7) :: ztab 
       INTEGER :: ji,jj,jn
       !!-----------------------------------------------------------------------
@@ -345,8 +350,11 @@
          adv_ice_sn(:,:,:,1) =  adv_ice_sn(:,:,:,2)
          ! interpolation of boundaries
-         ztab(:,:,:) = 0.
+         IF(.NOT.ALLOCATED(tabice_agr))THEN
+            ALLOCATE(tabice_agr(jpi,jpj,7))   
+         ENDIF
+         tabice_agr(:,:,:) = 0.
          Agrif_SpecialValue=-9999.
          Agrif_UseSpecialValue = .TRUE.
-         CALL Agrif_Bc_variable( ztab, adv_ice_id ,procname=interp_adv_ice,calledweight=1. )
+         CALL Agrif_Bc_variable( adv_ice_id ,procname=interp_adv_ice,calledweight=1. )
          Agrif_SpecialValue=0.
          Agrif_UseSpecialValue = .FALSE.
@@ -356,6 +364,6 @@
             DO jj = 1, jpj
                DO ji=1,2
-                  adv_ice_oe(ji  ,jj,jn,2) = ztab(ji       ,jj,jn) 
-                  adv_ice_oe(ji+2,jj,jn,2) = ztab(nlci-2+ji,jj,jn)
+                  adv_ice_oe(ji  ,jj,jn,2) = tabice_agr(ji       ,jj,jn) 
+                  adv_ice_oe(ji+2,jj,jn,2) = tabice_agr(nlci-2+ji,jj,jn)
                END DO
             END DO
@@ -365,6 +373,6 @@
             Do jj =1,2
                DO ji = 1, jpi
-                  adv_ice_sn(ji,jj  ,jn,2) = ztab(ji,jj       ,jn) 
-                  adv_ice_sn(ji,jj+2,jn,2) = ztab(ji,nlcj-2+jj,jn)
+                  adv_ice_sn(ji,jj  ,jn,2) = tabice_agr(ji,jj       ,jn) 
+                  adv_ice_sn(ji,jj+2,jn,2) = tabice_agr(ji,nlcj-2+jj,jn)
                END DO
             END DO
@@ -384,5 +392,4 @@
       INTEGER :: ji,jj,jn
       REAL(wp) :: zalpha
-      REAL(wp), DIMENSION(jpi,jpj,7) :: ztab 
       !!-----------------------------------------------------------------------      
       !
@@ -391,10 +398,10 @@
       zalpha = REAL(lim_nbstep,wp) / (Agrif_Rhot()*Agrif_PArent(nn_fsbc)/REAL(nn_fsbc))
       !
-      ztab(:,:,:) = 0.e0
+      tabice_agr(:,:,:) = 0.e0
       DO jn =1,7
          DO jj =1,2
             DO ji = 1, jpi
-               ztab(ji,jj        ,jn) = (1-zalpha)*adv_ice_sn(ji,jj  ,jn,1) + zalpha*adv_ice_sn(ji,jj  ,jn,2) 
-               ztab(ji,nlcj-2+jj ,jn) = (1-zalpha)*adv_ice_sn(ji,jj+2,jn,1) + zalpha*adv_ice_sn(ji,jj+2,jn,2) 
+               tabice_agr(ji,jj        ,jn) = (1-zalpha)*adv_ice_sn(ji,jj  ,jn,1) + zalpha*adv_ice_sn(ji,jj  ,jn,2) 
+               tabice_agr(ji,nlcj-2+jj ,jn) = (1-zalpha)*adv_ice_sn(ji,jj+2,jn,1) + zalpha*adv_ice_sn(ji,jj+2,jn,2) 
             END DO
          END DO
@@ -404,17 +411,17 @@
          DO jj = 1, jpj
             DO ji=1,2
-               ztab(ji       ,jj,jn) = (1-zalpha)*adv_ice_oe(ji  ,jj,jn,1) + zalpha*adv_ice_oe(ji  ,jj,jn,2) 
-               ztab(nlci-2+ji,jj,jn) = (1-zalpha)*adv_ice_oe(ji+2,jj,jn,1) + zalpha*adv_ice_oe(ji+2,jj,jn,2) 
+               tabice_agr(ji       ,jj,jn) = (1-zalpha)*adv_ice_oe(ji  ,jj,jn,1) + zalpha*adv_ice_oe(ji  ,jj,jn,2) 
+               tabice_agr(nlci-2+ji,jj,jn) = (1-zalpha)*adv_ice_oe(ji+2,jj,jn,1) + zalpha*adv_ice_oe(ji+2,jj,jn,2) 
             END DO
          END DO
       END DO
       !
-      CALL parcoursT( ztab(:,:, 1), frld  )
-      CALL parcoursT( ztab(:,:, 2), hicif )
-      CALL parcoursT( ztab(:,:, 3), hsnif )
-      CALL parcoursT( ztab(:,:, 4), tbif(:,:,1) )
-      CALL parcoursT( ztab(:,:, 5), tbif(:,:,2) )
-      CALL parcoursT( ztab(:,:, 6), tbif(:,:,3) )
-      CALL parcoursT( ztab(:,:, 7), qstoif )
+      CALL parcoursT( tabice_agr(:,:, 1), frld  )
+      CALL parcoursT( tabice_agr(:,:, 2), hicif )
+      CALL parcoursT( tabice_agr(:,:, 3), hsnif )
+      CALL parcoursT( tabice_agr(:,:, 4), tbif(:,:,1) )
+      CALL parcoursT( tabice_agr(:,:, 5), tbif(:,:,2) )
+      CALL parcoursT( tabice_agr(:,:, 6), tbif(:,:,3) )
+      CALL parcoursT( tabice_agr(:,:, 7), qstoif )
       !
    END SUBROUTINE agrif_trp_lim2
@@ -499,5 +506,5 @@
 
 
-   SUBROUTINE interp_u_ice( tabres, i1, i2, j1, j2 )
+   SUBROUTINE interp_u_ice( tabres, i1, i2, j1, j2, before )
       !!-----------------------------------------------------------------------
       !!                     *** ROUTINE interp_u_ice ***
@@ -505,4 +512,5 @@
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
       !!
       INTEGER :: ji,jj
@@ -510,28 +518,44 @@
       !
 #if defined key_lim2_vp
-      DO jj=MAX(j1,2),j2
-         DO ji=MAX(i1,2),i2
-            IF( tmu(ji,jj) == 0. ) THEN
-               tabres(ji,jj) = -9999.
-            ELSE
-               tabres(ji,jj) = e2f(ji-1,jj-1) * u_ice(ji,jj)
-            ENDIF
-         END DO
-      END DO
+      IF( before ) THEN
+         DO jj=MAX(j1,2),j2
+            DO ji=MAX(i1,2),i2
+               IF( tmu(ji,jj) == 0. ) THEN
+                  tabres(ji,jj) = -9999.
+               ELSE
+                  tabres(ji,jj) = e2f(ji-1,jj-1) * u_ice(ji,jj)
+               ENDIF
+            END DO
+         END DO
+      ELSE
+         DO jj=MAX(j1,2),j2
+            DO ji=MAX(i1,2),i2
+               uice_agr(ji,jj) = tabres(ji,jj)
+            END DO
+         END DO
+      ENDIF
 #else
-      DO jj= j1, j2
-         DO ji= i1, i2
-            IF( umask(ji,jj,1) == 0. ) THEN
-               tabres(ji,jj) = -9999.
-            ELSE
-               tabres(ji,jj) = e2u(ji,jj) * u_ice(ji,jj)
-            ENDIF
-         END DO
-      END DO
+      IF( before ) THEN
+         DO jj= j1, j2
+            DO ji= i1, i2
+               IF( umask(ji,jj,1) == 0. ) THEN
+                  tabres(ji,jj) = -9999.
+               ELSE
+                  tabres(ji,jj) = e2u(ji,jj) * u_ice(ji,jj)
+               ENDIF
+            END DO
+         END DO
+      ELSE
+         DO jj= j1, j2
+            DO ji= i1, i2
+               uice_agr(ji,jj) = tabres(ji,jj)
+            END DO
+         END DO
+      ENDIF
 #endif
    END SUBROUTINE interp_u_ice
 
 
-   SUBROUTINE interp_v_ice( tabres, i1, i2, j1, j2 )
+   SUBROUTINE interp_v_ice( tabres, i1, i2, j1, j2, before )
       !!-----------------------------------------------------------------------
       !!                    *** ROUTINE interp_v_ice ***
@@ -539,4 +563,5 @@
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
       !!
       INTEGER :: ji, jj
@@ -544,28 +569,44 @@
       !
 #if defined key_lim2_vp
-      DO jj=MAX(j1,2),j2
-         DO ji=MAX(i1,2),i2
-            IF( tmu(ji,jj) == 0. ) THEN
-               tabres(ji,jj) = -9999.
-            ELSE
-               tabres(ji,jj) = e1f(ji-1,jj-1) * v_ice(ji,jj)
-            ENDIF
-         END DO
-      END DO
+      IF( before ) THEN
+         DO jj=MAX(j1,2),j2
+            DO ji=MAX(i1,2),i2
+               IF( tmu(ji,jj) == 0. ) THEN
+                  tabres(ji,jj) = -9999.
+               ELSE
+                  tabres(ji,jj) = e1f(ji-1,jj-1) * v_ice(ji,jj)
+               ENDIF
+            END DO
+         END DO
+      ELSE
+         DO jj=MAX(j1,2),j2
+            DO ji=MAX(i1,2),i2
+               vice_agr(ji,jj) = tabres(ji,jj)
+            END DO
+         END DO
+      ENDIF   
 #else
-      DO jj= j1 ,j2
-         DO ji = i1, i2
-            IF( vmask(ji,jj,1) == 0. ) THEN
-               tabres(ji,jj) = -9999.
-            ELSE
-               tabres(ji,jj) = e1v(ji,jj) * v_ice(ji,jj)
-            ENDIF
-         END DO
-      END DO
+      IF( before ) THEN
+	      DO jj= j1 ,j2
+	         DO ji = i1, i2
+	            IF( vmask(ji,jj,1) == 0. ) THEN
+	               tabres(ji,jj) = -9999.
+	            ELSE
+	               tabres(ji,jj) = e1v(ji,jj) * v_ice(ji,jj)
+	            ENDIF
+	         END DO
+	      END DO
+      ELSE
+	      DO jj= j1 ,j2
+	         DO ji = i1, i2
+	            vice_agr(ji,jj) = tabres(ji,jj)
+	         END DO
+	      END DO
+      ENDIF
 #endif
    END SUBROUTINE interp_v_ice
 
 
-   SUBROUTINE interp_adv_ice( tabres, i1, i2, j1, j2 )
+   SUBROUTINE interp_adv_ice( tabres, i1, i2, j1, j2, k1, k2, before )
       !!-----------------------------------------------------------------------
       !!                    *** ROUTINE interp_adv_ice ***                           
@@ -575,25 +616,36 @@
       !!              put -9999 where no ice for correct extrapolation             
       !!-----------------------------------------------------------------------
-      INTEGER, INTENT(in) :: i1, i2, j1, j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2,7), INTENT(inout) :: tabres
+      INTEGER, INTENT(in) :: i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
       !!
       INTEGER :: ji, jj, jk
       !!-----------------------------------------------------------------------
       !
-      DO jj=j1,j2
-         DO ji=i1,i2
-            IF( tms(ji,jj) == 0. ) THEN
-               tabres(ji,jj,:) = -9999. 
-            ELSE
-               tabres(ji,jj, 1) = frld  (ji,jj)
-               tabres(ji,jj, 2) = hicif (ji,jj)
-               tabres(ji,jj, 3) = hsnif (ji,jj)
-               tabres(ji,jj, 4) = tbif  (ji,jj,1)
-               tabres(ji,jj, 5) = tbif  (ji,jj,2)
-               tabres(ji,jj, 6) = tbif  (ji,jj,3)
-               tabres(ji,jj, 7) = qstoif(ji,jj)
-            ENDIF
-         END DO
-      END DO
+      IF( before ) THEN
+         DO jj=j1,j2
+	    DO ji=i1,i2
+	       IF( tms(ji,jj) == 0. ) THEN
+	          tabres(ji,jj,:) = -9999 
+	       ELSE
+	          tabres(ji,jj, 1) = frld  (ji,jj)
+	          tabres(ji,jj, 2) = hicif (ji,jj)
+	          tabres(ji,jj, 3) = hsnif (ji,jj)
+	          tabres(ji,jj, 4) = tbif  (ji,jj,1)
+	          tabres(ji,jj, 5) = tbif  (ji,jj,2)
+	          tabres(ji,jj, 6) = tbif  (ji,jj,3)
+	          tabres(ji,jj, 7) = qstoif(ji,jj)
+	       ENDIF
+	    END DO
+         END DO
+      ELSE
+	 DO jj=j1,j2
+	    DO ji=i1,i2
+               DO jk=k1, k2
+	          tabice_agr(ji,jj,jk) = tabres(ji,jj,jk)
+               END DO
+	    END DO
+	 END DO
+      ENDIF
       !
    END SUBROUTINE interp_adv_ice
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_lim2_update.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_lim2_update.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_lim2_update.F90	(revision 9987)
@@ -52,6 +52,4 @@
       INTEGER, INTENT(in) :: kt
       !!
-      REAL(wp), DIMENSION(jpi,jpj)  :: zvel
-      REAL(wp), DIMENSION(jpi,jpj,7):: zadv
       !!----------------------------------------------------------------------
       !
@@ -60,14 +58,13 @@
       Agrif_UseSpecialValueInUpdate = .TRUE.
       Agrif_SpecialValueFineGrid = 0.
-
 # if defined TWO_WAY
       IF( MOD(nbcline,nbclineupdate) == 0) THEN
-         CALL Agrif_Update_Variable( zadv , adv_ice_id , procname = update_adv_ice  )
-         CALL Agrif_Update_Variable( zvel , u_ice_id   , procname = update_u_ice    )
-         CALL Agrif_Update_Variable( zvel , v_ice_id   , procname = update_v_ice    )
-      ELSE
-         CALL Agrif_Update_Variable( zadv , adv_ice_id , locupdate=(/0,2/), procname = update_adv_ice  )
-         CALL Agrif_Update_Variable( zvel , u_ice_id   , locupdate=(/0,1/), procname = update_u_ice    )
-         CALL Agrif_Update_Variable( zvel , v_ice_id   , locupdate=(/0,1/), procname = update_v_ice    )
+         CALL Agrif_Update_Variable( adv_ice_id , procname = update_adv_ice  )
+         CALL Agrif_Update_Variable( u_ice_id   , procname = update_u_ice    )
+         CALL Agrif_Update_Variable( v_ice_id   , procname = update_v_ice    )
+      ELSE
+         CALL Agrif_Update_Variable( adv_ice_id , locupdate=(/0,2/), procname = update_adv_ice  )
+         CALL Agrif_Update_Variable( u_ice_id   , locupdate=(/0,1/), procname = update_u_ice    )
+         CALL Agrif_Update_Variable( v_ice_id   , locupdate=(/0,1/), procname = update_v_ice    )
       ENDIF
 # endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_oce.F90	(revision 9987)
@@ -12,5 +12,5 @@
    USE par_oce      ! ocean parameters
    USE dom_oce      ! domain parameters
-   
+
    IMPLICIT NONE
    PRIVATE 
@@ -19,8 +19,10 @@
 
    !                                              !!* Namelist namagrif: AGRIF parameters
-   LOGICAL , PUBLIC ::   ln_spc_dyn      !:
-   INTEGER , PUBLIC ::   nn_cln_update   !: update frequency 
-   REAL(wp), PUBLIC ::   rn_sponge_tra   !: sponge coeff. for tracers
-   REAL(wp), PUBLIC ::   rn_sponge_dyn   !: sponge coeff. for dynamics
+   LOGICAL , PUBLIC ::   ln_spc_dyn    = .FALSE.   !:
+   INTEGER , PUBLIC ::   nn_cln_update = 3         !: update frequency 
+   INTEGER , PUBLIC, PARAMETER ::   nn_sponge_len = 2  !: Sponge width (in number of parent grid points)
+   REAL(wp), PUBLIC ::   rn_sponge_tra = 2800.     !: sponge coeff. for tracers
+   REAL(wp), PUBLIC ::   rn_sponge_dyn = 2800.     !: sponge coeff. for dynamics
+   LOGICAL , PUBLIC ::   ln_chk_bathy  = .FALSE.   !: check of parent bathymetry 
 
    !                                              !!! OLD namelist names
@@ -30,16 +32,42 @@
    REAL(wp), PUBLIC ::   visc_dyn                  !: sponge coeff. for dynamics
 
-   LOGICAL , PUBLIC :: spongedoneT = .FALSE.   !: tracer   sponge layer indicator
-   LOGICAL , PUBLIC :: spongedoneU = .FALSE.   !: dynamics sponge layer indicator
-   LOGICAL , PUBLIC :: lk_agrif_fstep = .TRUE. !: if true: first step
+   LOGICAL , PUBLIC :: spongedoneT = .FALSE.       !: tracer   sponge layer indicator
+   LOGICAL , PUBLIC :: spongedoneU = .FALSE.       !: dynamics sponge layer indicator
+   LOGICAL , PUBLIC :: lk_agrif_fstep = .TRUE.     !: if true: first step
+   LOGICAL , PUBLIC :: lk_agrif_doupd = .TRUE.     !: if true: send update from current grid
+   LOGICAL , PUBLIC :: lk_agrif_debug = .FALSE.    !: if true: print debugging info
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,  DIMENSION(:,:) ::   spe1ur , spe2vr , spbtr2   !: ???
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,  DIMENSION(:,:) ::   spe1ur2, spe2vr2, spbtr3   !: ???
-   
-   INTEGER :: tsn_id,tsb_id,tsa_id
-   INTEGER :: un_id, vn_id, ua_id, va_id
-   INTEGER :: e1u_id, e2v_id, sshn_id, gcb_id
-   INTEGER :: trn_id, trb_id, tra_id
-   INTEGER :: unb_id, vnb_id, ub2b_id, vb2b_id
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_tsn
+# if defined key_top
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_trn
+# endif
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_u
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_v
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,  DIMENSION(:,:) :: fsaht_spu, fsaht_spv !: sponge diffusivities
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,  DIMENSION(:,:) :: fsahm_spt, fsahm_spf !: sponge viscosities
+
+   ! Barotropic arrays used to store open boundary data during
+   ! time-splitting loop:
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_w, vbdy_w, hbdy_w
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_e, vbdy_e, hbdy_e
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_n, vbdy_n, hbdy_n
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_s, vbdy_s, hbdy_s
+
+   INTEGER :: tsn_id                                                  ! AGRIF profile for tracers interpolation and update
+   INTEGER :: un_interp_id, vn_interp_id                              ! AGRIF profiles for interpolations
+   INTEGER :: un_update_id, vn_update_id                              ! AGRIF profiles for udpates
+   INTEGER :: tsn_sponge_id, un_sponge_id, vn_sponge_id               ! AGRIF profiles for sponge layers
+# if defined key_top
+   INTEGER :: trn_id, trn_sponge_id
+# endif  
+   INTEGER :: unb_id, vnb_id, ub2b_interp_id, vb2b_interp_id
+   INTEGER :: ub2b_update_id, vb2b_update_id
+   INTEGER :: e3t_id, e1u_id, e2v_id, sshn_id
+   INTEGER :: scales_t_id
+# if defined key_zdftke
+   INTEGER :: avt_id, avm_id, en_id
+# endif  
+   INTEGER :: umsk_id, vmsk_id
+   INTEGER :: kindic_agr
 
    !!----------------------------------------------------------------------
@@ -54,6 +82,24 @@
       !!                ***  FUNCTION agrif_oce_alloc  ***
       !!----------------------------------------------------------------------
-      ALLOCATE( spe1ur (jpi,jpj) , spe2vr (jpi,jpj) , spbtr2(jpi,jpj) ,      &
-         &      spe1ur2(jpi,jpj) , spe2vr2(jpi,jpj) , spbtr3(jpi,jpj) , STAT = agrif_oce_alloc ) 
+      INTEGER, DIMENSION(2) :: ierr
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( fsaht_spu(jpi,jpj), fsaht_spv(jpi,jpj),   &
+         &      fsahm_spt(jpi,jpj), fsahm_spf(jpi,jpj),   &
+         &      tabspongedone_tsn(jpi,jpj),           &
+# if defined key_top         
+         &      tabspongedone_trn(jpi,jpj),           &
+# endif         
+         &      tabspongedone_u  (jpi,jpj),           &
+         &      tabspongedone_v  (jpi,jpj), STAT = ierr(1) )
+
+      ALLOCATE( ubdy_w(jpj), vbdy_w(jpj), hbdy_w(jpj),   &
+         &      ubdy_e(jpj), vbdy_e(jpj), hbdy_e(jpj),   & 
+         &      ubdy_n(jpi), vbdy_n(jpi), hbdy_n(jpi),   & 
+         &      ubdy_s(jpi), vbdy_s(jpi), hbdy_s(jpi), STAT = ierr(2) )
+
+      agrif_oce_alloc = MAXVAL(ierr)
+      !
    END FUNCTION agrif_oce_alloc
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_interp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_interp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_interp.F90	(revision 9987)
@@ -7,4 +7,5 @@
    !!             -   !  2005-11  (XXX) 
    !!            3.2  !  2009-04  (R. Benshila) 
+   !!            3.6  !  2014-09  (R. Benshila) 
    !!----------------------------------------------------------------------
 #if defined key_agrif && ! defined key_offline
@@ -29,139 +30,42 @@
    USE wrk_nemo
    USE dynspg_oce
-
+   USE zdf_oce
+ 
    IMPLICIT NONE
    PRIVATE
 
-   ! Barotropic arrays used to store open boundary data during
-   ! time-splitting loop:
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_w, vbdy_w, hbdy_w
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_e, vbdy_e, hbdy_e
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_n, vbdy_n, hbdy_n
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::  ubdy_s, vbdy_s, hbdy_s
-    
+   INTEGER :: bdy_tinterp = 0
+
    PUBLIC   Agrif_tra, Agrif_dyn, Agrif_ssh, Agrif_dyn_ts, Agrif_ssh_ts, Agrif_dta_ts
-   PUBLIC   interpu, interpv, interpunb, interpvnb, interpsshn
+   PUBLIC   interpun, interpvn, interpun2d, interpvn2d 
+   PUBLIC   interptsn,  interpsshn
+   PUBLIC   interpunb, interpvnb, interpub2b, interpvb2b
+   PUBLIC   interpe3t, interpumsk, interpvmsk
+# if defined key_zdftke
+   PUBLIC   Agrif_tke, interpavm
+# endif
 
 #  include "domzgr_substitute.h90"  
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/NST 3.3 , NEMO Consortium (2010)
+   !! NEMO/NST 3.6 , NEMO Consortium (2010)
    !! $Id$
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
 
-   CONTAINS
-   
+CONTAINS
+
    SUBROUTINE Agrif_tra
       !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE Agrif_Tra  ***
-      !!----------------------------------------------------------------------
-      !!
-      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp) ::   zrhox , alpha1, alpha2, alpha3
-      REAL(wp) ::   alpha4, alpha5, alpha6, alpha7
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztsa
+      !!                  ***  ROUTINE Agrif_tra  ***
       !!----------------------------------------------------------------------
       !
       IF( Agrif_Root() )   RETURN
-
-      CALL wrk_alloc( jpi, jpj, jpk, jpts, ztsa ) 
 
       Agrif_SpecialValue    = 0.e0
       Agrif_UseSpecialValue = .TRUE.
-      ztsa(:,:,:,:) = 0.e0
-
-      CALL Agrif_Bc_variable( ztsa, tsn_id, procname=interptsn )
+
+      CALL Agrif_Bc_variable( tsn_id, procname=interptsn )
       Agrif_UseSpecialValue = .FALSE.
-
-      zrhox = Agrif_Rhox()
-
-      alpha1 = ( zrhox - 1. ) * 0.5
-      alpha2 = 1. - alpha1
-
-      alpha3 = ( zrhox - 1. ) / ( zrhox + 1. )
-      alpha4 = 1. - alpha3
-
-      alpha6 = 2. * ( zrhox - 1. ) / ( zrhox + 1. )
-      alpha7 =    - ( zrhox - 1. ) / ( zrhox + 3. )
-      alpha5 = 1. - alpha6 - alpha7
-
-      IF( nbondi == 1 .OR. nbondi == 2 ) THEN
-
-         DO jn = 1, jpts
-            tsa(nlci,:,:,jn) = alpha1 * ztsa(nlci,:,:,jn) + alpha2 * ztsa(nlci-1,:,:,jn)
-            DO jk = 1, jpkm1
-               DO jj = 1, jpj
-                  IF( umask(nlci-2,jj,jk) == 0.e0 ) THEN
-                     tsa(nlci-1,jj,jk,jn) = tsa(nlci,jj,jk,jn) * tmask(nlci-1,jj,jk)
-                  ELSE
-                     tsa(nlci-1,jj,jk,jn)=(alpha4*tsa(nlci,jj,jk,jn)+alpha3*tsa(nlci-2,jj,jk,jn))*tmask(nlci-1,jj,jk)
-                     IF( un(nlci-2,jj,jk) > 0.e0 ) THEN
-                        tsa(nlci-1,jj,jk,jn)=( alpha6*tsa(nlci-2,jj,jk,jn)+alpha5*tsa(nlci,jj,jk,jn)  &
-                           &                 + alpha7*tsa(nlci-3,jj,jk,jn) ) * tmask(nlci-1,jj,jk)
-                     ENDIF
-                  ENDIF
-               END DO
-            END DO
-         ENDDO
-      ENDIF
-
-      IF( nbondj == 1 .OR. nbondj == 2 ) THEN
-
-         DO jn = 1, jpts
-            tsa(:,nlcj,:,jn) = alpha1 * ztsa(:,nlcj,:,jn) + alpha2 * ztsa(:,nlcj-1,:,jn)
-            DO jk = 1, jpkm1
-               DO ji = 1, jpi
-                  IF( vmask(ji,nlcj-2,jk) == 0.e0 ) THEN
-                     tsa(ji,nlcj-1,jk,jn) = tsa(ji,nlcj,jk,jn) * tmask(ji,nlcj-1,jk)
-                  ELSE
-                     tsa(ji,nlcj-1,jk,jn)=(alpha4*tsa(ji,nlcj,jk,jn)+alpha3*tsa(ji,nlcj-2,jk,jn))*tmask(ji,nlcj-1,jk)        
-                     IF (vn(ji,nlcj-2,jk) > 0.e0 ) THEN
-                        tsa(ji,nlcj-1,jk,jn)=( alpha6*tsa(ji,nlcj-2,jk,jn)+alpha5*tsa(ji,nlcj,jk,jn)  &
-                           &                 + alpha7*tsa(ji,nlcj-3,jk,jn) ) * tmask(ji,nlcj-1,jk)
-                     ENDIF
-                  ENDIF
-               END DO
-            END DO
-         ENDDO 
-      ENDIF
-
-      IF( nbondi == -1 .OR. nbondi == 2 ) THEN
-         DO jn = 1, jpts
-            tsa(1,:,:,jn) = alpha1 * ztsa(1,:,:,jn) + alpha2 * ztsa(2,:,:,jn)
-            DO jk = 1, jpkm1
-               DO jj = 1, jpj
-                  IF( umask(2,jj,jk) == 0.e0 ) THEN
-                     tsa(2,jj,jk,jn) = tsa(1,jj,jk,jn) * tmask(2,jj,jk)
-                  ELSE
-                     tsa(2,jj,jk,jn)=(alpha4*tsa(1,jj,jk,jn)+alpha3*tsa(3,jj,jk,jn))*tmask(2,jj,jk)        
-                     IF( un(2,jj,jk) < 0.e0 ) THEN
-                        tsa(2,jj,jk,jn)=(alpha6*tsa(3,jj,jk,jn)+alpha5*tsa(1,jj,jk,jn)+alpha7*tsa(4,jj,jk,jn))*tmask(2,jj,jk)
-                     ENDIF
-                  ENDIF
-               END DO
-            END DO
-         END DO
-      ENDIF
-
-      IF( nbondj == -1 .OR. nbondj == 2 ) THEN
-         DO jn = 1, jpts
-            tsa(:,1,:,jn) = alpha1 * ztsa(:,1,:,jn) + alpha2 * ztsa(:,2,:,jn)
-            DO jk=1,jpk      
-               DO ji=1,jpi
-                  IF( vmask(ji,2,jk) == 0.e0 ) THEN
-                     tsa(ji,2,jk,jn)=tsa(ji,1,jk,jn) * tmask(ji,2,jk)
-                  ELSE
-                     tsa(ji,2,jk,jn)=(alpha4*tsa(ji,1,jk,jn)+alpha3*tsa(ji,3,jk,jn))*tmask(ji,2,jk)
-                     IF( vn(ji,2,jk) < 0.e0 ) THEN
-                        tsa(ji,2,jk,jn)=(alpha6*tsa(ji,3,jk,jn)+alpha5*tsa(ji,1,jk,jn)+alpha7*tsa(ji,4,jk,jn))*tmask(ji,2,jk)
-                     ENDIF
-                  ENDIF
-               END DO
-            END DO
-         ENDDO
-      ENDIF
-      !
-      CALL wrk_dealloc( jpi, jpj, jpk, jpts, ztsa ) 
       !
    END SUBROUTINE Agrif_tra
@@ -175,16 +79,27 @@
       INTEGER, INTENT(in) ::   kt
       !!
-      INTEGER :: ji,jj,jk
+      INTEGER :: ji,jj,jk, j1,j2, i1,i2
       REAL(wp) :: timeref
       REAL(wp) :: z2dt, znugdt
       REAL(wp) :: zrhox, zrhoy
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zua, zva
-      REAL(wp), POINTER, DIMENSION(:,:) :: spgv1, spgu1, zua2d, zva2d
+      REAL(wp), POINTER, DIMENSION(:,:) :: spgv1, spgu1
       !!----------------------------------------------------------------------  
 
       IF( Agrif_Root() )   RETURN
 
-      CALL wrk_alloc( jpi, jpj, spgv1, spgu1, zua2d, zva2d )
-      CALL wrk_alloc( jpi, jpj, jpk, zua, zva )
+      CALL wrk_alloc( jpi, jpj, spgv1, spgu1 )
+
+      Agrif_SpecialValue=0.
+      Agrif_UseSpecialValue = ln_spc_dyn
+
+      CALL Agrif_Bc_variable(un_interp_id,procname=interpun)
+      CALL Agrif_Bc_variable(vn_interp_id,procname=interpvn)
+
+#if defined key_dynspg_flt
+      CALL Agrif_Bc_variable(e1u_id,calledweight=1., procname=interpun2d)
+      CALL Agrif_Bc_variable(e2v_id,calledweight=1., procname=interpvn2d)
+#endif
+
+      Agrif_UseSpecialValue = .FALSE.
 
       zrhox = Agrif_Rhox()
@@ -192,5 +107,4 @@
 
       timeref = 1.
-
       ! time step: leap-frog
       z2dt = 2. * rdt
@@ -200,50 +114,28 @@
       znugdt =  grav * z2dt    
 
-      Agrif_SpecialValue=0.
-      Agrif_UseSpecialValue = ln_spc_dyn
-
-      zua = 0.
-      zva = 0.
-      CALL Agrif_Bc_variable(zua,un_id,procname=interpu)
-      CALL Agrif_Bc_variable(zva,vn_id,procname=interpv)
-      zua2d = 0.
-      zva2d = 0.
-
+      ! prevent smoothing in ghost cells
+      i1=1
+      i2=jpi
+      j1=1
+      j2=jpj
+      IF((nbondj == -1).OR.(nbondj == 2)) j1 = 3
+      IF((nbondj == +1).OR.(nbondj == 2)) j2 = nlcj-2
+      IF((nbondi == -1).OR.(nbondi == 2)) i1 = 3
+      IF((nbondi == +1).OR.(nbondi == 2)) i2 = nlci-2
+
+
+      IF((nbondi == -1).OR.(nbondi == 2)) THEN
 #if defined key_dynspg_flt
-      Agrif_SpecialValue=0.
-      Agrif_UseSpecialValue = ln_spc_dyn
-      CALL Agrif_Bc_variable(zua2d,e1u_id,calledweight=1.,procname=interpu2d)
-      CALL Agrif_Bc_variable(zva2d,e2v_id,calledweight=1.,procname=interpv2d)
-#endif
-      Agrif_UseSpecialValue = .FALSE.
-
-
-      IF((nbondi == -1).OR.(nbondi == 2)) THEN
-
-#if defined key_dynspg_flt
-         DO jj=1,jpj
-            laplacu(2,jj) = timeref * (zua2d(2,jj)/(zrhoy*e2u(2,jj)))*umask(2,jj,1)
-         END DO
-#endif
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               ua(2,jj,jk) = (ua(2,jj,jk) - z2dt * znugdt * laplacu(2,jj))*umask(2,jj,jk)
+            END DO
+         END DO
+
+         spgu(2,:)=0.
 
          DO jk=1,jpkm1
             DO jj=1,jpj
-               ua(1:2,jj,jk) = (zua(1:2,jj,jk)/(zrhoy*e2u(1:2,jj)))
-               ua(1:2,jj,jk) = ua(1:2,jj,jk) / fse3u_a(1:2,jj,jk)
-            END DO
-         END DO
-
-#if defined key_dynspg_flt
-         DO jk=1,jpkm1
-            DO jj=1,jpj
-               ua(2,jj,jk) = (ua(2,jj,jk) - z2dt * znugdt * laplacu(2,jj))*umask(2,jj,jk)
-            END DO
-         END DO
-
-         spgu(2,:)=0.
-
-         DO jk=1,jpkm1
-            DO jj=1,jpj
-               spgu(2,jj)=spgu(2,jj)+fse3u_a(2,jj,jk)*ua(2,jj,jk)
+               spgu(2,jj)=spgu(2,jj)+fse3u(2,jj,jk)*ua(2,jj,jk)
             END DO
          END DO
@@ -251,5 +143,5 @@
          DO jj=1,jpj
             IF (umask(2,jj,1).NE.0.) THEN
-               spgu(2,jj)=spgu(2,jj)*hur_a(2,jj)
+               spgu(2,jj)=spgu(2,jj)/hu(2,jj)
             ENDIF
          END DO
@@ -259,5 +151,5 @@
 
          DO jk=1,jpkm1
-            DO jj=1,jpj
+            DO jj=j1,j2
                ua(2,jj,jk) = 0.25*(ua(1,jj,jk)+2.*ua(2,jj,jk)+ua(3,jj,jk))
                ua(2,jj,jk) = ua(2,jj,jk) * umask(2,jj,jk)
@@ -269,5 +161,5 @@
          DO jk=1,jpkm1
             DO jj=1,jpj
-               spgu1(2,jj)=spgu1(2,jj)+fse3u_a(2,jj,jk)*ua(2,jj,jk)
+               spgu1(2,jj)=spgu1(2,jj)+fse3u(2,jj,jk)*ua(2,jj,jk)
             END DO
          END DO
@@ -275,18 +167,11 @@
          DO jj=1,jpj
             IF (umask(2,jj,1).NE.0.) THEN
-               spgu1(2,jj)=spgu1(2,jj)*hur_a(2,jj)
-            ENDIF
-         END DO
-
-         DO jk=1,jpkm1
-            DO jj=1,jpj
+               spgu1(2,jj)=spgu1(2,jj)/hu(2,jj)
+            ENDIF
+         END DO
+
+         DO jk=1,jpkm1
+            DO jj=j1,j2
                ua(2,jj,jk) = (ua(2,jj,jk)+spgu(2,jj)-spgu1(2,jj))*umask(2,jj,jk)
-            END DO
-         END DO
-
-         DO jk=1,jpkm1
-            DO jj=1,jpj
-               va(2,jj,jk) = (zva(2,jj,jk)/(zrhox*e1v(2,jj)))*vmask(2,jj,jk)
-               va(2,jj,jk) = va(2,jj,jk) / fse3v_a(2,jj,jk)
             END DO
          END DO
@@ -300,9 +185,7 @@
             END DO
          END DO
-
          DO jj=1,jpj
             spgv1(2,jj)=spgv1(2,jj)*hvr_a(2,jj)
          END DO
-
          DO jk=1,jpkm1
             DO jj=1,jpj
@@ -316,35 +199,18 @@
       IF((nbondi == 1).OR.(nbondi == 2)) THEN
 #if defined key_dynspg_flt
-         DO jj=1,jpj
-            laplacu(nlci-2,jj) = timeref * (zua2d(nlci-2,jj)/(zrhoy*e2u(nlci-2,jj)))
-         END DO
-#endif
-
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               ua(nlci-2,jj,jk) = (ua(nlci-2,jj,jk)- z2dt * znugdt * laplacu(nlci-2,jj))*umask(nlci-2,jj,jk)
+            END DO
+         END DO
+         spgu(nlci-2,:)=0.
          DO jk=1,jpkm1
             DO jj=1,jpj
-               ua(nlci-2:nlci-1,jj,jk) = (zua(nlci-2:nlci-1,jj,jk)/(zrhoy*e2u(nlci-2:nlci-1,jj)))
-               ua(nlci-2:nlci-1,jj,jk) = ua(nlci-2:nlci-1,jj,jk) / fse3u_a(nlci-2:nlci-1,jj,jk)
-            END DO
-         END DO
-
-#if defined key_dynspg_flt
-         DO jk=1,jpkm1
-            DO jj=1,jpj
-               ua(nlci-2,jj,jk) = (ua(nlci-2,jj,jk)- z2dt * znugdt * laplacu(nlci-2,jj))*umask(nlci-2,jj,jk)
-            END DO
-         END DO
-
-
-         spgu(nlci-2,:)=0.
-
-         do jk=1,jpkm1
-            do jj=1,jpj
-               spgu(nlci-2,jj)=spgu(nlci-2,jj)+fse3u_a(nlci-2,jj,jk)*ua(nlci-2,jj,jk)
-            enddo
-         enddo
-
+               spgu(nlci-2,jj)=spgu(nlci-2,jj)+fse3u(nlci-2,jj,jk)*ua(nlci-2,jj,jk)
+            ENDDO
+         ENDDO
          DO jj=1,jpj
             IF (umask(nlci-2,jj,1).NE.0.) THEN
-               spgu(nlci-2,jj)=spgu(nlci-2,jj)*hur_a(nlci-2,jj)
+               spgu(nlci-2,jj)=spgu(nlci-2,jj)/hu(nlci-2,jj)
             ENDIF
          END DO
@@ -352,38 +218,26 @@
          spgu(nlci-2,:) = ua_b(nlci-2,:)
 #endif
-
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               ua(nlci-2,jj,jk) = 0.25*(ua(nlci-3,jj,jk)+2.*ua(nlci-2,jj,jk)+ua(nlci-1,jj,jk))
+
+               ua(nlci-2,jj,jk) = ua(nlci-2,jj,jk) * umask(nlci-2,jj,jk)
+
+            END DO
+         END DO
+         spgu1(nlci-2,:)=0.
          DO jk=1,jpkm1
             DO jj=1,jpj
-               ua(nlci-2,jj,jk) = 0.25*(ua(nlci-3,jj,jk)+2.*ua(nlci-2,jj,jk)+ua(nlci-1,jj,jk))
-
-               ua(nlci-2,jj,jk) = ua(nlci-2,jj,jk) * umask(nlci-2,jj,jk)
-
-            END DO
-         END DO
-
-         spgu1(nlci-2,:)=0.
-
-         DO jk=1,jpkm1
-            DO jj=1,jpj
-               spgu1(nlci-2,jj)=spgu1(nlci-2,jj)+fse3u_a(nlci-2,jj,jk)*ua(nlci-2,jj,jk)*umask(nlci-2,jj,jk)
-            END DO
-         END DO
-
+               spgu1(nlci-2,jj)=spgu1(nlci-2,jj)+fse3u(nlci-2,jj,jk)*ua(nlci-2,jj,jk)*umask(nlci-2,jj,jk)
+            END DO
+         END DO
          DO jj=1,jpj
             IF (umask(nlci-2,jj,1).NE.0.) THEN
-               spgu1(nlci-2,jj)=spgu1(nlci-2,jj)*hur_a(nlci-2,jj)
-            ENDIF
-         END DO
-
-         DO jk=1,jpkm1
-            DO jj=1,jpj
+               spgu1(nlci-2,jj)=spgu1(nlci-2,jj)/hu(nlci-2,jj)
+            ENDIF
+         END DO
+         DO jk=1,jpkm1
+            DO jj=j1,j2
                ua(nlci-2,jj,jk) = (ua(nlci-2,jj,jk)+spgu(nlci-2,jj)-spgu1(nlci-2,jj))*umask(nlci-2,jj,jk)
-            END DO
-         END DO
-
-         DO jk=1,jpkm1
-            DO jj=1,jpj-1
-               va(nlci-1,jj,jk) = (zva(nlci-1,jj,jk)/(zrhox*e1v(nlci-1,jj)))*vmask(nlci-1,jj,jk)
-               va(nlci-1,jj,jk) = va(nlci-1,jj,jk) / fse3v_a(nlci-1,jj,jk)
             END DO
          END DO
@@ -414,17 +268,4 @@
 
 #if defined key_dynspg_flt
-         DO ji=1,jpi
-            laplacv(ji,2) = timeref * (zva2d(ji,2)/(zrhox*e1v(ji,2)))
-         END DO
-#endif
-
-         DO jk=1,jpkm1
-            DO ji=1,jpi
-               va(ji,1:2,jk) = (zva(ji,1:2,jk)/(zrhox*e1v(ji,1:2)))
-               va(ji,1:2,jk) = va(ji,1:2,jk) / fse3v_a(ji,1:2,jk)
-            END DO
-         END DO
-
-#if defined key_dynspg_flt
          DO jk=1,jpkm1
             DO ji=1,jpi
@@ -437,5 +278,5 @@
          DO jk=1,jpkm1
             DO ji=1,jpi
-               spgv(ji,2)=spgv(ji,2)+fse3v_a(ji,2,jk)*va(ji,2,jk)
+               spgv(ji,2)=spgv(ji,2)+fse3v(ji,2,jk)*va(ji,2,jk)
             END DO
          END DO
@@ -443,5 +284,5 @@
          DO ji=1,jpi
             IF (vmask(ji,2,1).NE.0.) THEN
-               spgv(ji,2)=spgv(ji,2)*hvr_a(ji,2)
+               spgv(ji,2)=spgv(ji,2)/hv(ji,2)
             ENDIF
          END DO
@@ -451,5 +292,5 @@
 
          DO jk=1,jpkm1
-            DO ji=1,jpi
+            DO ji=i1,i2
                va(ji,2,jk)=0.25*(va(ji,1,jk)+2.*va(ji,2,jk)+va(ji,3,jk))
                va(ji,2,jk)=va(ji,2,jk)*vmask(ji,2,jk)
@@ -461,5 +302,5 @@
          DO jk=1,jpkm1
             DO ji=1,jpi
-               spgv1(ji,2)=spgv1(ji,2)+fse3v_a(ji,2,jk)*va(ji,2,jk)*vmask(ji,2,jk)
+               spgv1(ji,2)=spgv1(ji,2)+fse3v(ji,2,jk)*va(ji,2,jk)*vmask(ji,2,jk)
             END DO
          END DO
@@ -467,5 +308,5 @@
          DO ji=1,jpi
             IF (vmask(ji,2,1).NE.0.) THEN
-               spgv1(ji,2)=spgv1(ji,2)*hvr_a(ji,2)
+               spgv1(ji,2)=spgv1(ji,2)/hv(ji,2)
             ENDIF
          END DO
@@ -474,11 +315,4 @@
             DO ji=1,jpi
                va(ji,2,jk) = (va(ji,2,jk)+spgv(ji,2)-spgv1(ji,2))*vmask(ji,2,jk)
-            END DO
-         END DO
-
-         DO jk=1,jpkm1
-            DO ji=1,jpi
-               ua(ji,2,jk) = (zua(ji,2,jk)/(zrhoy*e2u(ji,2)))*umask(ji,2,jk) 
-               ua(ji,2,jk) = ua(ji,2,jk) / fse3u_a(ji,2,jk)
             END DO
          END DO
@@ -508,17 +342,4 @@
 
 #if defined key_dynspg_flt
-         DO ji=1,jpi
-            laplacv(ji,nlcj-2) = timeref * (zva2d(ji,nlcj-2)/(zrhox*e1v(ji,nlcj-2)))
-         END DO
-#endif
-
-         DO jk=1,jpkm1
-            DO ji=1,jpi
-               va(ji,nlcj-2:nlcj-1,jk) = (zva(ji,nlcj-2:nlcj-1,jk)/(zrhox*e1v(ji,nlcj-2:nlcj-1)))
-               va(ji,nlcj-2:nlcj-1,jk) = va(ji,nlcj-2:nlcj-1,jk) / fse3v_a(ji,nlcj-2:nlcj-1,jk)
-            END DO
-         END DO
-
-#if defined key_dynspg_flt
          DO jk=1,jpkm1
             DO ji=1,jpi
@@ -527,9 +348,10 @@
          END DO
 
+
          spgv(:,nlcj-2)=0.
 
          DO jk=1,jpkm1
             DO ji=1,jpi
-               spgv(ji,nlcj-2)=spgv(ji,nlcj-2)+fse3v_a(ji,nlcj-2,jk)*va(ji,nlcj-2,jk)
+               spgv(ji,nlcj-2)=spgv(ji,nlcj-2)+fse3v(ji,nlcj-2,jk)*va(ji,nlcj-2,jk)
             END DO
          END DO
@@ -537,7 +359,8 @@
          DO ji=1,jpi
             IF (vmask(ji,nlcj-2,1).NE.0.) THEN
-               spgv(ji,nlcj-2)=spgv(ji,nlcj-2)*hvr_a(ji,nlcj-2)
-            ENDIF
-         END DO
+               spgv(ji,nlcj-2)=spgv(ji,nlcj-2)/hv(ji,nlcj-2)
+            ENDIF
+         END DO
+
 #else
          spgv(:,nlcj-2)=va_b(:,nlcj-2)
@@ -545,5 +368,5 @@
 
          DO jk=1,jpkm1
-            DO ji=1,jpi
+            DO ji=i1,i2
                va(ji,nlcj-2,jk)=0.25*(va(ji,nlcj-3,jk)+2.*va(ji,nlcj-2,jk)+va(ji,nlcj-1,jk))
                va(ji,nlcj-2,jk) = va(ji,nlcj-2,jk) * vmask(ji,nlcj-2,jk)
@@ -555,5 +378,5 @@
          DO jk=1,jpkm1
             DO ji=1,jpi
-               spgv1(ji,nlcj-2)=spgv1(ji,nlcj-2)+fse3v_a(ji,nlcj-2,jk)*va(ji,nlcj-2,jk)
+               spgv1(ji,nlcj-2)=spgv1(ji,nlcj-2)+fse3v(ji,nlcj-2,jk)*va(ji,nlcj-2,jk)
             END DO
          END DO
@@ -561,5 +384,5 @@
          DO ji=1,jpi
             IF (vmask(ji,nlcj-2,1).NE.0.) THEN
-               spgv1(ji,nlcj-2)=spgv1(ji,nlcj-2)*hvr_a(ji,nlcj-2)
+               spgv1(ji,nlcj-2)=spgv1(ji,nlcj-2)/hv(ji,nlcj-2)
             ENDIF
          END DO
@@ -568,11 +391,4 @@
             DO ji=1,jpi
                va(ji,nlcj-2,jk) = (va(ji,nlcj-2,jk)+spgv(ji,nlcj-2)-spgv1(ji,nlcj-2))*vmask(ji,nlcj-2,jk)
-            END DO
-         END DO
-
-         DO jk=1,jpkm1
-            DO ji=1,jpi
-               ua(ji,nlcj-1,jk) = (zua(ji,nlcj-1,jk)/(zrhoy*e2u(ji,nlcj-1)))*umask(ji,nlcj-1,jk)
-               ua(ji,nlcj-1,jk) = ua(ji,nlcj-1,jk) / fse3u_a(ji,nlcj-1,jk)
             END DO
          END DO
@@ -600,6 +416,5 @@
       ENDIF
       !
-      CALL wrk_dealloc( jpi, jpj, spgv1, spgu1, zua2d, zva2d )
-      CALL wrk_dealloc( jpi, jpj, jpk, zua, zva )
+      CALL wrk_dealloc( jpi, jpj, spgv1, spgu1 )
       !
    END SUBROUTINE Agrif_dyn
@@ -620,9 +435,9 @@
          DO jj=1,jpj
             va_e(2,jj) = vbdy_w(jj) * hvr_e(2,jj)
-! Specified fluxes:
+            ! Specified fluxes:
             ua_e(2,jj) = ubdy_w(jj) * hur_e(2,jj)
-! Characteristics method:
-!alt            ua_e(2,jj) = 0.5_wp * ( ubdy_w(jj) * hur_e(2,jj) + ua_e(3,jj) &
-!alt                       &           - sqrt(grav * hur_e(2,jj)) * (sshn_e(3,jj) - hbdy_w(jj)) )
+            ! Characteristics method:
+            !alt            ua_e(2,jj) = 0.5_wp * ( ubdy_w(jj) * hur_e(2,jj) + ua_e(3,jj) &
+            !alt                       &           - sqrt(grav * hur_e(2,jj)) * (sshn_e(3,jj) - hbdy_w(jj)) )
          END DO
       ENDIF
@@ -631,9 +446,9 @@
          DO jj=1,jpj
             va_e(nlci-1,jj) = vbdy_e(jj) * hvr_e(nlci-1,jj)
-! Specified fluxes:
+            ! Specified fluxes:
             ua_e(nlci-2,jj) = ubdy_e(jj) * hur_e(nlci-2,jj)
-! Characteristics method:
-!alt            ua_e(nlci-2,jj) = 0.5_wp * ( ubdy_e(jj) * hur_e(nlci-2,jj) + ua_e(nlci-3,jj) &
-!alt                            &           + sqrt(grav * hur_e(nlci-2,jj)) * (sshn_e(nlci-2,jj) - hbdy_e(jj)) )
+            ! Characteristics method:
+            !alt            ua_e(nlci-2,jj) = 0.5_wp * ( ubdy_e(jj) * hur_e(nlci-2,jj) + ua_e(nlci-3,jj) &
+            !alt                            &           + sqrt(grav * hur_e(nlci-2,jj)) * (sshn_e(nlci-2,jj) - hbdy_e(jj)) )
          END DO
       ENDIF
@@ -642,9 +457,9 @@
          DO ji=1,jpi
             ua_e(ji,2) = ubdy_s(ji) * hur_e(ji,2)
-! Specified fluxes:
+            ! Specified fluxes:
             va_e(ji,2) = vbdy_s(ji) * hvr_e(ji,2)
-! Characteristics method:
-!alt            va_e(ji,2) = 0.5_wp * ( vbdy_s(ji) * hvr_e(ji,2) + va_e(ji,3) &
-!alt                       &           - sqrt(grav * hvr_e(ji,2)) * (sshn_e(ji,3) - hbdy_s(ji)) )
+            ! Characteristics method:
+            !alt            va_e(ji,2) = 0.5_wp * ( vbdy_s(ji) * hvr_e(ji,2) + va_e(ji,3) &
+            !alt                       &           - sqrt(grav * hvr_e(ji,2)) * (sshn_e(ji,3) - hbdy_s(ji)) )
          END DO
       ENDIF
@@ -653,9 +468,9 @@
          DO ji=1,jpi
             ua_e(ji,nlcj-1) = ubdy_n(ji) * hur_e(ji,nlcj-1)
-! Specified fluxes:
+            ! Specified fluxes:
             va_e(ji,nlcj-2) = vbdy_n(ji) * hvr_e(ji,nlcj-2)
-! Characteristics method:
-!alt            va_e(ji,nlcj-2) = 0.5_wp * ( vbdy_n(ji) * hvr_e(ji,nlcj-2)  + va_e(ji,nlcj-3) &
-!alt                            &           + sqrt(grav * hvr_e(ji,nlcj-2)) * (sshn_e(ji,nlcj-2) - hbdy_n(ji)) )
+            ! Characteristics method:
+            !alt            va_e(ji,nlcj-2) = 0.5_wp * ( vbdy_n(ji) * hvr_e(ji,nlcj-2)  + va_e(ji,nlcj-3) &
+            !alt                            &           + sqrt(grav * hvr_e(ji,nlcj-2)) * (sshn_e(ji,nlcj-2) - hbdy_n(ji)) )
          END DO
       ENDIF
@@ -672,9 +487,5 @@
       INTEGER :: ji, jj
       LOGICAL :: ll_int_cons
-      REAL(wp) :: zrhox, zrhoy, zrhot, zt
-      REAL(wp) :: zaa, zab, zat
-      REAL(wp) :: zt0, zt1
-      REAL(wp), POINTER, DIMENSION(:,:) :: zunb, zvnb, zsshn
-      REAL(wp), POINTER, DIMENSION(:,:) :: zuab, zvab, zubb, zvbb, zutn, zvtn
+      REAL(wp) :: zrhot, zt
       !!----------------------------------------------------------------------  
 
@@ -682,18 +493,7 @@
 
       ll_int_cons = ln_bt_fw ! Assume conservative temporal integration in
-                             ! the forward case only
-
-      zrhox = Agrif_Rhox()
-      zrhoy = Agrif_Rhoy()
+      ! the forward case only
+
       zrhot = Agrif_rhot()
-
-      IF ( kt==nit000 ) THEN ! Allocate boundary data arrays
-         ALLOCATE( ubdy_w(jpj), vbdy_w(jpj), hbdy_w(jpj))
-         ALLOCATE( ubdy_e(jpj), vbdy_e(jpj), hbdy_e(jpj))
-         ALLOCATE( ubdy_n(jpi), vbdy_n(jpi), hbdy_n(jpi))
-         ALLOCATE( ubdy_s(jpi), vbdy_s(jpi), hbdy_s(jpi))
-      ENDIF
-
-      CALL wrk_alloc( jpi, jpj, zunb, zvnb, zsshn )
 
       ! "Central" time index for interpolation:
@@ -707,5 +507,5 @@
       Agrif_SpecialValue    = 0.e0
       Agrif_UseSpecialValue = .TRUE.
-      CALL Agrif_Bc_variable(zsshn, sshn_id,calledweight=zt, procname=interpsshn )
+      CALL Agrif_Bc_variable(sshn_id,calledweight=zt, procname=interpsshn )
       Agrif_UseSpecialValue = .FALSE.
 
@@ -715,333 +515,827 @@
 
       IF (ll_int_cons) THEN ! Conservative interpolation
-         CALL wrk_alloc( jpi, jpj, zuab, zvab, zubb, zvbb, zutn, zvtn )
-         zuab(:,:) = 0._wp ; zvab(:,:) = 0._wp
-         zubb(:,:) = 0._wp ; zvbb(:,:) = 0._wp
-         zutn(:,:) = 0._wp ; zvtn(:,:) = 0._wp
-         CALL Agrif_Bc_variable(zubb,unb_id ,calledweight=0._wp, procname=interpunb) ! Before
-         CALL Agrif_Bc_variable(zvbb,vnb_id ,calledweight=0._wp, procname=interpvnb)
-         CALL Agrif_Bc_variable(zuab,unb_id ,calledweight=1._wp, procname=interpunb) ! After
-         CALL Agrif_Bc_variable(zvab,vnb_id ,calledweight=1._wp, procname=interpvnb)
-         CALL Agrif_Bc_variable(zutn,ub2b_id,calledweight=1._wp, procname=interpub2b)! Time integrated
-         CALL Agrif_Bc_variable(zvtn,vb2b_id,calledweight=1._wp, procname=interpvb2b)
-         
+         ! orders matters here !!!!!!
+         CALL Agrif_Bc_variable(ub2b_interp_id,calledweight=1._wp, procname=interpub2b) ! Time integrated
+         CALL Agrif_Bc_variable(vb2b_interp_id,calledweight=1._wp, procname=interpvb2b)
+         bdy_tinterp = 1
+         CALL Agrif_Bc_variable(unb_id ,calledweight=1._wp, procname=interpunb) ! After
+         CALL Agrif_Bc_variable(vnb_id ,calledweight=1._wp, procname=interpvnb)
+         bdy_tinterp = 2
+         CALL Agrif_Bc_variable(unb_id ,calledweight=0._wp, procname=interpunb) ! Before
+         CALL Agrif_Bc_variable(vnb_id ,calledweight=0._wp, procname=interpvnb)         
+      ELSE ! Linear interpolation
+         bdy_tinterp = 0
+         ubdy_w(:) = 0.e0 ; vbdy_w(:) = 0.e0 
+         ubdy_e(:) = 0.e0 ; vbdy_e(:) = 0.e0 
+         ubdy_n(:) = 0.e0 ; vbdy_n(:) = 0.e0 
+         ubdy_s(:) = 0.e0 ; vbdy_s(:) = 0.e0 
+         CALL Agrif_Bc_variable(unb_id,calledweight=zt, procname=interpunb)
+         CALL Agrif_Bc_variable(vnb_id,calledweight=zt, procname=interpvnb)
+      ENDIF
+      Agrif_UseSpecialValue = .FALSE.
+      ! 
+   END SUBROUTINE Agrif_dta_ts
+
+   SUBROUTINE Agrif_ssh( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_DYN  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   kt
+      !!
+      !!----------------------------------------------------------------------  
+
+      IF( Agrif_Root() )   RETURN
+
+      IF((nbondi == -1).OR.(nbondi == 2)) THEN
+         ssha(2,:)=ssha(3,:)
+         sshn(2,:)=sshn(3,:)
+      ENDIF
+
+      IF((nbondi == 1).OR.(nbondi == 2)) THEN
+         ssha(nlci-1,:)=ssha(nlci-2,:)
+         sshn(nlci-1,:)=sshn(nlci-2,:)
+      ENDIF
+
+      IF((nbondj == -1).OR.(nbondj == 2)) THEN
+         ssha(:,2)=ssha(:,3)
+         sshn(:,2)=sshn(:,3)
+      ENDIF
+
+      IF((nbondj == 1).OR.(nbondj == 2)) THEN
+         ssha(:,nlcj-1)=ssha(:,nlcj-2)
+         sshn(:,nlcj-1)=sshn(:,nlcj-2)
+      ENDIF
+
+   END SUBROUTINE Agrif_ssh
+
+   SUBROUTINE Agrif_ssh_ts( jn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_ssh_ts  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   jn
+      !!
+      INTEGER :: ji,jj
+      !!----------------------------------------------------------------------  
+
+      IF((nbondi == -1).OR.(nbondi == 2)) THEN
+         DO jj=1,jpj
+            ssha_e(2,jj) = hbdy_w(jj)
+         END DO
+      ENDIF
+
+      IF((nbondi == 1).OR.(nbondi == 2)) THEN
+         DO jj=1,jpj
+            ssha_e(nlci-1,jj) = hbdy_e(jj)
+         END DO
+      ENDIF
+
+      IF((nbondj == -1).OR.(nbondj == 2)) THEN
+         DO ji=1,jpi
+            ssha_e(ji,2) = hbdy_s(ji)
+         END DO
+      ENDIF
+
+      IF((nbondj == 1).OR.(nbondj == 2)) THEN
+         DO ji=1,jpi
+            ssha_e(ji,nlcj-1) = hbdy_n(ji)
+         END DO
+      ENDIF
+
+   END SUBROUTINE Agrif_ssh_ts
+
+# if defined key_zdftke
+   SUBROUTINE Agrif_tke
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_tke  ***
+      !!----------------------------------------------------------------------  
+      REAL(wp) ::   zalpha
+      !
+      zalpha = REAL( Agrif_NbStepint() + Agrif_IRhot() - 1, wp ) / REAL( Agrif_IRhot(), wp )
+      IF( zalpha > 1. )   zalpha = 1.
+      
+      Agrif_SpecialValue    = 0.e0
+      Agrif_UseSpecialValue = .TRUE.
+      
+      CALL Agrif_Bc_variable(avm_id ,calledweight=zalpha, procname=interpavm)       
+              
+      Agrif_UseSpecialValue = .FALSE.
+      !
+   END SUBROUTINE Agrif_tke
+# endif
+
+   SUBROUTINE interptsn(ptab,i1,i2,j1,j2,k1,k2,n1,n2,before,nb,ndir)
+      !!---------------------------------------------
+      !!   *** ROUTINE interptsn ***
+      !!---------------------------------------------
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: ptab
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER :: imin, imax, jmin, jmax
+      REAL(wp) ::   zrhox , zalpha1, zalpha2, zalpha3
+      REAL(wp) ::   zalpha4, zalpha5, zalpha6, zalpha7
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+
+      IF (before) THEN         
+         ptab(i1:i2,j1:j2,k1:k2,n1:n2) = tsn(i1:i2,j1:j2,k1:k2,n1:n2)
+      ELSE
+         !
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         !
+         zrhox = Agrif_Rhox()
+         ! 
+         zalpha1 = ( zrhox - 1. ) * 0.5
+         zalpha2 = 1. - zalpha1
+         ! 
+         zalpha3 = ( zrhox - 1. ) / ( zrhox + 1. )
+         zalpha4 = 1. - zalpha3
+         ! 
+         zalpha6 = 2. * ( zrhox - 1. ) / ( zrhox + 1. )
+         zalpha7 =    - ( zrhox - 1. ) / ( zrhox + 3. )
+         zalpha5 = 1. - zalpha6 - zalpha7
+         !
+         imin = i1
+         imax = i2
+         jmin = j1
+         jmax = j2
+         ! 
+         ! Remove CORNERS
+         IF((nbondj == -1).OR.(nbondj == 2)) jmin = 3
+         IF((nbondj == +1).OR.(nbondj == 2)) jmax = nlcj-2
+         IF((nbondi == -1).OR.(nbondi == 2)) imin = 3
+         IF((nbondi == +1).OR.(nbondi == 2)) imax = nlci-2        
+         !
+         IF( eastern_side) THEN
+            DO jn = 1, jpts
+               tsa(nlci,j1:j2,k1:k2,jn) = zalpha1 * ptab(nlci,j1:j2,k1:k2,jn) + zalpha2 * ptab(nlci-1,j1:j2,k1:k2,jn)
+               DO jk = 1, jpkm1
+                  DO jj = jmin,jmax
+                     IF( umask(nlci-2,jj,jk) == 0.e0 ) THEN
+                        tsa(nlci-1,jj,jk,jn) = tsa(nlci,jj,jk,jn) * tmask(nlci-1,jj,jk)
+                     ELSE
+                        tsa(nlci-1,jj,jk,jn)=(zalpha4*tsa(nlci,jj,jk,jn)+zalpha3*tsa(nlci-2,jj,jk,jn))*tmask(nlci-1,jj,jk)
+                        IF( un(nlci-2,jj,jk) > 0.e0 ) THEN
+                           tsa(nlci-1,jj,jk,jn)=( zalpha6*tsa(nlci-2,jj,jk,jn)+zalpha5*tsa(nlci,jj,jk,jn) & 
+                                 + zalpha7*tsa(nlci-3,jj,jk,jn) ) * tmask(nlci-1,jj,jk)
+                        ENDIF
+                     ENDIF
+                  END DO
+               END DO
+            ENDDO
+         ENDIF
+         ! 
+         IF( northern_side ) THEN            
+            DO jn = 1, jpts
+               tsa(i1:i2,nlcj,k1:k2,jn) = zalpha1 * ptab(i1:i2,nlcj,k1:k2,jn) + zalpha2 * ptab(i1:i2,nlcj-1,k1:k2,jn)
+               DO jk = 1, jpkm1
+                  DO ji = imin,imax
+                     IF( vmask(ji,nlcj-2,jk) == 0.e0 ) THEN
+                        tsa(ji,nlcj-1,jk,jn) = tsa(ji,nlcj,jk,jn) * tmask(ji,nlcj-1,jk)
+                     ELSE
+                        tsa(ji,nlcj-1,jk,jn)=(zalpha4*tsa(ji,nlcj,jk,jn)+zalpha3*tsa(ji,nlcj-2,jk,jn))*tmask(ji,nlcj-1,jk)        
+                        IF (vn(ji,nlcj-2,jk) > 0.e0 ) THEN
+                           tsa(ji,nlcj-1,jk,jn)=( zalpha6*tsa(ji,nlcj-2,jk,jn)+zalpha5*tsa(ji,nlcj,jk,jn)  &
+                                 + zalpha7*tsa(ji,nlcj-3,jk,jn) ) * tmask(ji,nlcj-1,jk)
+                        ENDIF
+                     ENDIF
+                  END DO
+               END DO
+            ENDDO
+         ENDIF
+         !
+         IF( western_side) THEN            
+            DO jn = 1, jpts
+               tsa(1,j1:j2,k1:k2,jn) = zalpha1 * ptab(1,j1:j2,k1:k2,jn) + zalpha2 * ptab(2,j1:j2,k1:k2,jn)
+               DO jk = 1, jpkm1
+                  DO jj = jmin,jmax
+                     IF( umask(2,jj,jk) == 0.e0 ) THEN
+                        tsa(2,jj,jk,jn) = tsa(1,jj,jk,jn) * tmask(2,jj,jk)
+                     ELSE
+                        tsa(2,jj,jk,jn)=(zalpha4*tsa(1,jj,jk,jn)+zalpha3*tsa(3,jj,jk,jn))*tmask(2,jj,jk)        
+                        IF( un(2,jj,jk) < 0.e0 ) THEN
+                           tsa(2,jj,jk,jn)=(zalpha6*tsa(3,jj,jk,jn)+zalpha5*tsa(1,jj,jk,jn)+zalpha7*tsa(4,jj,jk,jn))*tmask(2,jj,jk)
+                        ENDIF
+                     ENDIF
+                  END DO
+               END DO
+            END DO
+         ENDIF
+         !
+         IF( southern_side ) THEN           
+            DO jn = 1, jpts
+               tsa(i1:i2,1,k1:k2,jn) = zalpha1 * ptab(i1:i2,1,k1:k2,jn) + zalpha2 * ptab(i1:i2,2,k1:k2,jn)
+               DO jk=1,jpk      
+                  DO ji=imin,imax
+                     IF( vmask(ji,2,jk) == 0.e0 ) THEN
+                        tsa(ji,2,jk,jn)=tsa(ji,1,jk,jn) * tmask(ji,2,jk)
+                     ELSE
+                        tsa(ji,2,jk,jn)=(zalpha4*tsa(ji,1,jk,jn)+zalpha3*tsa(ji,3,jk,jn))*tmask(ji,2,jk)
+                        IF( vn(ji,2,jk) < 0.e0 ) THEN
+                           tsa(ji,2,jk,jn)=(zalpha6*tsa(ji,3,jk,jn)+zalpha5*tsa(ji,1,jk,jn)+zalpha7*tsa(ji,4,jk,jn))*tmask(ji,2,jk)
+                        ENDIF
+                     ENDIF
+                  END DO
+               END DO
+            ENDDO
+         ENDIF
+         !
+         ! Treatment of corners
+         ! 
+         ! East south
+         IF ((eastern_side).AND.((nbondj == -1).OR.(nbondj == 2))) THEN
+            tsa(nlci-1,2,:,:) = ptab(nlci-1,2,:,:)
+         ENDIF
+         ! East north
+         IF ((eastern_side).AND.((nbondj == 1).OR.(nbondj == 2))) THEN
+            tsa(nlci-1,nlcj-1,:,:) = ptab(nlci-1,nlcj-1,:,:)
+         ENDIF
+         ! West south
+         IF ((western_side).AND.((nbondj == -1).OR.(nbondj == 2))) THEN
+            tsa(2,2,:,:) = ptab(2,2,:,:)
+         ENDIF
+         ! West north
+         IF ((western_side).AND.((nbondj == 1).OR.(nbondj == 2))) THEN
+            tsa(2,nlcj-1,:,:) = ptab(2,nlcj-1,:,:)
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE interptsn
+
+   SUBROUTINE interpsshn(ptab,i1,i2,j1,j2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpsshn  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      !
+      IF( before) THEN
+         ptab(i1:i2,j1:j2) = sshn(i1:i2,j1:j2)
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         IF(western_side)  hbdy_w(j1:j2) = ptab(i1,j1:j2) * tmask(i1,j1:j2,1)
+         IF(eastern_side)  hbdy_e(j1:j2) = ptab(i1,j1:j2) * tmask(i1,j1:j2,1)
+         IF(southern_side) hbdy_s(i1:i2) = ptab(i1:i2,j1) * tmask(i1:i2,j1,1)
+         IF(northern_side) hbdy_n(i1:i2) = ptab(i1:i2,j1) * tmask(i1:i2,j1,1)
+      ENDIF
+      !
+   END SUBROUTINE interpsshn
+
+   SUBROUTINE interpun(ptab,i1,i2,j1,j2,k1,k2, before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpun ***
+      !!---------------------------------------------    
+      !!
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !!
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: zrhoy	
+      !!---------------------------------------------    
+      !
+      IF (before) THEN 
+         DO jk=1,jpk
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk) = e2u(ji,jj) * un(ji,jj,jk)
+                  ptab(ji,jj,jk) = ptab(ji,jj,jk) * fse3u(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE
+         zrhoy = Agrif_Rhoy()
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               ua(i1:i2,jj,jk) = (ptab(i1:i2,jj,jk)/(zrhoy*e2u(i1:i2,jj)))
+               ua(i1:i2,jj,jk) = ua(i1:i2,jj,jk) / fse3u(i1:i2,jj,jk)
+            END DO
+         END DO
+      ENDIF
+      ! 
+   END SUBROUTINE interpun
+
+
+   SUBROUTINE interpun2d(ptab,i1,i2,j1,j2,before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpun ***
+      !!---------------------------------------------    
+      !
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !
+      INTEGER :: ji,jj
+      REAL(wp) :: ztref
+      REAL(wp) :: zrhoy	
+      !!---------------------------------------------    
+      !
+      ztref = 1.
+
+      IF (before) THEN 
+         DO jj=j1,j2
+            DO ji=i1,MIN(i2,nlci-1)
+               ptab(ji,jj) = e2u(ji,jj) * ((gcx(ji+1,jj) - gcx(ji,jj))/e1u(ji,jj)) 
+            END DO
+         END DO
+      ELSE
+         zrhoy = Agrif_Rhoy()
+         DO jj=j1,j2
+            laplacu(i1:i2,jj) = ztref * (ptab(i1:i2,jj)/(zrhoy*e2u(i1:i2,jj))) !*umask(i1:i2,jj,1)
+         END DO
+      ENDIF
+      ! 
+   END SUBROUTINE interpun2d
+
+
+   SUBROUTINE interpvn(ptab,i1,i2,j1,j2,k1,k2, before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpvn ***
+      !!---------------------------------------------    
+      !
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: zrhox	
+      !!---------------------------------------------    
+      !      
+      IF (before) THEN          
+         !interpv entre 1 et k2 et interpv2d en jpkp1
+         DO jk=k1,jpk
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk) = e1v(ji,jj) * vn(ji,jj,jk)
+                  ptab(ji,jj,jk) = ptab(ji,jj,jk) * fse3v(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE          
+         zrhox= Agrif_Rhox()
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               va(i1:i2,jj,jk) = (ptab(i1:i2,jj,jk)/(zrhox*e1v(i1:i2,jj)))
+               va(i1:i2,jj,jk) = va(i1:i2,jj,jk) / fse3v(i1:i2,jj,jk)
+            END DO
+         END DO
+      ENDIF
+      !        
+   END SUBROUTINE interpvn
+
+   SUBROUTINE interpvn2d(ptab,i1,i2,j1,j2,before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpvn ***
+      !!---------------------------------------------    
+      !
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !
+      INTEGER :: ji,jj
+      REAL(wp) :: zrhox	
+      REAL(wp) :: ztref
+      !!---------------------------------------------    
+      ! 
+      ztref = 1.    
+      IF (before) THEN 
+         !interpv entre 1 et k2 et interpv2d en jpkp1
+         DO jj=j1,MIN(j2,nlcj-1)
+            DO ji=i1,i2
+               ptab(ji,jj) = e1v(ji,jj) * ((gcx(ji,jj+1) - gcx(ji,jj))/e2v(ji,jj)) * vmask(ji,jj,1)
+            END DO
+         END DO
+      ELSE           
+         zrhox = Agrif_Rhox()
+         DO ji=i1,i2
+            laplacv(ji,j1:j2) = ztref * (ptab(ji,j1:j2)/(zrhox*e1v(ji,j1:j2)))
+         END DO
+      ENDIF
+      !      
+   END SUBROUTINE interpvn2d
+
+   SUBROUTINE interpunb(ptab,i1,i2,j1,j2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpunb  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !!
+      INTEGER :: ji,jj
+      REAL(wp) :: zrhoy, zrhot, zt0, zt1, ztcoeff
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      !
+      IF (before) THEN 
+         DO jj=j1,j2
+            DO ji=i1,i2
+               ptab(ji,jj) = un_b(ji,jj) * e2u(ji,jj) * hu(ji,jj) 
+            END DO
+         END DO
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhoy = Agrif_Rhoy()
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot      
+         ! Polynomial interpolation coefficients:
+         IF( bdy_tinterp == 1 ) THEN
+            ztcoeff = zrhot * (  zt1**2._wp * (       zt1 - 1._wp)        &
+                  &      - zt0**2._wp * (       zt0 - 1._wp)        )
+         ELSEIF( bdy_tinterp == 2 ) THEN
+            ztcoeff = zrhot * (  zt1        * (       zt1 - 1._wp)**2._wp &
+                  &      - zt0        * (       zt0 - 1._wp)**2._wp ) 
+
+         ELSE
+            ztcoeff = 1
+         ENDIF
+         !   
+         IF(western_side) THEN
+            ubdy_w(j1:j2) = ubdy_w(j1:j2) + ztcoeff * ptab(i1,j1:j2)  
+         ENDIF
+         IF(eastern_side) THEN
+            ubdy_e(j1:j2) = ubdy_e(j1:j2) + ztcoeff * ptab(i1,j1:j2)  
+         ENDIF
+         IF(southern_side) THEN
+            ubdy_s(i1:i2) = ubdy_s(i1:i2) + ztcoeff * ptab(i1:i2,j1) 
+         ENDIF
+         IF(northern_side) THEN
+            ubdy_n(i1:i2) = ubdy_n(i1:i2) + ztcoeff * ptab(i1:i2,j1) 
+         ENDIF
+         !            
+         IF( bdy_tinterp == 0 .OR. bdy_tinterp == 2) THEN
+            IF(western_side) THEN
+               ubdy_w(j1:j2) = ubdy_w(j1:j2) / (zrhoy*e2u(i1,j1:j2))   &
+                     &                                  * umask(i1,j1:j2,1)
+            ENDIF
+            IF(eastern_side) THEN
+               ubdy_e(j1:j2) = ubdy_e(j1:j2) / (zrhoy*e2u(i1,j1:j2))   &
+                     &                                  * umask(i1,j1:j2,1)
+            ENDIF
+            IF(southern_side) THEN
+               ubdy_s(i1:i2) = ubdy_s(i1:i2) / (zrhoy*e2u(i1:i2,j1))   &
+                     &                                  * umask(i1:i2,j1,1)
+            ENDIF
+            IF(northern_side) THEN
+               ubdy_n(i1:i2) = ubdy_n(i1:i2) / (zrhoy*e2u(i1:i2,j1))   &
+                     &                                  * umask(i1:i2,j1,1)
+            ENDIF
+         ENDIF
+      ENDIF
+      ! 
+   END SUBROUTINE interpunb
+
+   SUBROUTINE interpvnb(ptab,i1,i2,j1,j2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpvnb  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !!
+      INTEGER :: ji,jj
+      REAL(wp) :: zrhox, zrhot, zt0, zt1, ztcoeff   
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      ! 
+      IF (before) THEN 
+         DO jj=j1,j2
+            DO ji=i1,i2
+               ptab(ji,jj) = vn_b(ji,jj) * e1v(ji,jj) * hv(ji,jj) 
+            END DO
+         END DO
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhox = Agrif_Rhox()
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot      
+         IF( bdy_tinterp == 1 ) THEN
+            ztcoeff = zrhot * (  zt1**2._wp * (       zt1 - 1._wp)        &
+                  &      - zt0**2._wp * (       zt0 - 1._wp)        )
+         ELSEIF( bdy_tinterp == 2 ) THEN
+            ztcoeff = zrhot * (  zt1        * (       zt1 - 1._wp)**2._wp &
+                  &      - zt0        * (       zt0 - 1._wp)**2._wp ) 
+
+         ELSE
+            ztcoeff = 1
+         ENDIF
+         !
+         IF(western_side) THEN
+            vbdy_w(j1:j2) = vbdy_w(j1:j2) + ztcoeff * ptab(i1,j1:j2)  
+         ENDIF
+         IF(eastern_side) THEN
+            vbdy_e(j1:j2) = vbdy_e(j1:j2) + ztcoeff * ptab(i1,j1:j2)  
+         ENDIF
+         IF(southern_side) THEN
+            vbdy_s(i1:i2) = vbdy_s(i1:i2) + ztcoeff * ptab(i1:i2,j1)
+         ENDIF
+         IF(northern_side) THEN
+            vbdy_n(i1:i2) = vbdy_n(i1:i2) + ztcoeff * ptab(i1:i2,j1) 
+         ENDIF
+         !            
+         IF( bdy_tinterp == 0 .OR. bdy_tinterp == 2) THEN
+            IF(western_side) THEN
+               vbdy_w(j1:j2) = vbdy_w(j1:j2) / (zrhox*e1v(i1,j1:j2))   &
+                     &                                  * vmask(i1,j1:j2,1)
+            ENDIF
+            IF(eastern_side) THEN
+               vbdy_e(j1:j2) = vbdy_e(j1:j2) / (zrhox*e1v(i1,j1:j2))   &
+                     &                                  * vmask(i1,j1:j2,1)
+            ENDIF
+            IF(southern_side) THEN
+               vbdy_s(i1:i2) = vbdy_s(i1:i2) / (zrhox*e1v(i1:i2,j1))   &
+                     &                                  * vmask(i1:i2,j1,1)
+            ENDIF
+            IF(northern_side) THEN
+               vbdy_n(i1:i2) = vbdy_n(i1:i2) / (zrhox*e1v(i1:i2,j1))   &
+                     &                                  * vmask(i1:i2,j1,1)
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE interpvnb
+
+   SUBROUTINE interpub2b(ptab,i1,i2,j1,j2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpub2b  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !!
+      INTEGER :: ji,jj
+      REAL(wp) :: zrhot, zt0, zt1,zat
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      IF( before ) THEN
+         DO jj=j1,j2
+            DO ji=i1,i2
+               ptab(ji,jj) = ub2_b(ji,jj) * e2u(ji,jj)
+            END DO
+         END DO
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhot = Agrif_rhot()
          ! Time indexes bounds for integration
          zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
          zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot
-
          ! Polynomial interpolation coefficients:
-         zaa = zrhot * (  zt1**2._wp * (       zt1 - 1._wp)        &
-                 &      - zt0**2._wp * (       zt0 - 1._wp)        )
-         zab = zrhot * (  zt1        * (       zt1 - 1._wp)**2._wp &
-                 &      - zt0        * (       zt0 - 1._wp)**2._wp )
          zat = zrhot * (  zt1**2._wp * (-2._wp*zt1 + 3._wp)        &
-                 &      - zt0**2._wp * (-2._wp*zt0 + 3._wp)        ) 
-
-         ! Do time interpolation
-         IF((nbondi == -1).OR.(nbondi == 2)) THEN
-            DO jj=1,jpj
-               zunb(2,jj) = zaa * zuab(2,jj) + zab * zubb(2,jj) + zat * zutn(2,jj)
-               zvnb(2,jj) = zaa * zvab(2,jj) + zab * zvbb(2,jj) + zat * zvtn(2,jj)
-            END DO
-         ENDIF
-         IF((nbondi == 1).OR.(nbondi == 2)) THEN
-            DO jj=1,jpj
-               zunb(nlci-2,jj) = zaa * zuab(nlci-2,jj) + zab * zubb(nlci-2,jj) + zat * zutn(nlci-2,jj)
-               zvnb(nlci-1,jj) = zaa * zvab(nlci-1,jj) + zab * zvbb(nlci-1,jj) + zat * zvtn(nlci-1,jj)
-            END DO
-         ENDIF
-         IF((nbondj == -1).OR.(nbondj == 2)) THEN
-            DO ji=1,jpi
-               zunb(ji,2) = zaa * zuab(ji,2) + zab * zubb(ji,2) + zat * zutn(ji,2)
-               zvnb(ji,2) = zaa * zvab(ji,2) + zab * zvbb(ji,2) + zat * zvtn(ji,2)
-            END DO
-         ENDIF
-         IF((nbondj == 1).OR.(nbondj == 2)) THEN
-            DO ji=1,jpi
-               zunb(ji,nlcj-1) = zaa * zuab(ji,nlcj-1) + zab * zubb(ji,nlcj-1) + zat * zutn(ji,nlcj-1)
-               zvnb(ji,nlcj-2) = zaa * zvab(ji,nlcj-2) + zab * zvbb(ji,nlcj-2) + zat * zvtn(ji,nlcj-2)
-            END DO
-         ENDIF
-         CALL wrk_dealloc( jpi, jpj, zuab, zvab, zubb, zvbb, zutn, zvtn )
-
-      ELSE ! Linear interpolation
-         zunb(:,:) = 0._wp ; zvnb(:,:) = 0._wp
-         CALL Agrif_Bc_variable(zunb,unb_id,calledweight=zt, procname=interpunb)
-         CALL Agrif_Bc_variable(zvnb,vnb_id,calledweight=zt, procname=interpvnb)
-      ENDIF
-      Agrif_UseSpecialValue = .FALSE.
-
-      ! Fill boundary data arrays:
-      IF((nbondi == -1).OR.(nbondi == 2)) THEN
-         DO jj=1,jpj
-               ubdy_w(jj) = (zunb(2,jj)/(zrhoy*e2u(2,jj))) * umask(2,jj,1)
-               vbdy_w(jj) = (zvnb(2,jj)/(zrhox*e1v(2,jj))) * vmask(2,jj,1)
-               hbdy_w(jj) = zsshn(2,jj) * tmask(2,jj,1)
-         END DO
-      ENDIF
-
-      IF((nbondi == 1).OR.(nbondi == 2)) THEN
-         DO jj=1,jpj
-               ubdy_e(jj) = zunb(nlci-2,jj)/(zrhoy*e2u(nlci-2,jj)) * umask(nlci-2,jj,1)
-               vbdy_e(jj) = zvnb(nlci-1,jj)/(zrhox*e1v(nlci-1,jj)) * vmask(nlci-1,jj,1)
-               hbdy_e(jj) = zsshn(nlci-1,jj) * tmask(nlci-1,jj,1)
-         END DO
-      ENDIF
-
-      IF((nbondj == -1).OR.(nbondj == 2)) THEN
-         DO ji=1,jpi
-               ubdy_s(ji) = zunb(ji,2)/(zrhoy*e2u(ji,2)) * umask(ji,2,1)
-               vbdy_s(ji) = zvnb(ji,2)/(zrhox*e1v(ji,2)) * vmask(ji,2,1)
-               hbdy_s(ji) = zsshn(ji,2) * tmask(ji,2,1)
-         END DO
-      ENDIF
-
-      IF((nbondj == 1).OR.(nbondj == 2)) THEN
-         DO ji=1,jpi
-            ubdy_n(ji) = zunb(ji,nlcj-1)/(zrhoy*e2u(ji,nlcj-1)) * umask(ji,nlcj-1,1)
-            vbdy_n(ji) = zvnb(ji,nlcj-2)/(zrhox*e1v(ji,nlcj-2)) * vmask(ji,nlcj-2,1)
-            hbdy_n(ji) = zsshn(ji,nlcj-1) * tmask(ji,nlcj-1,1)
-         END DO
-      ENDIF
-
-      CALL wrk_dealloc( jpi, jpj, zunb, zvnb, zsshn )
-
-   END SUBROUTINE Agrif_dta_ts
-
-   SUBROUTINE Agrif_ssh( kt )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE Agrif_DYN  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) ::   kt
-      !!
-      !!----------------------------------------------------------------------  
-
-      IF( Agrif_Root() )   RETURN
-
-
-      IF((nbondi == -1).OR.(nbondi == 2)) THEN
-         ssha(2,:)=ssha(3,:)
-         sshn(2,:)=sshn(3,:)
-      ENDIF
-
-      IF((nbondi == 1).OR.(nbondi == 2)) THEN
-         ssha(nlci-1,:)=ssha(nlci-2,:)
-         sshn(nlci-1,:)=sshn(nlci-2,:)        
-      ENDIF
-
-      IF((nbondj == -1).OR.(nbondj == 2)) THEN
-         ssha(:,2)=ssha(:,3)
-         sshn(:,2)=sshn(:,3)
-      ENDIF
-
-      IF((nbondj == 1).OR.(nbondj == 2)) THEN
-         ssha(:,nlcj-1)=ssha(:,nlcj-2)
-         sshn(:,nlcj-1)=sshn(:,nlcj-2)                
-      ENDIF
-
-   END SUBROUTINE Agrif_ssh
-
-   SUBROUTINE Agrif_ssh_ts( jn )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE Agrif_ssh_ts  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) ::   jn
+               &      - zt0**2._wp * (-2._wp*zt0 + 3._wp)        ) 
+         ! 
+         IF(western_side ) ubdy_w(j1:j2) = zat * ptab(i1,j1:j2)  
+         IF(eastern_side ) ubdy_e(j1:j2) = zat * ptab(i1,j1:j2)  
+         IF(southern_side) ubdy_s(i1:i2) = zat * ptab(i1:i2,j1) 
+         IF(northern_side) ubdy_n(i1:i2) = zat * ptab(i1:i2,j1) 
+      ENDIF
+      ! 
+   END SUBROUTINE interpub2b
+
+   SUBROUTINE interpvb2b(ptab,i1,i2,j1,j2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpvb2b  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) :: i1,i2,j1,j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
       !!
       INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      IF((nbondi == -1).OR.(nbondi == 2)) THEN
-         DO jj=1,jpj
-            ssha_e(2,jj) = hbdy_w(jj)
-         END DO
-      ENDIF
-
-      IF((nbondi == 1).OR.(nbondi == 2)) THEN
-         DO jj=1,jpj
-            ssha_e(nlci-1,jj) = hbdy_e(jj)
-         END DO
-      ENDIF
-
-      IF((nbondj == -1).OR.(nbondj == 2)) THEN
-         DO ji=1,jpi
-            ssha_e(ji,2) = hbdy_s(ji)
-         END DO
-      ENDIF
-
-      IF((nbondj == 1).OR.(nbondj == 2)) THEN
-         DO ji=1,jpi
-            ssha_e(ji,nlcj-1) = hbdy_n(ji)
-         END DO
-      ENDIF
-
-   END SUBROUTINE Agrif_ssh_ts
-
-   SUBROUTINE interpsshn(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpsshn  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      tabres(i1:i2,j1:j2) = sshn(i1:i2,j1:j2)
-
-   END SUBROUTINE interpsshn
-
-   SUBROUTINE interpu(tabres,i1,i2,j1,j2,k1,k2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpu  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
-      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj,jk
-      !!----------------------------------------------------------------------  
-
-      DO jk=k1,k2
+      REAL(wp) :: zrhot, zt0, zt1,zat
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      !
+      IF( before ) THEN
          DO jj=j1,j2
             DO ji=i1,i2
-               tabres(ji,jj,jk) = e2u(ji,jj) * un(ji,jj,jk)
-               tabres(ji,jj,jk) = tabres(ji,jj,jk) * fse3u_n(ji,jj,jk)
-            END DO
-         END DO
-      END DO
-   END SUBROUTINE interpu
-
-
-   SUBROUTINE interpu2d(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpu2d  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      DO jj=j1,j2
-         DO ji=i1,i2
-            tabres(ji,jj) = e2u(ji,jj) * ((gcx(ji+1,jj) - gcx(ji,jj))/e1u(ji,jj)) &
-               * umask(ji,jj,1)
-         END DO
-      END DO
-
-   END SUBROUTINE interpu2d
-
-
-   SUBROUTINE interpv(tabres,i1,i2,j1,j2,k1,k2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpv  ***
-      !!----------------------------------------------------------------------  
+               ptab(ji,jj) = vb2_b(ji,jj) * e1v(ji,jj)
+            END DO
+         END DO
+      ELSE      
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot
+         ! Polynomial interpolation coefficients:
+         zat = zrhot * (  zt1**2._wp * (-2._wp*zt1 + 3._wp)        &
+               &      - zt0**2._wp * (-2._wp*zt0 + 3._wp)        ) 
+         !
+         IF(western_side ) vbdy_w(j1:j2) = zat * ptab(i1,j1:j2)  
+         IF(eastern_side ) vbdy_e(j1:j2) = zat * ptab(i1,j1:j2)  
+         IF(southern_side) vbdy_s(i1:i2) = zat * ptab(i1:i2,j1) 
+         IF(northern_side) vbdy_n(i1:i2) = zat * ptab(i1:i2,j1) 
+      ENDIF
+      !      
+   END SUBROUTINE interpvb2b
+
+   SUBROUTINE interpe3t(ptab,i1,i2,j1,j2,k1,k2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpe3t  ***
+      !!----------------------------------------------------------------------  
+      ! 
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
-      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: tabres
-      !!
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
       INTEGER :: ji, jj, jk
-      !!----------------------------------------------------------------------  
-
-      DO jk=k1,k2
-         DO jj=j1,j2
-            DO ji=i1,i2
-               tabres(ji,jj,jk) = e1v(ji,jj) * vn(ji,jj,jk)
-               tabres(ji,jj,jk) = tabres(ji,jj,jk) * fse3v_n(ji,jj,jk)
-            END DO
-         END DO
-      END DO
-
-   END SUBROUTINE interpv
-
-
-   SUBROUTINE interpv2d(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpu2d  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      DO jj=j1,j2
-         DO ji=i1,i2
-            tabres(ji,jj) = e1v(ji,jj) * ((gcx(ji,jj+1) - gcx(ji,jj))/e2v(ji,jj)) &
-               * vmask(ji,jj,1)
-         END DO
-      END DO
-
-   END SUBROUTINE interpv2d
-
-   SUBROUTINE interpunb(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpunb  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      DO jj=j1,j2
-         DO ji=i1,i2
-            tabres(ji,jj) = un_b(ji,jj) * e2u(ji,jj) * hu(ji,jj) 
-         END DO
-      END DO
-
-   END SUBROUTINE interpunb
-
-   SUBROUTINE interpvnb(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpvnb  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      DO jj=j1,j2
-         DO ji=i1,i2
-            tabres(ji,jj) = vn_b(ji,jj) * e1v(ji,jj) * hv(ji,jj)
-         END DO
-      END DO
-
-   END SUBROUTINE interpvnb
-
-   SUBROUTINE interpub2b(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpub2b  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      DO jj=j1,j2
-         DO ji=i1,i2
-            tabres(ji,jj) = ub2_b(ji,jj) * e2u(ji,jj)
-         END DO
-      END DO
-
-   END SUBROUTINE interpub2b
-
-   SUBROUTINE interpvb2b(tabres,i1,i2,j1,j2)
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE interpvb2b  ***
-      !!----------------------------------------------------------------------  
-      INTEGER, INTENT(in) :: i1,i2,j1,j2
-      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
-      !!
-      INTEGER :: ji,jj
-      !!----------------------------------------------------------------------  
-
-      DO jj=j1,j2
-         DO ji=i1,i2
-            tabres(ji,jj) = vb2_b(ji,jj) * e1v(ji,jj)
-         END DO
-      END DO
-
-   END SUBROUTINE interpvb2b
+      LOGICAL :: western_side, eastern_side, northern_side, southern_side
+      REAL(wp) :: ztmpmsk      
+      !!----------------------------------------------------------------------  
+      !    
+      IF (before) THEN
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk) = tmask(ji,jj,jk) * e3t_0(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ! Get velocity mask at boundary edge points:
+                  IF (western_side)  ztmpmsk = umask(ji    ,jj    ,1)
+                  IF (eastern_side)  ztmpmsk = umask(nlci-2,jj    ,1)
+                  IF (northern_side) ztmpmsk = vmask(ji    ,nlcj-2,1)
+                  IF (southern_side) ztmpmsk = vmask(ji    ,2     ,1)
+
+                  IF (ABS(ptab(ji,jj,jk) - tmask(ji,jj,jk) * e3t_0(ji,jj,jk))*ztmpmsk > 1.D-2) THEN
+                     IF (western_side) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the western border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                     ELSEIF (eastern_side) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the eastern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                     ELSEIF (southern_side) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the southern border ji,jj,jk', ji+nimpp-1,jj+njmpp-1,jk
+                     ELSEIF (northern_side) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the northen border ji,jj,jk', ji+nimpp-1,jj+njmpp-1,jk
+                     ENDIF
+                     WRITE(numout,*) '      ptab(ji,jj,jk), fse3t(ji,jj,jk) ', ptab(ji,jj,jk), e3t_0(ji,jj,jk)
+                     kindic_agr = kindic_agr + 1
+                  ENDIF
+               END DO
+            END DO
+         END DO
+
+      ENDIF
+      ! 
+   END SUBROUTINE interpe3t
+
+   SUBROUTINE interpumsk(ptab,i1,i2,j1,j2,k1,k2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpumsk  ***
+      !!----------------------------------------------------------------------  
+      ! 
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
+      INTEGER :: ji, jj, jk
+      LOGICAL :: western_side, eastern_side   
+      !!----------------------------------------------------------------------  
+      !    
+      IF (before) THEN
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk) = umask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE
+
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                   ! Velocity mask at boundary edge points:
+                  IF (ABS(ptab(ji,jj,jk) - umask(ji,jj,jk)) > 1.D-2) THEN
+                     IF (western_side) THEN
+                        WRITE(numout,*) 'ERROR with umask at the western border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), umask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (eastern_side) THEN
+                        WRITE(numout,*) 'ERROR with umask at the eastern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), umask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+
+      ENDIF
+      ! 
+   END SUBROUTINE interpumsk
+
+   SUBROUTINE interpvmsk(ptab,i1,i2,j1,j2,k1,k2,before,nb,ndir)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpvmsk  ***
+      !!----------------------------------------------------------------------  
+      ! 
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
+      INTEGER :: ji, jj, jk
+      LOGICAL :: northern_side, southern_side     
+      !!----------------------------------------------------------------------  
+      !    
+      IF (before) THEN
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk) = vmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE
+
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                   ! Velocity mask at boundary edge points:
+                  IF (ABS(ptab(ji,jj,jk) - vmask(ji,jj,jk)) > 1.D-2) THEN
+                     IF (southern_side) THEN
+                        WRITE(numout,*) 'ERROR with vmask at the southern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), vmask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (northern_side) THEN
+                        WRITE(numout,*) 'ERROR with vmask at the northern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), vmask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+
+      ENDIF
+      ! 
+   END SUBROUTINE interpvmsk
+
+# if defined key_zdftke
+
+   SUBROUTINE interpavm(ptab,i1,i2,j1,j2,k1,k2,before)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interavm  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !!----------------------------------------------------------------------  
+      !      
+      IF( before) THEN
+         ptab (i1:i2,j1:j2,k1:k2) = avm_k(i1:i2,j1:j2,k1:k2)
+      ELSE
+         avm_k(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2)
+      ENDIF
+      !
+   END SUBROUTINE interpavm
+
+# endif /* key_zdftke */
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_sponge.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_sponge.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_sponge.F90	(revision 9987)
@@ -1,5 +1,5 @@
 #define SPONGE && define SPONGE_TOP
 
-Module agrif_opa_sponge
+MODULE agrif_opa_sponge
 #if defined key_agrif  && ! defined key_offline
    USE par_oce
@@ -9,11 +9,13 @@
    USE agrif_oce
    USE wrk_nemo  
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
 
    IMPLICIT NONE
    PRIVATE
 
-   PUBLIC Agrif_Sponge, Agrif_Sponge_Tra, Agrif_Sponge_Dyn, interptsn, interpun, interpvn
-
-  !! * Substitutions
+   PUBLIC Agrif_Sponge, Agrif_Sponge_Tra, Agrif_Sponge_Dyn
+   PUBLIC interptsn_sponge, interpun_sponge, interpvn_sponge
+
+   !! * Substitutions
 #  include "domzgr_substitute.h90"
    !!----------------------------------------------------------------------
@@ -23,5 +25,5 @@
    !!----------------------------------------------------------------------
 
-   CONTAINS
+CONTAINS
 
    SUBROUTINE Agrif_Sponge_Tra
@@ -30,55 +32,17 @@
       !!---------------------------------------------
       !!
-      INTEGER :: ji,jj,jk,jn
       REAL(wp) :: timecoeff
-      REAL(wp) :: ztsa, zabe1, zabe2, zbtr
-      REAL(wp), POINTER, DIMENSION(:,:    ) :: ztu, ztv
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztab
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: tsbdiff
 
 #if defined SPONGE
-      CALL wrk_alloc( jpi, jpj, ztu, ztv )
-      CALL wrk_alloc( jpi, jpj, jpk, jpts, ztab, tsbdiff  )
-
       timecoeff = REAL(Agrif_NbStepint(),wp)/Agrif_rhot()
 
+      CALL Agrif_Sponge
       Agrif_SpecialValue=0.
       Agrif_UseSpecialValue = .TRUE.
-      ztab = 0.e0
-      CALL Agrif_Bc_Variable(ztab, tsa_id,calledweight=timecoeff,procname=interptsn)
+      tabspongedone_tsn = .FALSE.
+
+      CALL Agrif_Bc_Variable(tsn_sponge_id,calledweight=timecoeff,procname=interptsn_sponge)
+
       Agrif_UseSpecialValue = .FALSE.
-
-      tsbdiff(:,:,:,:) = tsb(:,:,:,:) - ztab(:,:,:,:)
-
-      CALL Agrif_Sponge
-
-      DO jn = 1, jpts
-         DO jk = 1, jpkm1
-            !
-            DO jj = 1, jpjm1
-               DO ji = 1, jpim1
-                  zabe1 = umask(ji,jj,jk) * spe1ur(ji,jj) * fse3u(ji,jj,jk)
-                  zabe2 = vmask(ji,jj,jk) * spe2vr(ji,jj) * fse3v(ji,jj,jk)
-                  ztu(ji,jj) = zabe1 * ( tsbdiff(ji+1,jj  ,jk,jn) - tsbdiff(ji,jj,jk,jn) )
-                  ztv(ji,jj) = zabe2 * ( tsbdiff(ji  ,jj+1,jk,jn) - tsbdiff(ji,jj,jk,jn) )
-               ENDDO
-            ENDDO
-
-            DO jj = 2, jpjm1
-               DO ji = 2, jpim1
-                  zbtr = spbtr2(ji,jj) / fse3t(ji,jj,jk)
-                  ! horizontal diffusive trends
-                  ztsa = zbtr * (  ztu(ji,jj) - ztu(ji-1,jj  )   &
-                  &              + ztv(ji,jj) - ztv(ji  ,jj-1)  )
-                  ! add it to the general tracer trends
-                  tsa(ji,jj,jk,jn) = tsa(ji,jj,jk,jn) + ztsa
-               END DO
-            END DO
-            !
-         ENDDO
-      ENDDO
-
-      CALL wrk_dealloc( jpi, jpj, ztu, ztv )
-      CALL wrk_dealloc( jpi, jpj, jpk, jpts, ztab, tsbdiff  )
 #endif
 
@@ -90,89 +54,21 @@
       !!---------------------------------------------
       !!
-      INTEGER :: ji,jj,jk
       REAL(wp) :: timecoeff
-      REAL(wp) :: ze2u, ze1v, zua, zva, zbtr
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ubdiff, vbdiff
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: rotdiff, hdivdiff
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztab
 
 #if defined SPONGE
-      CALL wrk_alloc( jpi, jpj, jpk, ztab, ubdiff, vbdiff, rotdiff, hdivdiff )
-
       timecoeff = REAL(Agrif_NbStepint(),wp)/Agrif_rhot()
 
       Agrif_SpecialValue=0.
       Agrif_UseSpecialValue = ln_spc_dyn
-      ztab = 0.e0
-      CALL Agrif_Bc_Variable(ztab, ua_id,calledweight=timecoeff,procname=interpun)
+
+      tabspongedone_u = .FALSE.
+      tabspongedone_v = .FALSE.         
+      CALL Agrif_Bc_Variable(un_sponge_id,calledweight=timecoeff,procname=interpun_sponge)
+
+      tabspongedone_u = .FALSE.
+      tabspongedone_v = .FALSE.
+      CALL Agrif_Bc_Variable(vn_sponge_id,calledweight=timecoeff,procname=interpvn_sponge)
+
       Agrif_UseSpecialValue = .FALSE.
-
-      ubdiff(:,:,:) = ( ub(:,:,:) - ztab(:,:,:) ) * umask(:,:,:)
-
-      ztab = 0.e0
-      Agrif_SpecialValue=0.
-      Agrif_UseSpecialValue = ln_spc_dyn
-      CALL Agrif_Bc_Variable(ztab, va_id,calledweight=timecoeff,procname=interpvn)
-      Agrif_UseSpecialValue = .FALSE.
-
-      vbdiff(:,:,:) = ( vb(:,:,:) - ztab(:,:,:) ) * vmask(:,:,:)
-
-      CALL Agrif_Sponge
-
-      DO jk = 1,jpkm1
-         ubdiff(:,:,jk) = ubdiff(:,:,jk) * spe1ur2(:,:)
-         vbdiff(:,:,jk) = vbdiff(:,:,jk) * spe2vr2(:,:)
-      ENDDO
-      
-      hdivdiff = 0.
-      rotdiff = 0.
-
-      DO jk = 1, jpkm1                                 ! Horizontal slab
-         !                                             ! ===============
-
-         !                                             ! --------
-         ! Horizontal divergence                       !   div
-         !                                             ! --------
-         DO jj = 2, jpjm1
-            DO ji = 2, jpim1   ! vector opt.
-               zbtr = spbtr2(ji,jj) / fse3t(ji,jj,jk)
-               hdivdiff(ji,jj,jk) =  (  e2u(ji  ,jj  ) * fse3u(ji  ,jj  ,jk) * ubdiff(ji  ,jj  ,jk)     &
-                  &                   - e2u(ji-1,jj  ) * fse3u(ji-1,jj  ,jk) * ubdiff(ji-1,jj  ,jk)     &
-                  &                   + e1v(ji  ,jj  ) * fse3v(ji  ,jj  ,jk) * vbdiff(ji  ,jj  ,jk)     &
-                  &                   - e1v(ji  ,jj-1) * fse3v(ji  ,jj-1,jk) * vbdiff(ji  ,jj-1,jk)  ) * zbtr
-            END DO
-         END DO
-
-         DO jj = 1, jpjm1
-            DO ji = 1, jpim1   ! vector opt.
-               zbtr = spbtr3(ji,jj) * fse3f(ji,jj,jk)
-               rotdiff(ji,jj,jk) = (  e2v(ji+1,jj  ) * vbdiff(ji+1,jj  ,jk) - e2v(ji,jj) * vbdiff(ji,jj,jk)    &
-                  &                 - e1u(ji  ,jj+1) * ubdiff(ji  ,jj+1,jk) + e1u(ji,jj) * ubdiff(ji,jj,jk)  ) &
-                  &               * fmask(ji,jj,jk) * zbtr
-            END DO
-         END DO
-
-      ENDDO
-
-      !                                                ! ===============
-      DO jk = 1, jpkm1                                 ! Horizontal slab
-         !                                             ! ===============
-         DO jj = 2, jpjm1
-            DO ji = 2, jpim1   ! vector opt.
-               ! horizontal diffusive trends
-               zua = - ( rotdiff (ji  ,jj,jk) - rotdiff (ji,jj-1,jk) ) / ( e2u(ji,jj) * fse3u(ji,jj,jk) )   &
-                     + ( hdivdiff(ji+1,jj,jk) - hdivdiff(ji,jj  ,jk) ) / e1u(ji,jj)
-
-               zva = + ( rotdiff (ji,jj  ,jk) - rotdiff (ji-1,jj,jk) ) / ( e1v(ji,jj) * fse3v(ji,jj,jk) )   &
-                     + ( hdivdiff(ji,jj+1,jk) - hdivdiff(ji  ,jj,jk) ) / e2v(ji,jj)
-               ! add it to the general momentum trends
-               ua(ji,jj,jk) = ua(ji,jj,jk) + zua
-               va(ji,jj,jk) = va(ji,jj,jk) + zva
-            END DO
-         END DO
-         !                                             ! ===============
-      END DO                                           !   End of slab
-      !                                                ! ===============
-      CALL wrk_dealloc( jpi, jpj, jpk, ztab, ubdiff, vbdiff, rotdiff, hdivdiff )
 #endif
 
@@ -199,11 +95,10 @@
          CALL wrk_alloc( jpi, jpj, ztabramp )
 
-         ispongearea  = 2 + 2 * Agrif_irhox()
+         ispongearea  = 2 + nn_sponge_len * Agrif_irhox()
          ilci = nlci - ispongearea
          ilcj = nlcj - ispongearea 
          z1spongearea = 1._wp / REAL( ispongearea - 2 )
-         spbtr2(:,:) = 1. / ( e1t(:,:) * e2t(:,:) )
-
-         ztabramp(:,:) = 0.
+
+         ztabramp(:,:) = 0._wp
 
          IF( (nbondi == -1) .OR. (nbondi == 2) ) THEN
@@ -254,54 +149,15 @@
       ! Tracers
       IF( .NOT. spongedoneT ) THEN
-         spe1ur(:,:) = 0.
-         spe2vr(:,:) = 0.
-
-         IF( (nbondi == -1) .OR. (nbondi == 2) ) THEN
-            spe1ur(2:ispongearea-1,:       ) = visc_tra                                        &
-               &                             *    0.5 * (  ztabramp(2:ispongearea-1,:      )   &
-               &                                         + ztabramp(3:ispongearea  ,:      ) ) &
-               &                             * e2u(2:ispongearea-1,:) / e1u(2:ispongearea-1,:)
-
-            spe2vr(2:ispongearea  ,1:jpjm1 ) = visc_tra                                        &
-               &                             *    0.5 * (  ztabramp(2:ispongearea  ,1:jpjm1)   &
-               &                                         + ztabramp(2:ispongearea,2  :jpj  ) ) &
-               &                             * e1v(2:ispongearea,1:jpjm1) / e2v(2:ispongearea,1:jpjm1)
-         ENDIF
-
-         IF( (nbondi == 1) .OR. (nbondi == 2) ) THEN
-            spe1ur(ilci+1:nlci-2,:        ) = visc_tra                                   &
-               &                            * 0.5 * (  ztabramp(ilci+1:nlci-2,:      )   & 
-               &                                     + ztabramp(ilci+2:nlci-1,:      ) ) &
-               &                            * e2u(ilci+1:nlci-2,:) / e1u(ilci+1:nlci-2,:)
-
-            spe2vr(ilci+1:nlci-1,1:jpjm1  )  = visc_tra                                  &
-               &                            * 0.5 * (  ztabramp(ilci+1:nlci-1,1:jpjm1)   & 
-               &                                     + ztabramp(ilci+1:nlci-1,2:jpj  ) ) & 
-               &                            * e1v(ilci+1:nlci-1,1:jpjm1) / e2v(ilci+1:nlci-1,1:jpjm1)
-         ENDIF
-
-         IF( (nbondj == -1) .OR. (nbondj == 2) ) THEN
-            spe1ur(1:jpim1,2:ispongearea  ) = visc_tra                                     &
-               &                            * 0.5 * (  ztabramp(1:jpim1,2:ispongearea  )   & 
-               &                                     + ztabramp(2:jpi  ,2:ispongearea  ) ) &
-               &                            * e2u(1:jpim1,2:ispongearea) / e1u(1:jpim1,2:ispongearea)
-   
-            spe2vr(:      ,2:ispongearea-1) = visc_tra                                     &
-               &                            * 0.5 * (  ztabramp(:      ,2:ispongearea-1)   &
-               &                                     + ztabramp(:      ,3:ispongearea  ) ) &
-               &                            * e1v(:,2:ispongearea-1) / e2v(:,2:ispongearea-1)
-         ENDIF
-
-         IF( (nbondj == 1) .OR. (nbondj == 2) ) THEN
-            spe1ur(1:jpim1,ilcj+1:nlcj-1) = visc_tra                                   &
-               &                          * 0.5 * (  ztabramp(1:jpim1,ilcj+1:nlcj-1)   &
-               &                                   + ztabramp(2:jpi  ,ilcj+1:nlcj-1) ) &
-               &                                * e2u(1:jpim1,ilcj+1:nlcj-1) / e1u(1:jpim1,ilcj+1:nlcj-1)
-
-            spe2vr(:      ,ilcj+1:nlcj-2) = visc_tra                                   &
-               &                          * 0.5 * (  ztabramp(:      ,ilcj+1:nlcj-2)   &
-               &                                   + ztabramp(:      ,ilcj+2:nlcj-1) ) &
-               &                                * e1v(:,ilcj+1:nlcj-2) / e2v(:,ilcj+1:nlcj-2)
-         ENDIF
+         fsaht_spu(:,:) = 0._wp
+         fsaht_spv(:,:) = 0._wp
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   ! vector opt.
+               fsaht_spu(ji,jj) = 0.5_wp * visc_tra * (ztabramp(ji,jj) + ztabramp(ji+1,jj  ))
+               fsaht_spv(ji,jj) = 0.5_wp * visc_tra * (ztabramp(ji,jj) + ztabramp(ji  ,jj+1))
+            END DO
+         END DO
+
+         CALL lbc_lnk( fsaht_spu, 'U', 1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( fsaht_spv, 'V', 1. )
          spongedoneT = .TRUE.
       ENDIF
@@ -309,44 +165,17 @@
       ! Dynamics
       IF( .NOT. spongedoneU ) THEN
-         spe1ur2(:,:) = 0.
-         spe2vr2(:,:) = 0.
-
-         IF( (nbondi == -1) .OR. (nbondi == 2) ) THEN
-            spe1ur2(2:ispongearea-1,:      ) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(2:ispongearea-1,:      ) &
-               &                                      + ztabramp(3:ispongearea  ,:      ) )
-            spe2vr2(2:ispongearea  ,1:jpjm1) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(2:ispongearea  ,1:jpjm1) &
-               &                                      + ztabramp(2:ispongearea  ,2:jpj  ) ) 
-         ENDIF
-
-         IF( (nbondi == 1) .OR. (nbondi == 2) ) THEN
-            spe1ur2(ilci+1:nlci-2  ,:      ) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(ilci+1:nlci-2, :       ) &
-               &                                      + ztabramp(ilci+2:nlci-1, :       ) )                      
-            spe2vr2(ilci+1:nlci-1  ,1:jpjm1) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(ilci+1:nlci-1,1:jpjm1  ) &
-               &                                      + ztabramp(ilci+1:nlci-1,2:jpj    ) ) 
-         ENDIF
-
-         IF( (nbondj == -1) .OR. (nbondj == 2) ) THEN
-            spe1ur2(1:jpim1,2:ispongearea  ) = visc_dyn                                   &  
-               &                             * 0.5 * (  ztabramp(1:jpim1,2:ispongearea  ) &
-               &                                      + ztabramp(2:jpi  ,2:ispongearea  ) ) 
-            spe2vr2(:      ,2:ispongearea-1) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(:      ,2:ispongearea-1) &
-               &                                      + ztabramp(:      ,3:ispongearea  ) )
-         ENDIF
-
-         IF( (nbondj == 1) .OR. (nbondj == 2) ) THEN
-            spe1ur2(1:jpim1,ilcj+1:nlcj-1  ) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(1:jpim1,ilcj+1:nlcj-1  ) &
-               &                                      + ztabramp(2:jpi  ,ilcj+1:nlcj-1  ) ) 
-            spe2vr2(:      ,ilcj+1:nlcj-2  ) = visc_dyn                                   &
-               &                             * 0.5 * (  ztabramp(:      ,ilcj+1:nlcj-2  ) &
-               &                                      + ztabramp(:      ,ilcj+2:nlcj-1  ) )
-         ENDIF
+         fsahm_spt(:,:) = 0._wp
+         fsahm_spf(:,:) = 0._wp
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   ! vector opt.
+               fsahm_spt(ji,jj) = visc_dyn * ztabramp(ji,jj)
+               fsahm_spf(ji,jj) = 0.25_wp * visc_dyn * ( ztabramp(ji,jj) + ztabramp(ji  ,jj+1) &
+                                                     &  +ztabramp(ji,jj) + ztabramp(ji+1,jj  ) )
+            END DO
+         END DO
+
+         CALL lbc_lnk( fsahm_spt, 'T', 1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( fsahm_spf, 'F', 1. )
          spongedoneU = .TRUE.
-         spbtr3(:,:) = 1. / ( e1f(:,:) * e2f(:,:) )
       ENDIF
       !
@@ -357,36 +186,277 @@
    END SUBROUTINE Agrif_Sponge
 
-   SUBROUTINE interptsn(tabres,i1,i2,j1,j2,k1,k2,n1,n2)
-      !!---------------------------------------------
-      !!   *** ROUTINE interptsn ***
+   SUBROUTINE interptsn_sponge(tabres,i1,i2,j1,j2,k1,k2,n1,n2,before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interptsn_sponge ***
       !!---------------------------------------------
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
       REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
-
-      tabres(i1:i2,j1:j2,k1:k2,n1:n2) = tsn(i1:i2,j1:j2,k1:k2,n1:n2)
-
-   END SUBROUTINE interptsn
-
-   SUBROUTINE interpun(tabres,i1,i2,j1,j2,k1,k2)
-      !!---------------------------------------------
-      !!   *** ROUTINE interpun ***
-      !!---------------------------------------------
+      LOGICAL, INTENT(in) :: before
+
+
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::   iku, ikv
+      REAL(wp) :: ztsa, zabe1, zabe2, zbtr
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: ztu, ztv
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2) ::tsbdiff
+      !
+      IF (before) THEN
+         tabres(i1:i2,j1:j2,k1:k2,n1:n2) = tsn(i1:i2,j1:j2,k1:k2,n1:n2)
+      ELSE   
+   
+         tsbdiff(:,:,:,:) = tsb(i1:i2,j1:j2,:,:) - tabres(:,:,:,:)    
+         DO jn = 1, jpts            
+            DO jk = 1, jpkm1
+               DO jj = j1,j2-1
+                  DO ji = i1,i2-1
+                     zabe1 = fsaht_spu(ji,jj) * umask(ji,jj,jk) * re2u_e1u(ji,jj) * fse3u_n(ji,jj,jk)
+                     zabe2 = fsaht_spv(ji,jj) * vmask(ji,jj,jk) * re1v_e2v(ji,jj) * fse3v_n(ji,jj,jk)
+                     ztu(ji,jj,jk) = zabe1 * ( tsbdiff(ji+1,jj  ,jk,jn) - tsbdiff(ji,jj,jk,jn) ) 
+                     ztv(ji,jj,jk) = zabe2 * ( tsbdiff(ji  ,jj+1,jk,jn) - tsbdiff(ji,jj,jk,jn) )
+                  ENDDO
+               ENDDO
+
+               IF( ln_zps ) THEN      ! set gradient at partial step level
+                  DO jj = j1,j2-1
+                     DO ji = i1,i2-1
+                        ! last level
+                        iku = mbku(ji,jj)
+                        ikv = mbkv(ji,jj)
+                        IF( iku == jk ) THEN
+                           ztu(ji,jj,jk) = 0._wp
+                        ENDIF
+                        IF( ikv == jk ) THEN
+                           ztv(ji,jj,jk) = 0._wp
+                        ENDIF
+                     END DO
+                  END DO
+               ENDIF
+            ENDDO
+
+            DO jk = 1, jpkm1
+               DO jj = j1+1,j2-1
+                  DO ji = i1+1,i2-1
+
+                     IF (.NOT. tabspongedone_tsn(ji,jj)) THEN 
+                        zbtr = r1_e12t(ji,jj) / fse3t_n(ji,jj,jk)
+                        ! horizontal diffusive trends
+                        ztsa = zbtr * (  ztu(ji,jj,jk) - ztu(ji-1,jj,jk) + ztv(ji,jj,jk) - ztv(ji  ,jj-1,jk)  )
+                        ! add it to the general tracer trends
+                        tsa(ji,jj,jk,jn) = tsa(ji,jj,jk,jn) + ztsa
+                     ENDIF
+
+                  ENDDO
+               ENDDO
+
+            ENDDO
+         ENDDO
+
+         tabspongedone_tsn(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+
+      ENDIF
+
+   END SUBROUTINE interptsn_sponge
+
+   SUBROUTINE interpun_sponge(tabres,i1,i2,j1,j2,k1,k2, before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpun_sponge ***
+      !!---------------------------------------------    
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
       REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: tabres
-
-      tabres(i1:i2,j1:j2,k1:k2) = un(i1:i2,j1:j2,k1:k2)
-
-   END SUBROUTINE interpun
-
-   SUBROUTINE interpvn(tabres,i1,i2,j1,j2,k1,k2)
-      !!---------------------------------------------
-      !!   *** ROUTINE interpvn ***
-      !!---------------------------------------------
+      LOGICAL, INTENT(in) :: before
+
+      INTEGER :: ji,jj,jk
+
+      ! sponge parameters 
+      REAL(wp) :: ze2u, ze1v, zua, zva, zbtr
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: ubdiff
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: rotdiff, hdivdiff
+      INTEGER :: jmax
+      !
+
+
+      IF (before) THEN
+         tabres = un(i1:i2,j1:j2,:)
+      ELSE
+
+         ubdiff(i1:i2,j1:j2,:) = (ub(i1:i2,j1:j2,:) - tabres(:,:,:))*umask(i1:i2,j1:j2,:)
+
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            !                                             ! ===============
+
+            !                                             ! --------
+            ! Horizontal divergence                       !   div
+            !                                             ! --------
+            DO jj = j1,j2
+               DO ji = i1+1,i2   ! vector opt.
+                  zbtr = r1_e12t(ji,jj) / fse3t_n(ji,jj,jk) * fsahm_spt(ji,jj)
+                  hdivdiff(ji,jj,jk) = (  e2u(ji  ,jj)*fse3u_n(ji  ,jj,jk) * ubdiff(ji  ,jj,jk) &
+                                     &   -e2u(ji-1,jj)*fse3u_n(ji-1,jj,jk) * ubdiff(ji-1,jj,jk) ) * zbtr
+               END DO
+            END DO
+
+            DO jj = j1,j2-1
+               DO ji = i1,i2   ! vector opt.
+                  zbtr = r1_e12f(ji,jj) * fse3f_n(ji,jj,jk) * fsahm_spf(ji,jj)
+                  rotdiff(ji,jj,jk) = (-e1u(ji,jj+1) * ubdiff(ji,jj+1,jk) &
+                                       +e1u(ji,jj  ) * ubdiff(ji,jj  ,jk) & 
+                                    & ) * fmask(ji,jj,jk) * zbtr 
+               END DO
+            END DO
+         ENDDO
+
+         !
+
+
+
+         DO jj = j1+1, j2-1
+            DO ji = i1+1, i2-1   ! vector opt.
+
+               IF (.NOT. tabspongedone_u(ji,jj)) THEN
+                  DO jk = 1, jpkm1                                 ! Horizontal slab
+                     ze2u = rotdiff (ji,jj,jk)
+                     ze1v = hdivdiff(ji,jj,jk)
+                     ! horizontal diffusive trends
+                     zua = - ( ze2u - rotdiff (ji,jj-1,jk)) / ( e2u(ji,jj) * fse3u_n(ji,jj,jk) )   &
+                           + ( hdivdiff(ji+1,jj,jk) - ze1v  ) / e1u(ji,jj)
+
+                     ! add it to the general momentum trends
+                     ua(ji,jj,jk) = ua(ji,jj,jk) + zua
+
+                  END DO
+               ENDIF
+
+            END DO
+         END DO
+
+         tabspongedone_u(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+
+         jmax = j2-1
+         IF ((nbondj == 1).OR.(nbondj == 2)) jmax = MIN(jmax,nlcj-3)
+
+         DO jj = j1+1, jmax
+            DO ji = i1+1, i2   ! vector opt.
+
+               IF (.NOT. tabspongedone_v(ji,jj)) THEN
+                  DO jk = 1, jpkm1                                 ! Horizontal slab
+                     ze2u = rotdiff (ji,jj,jk)
+                     ze1v = hdivdiff(ji,jj,jk)
+
+                     ! horizontal diffusive trends
+                     zva = + ( ze2u - rotdiff (ji-1,jj,jk)) / ( e1v(ji,jj) * fse3v_n(ji,jj,jk) )   &
+                           + ( hdivdiff(ji,jj+1,jk) - ze1v  ) / e2v(ji,jj)
+
+                     ! add it to the general momentum trends
+                     va(ji,jj,jk) = va(ji,jj,jk) + zva
+                  END DO
+               ENDIF
+
+            END DO
+         END DO
+
+
+         tabspongedone_v(i1+1:i2,j1+1:jmax) = .TRUE.
+
+      ENDIF
+
+
+   END SUBROUTINE interpun_sponge
+
+
+   SUBROUTINE interpvn_sponge(tabres,i1,i2,j1,j2,k1,k2, before,nb,ndir)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpvn_sponge ***
+      !!--------------------------------------------- 
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2
       REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: tabres
-
-      tabres(i1:i2,j1:j2,k1:k2) = vn(i1:i2,j1:j2,k1:k2)
-
-   END SUBROUTINE interpvn
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+
+      INTEGER :: ji,jj,jk
+
+      REAL(wp) :: ze2u, ze1v, zua, zva, zbtr
+
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: vbdiff
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: rotdiff, hdivdiff
+      INTEGER :: imax
+      !
+
+      IF (before) THEN 
+         tabres = vn(i1:i2,j1:j2,:)
+      ELSE
+
+         vbdiff(i1:i2,j1:j2,:) = (vb(i1:i2,j1:j2,:) - tabres(:,:,:))*vmask(i1:i2,j1:j2,:)
+
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            !                                             ! ===============
+
+            !                                             ! --------
+            ! Horizontal divergence                       !   div
+            !                                             ! --------
+            DO jj = j1+1,j2
+               DO ji = i1,i2   ! vector opt.
+                  zbtr = r1_e12t(ji,jj) / fse3t_n(ji,jj,jk) * fsahm_spt(ji,jj)
+                  hdivdiff(ji,jj,jk) = ( e1v(ji,jj  ) * fse3v(ji,jj  ,jk) * vbdiff(ji,jj  ,jk)  &
+                                     &  -e1v(ji,jj-1) * fse3v(ji,jj-1,jk) * vbdiff(ji,jj-1,jk)  ) * zbtr
+               END DO
+            END DO
+            DO jj = j1,j2
+               DO ji = i1,i2-1   ! vector opt.
+                  zbtr = r1_e12f(ji,jj) * fse3f_n(ji,jj,jk) * fsahm_spf(ji,jj)
+                  rotdiff(ji,jj,jk) = ( e2v(ji+1,jj) * vbdiff(ji+1,jj,jk) & 
+                                    &  -e2v(ji  ,jj) * vbdiff(ji  ,jj,jk) &
+                                    & ) * fmask(ji,jj,jk) * zbtr
+               END DO
+            END DO
+         ENDDO
+
+         !                                                ! ===============
+         !                                                
+
+         imax = i2-1
+         IF ((nbondi == 1).OR.(nbondi == 2)) imax = MIN(imax,nlci-3)
+
+         DO jj = j1+1, j2
+            DO ji = i1+1, imax   ! vector opt.
+               IF (.NOT. tabspongedone_u(ji,jj)) THEN
+                  DO jk = 1, jpkm1                                 ! Horizontal slab
+                     ze2u = rotdiff (ji,jj,jk)
+                     ze1v = hdivdiff(ji,jj,jk)
+                     ! horizontal diffusive trends
+                     zua = - ( ze2u - rotdiff (ji,jj-1,jk)) / ( e2u(ji,jj) * fse3u_n(ji,jj,jk) ) + ( hdivdiff(ji+1,jj,jk) - ze1v) &
+                           / e1u(ji,jj)
+
+
+                     ! add it to the general momentum trends
+                     ua(ji,jj,jk) = ua(ji,jj,jk) + zua
+                  END DO
+
+               ENDIF
+            END DO
+         END DO
+
+         tabspongedone_u(i1+1:imax,j1+1:j2) = .TRUE.
+
+         DO jj = j1+1, j2-1
+            DO ji = i1+1, i2-1   ! vector opt.
+               IF (.NOT. tabspongedone_v(ji,jj)) THEN
+                  DO jk = 1, jpkm1                                 ! Horizontal slab
+                     ze2u = rotdiff (ji,jj,jk)
+                     ze1v = hdivdiff(ji,jj,jk)
+                     ! horizontal diffusive trends
+
+                     zva = + ( ze2u - rotdiff (ji-1,jj,jk)) / ( e1v(ji,jj) * fse3v_n(ji,jj,jk) ) + ( hdivdiff(ji,jj+1,jk) - ze1v) &
+                           / e2v(ji,jj)
+
+                     ! add it to the general momentum trends
+                     va(ji,jj,jk) = va(ji,jj,jk) + zva
+                  END DO
+               ENDIF
+            END DO
+         END DO
+         tabspongedone_v(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+      ENDIF
+
+   END SUBROUTINE interpvn_sponge
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_update.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_update.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_opa_update.F90	(revision 9987)
@@ -1,4 +1,5 @@
-#define TWO_WAY
-
+#define TWO_WAY        /* TWO WAY NESTING */
+#undef DECAL_FEEDBACK /* SEPARATION of INTERFACES*/
+ 
 MODULE agrif_opa_update
 #if defined key_agrif  && ! defined key_offline
@@ -11,14 +12,15 @@
    USE wrk_nemo  
    USE dynspg_oce
+   USE zdf_oce        ! vertical physics: ocean variables 
 
    IMPLICIT NONE
    PRIVATE
 
-   PUBLIC Agrif_Update_Tra, Agrif_Update_Dyn
-
-   INTEGER, PUBLIC :: nbcline = 0
-
+   PUBLIC Agrif_Update_Tra, Agrif_Update_Dyn,Update_Scales
+# if defined key_zdftke
+   PUBLIC Agrif_Update_Tke
+# endif
    !!----------------------------------------------------------------------
-   !! NEMO/NST 3.3 , NEMO Consortium (2010)
+   !! NEMO/NST 3.6 , NEMO Consortium (2010)
    !! $Id$
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
@@ -27,98 +29,151 @@
 CONTAINS
 
-   SUBROUTINE Agrif_Update_Tra( kt )
+   RECURSIVE SUBROUTINE Agrif_Update_Tra( )
       !!---------------------------------------------
       !!   *** ROUTINE Agrif_Update_Tra ***
       !!---------------------------------------------
-      !!
-      INTEGER, INTENT(in) :: kt
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztab
-
-
-      IF((Agrif_NbStepint() .NE. (Agrif_irhot()-1)).AND.(kt /= 0)) RETURN
-#if defined TWO_WAY
-      CALL wrk_alloc( jpi, jpj, jpk, jpts, ztab )
+      ! 
+      IF (Agrif_Root()) RETURN
+      !
+#if defined TWO_WAY  
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Update tracers  from grid Number',Agrif_Fixed(), 'nbcline', nbcline
 
       Agrif_UseSpecialValueInUpdate = .TRUE.
       Agrif_SpecialValueFineGrid = 0.
-
+      ! 
       IF (MOD(nbcline,nbclineupdate) == 0) THEN
-         CALL Agrif_Update_Variable(ztab,tsn_id, procname=updateTS)
-      ELSE
-         CALL Agrif_Update_Variable(ztab,tsn_id,locupdate=(/0,2/), procname=updateTS)
-      ENDIF
-
+# if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(tsn_id, procname=updateTS)
+# else
+         CALL Agrif_Update_Variable(tsn_id, locupdate=(/1,0/),procname=updateTS)
+# endif
+      ELSE
+# if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(tsn_id,locupdate=(/0,2/), procname=updateTS)
+# else
+         CALL Agrif_Update_Variable(tsn_id,locupdate=(/1,2/), procname=updateTS)
+# endif
+      ENDIF
+      !
       Agrif_UseSpecialValueInUpdate = .FALSE.
-
-      CALL wrk_dealloc( jpi, jpj, jpk, jpts, ztab )
+      !
+      IF ( lk_agrif_doupd ) THEN ! Initialisation: do recursive update:
+         CALL Agrif_ChildGrid_To_ParentGrid()
+         CALL Agrif_Update_Tra()
+         CALL Agrif_ParentGrid_To_ChildGrid()
+      ENDIF
+      !
 #endif
-
+      !
    END SUBROUTINE Agrif_Update_Tra
 
-   SUBROUTINE Agrif_Update_Dyn( kt )
+   RECURSIVE SUBROUTINE Agrif_Update_Dyn( )
       !!---------------------------------------------
       !!   *** ROUTINE Agrif_Update_Dyn ***
       !!---------------------------------------------
-      !!
-      INTEGER, INTENT(in) :: kt
-      REAL(wp), POINTER, DIMENSION(:,:) :: ztab2d
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztab
-
-
-      IF ((Agrif_NbStepint() .NE. (Agrif_irhot()-1)).AND.(kt /= 0)) Return
+      ! 
+      IF (Agrif_Root()) RETURN
+      !
 #if defined TWO_WAY
-      CALL wrk_alloc( jpi, jpj,      ztab2d )
-      CALL wrk_alloc( jpi, jpj, jpk, ztab   )
-
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Update momentum from grid Number',Agrif_Fixed(), 'nbcline', nbcline
+
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      Agrif_SpecialValueFineGrid = 0.
+      !     
       IF (mod(nbcline,nbclineupdate) == 0) THEN
-         CALL Agrif_Update_Variable(ztab,un_id,procname = updateU)
-         CALL Agrif_Update_Variable(ztab,vn_id,procname = updateV)
-      ELSE
-         CALL Agrif_Update_Variable(ztab,un_id,locupdate=(/0,1/),procname = updateU)
-         CALL Agrif_Update_Variable(ztab,vn_id,locupdate=(/0,1/),procname = updateV)         
-      ENDIF
-
-      CALL Agrif_Update_Variable(ztab2d,e1u_id,procname = updateU2d)
-      CALL Agrif_Update_Variable(ztab2d,e2v_id,procname = updateV2d)
-
-#if defined key_dynspg_ts
+# if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(un_update_id,procname = updateU)
+         CALL Agrif_Update_Variable(vn_update_id,procname = updateV)
+# else
+         CALL Agrif_Update_Variable(un_update_id,locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname = updateU)
+         CALL Agrif_Update_Variable(vn_update_id,locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname = updateV)
+# endif
+      ELSE
+# if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(un_update_id,locupdate=(/0,1/),procname = updateU)
+         CALL Agrif_Update_Variable(vn_update_id,locupdate=(/0,1/),procname = updateV)         
+# else
+         CALL Agrif_Update_Variable(un_update_id,locupdate1=(/0,1/),locupdate2=(/1,1/),procname = updateU)
+         CALL Agrif_Update_Variable(vn_update_id,locupdate1=(/1,1/),locupdate2=(/0,1/),procname = updateV)
+# endif
+      ENDIF
+
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(e1u_id,procname = updateU2d)
+      CALL Agrif_Update_Variable(e2v_id,procname = updateV2d)  
+# else
+      CALL Agrif_Update_Variable(e1u_id,locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname = updateU2d)
+      CALL Agrif_Update_Variable(e2v_id,locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname = updateV2d)  
+# endif
+
+# if defined key_dynspg_ts
       IF (ln_bt_fw) THEN
          ! Update time integrated transports
          IF (mod(nbcline,nbclineupdate) == 0) THEN
-            CALL Agrif_Update_Variable(ztab2d,ub2b_id,procname = updateub2b)
-            CALL Agrif_Update_Variable(ztab2d,vb2b_id,procname = updatevb2b)
+#  if ! defined DECAL_FEEDBACK
+            CALL Agrif_Update_Variable(ub2b_update_id,procname = updateub2b)
+            CALL Agrif_Update_Variable(vb2b_update_id,procname = updatevb2b)
+#  else
+            CALL Agrif_Update_Variable(ub2b_update_id,locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname = updateub2b)
+            CALL Agrif_Update_Variable(vb2b_update_id,locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname = updatevb2b)
+#  endif
          ELSE
-            CALL Agrif_Update_Variable(ztab2d,ub2b_id,locupdate=(/0,1/),procname = updateub2b)
-            CALL Agrif_Update_Variable(ztab2d,vb2b_id,locupdate=(/0,1/),procname = updatevb2b)
+#  if ! defined DECAL_FEEDBACK
+            CALL Agrif_Update_Variable(ub2b_update_id,locupdate=(/0,1/),procname = updateub2b)
+            CALL Agrif_Update_Variable(vb2b_update_id,locupdate=(/0,1/),procname = updatevb2b)
+#  else
+            CALL Agrif_Update_Variable(ub2b_update_id,locupdate1=(/0,1/),locupdate2=(/1,1/),procname = updateub2b)
+            CALL Agrif_Update_Variable(vb2b_update_id,locupdate1=(/1,1/),locupdate2=(/0,1/),procname = updatevb2b)
+#  endif
          ENDIF
-      END IF 
+      END IF
+# endif
+      !
+      nbcline = nbcline + 1
+      !
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+      Agrif_SpecialValueFineGrid = 0.
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(sshn_id,procname = updateSSH)
+# else
+      CALL Agrif_Update_Variable(sshn_id,locupdate=(/1,0/),procname = updateSSH)
+# endif
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      ! 
 #endif
-
-      nbcline = nbcline + 1
-
-      Agrif_UseSpecialValueInUpdate = .TRUE. 
+      !
+      ! Do recursive update:
+      IF ( lk_agrif_doupd ) THEN ! Initialisation: do recursive update:
+         CALL Agrif_ChildGrid_To_ParentGrid()
+         CALL Agrif_Update_Dyn()
+         CALL Agrif_ParentGrid_To_ChildGrid()
+      ENDIF
+      !
+   END SUBROUTINE Agrif_Update_Dyn
+
+# if defined key_zdftke
+   SUBROUTINE Agrif_Update_Tke( kt )
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Update_Tke ***
+      !!---------------------------------------------
+      !!
+      INTEGER, INTENT(in) :: kt
+      !       
+      IF( ( Agrif_NbStepint() .NE. 0 ) .AND. (kt /= 0) ) RETURN
+#  if defined TWO_WAY
+
+      Agrif_UseSpecialValueInUpdate = .TRUE.
       Agrif_SpecialValueFineGrid = 0.
-      CALL Agrif_Update_Variable(ztab2d,sshn_id,procname = updateSSH)
+
+      CALL Agrif_Update_Variable( en_id, locupdate=(/0,0/), procname=updateEN  )
+      CALL Agrif_Update_Variable(avt_id, locupdate=(/0,0/), procname=updateAVT )
+      CALL Agrif_Update_Variable(avm_id, locupdate=(/0,0/), procname=updateAVM )
+
       Agrif_UseSpecialValueInUpdate = .FALSE.
 
-      CALL wrk_dealloc( jpi, jpj,      ztab2d )
-      CALL wrk_dealloc( jpi, jpj, jpk, ztab   )
-
-!Done in step
-!      CALL Agrif_ChildGrid_To_ParentGrid()
-!      CALL recompute_diags( kt )
-!      CALL Agrif_ParentGrid_To_ChildGrid()
-
-#endif
-
-   END SUBROUTINE Agrif_Update_Dyn
-
-   SUBROUTINE recompute_diags( kt )
-      !!---------------------------------------------
-      !!   *** ROUTINE recompute_diags ***
-      !!---------------------------------------------
-      INTEGER, INTENT(in) :: kt
-
-   END SUBROUTINE recompute_diags
+#  endif
+      
+   END SUBROUTINE Agrif_Update_Tke
+# endif /* key_zdftke */
 
    SUBROUTINE updateTS( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
@@ -127,11 +182,11 @@
       !!---------------------------------------------
 #  include "domzgr_substitute.h90"
-
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
       REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
-      LOGICAL, iNTENT(in) :: before
-
+      LOGICAL, INTENT(in) :: before
+      !!
       INTEGER :: ji,jj,jk,jn
-
+      !!---------------------------------------------
+      !
       IF (before) THEN
          DO jn = n1,n2
@@ -146,5 +201,5 @@
       ELSE
          IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
-         ! Add asselin part
+            ! Add asselin part
             DO jn = n1,n2
                DO jk=k1,k2
@@ -153,6 +208,6 @@
                         IF( tabres(ji,jj,jk,jn) .NE. 0. ) THEN
                            tsb(ji,jj,jk,jn) = tsb(ji,jj,jk,jn) & 
-                              & + atfp * ( tabres(ji,jj,jk,jn) &
-                              &             - tsn(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
+                                 & + atfp * ( tabres(ji,jj,jk,jn) &
+                                 &             - tsn(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
                         ENDIF
                      ENDDO
@@ -161,5 +216,4 @@
             ENDDO
          ENDIF
-
          DO jn = n1,n2
             DO jk=k1,k2
@@ -174,5 +228,5 @@
          END DO
       ENDIF
-
+      ! 
    END SUBROUTINE updateTS
 
@@ -182,12 +236,13 @@
       !!---------------------------------------------
 #  include "domzgr_substitute.h90"
-
+      !!
       INTEGER, INTENT(in) :: i1, i2, j1, j2, k1, k2
       REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: tabres
       LOGICAL, INTENT(in) :: before
-
+      !! 
       INTEGER :: ji, jj, jk
       REAL(wp) :: zrhoy
-
+      !!---------------------------------------------
+      ! 
       IF (before) THEN
          zrhoy = Agrif_Rhoy()
@@ -209,5 +264,5 @@
                   IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
                      ub(ji,jj,jk) = ub(ji,jj,jk) & 
-                       & + atfp * ( tabres(ji,jj,jk) - un(ji,jj,jk) ) * umask(ji,jj,jk)
+                           & + atfp * ( tabres(ji,jj,jk) - un(ji,jj,jk) ) * umask(ji,jj,jk)
                   ENDIF
                   !
@@ -217,5 +272,5 @@
          END DO
       ENDIF
-
+      ! 
    END SUBROUTINE updateu
 
@@ -225,12 +280,13 @@
       !!---------------------------------------------
 #  include "domzgr_substitute.h90"
-
+      !!
       INTEGER :: i1,i2,j1,j2,k1,k2
       INTEGER :: ji,jj,jk
       REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: tabres
       LOGICAL :: before
-
+      !!
       REAL(wp) :: zrhox
-
+      !!---------------------------------------------      
+      !
       IF (before) THEN
          zrhox = Agrif_Rhox()
@@ -252,5 +308,5 @@
                   IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
                      vb(ji,jj,jk) = vb(ji,jj,jk) & 
-                       & + atfp * ( tabres(ji,jj,jk) - vn(ji,jj,jk) ) * vmask(ji,jj,jk)
+                           & + atfp * ( tabres(ji,jj,jk) - vn(ji,jj,jk) ) * vmask(ji,jj,jk)
                   ENDIF
                   !
@@ -260,5 +316,5 @@
          END DO
       ENDIF
-
+      ! 
    END SUBROUTINE updatev
 
@@ -268,13 +324,14 @@
       !!---------------------------------------------
 #  include "domzgr_substitute.h90"
-
+      !!
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
       LOGICAL, INTENT(in) :: before
-
+      !! 
       INTEGER :: ji, jj, jk
       REAL(wp) :: zrhoy
       REAL(wp) :: zcorr
-
+      !!---------------------------------------------
+      !
       IF (before) THEN
          zrhoy = Agrif_Rhoy()
@@ -326,5 +383,5 @@
          END DO
       ENDIF
-
+      !
    END SUBROUTINE updateu2d
 
@@ -333,13 +390,13 @@
       !!          *** ROUTINE updatev2d ***
       !!---------------------------------------------
-
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
       LOGICAL, INTENT(in) :: before
-
+      !! 
       INTEGER :: ji, jj, jk
       REAL(wp) :: zrhox
       REAL(wp) :: zcorr
-
+      !!---------------------------------------------
+      !
       IF (before) THEN
          zrhox = Agrif_Rhox()
@@ -391,19 +448,19 @@
          END DO
       ENDIF
-
+      ! 
    END SUBROUTINE updatev2d
 
+
    SUBROUTINE updateSSH( tabres, i1, i2, j1, j2, before )
       !!---------------------------------------------
       !!          *** ROUTINE updateSSH ***
       !!---------------------------------------------
-#  include "domzgr_substitute.h90"
-
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
       LOGICAL, INTENT(in) :: before
-
+      !!
       INTEGER :: ji, jj
-
+      !!---------------------------------------------
+      ! 
       IF (before) THEN
          DO jj=j1,j2
@@ -413,11 +470,10 @@
          END DO
       ELSE
-
 #if ! defined key_dynspg_ts
          IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
             DO jj=j1,j2
                DO ji=i1,i2
-                sshb(ji,jj) =   sshb(ji,jj) &
-                 & + atfp * ( tabres(ji,jj) - sshn(ji,jj) ) * tmask(ji,jj,1)
+                  sshb(ji,jj) =   sshb(ji,jj) &
+                        & + atfp * ( tabres(ji,jj) - sshn(ji,jj) ) * tmask(ji,jj,1)
                END DO
             END DO
@@ -430,5 +486,5 @@
          END DO
       ENDIF
-
+      !
    END SUBROUTINE updateSSH
 
@@ -437,12 +493,12 @@
       !!          *** ROUTINE updateub2b ***
       !!---------------------------------------------
-
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
       LOGICAL, INTENT(in) :: before
-
+      !!
       INTEGER :: ji, jj
       REAL(wp) :: zrhoy
-
+      !!---------------------------------------------
+      !
       IF (before) THEN
          zrhoy = Agrif_Rhoy()
@@ -460,5 +516,5 @@
          END DO
       ENDIF
-
+      !
    END SUBROUTINE updateub2b
 
@@ -467,12 +523,12 @@
       !!          *** ROUTINE updatevb2b ***
       !!---------------------------------------------
-
       INTEGER, INTENT(in) :: i1, i2, j1, j2
       REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
       LOGICAL, INTENT(in) :: before
-
+      !!
       INTEGER :: ji, jj
       REAL(wp) :: zrhox
-
+      !!---------------------------------------------
+      !
       IF (before) THEN
          zrhox = Agrif_Rhox()
@@ -490,6 +546,112 @@
          END DO
       ENDIF
-
+      !
    END SUBROUTINE updatevb2b
+
+
+   SUBROUTINE update_scales( tabres, i1, i2, j1, j2, k1, k2, n1,n2, before )
+      ! currently not used
+      !!---------------------------------------------
+      !!           *** ROUTINE updateT ***
+      !!---------------------------------------------
+#  include "domzgr_substitute.h90"
+
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL, iNTENT(in) :: before
+
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: ztemp
+
+      IF (before) THEN
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = e1t(ji,jj)*e2t(ji,jj)*tmask(ji,jj,jk)
+                  tabres(ji,jj,jk,2) = e1t(ji,jj)*tmask(ji,jj,jk)
+                  tabres(ji,jj,jk,3) = e2t(ji,jj)*tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         tabres(:,:,:,1)=tabres(:,:,:,1)*Agrif_Rhox()*Agrif_Rhoy()
+         tabres(:,:,:,2)=tabres(:,:,:,2)*Agrif_Rhox()
+         tabres(:,:,:,3)=tabres(:,:,:,3)*Agrif_Rhoy()
+      ELSE
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  IF( tabres(ji,jj,jk,1) .NE. 0. ) THEN 
+                     print *,'VAL = ',ji,jj,jk,tabres(ji,jj,jk,1),e1t(ji,jj)*e2t(ji,jj)*tmask(ji,jj,jk)
+                     print *,'VAL2 = ',ji,jj,jk,tabres(ji,jj,jk,2),e1t(ji,jj)*tmask(ji,jj,jk)
+                     print *,'VAL3 = ',ji,jj,jk,tabres(ji,jj,jk,3),e2t(ji,jj)*tmask(ji,jj,jk)
+                     ztemp = sqrt(tabres(ji,jj,jk,1)/(tabres(ji,jj,jk,2)*tabres(ji,jj,jk,3)))
+                     print *,'CORR = ',ztemp-1.
+                     print *,'NEW VALS = ',tabres(ji,jj,jk,2)*ztemp,tabres(ji,jj,jk,3)*ztemp, &
+                           tabres(ji,jj,jk,2)*ztemp*tabres(ji,jj,jk,3)*ztemp
+                     e1t(ji,jj) = tabres(ji,jj,jk,2)*ztemp
+                     e2t(ji,jj) = tabres(ji,jj,jk,3)*ztemp
+                  END IF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE update_scales
+
+# if defined key_zdftke
+   SUBROUTINE updateEN( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateen ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         ptab (i1:i2,j1:j2,k1:k2) = en(i1:i2,j1:j2,k1:k2)
+      ELSE
+         en(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2) 
+      ENDIF
+      !
+   END SUBROUTINE updateEN
+
+
+   SUBROUTINE updateAVT( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateavt ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         ptab (i1:i2,j1:j2,k1:k2) = avt_k(i1:i2,j1:j2,k1:k2)
+      ELSE
+         avt_k(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2) 
+      ENDIF
+      !
+   END SUBROUTINE updateAVT
+
+
+   SUBROUTINE updateAVM( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateavm ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         ptab (i1:i2,j1:j2,k1:k2) = avm_k(i1:i2,j1:j2,k1:k2)
+      ELSE
+         avm_k(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2) 
+      ENDIF
+      !
+   END SUBROUTINE updateAVM
+
+# endif /* key_zdftke */ 
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_interp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_interp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_interp.F90	(revision 9987)
@@ -7,4 +7,5 @@
    USE agrif_oce
    USE agrif_top_sponge
+   USE par_trc
    USE trc
    USE lib_mpp
@@ -14,10 +15,10 @@
    PRIVATE
 
-   PUBLIC Agrif_trc
+   PUBLIC Agrif_trc, interptrn
 
 #  include "domzgr_substitute.h90"  
 #  include "vectopt_loop_substitute.h90"
   !!----------------------------------------------------------------------
-   !! NEMO/NST 3.3 , NEMO Consortium (2010)
+   !! NEMO/NST 3.6 , NEMO Consortium (2010)
    !! $Id$
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
@@ -28,114 +29,160 @@
    SUBROUTINE Agrif_trc
       !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE Agrif_Tra  ***
-      !!----------------------------------------------------------------------
-      !!
-      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp) ::   zrhox , alpha1, alpha2, alpha3
-      REAL(wp) ::   alpha4, alpha5, alpha6, alpha7
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztra
+      !!                  ***  ROUTINE Agrif_trc  ***
       !!----------------------------------------------------------------------
       !
       IF( Agrif_Root() )   RETURN
 
-      CALL wrk_alloc( jpi, jpj, jpk, jptra, ztra )
-
       Agrif_SpecialValue    = 0.e0
       Agrif_UseSpecialValue = .TRUE.
-      ztra(:,:,:,:) = 0.e0
 
-      CALL Agrif_Bc_variable( ztra, trn_id, procname=interptrn )
+      CALL Agrif_Bc_variable( trn_id, procname=interptrn )
       Agrif_UseSpecialValue = .FALSE.
+      !
+   END SUBROUTINE Agrif_trc
 
-      zrhox = Agrif_Rhox()
+   SUBROUTINE interptrn(ptab,i1,i2,j1,j2,k1,k2,n1,n2,before,nb,ndir)
+      !!---------------------------------------------
+      !!   *** ROUTINE interptrn ***
+      !!---------------------------------------------
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: ptab
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER :: imin, imax, jmin, jmax
+      REAL(wp) ::   zrhox , zalpha1, zalpha2, zalpha3
+      REAL(wp) ::   zalpha4, zalpha5, zalpha6, zalpha7
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
 
-      alpha1 = ( zrhox - 1. ) * 0.5
-      alpha2 = 1. - alpha1
-
-      alpha3 = ( zrhox - 1. ) / ( zrhox + 1. )
-      alpha4 = 1. - alpha3
-
-      alpha6 = 2. * ( zrhox - 1. ) / ( zrhox + 1. )
-      alpha7 =    - ( zrhox - 1. ) / ( zrhox + 3. )
-      alpha5 = 1. - alpha6 - alpha7
-      IF( nbondi == 1 .OR. nbondi == 2 ) THEN
-
-         DO jn = 1, jptra
-            tra(nlci,:,:,jn) = alpha1 * ztra(nlci,:,:,jn) + alpha2 * ztra(nlci-1,:,:,jn)
-            DO jk = 1, jpkm1
-               DO jj = 1, jpj
-                  IF( umask(nlci-2,jj,jk) == 0.e0 ) THEN
-                     tra(nlci-1,jj,jk,jn) = tra(nlci,jj,jk,jn) * tmask(nlci-1,jj,jk)
-                  ELSE
-                     tra(nlci-1,jj,jk,jn)=(alpha4*tra(nlci,jj,jk,jn)+alpha3*tra(nlci-2,jj,jk,jn))*tmask(nlci-1,jj,jk)
-                     IF( un(nlci-2,jj,jk) > 0.e0 ) THEN
-                        tra(nlci-1,jj,jk,jn)=( alpha6*tra(nlci-2,jj,jk,jn)+alpha5*tra(nlci,jj,jk,jn)  &
-                           &                 + alpha7*tra(nlci-3,jj,jk,jn) ) * tmask(nlci-1,jj,jk)
+      IF (before) THEN         
+         ptab(i1:i2,j1:j2,k1:k2,n1:n2) = trn(i1:i2,j1:j2,k1:k2,n1:n2)
+      ELSE
+         !
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         !
+         zrhox = Agrif_Rhox()
+         ! 
+         zalpha1 = ( zrhox - 1. ) * 0.5
+         zalpha2 = 1. - zalpha1
+         ! 
+         zalpha3 = ( zrhox - 1. ) / ( zrhox + 1. )
+         zalpha4 = 1. - zalpha3
+         ! 
+         zalpha6 = 2. * ( zrhox - 1. ) / ( zrhox + 1. )
+         zalpha7 =    - ( zrhox - 1. ) / ( zrhox + 3. )
+         zalpha5 = 1. - zalpha6 - zalpha7
+         !
+         imin = i1
+         imax = i2
+         jmin = j1
+         jmax = j2
+         ! 
+         ! Remove CORNERS
+         IF((nbondj == -1).OR.(nbondj == 2)) jmin = 3
+         IF((nbondj == +1).OR.(nbondj == 2)) jmax = nlcj-2
+         IF((nbondi == -1).OR.(nbondi == 2)) imin = 3
+         IF((nbondi == +1).OR.(nbondi == 2)) imax = nlci-2        
+         !
+         IF( eastern_side) THEN
+            DO jn = 1, jptra
+               tra(nlci,j1:j2,k1:k2,jn) = zalpha1 * ptab(nlci,j1:j2,k1:k2,jn) + zalpha2 * ptab(nlci-1,j1:j2,k1:k2,jn)
+               DO jk = 1, jpkm1
+                  DO jj = jmin,jmax
+                     IF( umask(nlci-2,jj,jk) == 0.e0 ) THEN
+                        tra(nlci-1,jj,jk,jn) = tra(nlci,jj,jk,jn) * tmask(nlci-1,jj,jk)
+                     ELSE
+                        tra(nlci-1,jj,jk,jn)=(zalpha4*tra(nlci,jj,jk,jn)+zalpha3*tra(nlci-2,jj,jk,jn))*tmask(nlci-1,jj,jk)
+                        IF( un(nlci-2,jj,jk) > 0.e0 ) THEN
+                           tra(nlci-1,jj,jk,jn)=( zalpha6*tra(nlci-2,jj,jk,jn)+zalpha5*tra(nlci,jj,jk,jn) & 
+                                 + zalpha7*tra(nlci-3,jj,jk,jn) ) * tmask(nlci-1,jj,jk)
+                        ENDIF
                      ENDIF
-                  ENDIF
+                  END DO
+               END DO
+            ENDDO
+         ENDIF
+         ! 
+         IF( northern_side ) THEN            
+            DO jn = 1, jptra
+               tra(i1:i2,nlcj,k1:k2,jn) = zalpha1 * ptab(i1:i2,nlcj,k1:k2,jn) + zalpha2 * ptab(i1:i2,nlcj-1,k1:k2,jn)
+               DO jk = 1, jpkm1
+                  DO ji = imin,imax
+                     IF( vmask(ji,nlcj-2,jk) == 0.e0 ) THEN
+                        tra(ji,nlcj-1,jk,jn) = tra(ji,nlcj,jk,jn) * tmask(ji,nlcj-1,jk)
+                     ELSE
+                        tra(ji,nlcj-1,jk,jn)=(zalpha4*tra(ji,nlcj,jk,jn)+zalpha3*tra(ji,nlcj-2,jk,jn))*tmask(ji,nlcj-1,jk)        
+                        IF (vn(ji,nlcj-2,jk) > 0.e0 ) THEN
+                           tra(ji,nlcj-1,jk,jn)=( zalpha6*tra(ji,nlcj-2,jk,jn)+zalpha5*tra(ji,nlcj,jk,jn)  &
+                                 + zalpha7*tra(ji,nlcj-3,jk,jn) ) * tmask(ji,nlcj-1,jk)
+                        ENDIF
+                     ENDIF
+                  END DO
+               END DO
+            ENDDO
+         ENDIF
+         !
+         IF( western_side) THEN            
+            DO jn = 1, jptra
+               tra(1,j1:j2,k1:k2,jn) = zalpha1 * ptab(1,j1:j2,k1:k2,jn) + zalpha2 * ptab(2,j1:j2,k1:k2,jn)
+               DO jk = 1, jpkm1
+                  DO jj = jmin,jmax
+                     IF( umask(2,jj,jk) == 0.e0 ) THEN
+                        tra(2,jj,jk,jn) = tra(1,jj,jk,jn) * tmask(2,jj,jk)
+                     ELSE
+                        tra(2,jj,jk,jn)=(zalpha4*tra(1,jj,jk,jn)+zalpha3*tra(3,jj,jk,jn))*tmask(2,jj,jk)        
+                        IF( un(2,jj,jk) < 0.e0 ) THEN
+                           tra(2,jj,jk,jn)=(zalpha6*tra(3,jj,jk,jn)+zalpha5*tra(1,jj,jk,jn)+zalpha7*tra(4,jj,jk,jn))*tmask(2,jj,jk)
+                        ENDIF
+                     ENDIF
+                  END DO
                END DO
             END DO
-         ENDDO
-      ENDIF
-
-      IF( nbondj == 1 .OR. nbondj == 2 ) THEN
-
-         DO jn = 1, jptra
-            tra(:,nlcj,:,jn) = alpha1 * ztra(:,nlcj,:,jn) + alpha2 * ztra(:,nlcj-1,:,jn)
-            DO jk = 1, jpkm1
-               DO ji = 1, jpi
-                  IF( vmask(ji,nlcj-2,jk) == 0.e0 ) THEN
-                     tra(ji,nlcj-1,jk,jn) = tra(ji,nlcj,jk,jn) * tmask(ji,nlcj-1,jk)
-                  ELSE
-                     tra(ji,nlcj-1,jk,jn)=(alpha4*tra(ji,nlcj,jk,jn)+alpha3*tra(ji,nlcj-2,jk,jn))*tmask(ji,nlcj-1,jk)
-                     IF (vn(ji,nlcj-2,jk) > 0.e0 ) THEN
-                        tra(ji,nlcj-1,jk,jn)=( alpha6*tra(ji,nlcj-2,jk,jn)+alpha5*tra(ji,nlcj,jk,jn)  &
-                           &                 + alpha7*tra(ji,nlcj-3,jk,jn) ) * tmask(ji,nlcj-1,jk)
+         ENDIF
+         !
+         IF( southern_side ) THEN           
+            DO jn = 1, jptra
+               tra(i1:i2,1,k1:k2,jn) = zalpha1 * ptab(i1:i2,1,k1:k2,jn) + zalpha2 * ptab(i1:i2,2,k1:k2,jn)
+               DO jk=1,jpk      
+                  DO ji=imin,imax
+                     IF( vmask(ji,2,jk) == 0.e0 ) THEN
+                        tra(ji,2,jk,jn)=tra(ji,1,jk,jn) * tmask(ji,2,jk)
+                     ELSE
+                        tra(ji,2,jk,jn)=(zalpha4*tra(ji,1,jk,jn)+zalpha3*tra(ji,3,jk,jn))*tmask(ji,2,jk)
+                        IF( vn(ji,2,jk) < 0.e0 ) THEN
+                           tra(ji,2,jk,jn)=(zalpha6*tra(ji,3,jk,jn)+zalpha5*tra(ji,1,jk,jn)+zalpha7*tra(ji,4,jk,jn))*tmask(ji,2,jk)
+                        ENDIF
                      ENDIF
-                  ENDIF
+                  END DO
                END DO
-            END DO
-         ENDDO
-      ENDIF
-      IF( nbondi == -1 .OR. nbondi == 2 ) THEN
-         DO jn = 1, jptra
-            tra(1,:,:,jn) = alpha1 * ztra(1,:,:,jn) + alpha2 * ztra(2,:,:,jn)
-            DO jk = 1, jpkm1
-               DO jj = 1, jpj
-                  IF( umask(2,jj,jk) == 0.e0 ) THEN
-                     tra(2,jj,jk,jn) = tra(1,jj,jk,jn) * tmask(2,jj,jk)
-                  ELSE
-                     tra(2,jj,jk,jn)=(alpha4*tra(1,jj,jk,jn)+alpha3*tra(3,jj,jk,jn))*tmask(2,jj,jk)
-                     IF( un(2,jj,jk) < 0.e0 ) THEN
-                        tra(2,jj,jk,jn)=(alpha6*tra(3,jj,jk,jn)+alpha5*tra(1,jj,jk,jn)+alpha7*tra(4,jj,jk,jn))*tmask(2,jj,jk)
-                     ENDIF
-                  ENDIF
-               END DO
-            END DO
-         END DO
-      ENDIF
-
-      IF( nbondj == -1 .OR. nbondj == 2 ) THEN
-         DO jn = 1, jptra
-            tra(:,1,:,jn) = alpha1 * ztra(:,1,:,jn) + alpha2 * ztra(:,2,:,jn)
-            DO jk=1,jpk
-               DO ji=1,jpi
-                  IF( vmask(ji,2,jk) == 0.e0 ) THEN
-                     tra(ji,2,jk,jn)=tra(ji,1,jk,jn) * tmask(ji,2,jk)
-                  ELSE
-                     tra(ji,2,jk,jn)=(alpha4*tra(ji,1,jk,jn)+alpha3*tra(ji,3,jk,jn))*tmask(ji,2,jk)
-                     IF( vn(ji,2,jk) < 0.e0 ) THEN
-                        tra(ji,2,jk,jn)=(alpha6*tra(ji,3,jk,jn)+alpha5*tra(ji,1,jk,jn)+alpha7*tra(ji,4,jk,jn))*tmask(ji,2,jk)
-                     ENDIF
-                  ENDIF
-               END DO
-            END DO
-         ENDDO
+            ENDDO
+         ENDIF
+         !
+         ! Treatment of corners
+         ! 
+         ! East south
+         IF ((eastern_side).AND.((nbondj == -1).OR.(nbondj == 2))) THEN
+            tra(nlci-1,2,:,:) = ptab(nlci-1,2,:,:)
+         ENDIF
+         ! East north
+         IF ((eastern_side).AND.((nbondj == 1).OR.(nbondj == 2))) THEN
+            tra(nlci-1,nlcj-1,:,:) = ptab(nlci-1,nlcj-1,:,:)
+         ENDIF
+         ! West south
+         IF ((western_side).AND.((nbondj == -1).OR.(nbondj == 2))) THEN
+            tra(2,2,:,:) = ptab(2,2,:,:)
+         ENDIF
+         ! West north
+         IF ((western_side).AND.((nbondj == 1).OR.(nbondj == 2))) THEN
+            tra(2,nlcj-1,:,:) = ptab(2,nlcj-1,:,:)
+         ENDIF
+         !
       ENDIF
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztra )
-      !
-
-   END SUBROUTINE Agrif_trc
+   END SUBROUTINE interptrn
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_sponge.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_sponge.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_sponge.F90	(revision 9987)
@@ -1,7 +1,8 @@
 #define SPONGE_TOP
 
-Module agrif_top_sponge
+MODULE agrif_top_sponge
 #if defined key_agrif && defined key_top
    USE par_oce
+   USE par_trc
    USE oce
    USE dom_oce
@@ -16,71 +17,31 @@
    PRIVATE
 
-   PUBLIC Agrif_Sponge_Trc, interptrn
+   PUBLIC Agrif_Sponge_trc, interptrn_sponge
 
-  !! * Substitutions
+   !! * Substitutions
 #  include "domzgr_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/NST 3.3 , NEMO Consortium (2010)
+   !! NEMO/NST 3.6 , NEMO Consortium (2010)
    !! $Id$
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
 
-   CONTAINS
+CONTAINS
 
-   SUBROUTINE Agrif_Sponge_Trc
+   SUBROUTINE Agrif_Sponge_trc
       !!---------------------------------------------
       !!   *** ROUTINE Agrif_Sponge_Trc ***
       !!---------------------------------------------
       !! 
-      INTEGER :: ji,jj,jk,jn
       REAL(wp) :: timecoeff
-      REAL(wp) :: ztra, zabe1, zabe2, zbtr
-      REAL(wp), POINTER, DIMENSION(:,:) :: ztru, ztrv
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztabr
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: trbdiff
 
 #if defined SPONGE_TOP
-      CALL wrk_alloc( jpi, jpj, ztru, ztrv )
-      CALL wrk_alloc( jpi, jpj, jpk, jptra, ztabr, trbdiff )
-
       timecoeff = REAL(Agrif_NbStepint(),wp)/Agrif_rhot()
-
+      CALL Agrif_sponge
       Agrif_SpecialValue=0.
       Agrif_UseSpecialValue = .TRUE.
-      ztabr = 0.e0
-      CALL Agrif_Bc_Variable(ztabr, tra_id,calledweight=timecoeff,procname=interptrn)
+      tabspongedone_trn = .FALSE.
+      CALL Agrif_Bc_Variable(trn_sponge_id,calledweight=timecoeff,procname=interptrn_sponge)
       Agrif_UseSpecialValue = .FALSE.
-
-      trbdiff(:,:,:,:) = trb(:,:,:,:) - ztabr(:,:,:,:)
-
-      CALL Agrif_sponge
-
-      DO jn = 1, jptra
-         DO jk = 1, jpkm1
-            !
-            DO jj = 1, jpjm1
-               DO ji = 1, jpim1
-                  zabe1 = umask(ji,jj,jk) * spe1ur(ji,jj) * fse3u(ji,jj,jk)
-                  zabe2 = vmask(ji,jj,jk) * spe2vr(ji,jj) * fse3v(ji,jj,jk)
-                  ztru(ji,jj) = zabe1 * ( trbdiff(ji+1,jj  ,jk,jn) - trbdiff(ji,jj,jk,jn) )
-                  ztrv(ji,jj) = zabe2 * ( trbdiff(ji  ,jj+1,jk,jn) - trbdiff(ji,jj,jk,jn) )
-               ENDDO
-            ENDDO
-
-            DO jj = 2,jpjm1
-               DO ji = 2,jpim1
-                  zbtr = spbtr2(ji,jj) / fse3t(ji,jj,jk)
-                  ! horizontal diffusive trends
-                  ztra = zbtr * ( ztru(ji,jj) - ztru(ji-1,jj) + ztrv(ji,jj) - ztrv(ji,jj-1)  )
-                  ! add it to the general tracer trends
-                  tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + ztra
-               END DO
-            END DO
-            !
-         ENDDO
-      ENDDO
- 
-      CALL wrk_dealloc( jpi, jpj, ztru, ztrv )
-      CALL wrk_dealloc( jpi, jpj, jpk, jptra, trbdiff, ztabr )
 
 #endif
@@ -88,14 +49,57 @@
    END SUBROUTINE Agrif_Sponge_Trc
 
-   SUBROUTINE interptrn(tabres,i1,i2,j1,j2,k1,k2,n1,n2)
+   SUBROUTINE interptrn_sponge(tabres,i1,i2,j1,j2,k1,k2,n1,n2,before)
       !!---------------------------------------------
-      !!   *** ROUTINE interptn ***
+      !!   *** ROUTINE interptrn_sponge ***
       !!---------------------------------------------
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
       REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+
+
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+
+      REAL(wp) :: ztra, zabe1, zabe2, zbtr
+      REAL(wp), DIMENSION(i1:i2,j1:j2) :: ztu, ztv
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2) ::trbdiff
       !
-      tabres(i1:i2,j1:j2,k1:k2,n1:n2) = trn(i1:i2,j1:j2,k1:k2,n1:n2)
+      IF (before) THEN
+         tabres(i1:i2,j1:j2,k1:k2,n1:n2) = trn(i1:i2,j1:j2,k1:k2,n1:n2)
+      ELSE      
 
-   END SUBROUTINE interptrn
+         trbdiff(:,:,:,:) = trb(i1:i2,j1:j2,:,:) - tabres(:,:,:,:)      
+         DO jn = 1, jptra
+            DO jk = 1, jpkm1
+
+               DO jj = j1,j2-1
+                  DO ji = i1,i2-1
+                     zabe1 = fsaht_spu(ji,jj) * umask(ji,jj,jk) * re2u_e1u(ji,jj) * fse3u_n(ji,jj,jk)
+                     zabe2 = fsaht_spv(ji,jj) * vmask(ji,jj,jk) * re1v_e2v(ji,jj) * fse3v_n(ji,jj,jk)
+                     ztu(ji,jj) = zabe1 * ( trbdiff(ji+1,jj  ,jk,jn) - trbdiff(ji,jj,jk,jn) )
+                     ztv(ji,jj) = zabe2 * ( trbdiff(ji  ,jj+1,jk,jn) - trbdiff(ji,jj,jk,jn) )
+                  ENDDO
+               ENDDO
+
+               DO jj = j1+1,j2-1
+                  DO ji = i1+1,i2-1
+
+                     IF (.NOT. tabspongedone_trn(ji,jj)) THEN 
+                        zbtr = r1_e12t(ji,jj) / fse3t(ji,jj,jk)
+                        ! horizontal diffusive trends
+                        ztra = zbtr * (  ztu(ji,jj) - ztu(ji-1,jj  ) + ztv(ji,jj) - ztv(ji  ,jj-1)  )
+                        ! add it to the general tracer trends
+                        tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + ztra
+                     ENDIF
+
+                  ENDDO
+               ENDDO
+
+            ENDDO
+         ENDDO
+
+         tabspongedone_trn(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+      ENDIF
+      !                 
+   END SUBROUTINE interptrn_sponge
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_update.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_update.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_top_update.F90	(revision 9987)
@@ -1,3 +1,4 @@
 #define TWO_WAY
+#undef DECAL_FEEDBACK
 
 MODULE agrif_top_update
@@ -8,4 +9,5 @@
    USE dom_oce
    USE agrif_oce
+   USE par_trc
    USE trc
    USE wrk_nemo  
@@ -24,5 +26,5 @@
    !!----------------------------------------------------------------------
 
-   CONTAINS
+CONTAINS
 
    SUBROUTINE Agrif_Update_Trc( kt )
@@ -30,75 +32,65 @@
       !!   *** ROUTINE Agrif_Update_Trc ***
       !!---------------------------------------------
-      !!
       INTEGER, INTENT(in) :: kt
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztra
-
-  
-      IF ((Agrif_NbStepint() .NE. (Agrif_irhot()-1)).AND.(kt /= 0)) RETURN
-
-#if defined TWO_WAY
-      CALL wrk_alloc( jpi, jpj, jpk, jptra, ztra )
-
+      !!---------------------------------------------
+      ! 
+      IF((Agrif_NbStepint() .NE. (Agrif_irhot()-1)).AND.(kt /= 0)) RETURN
+#if defined TWO_WAY   
       Agrif_UseSpecialValueInUpdate = .TRUE.
       Agrif_SpecialValueFineGrid = 0.
- 
-     IF (MOD(nbcline_trc,nbclineupdate) == 0) THEN
-         CALL Agrif_Update_Variable(ztra,trn_id, procname=updateTRC)
+      ! 
+      IF (MOD(nbcline_trc,nbclineupdate) == 0) THEN
+# if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(trn_id, procname=updateTRC)
+# else
+         CALL Agrif_Update_Variable(trn_id, locupdate=(/1,0/),procname=updateTRC)
+# endif
       ELSE
-         CALL Agrif_Update_Variable(ztra,trn_id,locupdate=(/0,2/), procname=updateTRC)
+# if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(trn_id,locupdate=(/0,2/), procname=updateTRC)
+# else
+         CALL Agrif_Update_Variable(trn_id,locupdate=(/1,2/), procname=updateTRC)
+# endif
       ENDIF
-
+      !
       Agrif_UseSpecialValueInUpdate = .FALSE.
       nbcline_trc = nbcline_trc + 1
-
-      CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztra )
 #endif
-
+      !
    END SUBROUTINE Agrif_Update_Trc
 
-   SUBROUTINE updateTRC(tabres,i1,i2,j1,j2,k1,k2,n1,n2,before)
+   SUBROUTINE updateTRC( ptab, i1, i2, j1, j2, k1, k2, n1, n2, before )
       !!---------------------------------------------
-      !!   *** ROUTINE UpdateTrc ***
+      !!           *** ROUTINE updateT ***
       !!---------------------------------------------
+#  include "domzgr_substitute.h90"
       INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
-      REAL, DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: ptab
       LOGICAL, INTENT(in) :: before
-   
+      !!
       INTEGER :: ji,jj,jk,jn
-
-         IF( before ) THEN
-            DO jn = n1, n2
-               DO jk = k1, k2
-                  DO jj = j1, j2
-                     DO ji = i1, i2
-                        tabres(ji,jj,jk,jn) = trn(ji,jj,jk,jn)
-                     ENDDO
-                  ENDDO
-               ENDDO
-            ENDDO
-         ELSE
-            IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         DO jn = n1,n2
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     ptab(ji,jj,jk,jn) = trn(ji,jj,jk,jn)
+                  END DO
+               END DO
+            END DO
+         END DO
+      ELSE
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
             ! Add asselin part
-               DO jn = n1, n2
-                  DO jk = k1, k2
-                     DO jj = j1, j2
-                        DO ji = i1, i2
-                           IF( tabres(ji,jj,jk,jn) .NE. 0. ) THEN
-                              trb(ji,jj,jk,jn) = trb(ji,jj,jk,jn) & 
-                                 & + atfp * ( tabres(ji,jj,jk,jn) &
-                                               - trn(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
-                           ENDIF
-                        ENDDO
-                     ENDDO
-                  ENDDO
-               ENDDO
-            ENDIF
-
-            DO jn = n1, n2
-               DO jk = k1, k2
-                  DO jj = j1, j2
-                     DO ji = i1, i2
-                        IF( tabres(ji,jj,jk,jn) .NE. 0. ) THEN
-                           trn(ji,jj,jk,jn) = tabres(ji,jj,jk,jn) * tmask(ji,jj,jk)
+            DO jn = n1,n2
+               DO jk=k1,k2
+                  DO jj=j1,j2
+                     DO ji=i1,i2
+                        IF( ptab(ji,jj,jk,jn) .NE. 0. ) THEN
+                           trb(ji,jj,jk,jn) = trb(ji,jj,jk,jn) & 
+                                 & + atfp * ( ptab(ji,jj,jk,jn) &
+                                 &             - trn(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
                         ENDIF
                      ENDDO
@@ -107,5 +99,17 @@
             ENDDO
          ENDIF
-
+         DO jn = n1,n2
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     IF( ptab(ji,jj,jk,jn) .NE. 0. ) THEN 
+                        trn(ji,jj,jk,jn) = ptab(ji,jj,jk,jn) * tmask(ji,jj,jk)
+                     END IF
+                  END DO
+               END DO
+            END DO
+         END DO
+      ENDIF
+      ! 
    END SUBROUTINE updateTRC
 
@@ -119,3 +123,3 @@
    END SUBROUTINE agrif_top_update_empty
 #endif
-END Module agrif_top_update
+END MODULE agrif_top_update
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_user.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_user.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/NST_SRC/agrif_user.F90	(revision 9987)
@@ -17,5 +17,4 @@
    USE par_oce
    USE dom_oce
-   USE Agrif_Util
    USE nemogcm
    !
@@ -31,5 +30,9 @@
       jpi     = ( jpiglo-2*jpreci + (jpni-1+0) ) / jpni + 2*jpreci
       jpj     = ( jpjglo-2*jprecj + (jpnj-1+0) ) / jpnj + 2*jprecj
-      jpk     = jpkdta 
+! JC: change to allow for different vertical levels
+!     jpk is already set
+!     keep it jpk possibly different from jpkdta which 
+!     hold parent grid vertical levels number (set earlier)
+!      jpk     = jpkdta 
       jpim1   = jpi-1 
       jpjm1   = jpj-1 
@@ -64,7 +67,7 @@
    ! 0. Initializations
    !-------------------
-   IF( cp_cfg == 'orca' ) then
+   IF( cp_cfg == 'orca' ) THEN
       IF ( jp_cfg == 2 .OR. jp_cfg == 025 .OR. jp_cfg == 05 &
-  &                      .OR. jp_cfg == 4 ) THEN
+            &                      .OR. jp_cfg == 4 ) THEN
          jp_cfg = -1    ! set special value for jp_cfg on fine grids
          cp_cfg = "default"
@@ -120,10 +123,10 @@
 SUBROUTINE agrif_declare_var_dom
    !!----------------------------------------------------------------------
-   !!                 *** ROUTINE agrif_declarE_var ***
+   !!                 *** ROUTINE agrif_declare_var ***
    !!
    !! ** Purpose :: Declaration of variables to be interpolated
    !!----------------------------------------------------------------------
    USE agrif_util
-   USE par_oce       !   ONLY : jpts
+   USE par_oce       
    USE oce
    IMPLICIT NONE
@@ -132,23 +135,26 @@
    ! 1. Declaration of the type of variable which have to be interpolated
    !---------------------------------------------------------------------
-   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/jpi,jpj/),e1u_id)
-   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/jpi,jpj/),e2v_id)
-
+   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),e1u_id)
+   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),e2v_id)
 
    ! 2. Type of interpolation
    !-------------------------
-   Call Agrif_Set_bcinterp(e1u_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
-   Call Agrif_Set_bcinterp(e2v_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+   CALL Agrif_Set_bcinterp(e1u_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(e2v_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
 
    ! 3. Location of interpolation
    !-----------------------------
-   Call Agrif_Set_bc(e1u_id,(/0,0/))
-   Call Agrif_Set_bc(e2v_id,(/0,0/))
+   CALL Agrif_Set_bc(e1u_id,(/0,0/))
+   CALL Agrif_Set_bc(e2v_id,(/0,0/))
 
    ! 5. Update type
    !--------------- 
-   Call Agrif_Set_Updatetype(e1u_id,update1 = Agrif_Update_Copy, update2=Agrif_Update_Average)
-   Call Agrif_Set_Updatetype(e2v_id,update1 = Agrif_Update_Average, update2=Agrif_Update_Copy)
-
+   CALL Agrif_Set_Updatetype(e1u_id,update1 = Agrif_Update_Copy, update2=Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(e2v_id,update1 = Agrif_Update_Average, update2=Agrif_Update_Copy)
+
+! High order updates
+!   CALL Agrif_Set_Updatetype(e1u_id,update1 = Agrif_Update_Average,            update2=Agrif_Update_Full_Weighting)
+!   CALL Agrif_Set_Updatetype(e2v_id,update1 = Agrif_Update_Full_Weighting,     update2=Agrif_Update_Average)
+    !
 END SUBROUTINE agrif_declare_var_dom
 
@@ -167,4 +173,5 @@
    USE nemogcm
    USE sol_oce
+   USE lib_mpp
    USE in_out_manager
    USE agrif_opa_update
@@ -174,14 +181,7 @@
    IMPLICIT NONE
    !
-   REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE :: tabtstemp
-   REAL(wp), DIMENSION(:,:,:  ), ALLOCATABLE :: tabuvtemp
-   REAL(wp), DIMENSION(:,:    ), ALLOCATABLE :: tab2d
    LOGICAL :: check_namelist
-   !!----------------------------------------------------------------------
-
-   ALLOCATE( tabtstemp(jpi, jpj, jpk, jpts) )
-   ALLOCATE( tabuvtemp(jpi, jpj, jpk)       )
-   ALLOCATE( tab2d(jpi, jpj)                )
-
+   CHARACTER(len=15) :: cl_check1, cl_check2, cl_check3
+   !!----------------------------------------------------------------------
 
    ! 1. Declaration of the type of variable which have to be interpolated
@@ -193,44 +193,69 @@
    Agrif_SpecialValue=0.
    Agrif_UseSpecialValue = .TRUE.
-   Call Agrif_Bc_variable(tabtstemp,tsn_id,calledweight=1.,procname=interptsn)
-   Call Agrif_Bc_variable(tabtstemp,tsa_id,calledweight=1.,procname=interptsn)
-
-   Call Agrif_Bc_variable(tabuvtemp,un_id,calledweight=1.,procname=interpu)
-   Call Agrif_Bc_variable(tabuvtemp,vn_id,calledweight=1.,procname=interpv)
-   Call Agrif_Bc_variable(tabuvtemp,ua_id,calledweight=1.,procname=interpun)
-   Call Agrif_Bc_variable(tabuvtemp,va_id,calledweight=1.,procname=interpvn)
-
-   Call Agrif_Bc_variable(tab2d,unb_id,calledweight=1.,procname=interpunb)
-   Call Agrif_Bc_variable(tab2d,vnb_id,calledweight=1.,procname=interpvnb)
-   Call Agrif_Bc_variable(tab2d,sshn_id,calledweight=1.,procname=interpsshn)
-   Agrif_UseSpecialValue = .FALSE.
+   CALL Agrif_Bc_variable(tsn_id,calledweight=1.,procname=interptsn)
+   CALL Agrif_Sponge
+   tabspongedone_tsn = .FALSE.
+   CALL Agrif_Bc_variable(tsn_sponge_id,calledweight=1.,procname=interptsn_sponge)
+   ! reset tsa to zero
+   tsa(:,:,:,:) = 0.
+
+   Agrif_UseSpecialValue = ln_spc_dyn
+   CALL Agrif_Bc_variable(un_interp_id,calledweight=1.,procname=interpun)
+   CALL Agrif_Bc_variable(vn_interp_id,calledweight=1.,procname=interpvn)
+   tabspongedone_u = .FALSE.
+   tabspongedone_v = .FALSE.
+   CALL Agrif_Bc_variable(un_sponge_id,calledweight=1.,procname=interpun_sponge)
+   tabspongedone_u = .FALSE.
+   tabspongedone_v = .FALSE.
+   CALL Agrif_Bc_variable(vn_sponge_id,calledweight=1.,procname=interpvn_sponge)
+
+#if defined key_dynspg_ts
+   Agrif_UseSpecialValue = .TRUE.
+   CALL Agrif_Bc_variable(sshn_id,calledweight=1., procname=interpsshn )
+
+   Agrif_UseSpecialValue = ln_spc_dyn
+   CALL Agrif_Bc_variable(unb_id,calledweight=1.,procname=interpunb)
+   CALL Agrif_Bc_variable(vnb_id,calledweight=1.,procname=interpvnb)
+   CALL Agrif_Bc_variable(ub2b_interp_id,calledweight=1.,procname=interpub2b)
+   CALL Agrif_Bc_variable(vb2b_interp_id,calledweight=1.,procname=interpvb2b)
+   ubdy_w(:) = 0.e0 ; vbdy_w(:) = 0.e0 ; hbdy_w(:) =0.e0
+   ubdy_e(:) = 0.e0 ; vbdy_e(:) = 0.e0 ; hbdy_e(:) =0.e0 
+   ubdy_n(:) = 0.e0 ; vbdy_n(:) = 0.e0 ; hbdy_n(:) =0.e0 
+   ubdy_s(:) = 0.e0 ; vbdy_s(:) = 0.e0 ; hbdy_s(:) =0.e0
+#endif
+
+   Agrif_UseSpecialValue = .FALSE. 
+   ! reset velocities to zero
+   ua(:,:,:) = 0.
+   va(:,:,:) = 0.
 
    ! 3. Some controls
    !-----------------
-   check_namelist = .true.
-
-   IF( check_namelist ) THEN
+   check_namelist = .TRUE.
+
+   IF( check_namelist ) THEN 
 
       ! Check time steps           
-      IF( NINT(Agrif_Rhot()) * nint(rdt) /= Agrif_Parent(rdt) ) THEN
-         WRITE(*,*) 'incompatible time step between grids'
-         WRITE(*,*) 'parent grid value : ',Agrif_Parent(rdt)
-         WRITE(*,*) 'child  grid value : ',nint(rdt)
-         WRITE(*,*) 'value on parent grid should be : ',rdt*Agrif_Rhot()
-         STOP
+      IF( NINT(Agrif_Rhot()) * NINT(rdt) .NE. Agrif_Parent(rdt) ) THEN
+         WRITE(cl_check1,*)  NINT(Agrif_Parent(rdt))
+         WRITE(cl_check2,*)  NINT(rdt)
+         WRITE(cl_check3,*)  NINT(Agrif_Parent(rdt)/Agrif_Rhot())
+         CALL ctl_warn( 'incompatible time step between grids',   &
+               &               'parent grid value : '//cl_check1    ,   & 
+               &               'child  grid value : '//cl_check2    ,   & 
+               &               'value on child grid will be changed to : '//cl_check3 )
+         rdt=Agrif_Parent(rdt)/Agrif_Rhot()
       ENDIF
 
       ! Check run length
       IF( Agrif_IRhot() * (Agrif_Parent(nitend)- &
-           Agrif_Parent(nit000)+1) .ne. (nitend-nit000+1) ) THEN
-         WRITE(*,*) 'incompatible run length between grids'
-         WRITE(*,*) 'parent grid value : ',(Agrif_Parent(nitend)- &
-              Agrif_Parent(nit000)+1),' time step'
-         WRITE(*,*) 'child  grid value : ', &
-              (nitend-nit000+1),' time step'
-         WRITE(*,*) 'value on child grid should be : ', &
-              Agrif_IRhot() * (Agrif_Parent(nitend)- &
-              Agrif_Parent(nit000)+1)
-         STOP
+            Agrif_Parent(nit000)+1) .NE. (nitend-nit000+1) ) THEN
+         WRITE(cl_check1,*)  (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         WRITE(cl_check2,*)   Agrif_Parent(nitend)   *Agrif_IRhot()
+         CALL ctl_warn( 'incompatible run length between grids'               ,   &
+               &              ' nit000 on fine grid will be change to : '//cl_check1,   &
+               &              ' nitend on fine grid will be change to : '//cl_check2    )
+         nit000 = (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         nitend =  Agrif_Parent(nitend)   *Agrif_IRhot()
       ENDIF
 
@@ -238,5 +263,5 @@
       IF( ln_zps ) THEN
          ! check parameters for partial steps 
-         IF( Agrif_Parent(e3zps_min) .ne. e3zps_min ) THEN
+         IF( Agrif_Parent(e3zps_min) .NE. e3zps_min ) THEN
             WRITE(*,*) 'incompatible e3zps_min between grids'
             WRITE(*,*) 'parent grid :',Agrif_Parent(e3zps_min)
@@ -253,14 +278,47 @@
          ENDIF
       ENDIF
+      ! check if masks and bathymetries match
+      IF(ln_chk_bathy) THEN
+         !
+         IF(lwp) WRITE(numout,*) 'AGRIF: Check Bathymetry and masks near bdys. Level: ', Agrif_Level()
+         !
+         kindic_agr = 0
+         ! check if umask agree with parent along western and eastern boundaries:
+         CALL Agrif_Bc_variable(umsk_id,calledweight=1.,procname=interpumsk)
+         ! check if vmask agree with parent along northern and southern boundaries:
+         CALL Agrif_Bc_variable(vmsk_id,calledweight=1.,procname=interpvmsk)
+	 ! check if tmask and vertical scale factors agree with parent over first two coarse grid points:
+         CALL Agrif_Bc_variable(e3t_id,calledweight=1.,procname=interpe3t)
+         !
+         IF (lk_mpp) CALL mpp_sum( kindic_agr )
+         IF( kindic_agr /= 0 ) THEN             		
+            CALL ctl_stop('Child Bathymetry is not correct near boundaries.')
+         ELSE
+            IF(lwp) WRITE(numout,*) 'Child Bathymetry is ok near boundaries.'
+         END IF
+      ENDIF
+      !
    ENDIF
-
-   CALL Agrif_Update_tra(0)
-   CALL Agrif_Update_dyn(0)
-
+   ! 
+   ! Do update at initialisation because not done before writing restarts
+   ! This would indeed change boundary conditions values at initial time
+   ! hence produce restartability issues.
+   ! Note that update below is recursive (with lk_agrif_doupd=T):
+   ! 
+! JC: I am not sure if Agrif_MaxLevel() is the "relative"
+!     or the absolute maximum nesting level...TBC                        
+   IF ( Agrif_Level().EQ.Agrif_MaxLevel() ) THEN 
+      ! NB: Do tracers first, dynamics after because nbcline incremented in dynamics
+      CALL Agrif_Update_tra()
+      CALL Agrif_Update_dyn()
+   ENDIF
+   !
+# if defined key_zdftke
+!   CALL Agrif_Update_tke(0)
+# endif
+   !
+   Agrif_UseSpecialValueInUpdate = .FALSE.
    nbcline = 0
-   !
-   DEALLOCATE(tabtstemp)
-   DEALLOCATE(tabuvtemp)
-   DEALLOCATE(tab2d)
+   lk_agrif_doupd = .FALSE.
    !
 END SUBROUTINE Agrif_InitValues_cont
@@ -276,4 +334,5 @@
    USE par_oce       !   ONLY : jpts
    USE oce
+   USE agrif_oce
    IMPLICIT NONE
    !!----------------------------------------------------------------------
@@ -281,68 +340,120 @@
    ! 1. Declaration of the type of variable which have to be interpolated
    !---------------------------------------------------------------------
-   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/jpi,jpj,jpk,jpts/),tsn_id)
-   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/jpi,jpj,jpk,jpts/),tsa_id)
-   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/jpi,jpj,jpk,jpts/),tsb_id)
-
-   CALL agrif_declare_variable((/1,2,0/),(/2,3,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/),un_id)
-   CALL agrif_declare_variable((/2,1,0/),(/3,2,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/),vn_id)
-   CALL agrif_declare_variable((/1,2,0/),(/2,3,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/),ua_id)
-   CALL agrif_declare_variable((/2,1,0/),(/3,2,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/),va_id)
-
-   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/jpi,jpj/),unb_id)
-   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/jpi,jpj/),vnb_id)
-   CALL agrif_declare_variable((/2,2/),(/3,3/),(/'x','y'/),(/1,1/),(/jpi,jpj/),sshn_id)
-   CALL agrif_declare_variable((/2,2/),(/3,3/),(/'x','y'/),(/1,1/),(/jpi,jpj/),gcb_id)
-   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/jpi,jpj/),ub2b_id)
-   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/jpi,jpj/),vb2b_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jpts/),tsn_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jpts/),tsn_sponge_id)
+
+   CALL agrif_declare_variable((/1,2,0/),(/2,3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),un_interp_id)
+   CALL agrif_declare_variable((/2,1,0/),(/3,2,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),vn_interp_id)
+   CALL agrif_declare_variable((/1,2,0/),(/2,3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),un_update_id)
+   CALL agrif_declare_variable((/2,1,0/),(/3,2,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),vn_update_id)
+   CALL agrif_declare_variable((/1,2,0/),(/2,3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),un_sponge_id)
+   CALL agrif_declare_variable((/2,1,0/),(/3,2,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),vn_sponge_id)
+
+   CALL agrif_declare_variable((/2,2,0/),(/3,3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),e3t_id)
+   CALL agrif_declare_variable((/1,2,0/),(/2,3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),umsk_id)
+   CALL agrif_declare_variable((/2,1,0/),(/3,2,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),vmsk_id)
+
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,3/),scales_t_id)
+
+   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),unb_id)
+   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),vnb_id)
+   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),ub2b_interp_id)
+   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),vb2b_interp_id)
+   CALL agrif_declare_variable((/1,2/),(/2,3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),ub2b_update_id)
+   CALL agrif_declare_variable((/2,1/),(/3,2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),vb2b_update_id)
+
+   CALL agrif_declare_variable((/2,2/),(/3,3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),sshn_id)
+
+# if defined key_zdftke
+   CALL agrif_declare_variable((/2,2,0/),(/3,3,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/), en_id)
+   CALL agrif_declare_variable((/2,2,0/),(/3,3,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/),avt_id)
+   CALL agrif_declare_variable((/2,2,0/),(/3,3,0/),(/'x','y','N'/),(/1,1,1/),(/jpi,jpj,jpk/),avm_id)
+# endif
 
    ! 2. Type of interpolation
    !-------------------------
    CALL Agrif_Set_bcinterp(tsn_id,interp=AGRIF_linear)
-   CALL Agrif_Set_bcinterp(tsa_id,interp=AGRIF_linear)
-
-   Call Agrif_Set_bcinterp(un_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
-   Call Agrif_Set_bcinterp(vn_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
-
-   Call Agrif_Set_bcinterp(ua_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
-   Call Agrif_Set_bcinterp(va_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+   CALL Agrif_Set_bcinterp(un_interp_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vn_interp_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+   CALL Agrif_Set_bcinterp(tsn_sponge_id,interp=AGRIF_linear)
 
    CALL Agrif_Set_bcinterp(sshn_id,interp=AGRIF_linear)
-   Call Agrif_Set_bcinterp(unb_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
-   Call Agrif_Set_bcinterp(vnb_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
-   Call Agrif_Set_bcinterp(ub2b_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
-   Call Agrif_Set_bcinterp(vb2b_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+   CALL Agrif_Set_bcinterp(unb_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vnb_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+   CALL Agrif_Set_bcinterp(ub2b_interp_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vb2b_interp_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+
+   CALL Agrif_Set_bcinterp(un_sponge_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vn_sponge_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+   CALL Agrif_Set_bcinterp(e3t_id,interp=AGRIF_constant)
+   CALL Agrif_Set_bcinterp(umsk_id,interp=AGRIF_constant)
+   CALL Agrif_Set_bcinterp(vmsk_id,interp=AGRIF_constant)
+
+# if defined key_zdftke
+   CALL Agrif_Set_bcinterp(avm_id ,interp=AGRIF_linear)
+# endif
+
 
    ! 3. Location of interpolation
    !-----------------------------
-   Call Agrif_Set_bc(un_id,(/0,1/))
-   Call Agrif_Set_bc(vn_id,(/0,1/))
-
-   Call Agrif_Set_bc(sshn_id,(/0,1/))
-   Call Agrif_Set_bc(unb_id,(/0,1/))
-   Call Agrif_Set_bc(vnb_id,(/0,1/))
-   Call Agrif_Set_bc(ub2b_id,(/0,1/))
-   Call Agrif_Set_bc(vb2b_id,(/0,1/))
-
-   Call Agrif_Set_bc(tsn_id,(/0,1/))
-   Call Agrif_Set_bc(tsa_id,(/-3*Agrif_irhox(),0/))
-
-   Call Agrif_Set_bc(ua_id,(/-2*Agrif_irhox(),0/))
-   Call Agrif_Set_bc(va_id,(/-2*Agrif_irhox(),0/))
+   CALL Agrif_Set_bc(tsn_id,(/0,1/))
+   CALL Agrif_Set_bc(un_interp_id,(/0,1/))
+   CALL Agrif_Set_bc(vn_interp_id,(/0,1/))
+
+!   CALL Agrif_Set_bc(tsn_sponge_id,(/-3*Agrif_irhox(),0/))
+!   CALL Agrif_Set_bc(un_sponge_id,(/-2*Agrif_irhox()-1,0/))
+!   CALL Agrif_Set_bc(vn_sponge_id,(/-2*Agrif_irhox()-1,0/))
+   CALL Agrif_Set_bc(tsn_sponge_id,(/-nn_sponge_len*Agrif_irhox()-1,0/))
+   CALL Agrif_Set_bc(un_sponge_id ,(/-nn_sponge_len*Agrif_irhox()-1,0/))
+   CALL Agrif_Set_bc(vn_sponge_id ,(/-nn_sponge_len*Agrif_irhox()-1,0/))
+
+   CALL Agrif_Set_bc(sshn_id,(/0,0/))
+   CALL Agrif_Set_bc(unb_id ,(/0,0/))
+   CALL Agrif_Set_bc(vnb_id ,(/0,0/))
+   CALL Agrif_Set_bc(ub2b_interp_id,(/0,0/))
+   CALL Agrif_Set_bc(vb2b_interp_id,(/0,0/))
+
+   CALL Agrif_Set_bc(e3t_id,(/-2*Agrif_irhox()-1,0/))   ! if west and rhox=3: column 2 to 9
+   CALL Agrif_Set_bc(umsk_id,(/0,0/))
+   CALL Agrif_Set_bc(vmsk_id,(/0,0/))
+
+# if defined key_zdftke
+   CALL Agrif_Set_bc(avm_id ,(/0,1/))
+# endif
 
    ! 5. Update type
    !--------------- 
-   Call Agrif_Set_Updatetype(tsn_id, update = AGRIF_Update_Average)
-   Call Agrif_Set_Updatetype(tsb_id, update = AGRIF_Update_Average)
-
-   Call Agrif_Set_Updatetype(sshn_id, update = AGRIF_Update_Average)
-   Call Agrif_Set_Updatetype(gcb_id,update = AGRIF_Update_Average)
-
-   Call Agrif_Set_Updatetype(un_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
-   Call Agrif_Set_Updatetype(vn_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
-
-   Call Agrif_Set_Updatetype(ub2b_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
-   Call Agrif_Set_Updatetype(vb2b_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
-
+   CALL Agrif_Set_Updatetype(tsn_id, update = AGRIF_Update_Average)
+
+   CALL Agrif_Set_Updatetype(scales_t_id, update = AGRIF_Update_Average)
+
+   CALL Agrif_Set_Updatetype(un_update_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(vn_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
+
+   CALL Agrif_Set_Updatetype(sshn_id, update = AGRIF_Update_Average)
+
+   CALL Agrif_Set_Updatetype(ub2b_update_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(vb2b_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
+
+# if defined key_zdftke
+   CALL Agrif_Set_Updatetype( en_id, update = AGRIF_Update_Average)
+   CALL Agrif_Set_Updatetype(avt_id, update = AGRIF_Update_Average)
+   CALL Agrif_Set_Updatetype(avm_id, update = AGRIF_Update_Average)
+# endif
+
+! High order updates
+!   CALL Agrif_Set_Updatetype(tsn_id, update = Agrif_Update_Full_Weighting)
+!   CALL Agrif_Set_Updatetype(un_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Full_Weighting)
+!   CALL Agrif_Set_Updatetype(vn_update_id,update1 = Agrif_Update_Full_Weighting, update2 = Agrif_Update_Average)
+!
+!   CALL Agrif_Set_Updatetype(ub2b_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Full_Weighting)
+!   CALL Agrif_Set_Updatetype(vb2b_update_id,update1 = Agrif_Update_Full_Weighting, update2 = Agrif_Update_Average)
+!   CALL Agrif_Set_Updatetype(sshn_id, update = Agrif_Update_Full_Weighting)
+ 
+   !
 END SUBROUTINE agrif_declare_var
 # endif
@@ -365,9 +476,5 @@
    IMPLICIT NONE
    !
-   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE :: zvel
-   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: zadv
-   !!----------------------------------------------------------------------
-
-   ALLOCATE( zvel(jpi,jpj), zadv(jpi,jpj,7))
+   !!----------------------------------------------------------------------
 
    ! 1. Declaration of the type of variable which have to be interpolated
@@ -401,6 +508,4 @@
    CALL Agrif_Update_lim2(0)
    !
-   DEALLOCATE( zvel, zadv )
-   !
 END SUBROUTINE Agrif_InitValues_cont_lim2
 
@@ -431,19 +536,19 @@
    !-------------------------
    CALL Agrif_Set_bcinterp(adv_ice_id ,interp=AGRIF_linear)
-   Call Agrif_Set_bcinterp(u_ice_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
-   Call Agrif_Set_bcinterp(v_ice_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+   CALL Agrif_Set_bcinterp(u_ice_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(v_ice_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
 
    ! 3. Location of interpolation
    !-----------------------------
-   Call Agrif_Set_bc(adv_ice_id ,(/0,1/))
-   Call Agrif_Set_bc(u_ice_id,(/0,1/))
-   Call Agrif_Set_bc(v_ice_id,(/0,1/))
+   CALL Agrif_Set_bc(adv_ice_id ,(/0,1/))
+   CALL Agrif_Set_bc(u_ice_id,(/0,1/))
+   CALL Agrif_Set_bc(v_ice_id,(/0,1/))
 
    ! 5. Update type
    !---------------
-   Call Agrif_Set_Updatetype(adv_ice_id , update = AGRIF_Update_Average)
-   Call Agrif_Set_Updatetype(u_ice_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
-   Call Agrif_Set_Updatetype(v_ice_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
-
+   CALL Agrif_Set_Updatetype(adv_ice_id , update = AGRIF_Update_Average)
+   CALL Agrif_Set_Updatetype(u_ice_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(v_ice_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
+   ! 
 END SUBROUTINE agrif_declare_var_lim2
 #  endif
@@ -462,6 +567,8 @@
    USE nemogcm
    USE par_trc
+   USE lib_mpp
    USE trc
    USE in_out_manager
+   USE agrif_opa_sponge
    USE agrif_top_update
    USE agrif_top_interp
@@ -470,9 +577,7 @@
    IMPLICIT NONE
    !
-   REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE :: tabtrtemp
+   CHARACTER(len=10) :: cl_check1, cl_check2, cl_check3
    LOGICAL :: check_namelist
    !!----------------------------------------------------------------------
-
-   ALLOCATE( tabtrtemp(jpi,jpj,jpk,jptra) )
 
 
@@ -485,35 +590,42 @@
    Agrif_SpecialValue=0.
    Agrif_UseSpecialValue = .TRUE.
-   Call Agrif_Bc_variable(tabtrtemp,trn_id,calledweight=1.,procname=interptrn)
-   Call Agrif_Bc_variable(tabtrtemp,tra_id,calledweight=1.,procname=interptrn)
+   CALL Agrif_Bc_variable(trn_id,calledweight=1.,procname=interptrn)
    Agrif_UseSpecialValue = .FALSE.
+   CALL Agrif_Sponge
+   tabspongedone_trn = .FALSE.
+   CALL Agrif_Bc_variable(trn_sponge_id,calledweight=1.,procname=interptrn_sponge)
+   ! reset tsa to zero
+   tra(:,:,:,:) = 0.
+
 
    ! 3. Some controls
    !-----------------
-   check_namelist = .true.
+   check_namelist = .TRUE.
 
    IF( check_namelist ) THEN
-#  if defined offline     
+# if defined key_offline
       ! Check time steps
-      IF( nint(Agrif_Rhot()) * nint(rdt) .ne. Agrif_Parent(rdt) ) THEN
-         WRITE(*,*) 'incompatible time step between grids'
-         WRITE(*,*) 'parent grid value : ',Agrif_Parent(rdt)
-         WRITE(*,*) 'child  grid value : ',nint(rdt)
-         WRITE(*,*) 'value on parent grid should be : ',rdt*Agrif_Rhot()
-         STOP
+      IF( NINT(Agrif_Rhot()) * NINT(rdt) .NE. Agrif_Parent(rdt) ) THEN
+         WRITE(cl_check1,*)  Agrif_Parent(rdt)
+         WRITE(cl_check2,*)  rdt
+         WRITE(cl_check3,*)  rdt*Agrif_Rhot()
+         CALL ctl_warn( 'incompatible time step between grids',   &
+               &               'parent grid value : '//cl_check1    ,   & 
+               &               'child  grid value : '//cl_check2    ,   & 
+               &               'value on child grid will be changed to  &
+               &               :'//cl_check3  )
+         rdt=rdt*Agrif_Rhot()
       ENDIF
 
       ! Check run length
       IF( Agrif_IRhot() * (Agrif_Parent(nitend)- &
-           Agrif_Parent(nit000)+1) .ne. (nitend-nit000+1) ) THEN
-         WRITE(*,*) 'incompatible run length between grids'
-         WRITE(*,*) 'parent grid value : ',(Agrif_Parent(nitend)- &
-              Agrif_Parent(nit000)+1),' time step'
-         WRITE(*,*) 'child  grid value : ', &
-              (nitend-nit000+1),' time step'
-         WRITE(*,*) 'value on child grid should be : ', &
-              Agrif_IRhot() * (Agrif_Parent(nitend)- &
-              Agrif_Parent(nit000)+1)
-         STOP
+            Agrif_Parent(nit000)+1) .NE. (nitend-nit000+1) ) THEN
+         WRITE(cl_check1,*)  (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         WRITE(cl_check2,*)   Agrif_Parent(nitend)   *Agrif_IRhot()
+         CALL ctl_warn( 'incompatible run length between grids'               ,   &
+               &              ' nit000 on fine grid will be change to : '//cl_check1,   &
+               &              ' nitend on fine grid will be change to : '//cl_check2    )
+         nit000 = (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         nitend =  Agrif_Parent(nitend)   *Agrif_IRhot()
       ENDIF
 
@@ -521,5 +633,5 @@
       IF( ln_zps ) THEN
          ! check parameters for partial steps 
-         IF( Agrif_Parent(e3zps_min) .ne. e3zps_min ) THEN
+         IF( Agrif_Parent(e3zps_min) .NE. e3zps_min ) THEN
             WRITE(*,*) 'incompatible e3zps_min between grids'
             WRITE(*,*) 'parent grid :',Agrif_Parent(e3zps_min)
@@ -528,5 +640,5 @@
             STOP
          ENDIF
-         IF( Agrif_Parent(e3zps_rat) .ne. e3zps_rat ) THEN
+         IF( Agrif_Parent(e3zps_rat) .NE. e3zps_rat ) THEN
             WRITE(*,*) 'incompatible e3zps_rat between grids'
             WRITE(*,*) 'parent grid :',Agrif_Parent(e3zps_rat)
@@ -538,13 +650,13 @@
 #  endif         
       ! Check passive tracer cell
-      IF( nn_dttrc .ne. 1 ) THEN
+      IF( nn_dttrc .NE. 1 ) THEN
          WRITE(*,*) 'nn_dttrc should be equal to 1'
       ENDIF
    ENDIF
 
-!ch   CALL Agrif_Update_trc(0)
+   CALL Agrif_Update_trc(0)
+   !
+   Agrif_UseSpecialValueInUpdate = .FALSE.
    nbcline_trc = 0
-   !
-   DEALLOCATE(tabtrtemp)
    !
 END SUBROUTINE Agrif_InitValues_cont_top
@@ -558,4 +670,5 @@
    !!----------------------------------------------------------------------
    USE agrif_util
+   USE agrif_oce
    USE dom_oce
    USE trc
@@ -565,24 +678,26 @@
    ! 1. Declaration of the type of variable which have to be interpolated
    !---------------------------------------------------------------------
-   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/jpi,jpj,jpk,jptra/),trn_id)
-   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/jpi,jpj,jpk,jptra/),trb_id)
-   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/jpi,jpj,jpk,jptra/),tra_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jptra/),trn_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jptra/),trn_sponge_id)
 
    ! 2. Type of interpolation
    !-------------------------
    CALL Agrif_Set_bcinterp(trn_id,interp=AGRIF_linear)
-   CALL Agrif_Set_bcinterp(tra_id,interp=AGRIF_linear)
+   CALL Agrif_Set_bcinterp(trn_sponge_id,interp=AGRIF_linear)
 
    ! 3. Location of interpolation
    !-----------------------------
-   Call Agrif_Set_bc(trn_id,(/0,1/))
-   Call Agrif_Set_bc(tra_id,(/-3*Agrif_irhox(),0/))
+   CALL Agrif_Set_bc(trn_id,(/0,1/))
+!   CALL Agrif_Set_bc(trn_sponge_id,(/-3*Agrif_irhox(),0/))
+   CALL Agrif_Set_bc(trn_sponge_id,(/-nn_sponge_len*Agrif_irhox()-1,0/))
 
    ! 5. Update type
    !--------------- 
-   Call Agrif_Set_Updatetype(trn_id, update = AGRIF_Update_Average)
-   Call Agrif_Set_Updatetype(trb_id, update = AGRIF_Update_Average)
-
-
+   CALL Agrif_Set_Updatetype(trn_id, update = AGRIF_Update_Average)
+
+!   Higher order update
+!   CALL Agrif_Set_Updatetype(tsn_id, update = Agrif_Update_Full_Weighting)
+
+   !
 END SUBROUTINE agrif_declare_var_top
 # endif
@@ -592,5 +707,4 @@
    !!   *** ROUTINE Agrif_detect ***
    !!----------------------------------------------------------------------
-   USE Agrif_Types
    !
    INTEGER, DIMENSION(2) :: ksizex
@@ -614,15 +728,16 @@
    !
    INTEGER  ::   ios                 ! Local integer output status for namelist read
-   NAMELIST/namagrif/ nn_cln_update, rn_sponge_tra, rn_sponge_dyn, ln_spc_dyn
-   !!----------------------------------------------------------------------
-   !
-      REWIND( numnam_ref )              ! Namelist namagrif in reference namelist : AGRIF zoom
-      READ  ( numnam_ref, namagrif, IOSTAT = ios, ERR = 901)
-901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namagrif in reference namelist', lwp )
-
-      REWIND( numnam_cfg )              ! Namelist namagrif in configuration namelist : AGRIF zoom
-      READ  ( numnam_cfg, namagrif, IOSTAT = ios, ERR = 902 )
-902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namagrif in configuration namelist', lwp )
-      IF(lwm) WRITE ( numond, namagrif )
+   INTEGER  ::   iminspon
+   NAMELIST/namagrif/ nn_cln_update, rn_sponge_tra, rn_sponge_dyn, ln_spc_dyn, ln_chk_bathy
+   !!--------------------------------------------------------------------------------------
+   !
+   REWIND( numnam_ref )              ! Namelist namagrif in reference namelist : AGRIF zoom
+   READ  ( numnam_ref, namagrif, IOSTAT = ios, ERR = 901)
+901 IF( ios /= 0 ) CALL ctl_nam ( ios , 'namagrif in reference namelist', lwp )
+
+   REWIND( numnam_cfg )              ! Namelist namagrif in configuration namelist : AGRIF zoom
+   READ  ( numnam_cfg, namagrif, IOSTAT = ios, ERR = 902 )
+902 IF( ios /= 0 ) CALL ctl_nam ( ios , 'namagrif in configuration namelist', lwp )
+   IF(lwm) WRITE ( numond, namagrif )
    !
    IF(lwp) THEN                    ! control print
@@ -635,4 +750,5 @@
       WRITE(numout,*) '      sponge coefficient for dynamics   rn_sponge_tra = ', rn_sponge_dyn, ' s'
       WRITE(numout,*) '      use special values for dynamics   ln_spc_dyn    = ', ln_spc_dyn
+      WRITE(numout,*) '      check bathymetry                  ln_chk_bathy  = ', ln_chk_bathy
       WRITE(numout,*) 
    ENDIF
@@ -643,5 +759,10 @@
    visc_dyn      = rn_sponge_dyn
    !
-   IF( agrif_oce_alloc()  > 0 )   CALL ctl_warn('agrif sol_oce_alloc: allocation of arrays failed')
+   ! Check sponge length:
+   iminspon = MIN(FLOOR(REAL(jpiglo-4)/REAL(2*Agrif_irhox())), FLOOR(REAL(jpjglo-4)/REAL(2*Agrif_irhox())) )
+   IF (lk_mpp) iminspon = MIN(iminspon,FLOOR(REAL(jpi-2)/REAL(Agrif_irhox())), FLOOR(REAL(jpj-2)/REAL(Agrif_irhox())) )
+   IF (nn_sponge_len > iminspon)  CALL ctl_stop('agrif sponge length is too large')
+   !
+   IF( agrif_oce_alloc()  > 0 )   CALL ctl_warn('agrif agrif_oce_alloc: allocation of arrays failed')
 # if defined key_lim2
    IF( agrif_ice_alloc()  > 0 )   CALL ctl_stop('agrif agrif_ice_alloc: allocation of arrays failed')
@@ -664,10 +785,45 @@
    SELECT CASE( i )
    CASE(1)   ;   indglob = indloc + nimppt(nprocloc+1) - 1
-   CASE(2)   ;   indglob = indloc + njmppt(nprocloc+1) - 1 
-   CASE(3)   ;   indglob = indloc
-   CASE(4)   ;   indglob = indloc
+   CASE(2)   ;   indglob = indloc + njmppt(nprocloc+1) - 1
+   CASE DEFAULT
+      indglob = indloc
    END SELECT
    !
 END SUBROUTINE Agrif_InvLoc
+
+SUBROUTINE Agrif_get_proc_info( imin, imax, jmin, jmax )
+   !!----------------------------------------------------------------------
+   !!                 *** ROUTINE Agrif_get_proc_info ***
+   !!----------------------------------------------------------------------
+   USE par_oce
+   IMPLICIT NONE
+   !
+   INTEGER, INTENT(out) :: imin, imax
+   INTEGER, INTENT(out) :: jmin, jmax
+   !!----------------------------------------------------------------------
+   !
+   imin = nimppt(Agrif_Procrank+1)  ! ?????
+   jmin = njmppt(Agrif_Procrank+1)  ! ?????
+   imax = imin + jpi - 1
+   jmax = jmin + jpj - 1
+   ! 
+END SUBROUTINE Agrif_get_proc_info
+
+SUBROUTINE Agrif_estimate_parallel_cost(imin, imax,jmin, jmax, nbprocs, grid_cost)
+   !!----------------------------------------------------------------------
+   !!                 *** ROUTINE Agrif_estimate_parallel_cost ***
+   !!----------------------------------------------------------------------
+   USE par_oce
+   IMPLICIT NONE
+   !
+   INTEGER,  INTENT(in)  :: imin, imax
+   INTEGER,  INTENT(in)  :: jmin, jmax
+   INTEGER,  INTENT(in)  :: nbprocs
+   REAL(wp), INTENT(out) :: grid_cost
+   !!----------------------------------------------------------------------
+   !
+   grid_cost = REAL(imax-imin+1,wp)*REAL(jmax-jmin+1,wp) / REAL(nbprocs,wp)
+   !
+END SUBROUTINE Agrif_estimate_parallel_cost
 
 # endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OFF_SRC/dtadyn.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OFF_SRC/dtadyn.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OFF_SRC/dtadyn.F90	(revision 9987)
@@ -431,10 +431,13 @@
          CALL ctl_stop( 'dta_dyn: unable to allocate sf structure' )   ;   RETURN
       ENDIF
+      !                                         ! fill sf with slf_i and control print
+      CALL fld_fill( sf_dyn, slf_d, cn_dir, 'dta_dyn_init', 'Data in file', 'namdta_dyn' )
       ! Open file for each variable to get his number of dimension
       DO ifpr = 1, jfld
-         CALL iom_open( TRIM( cn_dir )//TRIM( slf_d(ifpr)%clname ), inum )
-         idv   = iom_varid( inum , slf_d(ifpr)%clvar )  ! id of the variable sdjf%clvar
-         idimv = iom_file ( inum )%ndims(idv)             ! number of dimension for variable sdjf%clvar
-         IF( inum /= 0 )   CALL iom_close( inum )       ! close file if already open
+         CALL fld_clopn( sf_dyn(ifpr), nyear, nmonth, nday )
+         idv   = iom_varid( sf_dyn(ifpr)%num , slf_d(ifpr)%clvar )        ! id of the variable sdjf%clvar
+         idimv = iom_file ( sf_dyn(ifpr)%num )%ndims(idv)                 ! number of dimension for variable sdjf%clvar
+         IF( sf_dyn(ifpr)%num /= 0 )   CALL iom_close( sf_dyn(ifpr)%num ) ! close file if already open
+         ierr1=0
          IF( idimv == 3 ) THEN    ! 2D variable
                                       ALLOCATE( sf_dyn(ifpr)%fnow(jpi,jpj,1)    , STAT=ierr0 )
@@ -448,6 +451,4 @@
          ENDIF
       END DO
-      !                                         ! fill sf with slf_i and control print
-      CALL fld_fill( sf_dyn, slf_d, cn_dir, 'dta_dyn_init', 'Data in file', 'namdta_dyn' )
       !
       IF( lk_ldfslp .AND. .NOT.lk_c1d ) THEN                  ! slopes 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/asmbkg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/asmbkg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/asmbkg.F90	(revision 9987)
@@ -119,5 +119,6 @@
             CALL iom_rstput( kt, nitbkg_r, inum, 'en'     , en                )
 #endif
-            CALL iom_rstput( kt, nitbkg_r, inum, 'gcx'    , gcx               )
+!            CALL iom_rstput( kt, nitbkg_r, inum, 'gcx'    , gcx               )
+            CALL iom_rstput( kt, nitbkg_r, inum, 'avt'    , avt               )
             !
             CALL iom_close( inum )
@@ -153,4 +154,5 @@
             CALL iom_rstput( kt, nitdin_r, inum, 'tn'     , tsn(:,:,:,jp_tem) )
             CALL iom_rstput( kt, nitdin_r, inum, 'sn'     , tsn(:,:,:,jp_sal) )
+            CALL iom_rstput( kt, nitdin_r, inum, 'avt'    , avt     )
             CALL iom_rstput( kt, nitdin_r, inum, 'sshn'   , sshn              )
 #if defined key_lim2 || defined key_lim3
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/asminc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/asminc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/asminc.F90	(revision 9987)
@@ -39,4 +39,8 @@
    USE ice_2            ! LIM2
 #endif
+#if defined key_cice && defined key_asminc
+   USE sbc_ice, ONLY : & ! CICE Ice model variables
+   & ndaice_da, nfresh_da, nfsalt_da
+#endif
    USE sbc_oce          ! Surface boundary condition variables.
 
@@ -131,5 +135,6 @@
          &                 ln_asmdin, ln_asmiau,                           &
          &                 nitbkg, nitdin, nitiaustr, nitiaufin, niaufn,   &
-         &                 ln_salfix, salfixmin, nn_divdmp
+         &                 ln_salfix, salfixmin, nn_divdmp,                &
+         &                 ln_seaiceinc, ln_temnofreeze
       !!----------------------------------------------------------------------
 
@@ -656,5 +661,5 @@
 
       DO jk = 1, jpkm1
-         fzptnz(:,:,jk) = eos_fzp( tsn(:,:,jk,jp_sal), fsdept(:,:,jk) )
+        CALL eos_fzp( tsn(:,:,jk,jp_sal), fzptnz(:,:,jk), fsdept(:,:,jk) )
       END DO
 
@@ -890,4 +895,8 @@
             ENDIF
 
+         ELSE
+#if defined key_asminc
+            ssh_iau(:,:) = 0.0
+#endif
          ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/bias.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/bias.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/bias.F90	(revision 9987)
@@ -0,0 +1,1054 @@
+MODULE bias 
+   !! Is used by OPA and STEP
+   !!======================================================================
+   !!                 *** Module bias ***
+   !! Code to estimate and apply bias correction.
+   !! The bias is in T/S and Pressure. It follows the generalized
+   !! bias algorithm presented in Balmaseda et al 2007.
+   !!
+   !! It can be read from a file offline, estimated online from relaxation
+   !! terms or from assimilation increments (this latter estimtd in inner loop)
+   !!
+   !! The parameters for the time evolution of the bias can be different
+   !! from the relaxation terms and for the assim increments. Only the 
+   !! parameter for the relaxtion terms are considered here.
+   !! 
+   !! The offline bias term can contain the seasonal cycle.
+   !!
+   !! The time evolution of the bias for relaxtion is estimated as followed
+   !!   bias_rlx(t+1)=t_rlx_mem*bias_rlx(t)+t_rlx_upd*(t/s)trdmp.
+   !!
+   !! The total bias in T/S is partion between the correction to T/S only
+   !!  (fb_t) and the correction applied to the pressure gradient (fb_p).
+   !!  We impose that (fb_p=1.-fb_t). These factors can be different for the
+   !!  different terms(fb_t_rxl,fb_t_asm,fb_t_ofl)
+   !!
+   !!    (t/s)bias =  fb_t_ofl * (t/s)bias_ofl +
+   !!                 fb_t_rlx * (t/s)bias_rlx +
+   !!                 fb_t_asm * (t/s)bias_asm
+   !!    (t/s)bias_p =fb_p_ofl * (t/s)bias_ofl+ 
+   !!                 fb_p_rlx * (t/s)bias_rlx_p +
+   !!                 fb_p_asm * (t/s)bias_asm_p
+   !!    (t/s)bias is applied directely to correct T and S
+   !!    (t/s)bias_p is used to compute rhd_pc and gru/v_pc
+   !!
+   !!  Note: the above is an adhoc /simple way of making the partition
+   !!        between bias in pressure and bias in T/S. It would be better
+   !!        if the partition is done at the time of estimating the time
+   !!        evolution of the bias. That would mean doubling the number of
+   !!        3D arrays.
+   !!
+   !!  New addtion: (not in Balmaseda et al 2007):
+   !!  A more physical alternative to the partition of the bias can be
+   !!  done in terms of the inertial frequency: when the time scales of 
+   !!  adjustment are shorter that >1/f (Equator), the bias correction should
+   !!  be in the the pressure term. Otherwise, it can act directly in T/S.
+   !!  NOTE that the bias correction in the pressure term here (following
+   !!  (Bell et al 2007) is just the "opposite" as the semi-prognostic method 
+   !!  in Greatbatch et al 2004. 
+   !!  The use of this partition is controlled by ln_inertial=.true.
+   !!  
+   !!
+   !!        2009-03              (M.A. Balmaseda ECMWF)
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   bias_init  : Read in the bias namelist and the bias arrays
+   !!   tra_bias   : Apply the bias fields on T/S directly
+   !!   dyn_bias   : Compute density correction for dynamic hpg
+   !!   bias_opn   : open bias files for restart capabilities
+   !!   bias_wrt   : write bias fies "     "          "
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY: &
+      & wp
+   USE par_oce, ONLY: &
+      & jpi, &
+      & jpj, &
+      & jpk
+   USE dom_oce, ONLY: &
+      & rdt,          &
+      & ln_zps,       &
+      & gphit
+   USE phycst,  ONLY: &
+      & rday,         &
+      & rad
+   USE oce, ONLY: &
+      & tsb, tsn, tsa, &
+      & rhop,  &
+      & gtsu, gtsv
+   USE dynhpg, ONLY:   &
+      & ln_dynhpg_imp      
+   USE tradmp
+   USE dtatsd, ONLY: &
+      & ln_tsd_tradmp
+   USE in_out_manager, ONLY: &
+      & lwp,          &
+      & numnam_ref,   &
+      & numnam_cfg,   &
+      & numond,       &
+      & numout,       &
+      & lrst_oce,     &
+      & nit000
+   USE iom
+   USE eosbn2
+   USE zpshde          ! partial step: hor. derivative (zps_hde routine)
+   USE biaspar
+   USE fldread         ! read input fields
+   USE lbclnk          ! lateral boundary conditions (or mpp link)
+   USE asmpar
+   USE asminc
+   USE lib_mpp, ONLY: &
+      & ctl_stop, &
+      & ctl_nam
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE   
+   PUBLIC bias_init,   &   !: Read in the bias namelist and the bias arrays
+      &   tra_bias,    &   !: Estimate/apply bias on traces
+      &   dyn_bias,    &   !: " density correction for pressure gradient.
+      &   bias_opn,    &
+      &   bias_wrt
+
+   !! * Substitutions needed to have the variable fsdept_n
+#  include "domzgr_substitute.h90"
+   !! * Shared variables
+   !! * Private module variables
+   REAL(wp), PRIVATE :: &
+      & bias_time_unit_asm,   &  !: bias_asm units in s ( per day = 86400 s)   
+      & bias_time_unit_rlx,   &  !: bias_rlx units in s ( 1 second) 
+      & bias_time_unit_ofl,   &  !: bias_ofl units in s ( 1 second) 
+      & t_rlx_mem,            &  !: time param for mem in bias_rlx model
+      & t_rlx_upd,            &  !: time param for update in bias_rlx model
+                                 !: (pct of incr for computation of bias)
+      & t_asm_mem,            &  !: time param for mem in bias_asm model
+      & t_asm_upd,            &  !: time param for update in bias_asm model
+                                 !: (pct of incr for computation of bias)
+      & fb_t_rlx,             &  !: parition of bias in T for rlx bias term
+      & fb_t_asm,             &  !: parition of bias in T for asm bias term
+      & fb_t_ofl,             &  !: parition of bias in T for ofl bias term
+      & fb_p_rlx,             &  !: parition of bias in P for rlx bias term
+      & fb_p_asm,             &  !: parition of bias in P for asm bias term
+      & fb_p_ofl,             &  !: parition of bias in P for ofl bias term
+      & fctamp,               &  !: amplification factor for T if inertial
+      & rn_maxlat_bias,       &  !: Max lat for latitudinal ramp
+      & rn_minlat_bias,       &  !: Min lat for latitudinal ramp
+      & zwgt,                 &  !: weight for IPC
+      & ztscale                  !: decay rate for IPC
+
+   LOGICAL,  PRIVATE :: lalloc
+   REAL(wp), PRIVATE, DIMENSION(:,:,:), ALLOCATABLE :: &
+      & tbias_asm, &       !: Temperature bias field
+      & sbias_asm, &       !: Salinity bias field
+      & tbias_rlx, &       !: Temperature bias field
+      & sbias_rlx, &       !: Salinity bias field
+      & tbias_asm_out, &   !: Output temperature bias field
+      & sbias_asm_out, &   !: Output salinity bias field
+      & tbias_rlx_out, &   !: Output temperature bias field
+      & sbias_rlx_out, &   !: Output salinity bias field
+      & tbias_p_out,   &   !: Output temperature bias field for P correction
+      & sbias_p_out,   &   !: Output salinity bias field for P correction
+      & tbias_i_out,   &   !: Output temperature bias field for incremental P correction
+      & sbias_i_out,   &   !: Output salinity bias field for incremental P correction
+      & tbias_asm_stscale, &   !: Short time scale temperature bias field
+      & sbias_asm_stscale, &   !: Short time scale salinity bias field
+      & tbias_asm_stscale_out, &   !: Short time scale temperature bias output field
+      & sbias_asm_stscale_out   !: Short time scale salinity bias output field
+
+   INTEGER, PRIVATE :: nn_lat_ramp     ! choice of latitude dependent ramp
+                                       ! for the pressure correction.
+				       ! 1:inertial ramp, 2:linear ramp, else:no ramp
+   LOGICAL, PRIVATE :: ln_bsyncro      ! syncronous or assincrous bias correction   
+   LOGICAL, PRIVATE :: ln_itdecay      ! evolve bias correction at every time step.  
+   LOGICAL, PRIVATE :: ln_incpc        ! incremental pressure correction plus pressure correction
+   LOGICAL, PRIVATE :: ln_incpc_only        ! incremental pressure correction only
+
+   REAL(wp), PRIVATE, DIMENSION(:,:), ALLOCATABLE :: fbcoef
+   REAL(wp), PRIVATE, DIMENSION(:,:), ALLOCATABLE :: fbcoef_stscale
+
+   INTEGER, PRIVATE ::  &
+      & numbias_asm, &    ! netcdf id of bias file from assim
+      & numbias_tot, &    ! netcdf id of bias file with total bias
+      & nn_bias_itwrt     ! time step for outputting bias pressure corr
+         
+   CHARACTER(LEN=128), PRIVATE :: &
+      & cn_bias_asm,   &  ! name of bias file from assim
+      & cn_bias_tot       ! name of bias with total/rlx bias
+
+   ! Structure of input T and S bias offline (file informations, fields read)
+   TYPE(FLD), PRIVATE, ALLOCATABLE, DIMENSION(:) ::   sf_tbias_ofl  
+   TYPE(FLD), PRIVATE, ALLOCATABLE, DIMENSION(:) ::   sf_sbias_ofl
+
+   TYPE(FLD_N), PRIVATE ::&   ! information about the fields to be read
+      &  sn_tbias_ofl, sn_sbias_ofl  
+   
+CONTAINS
+
+   SUBROUTINE bias_init
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE bias_init  ***
+      !!
+      !! ** Purpose : Read in the bias namelist and read in the bias fields.
+      !!
+      !! ** Method  : Read in the bias namelist and read in the bias fields.
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        !  08-05  (D. Lea)    Initial version
+      !!        !  08-10  (M. Martin) Tidy
+      !!        !  09-03  (M. Balmaseda). Generalize to estimate the bias
+      !!                                  from relax and offline bias term.
+      !!                                  Introduce parameters to control the
+      !!                                  model for the bias 
+      !!                                  (variables and time evolution)
+      !!----------------------------------------------------------------------
+
+      IMPLICIT NONE
+      
+      !! * Local declarations
+
+      CHARACTER(len=100) ::  cn_dir          ! dir for location ofline bias
+      INTEGER            ::  ierror
+      INTEGER            ::  ios             ! Local integer output status for namelist read
+      REAL(wp)           ::  eft_rlx,  &     ! efolding time (bias memory) in days
+         &                   eft_asm,  &     !     "      "
+         &                   log2,     &
+         &                   lenscl_bias, &  ! lengthscale pressure bias decay between minlat and maxlat.
+         &                   minlat_bias, &  ! used in ipc
+         &                   maxlat_bias     ! used in ipc
+      
+      NAMELIST/nambias/ ln_bias, ln_bias_asm, ln_bias_rlx, ln_bias_ofl,   &
+         & ln_bias_ts_app, ln_bias_pc_app,                                &
+         & fb_t_asm, fb_t_rlx, fb_t_ofl, fb_p_asm, fb_p_rlx, fb_p_ofl,    &
+         & eft_rlx, t_rlx_upd, eft_asm, t_asm_upd, nn_lat_ramp,           &
+         & bias_time_unit_asm, bias_time_unit_rlx, bias_time_unit_ofl,    &
+         & cn_bias_tot, cn_bias_asm, cn_dir, sn_tbias_ofl, sn_sbias_ofl,  &
+         & ln_bsyncro, fctamp, rn_maxlat_bias, rn_minlat_bias,            &
+         & nn_bias_itwrt, ln_itdecay, ln_incpc,ln_incpc_only, ztscale, zwgt
+ 
+
+      !-----------------------------------------------------------------------
+      ! Read Namelist : bias interface
+      !-----------------------------------------------------------------------
+
+
+      REWIND( numnam_ref )              ! Namelist nambias in reference namelist : Bias pressure correction
+      READ  ( numnam_ref, nambias, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nambias in reference namelist', lwp )
+
+
+      ! Set additional default values (note that most values are set in the reference namelist)
+      
+      IF ( ln_asmiau ) nn_bias_itwrt = nitiaufin
+      
+      ! ... default values (NB: frequency positive => hours, negative => months)
+      !            !   file    ! frequency !  variable  ! time intep !  clim   ! 'yearly' or !
+      !            !   name    !  (hours)  !   name     !   (T/F)    !  (T/F)  !  'monthly'  !
+      sn_tbias_ofl = FLD_N( 'tbias_ofl'    ,    -1.    ,  'tbias'     ,  .TRUE.   , .FALSE. ,   'yearly', '', '', ''  )
+      sn_sbias_ofl = FLD_N( 'sbias_ofl'    ,    -1.    ,  'sbias'     ,  .TRUE.   , .FALSE. ,   'yearly', '', '', ''  )
+
+
+      REWIND( numnam_cfg )              ! Namelist nambias in configuration namelist : Bias pressure correction
+      READ  ( numnam_cfg, nambias, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nambias in configuration namelist', lwp )
+      IF(lwm) WRITE ( numond, nambias )
+
+
+      IF ( ( .NOT. ln_bias_asm ) .AND. ( .NOT. ln_bias_ofl ) .AND. ( .NOT. ln_bias_rlx ) ) THEN
+         ln_bias_ts_app = .FALSE.
+         ln_bias_pc_app = .FALSE.
+         ln_bias        = .FALSE.
+      ENDIF
+      
+      ! set up decay scales
+      log2           = LOG( 2.0_wp )
+      t_rlx_mem      = EXP( - log2 * rdt / ( eft_rlx * rday ) )
+      t_asm_mem      = EXP( - log2 * bias_time_unit_asm/ ( eft_asm * rday ) )
+      
+      ! Control print
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'bias_init : '
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '  Namelist nambias : '
+
+         WRITE(numout,*) '  Bias switches/options/variables '
+         WRITE(numout,*) '     bias main switch               ln_bias        = ',ln_bias
+         WRITE(numout,*) '     bias from assim                ln_bias_asm    = ',ln_bias_asm
+         WRITE(numout,*) '     bias from relax                ln_bias_rlx    = ',ln_bias_rlx
+         WRITE(numout,*) '     bias from offln                ln_bias_ofl    = ',ln_bias_ofl
+         WRITE(numout,*) '     bias T and S apply             ln_bias_ts_app = ',ln_bias_ts_app
+         WRITE(numout,*) '     bias pressure correctn apply   ln_bias_pc_app = ',ln_bias_pc_app
+         WRITE(numout,*) '     bias pressure correctn apply   ln_bias_pc_app = ',ln_bias_pc_app
+         WRITE(numout,*) '     lat ramp for bias correction   nn_lat_ramp    = ',nn_lat_ramp
+         WRITE(numout,*) '     time step for writing bias fld nn_bias_itwrt  = ',nn_bias_itwrt
+	 WRITE(numout,*) '     evolve pcbias at each timestep ln_itdecay     = ',ln_itdecay
+	 WRITE(numout,*) '     incremental press. correction  ln_incpc       = ',ln_incpc
+	 WRITE(numout,*) '     incremental press. correction only  ln_incpc_only       = ',ln_incpc_only
+	 WRITE(numout,*) '     incremental press. correction  zwgt           = ',zwgt
+	 WRITE(numout,*) '     incremental press. correction  ztscale        = ',ztscale
+         WRITE(numout,*) '  Parameters for parition of bias term '
+         WRITE(numout,*) '                                    fb_t_rlx       = ',fb_t_rlx
+         WRITE(numout,*) '                                    fb_t_asm       = ',fb_t_asm
+         WRITE(numout,*) '                                    fb_t_ofl       = ',fb_t_ofl
+         WRITE(numout,*) '                                    fb_p_rlx       = ',fb_p_rlx
+         WRITE(numout,*) '                                    fb_p_asm       = ',fb_p_asm
+         WRITE(numout,*) '                                    fb_p_ofl       = ',fb_p_ofl
+         WRITE(numout,*) '  Parameters for time evolution of bias '
+         WRITE(numout,*) '  Rlx   efolding time (mem)         eft_rlx,t_rlx_mem = ', eft_rlx, t_rlx_mem, 1. - log2 * rdt / (eft_rlx * rday)
+         WRITE(numout,*) '        uptdate factor              t_rlx_upd         = ',t_rlx_upd
+         WRITE(numout,*) '  Asm   efolding time (mem)         eft_asm,t_asm_mem = ', eft_asm, t_asm_mem, 1. - log2 * rdt / (eft_asm * rday)
+         WRITE(numout,*) '        uptdate factor              t_asm_upd         = ',t_asm_upd
+         WRITE(numout,*) '  Filenames and input structures'
+         WRITE(numout,*) '     bias_tot filename              cn_bias_to     = ',cn_bias_tot
+         WRITE(numout,*) '     bias_asm filename              cn_bias_asm    = ',cn_bias_asm
+         WRITE(numout,*) '     bias_asm time unit (secs)  bias_time_unit_asm = ',bias_time_unit_asm
+         WRITE(numout,*) '     structure Tem bias ofl         sn_tbias_ofl   = ',sn_tbias_ofl
+         WRITE(numout,*) '     structure Sal bias ofl         sn_sbias_ofl   = ',sn_sbias_ofl
+         
+         IF ( ( (.NOT. ln_tsd_tradmp) .OR. (.NOT. ln_tradmp) ) .AND. ln_bias_rlx ) &
+            &   CALL ctl_stop (' lk_dtatem, lk_dtasal and lk_tradmp need to be true with ln_bias_rlx' )
+
+         IF ( (.NOT. ln_itdecay) .AND. ln_incpc) &   
+            &   CALL ctl_stop (' if you set ln_incpc to .true. then you need to set ln_itdecay to .true. as well' )
+
+         IF ( (.NOT. ln_incpc) .AND. ln_incpc_only) &   
+            &   CALL ctl_stop (' if you set ln_incpc_only to .true. then you need to set ln_incpc to .true. as well' )
+         
+         WRITE(numout,*) '     time step is    = ',rdt,'you choose to write pcbias at nn_bias_itwrt  = ',nn_bias_itwrt,'and end of iau is rday/rdt=',rday/rdt 
+      ENDIF
+      IF( .NOT. ln_bias ) RETURN
+
+      IF( .NOT. lalloc ) THEN
+
+         ALLOCATE( tbias(jpi,jpj,jpk)  , &
+            &      sbias(jpi,jpj,jpk)  , &
+            &      tbias_p(jpi,jpj,jpk), &
+            &      sbias_p(jpi,jpj,jpk), &
+            &      tbias_i(jpi,jpj,jpk), &
+            &      sbias_i(jpi,jpj,jpk), &
+            &      rhd_pc(jpi,jpj,jpk) , &
+            &      gru_pc(jpi,jpj)     , &
+            &      grv_pc(jpi,jpj)       )
+
+         ALLOCATE( fbcoef(jpi,jpj), fbcoef_stscale(jpi,jpj) )
+         
+         IF( ln_bias_asm ) ALLOCATE(  tbias_asm(jpi,jpj,jpk),     &
+            &                         sbias_asm(jpi,jpj,jpk),     &
+                                      tbias_asm_out(jpi,jpj,jpk), &  
+                                      sbias_asm_out(jpi,jpj,jpk), &  
+                                      tbias_p_out(jpi,jpj,jpk),   & 			      
+                                      sbias_p_out(jpi,jpj,jpk)    )
+
+         IF( ln_bias_rlx ) ALLOCATE(  tbias_rlx(jpi,jpj,jpk),     &
+            &                         sbias_rlx(jpi,jpj,jpk),     &
+                                      tbias_rlx_out(jpi,jpj,jpk), &  
+                                      sbias_rlx_out(jpi,jpj,jpk)  )
+
+         IF( ln_incpc )    ALLOCATE(  tbias_asm_stscale(jpi,jpj,jpk), &
+            &                         sbias_asm_stscale(jpi,jpj,jpk), &
+                                      tbias_asm_stscale_out(jpi,jpj,jpk), &
+                                      sbias_asm_stscale_out(jpi,jpj,jpk), &
+                                      tbias_i_out(jpi,jpj,jpk),   &  
+                                      sbias_i_out(jpi,jpj,jpk)   )
+
+         lalloc = .TRUE.
+
+      ENDIF
+
+      IF( ln_bias_ofl ) THEN      ! set sf_tbias_ofl and sf_sbias_ofl strctrs
+         !
+         ! tbias
+         !
+         ALLOCATE( sf_tbias_ofl(1), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'bias_init: unable to allocate sf_tbias_ofl structure' )   ;    RETURN
+         ENDIF
+         ALLOCATE( sf_tbias_ofl(1)%fnow(jpi,jpj,jpk) )
+         ALLOCATE( sf_tbias_ofl(1)%fdta(jpi,jpj,jpk,2) )
+         
+         ! fill structure with values and control print
+         CALL fld_fill( sf_tbias_ofl, (/ sn_tbias_ofl /), cn_dir, 'bias_init', 'Offline T bias term ', 'nam_tbias_ofl' )
+         !
+         ! salinity bias
+         ! 
+         ALLOCATE( sf_sbias_ofl(1), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'bias_init: unable to allocate sf_sbias_ofl structure' )   ;   RETURN
+         ENDIF
+         ALLOCATE( sf_sbias_ofl(1)%fnow(jpi,jpj,jpk) )
+         ALLOCATE( sf_sbias_ofl(1)%fdta(jpi,jpj,jpk,2) )
+         
+         ! fill structure with values and control print
+         CALL fld_fill( sf_sbias_ofl, (/ sn_sbias_ofl /), cn_dir, 'bias_init', 'Offline S bias term ', 'nam_sbias_ofl' )
+         
+      ENDIF
+
+      ! Read total bias
+      IF ( ln_bias ) THEN
+         tbias(:,:,:)   = 0.0_wp
+         sbias(:,:,:)   = 0.0_wp
+         tbias_p(:,:,:) = 0.0_wp
+         sbias_p(:,:,:) = 0.0_wp
+         tbias_i(:,:,:) = 0.0_wp
+         sbias_i(:,:,:) = 0.0_wp
+         gru_pc(:,:)    = 0.0_wp
+         grv_pc(:,:)    = 0.0_wp
+         
+         IF ( ln_bias_rlx ) THEN
+            tbias_rlx(:,:,:) = 0.0_wp
+            sbias_rlx(:,:,:) = 0.0_wp
+         ENDIF
+
+         IF ( ln_bias_asm ) THEN   !now rlx and asm bias in same file
+            tbias_asm(:,:,:) = 0.0_wp
+            sbias_asm(:,:,:) = 0.0_wp
+            tbias_asm_out(:,:,:) = 0.0_wp
+            sbias_asm_out(:,:,:) = 0.0_wp
+         ENDIF
+
+         IF ( ln_incpc ) THEN   !incr pressure correction
+            tbias_asm_stscale(:,:,:) = 0.0_wp
+            sbias_asm_stscale(:,:,:) = 0.0_wp
+            tbias_asm_stscale_out(:,:,:) = 0.0_wp
+            sbias_asm_stscale_out(:,:,:) = 0.0_wp
+         ENDIF
+
+
+         numbias_tot    = 0
+         ! Get bias from file and prevent fail if the file does not exist
+         IF(lwp) WRITE(numout,*) 'Opening ',TRIM( cn_bias_tot ) 
+         CALL iom_open( cn_bias_tot, numbias_tot, ldstop=.FALSE. )
+         
+         IF ( numbias_tot > 0 ) THEN      
+            ! Could check validity time of bias fields here...
+            ! Get the T and S bias data
+            IF(lwp) WRITE(numout,*) 'Reading bias fields from tot...'
+
+            !Search for bias from relaxation term if needed. Use same file
+            IF ( ln_bias_rlx ) THEN
+               IF(lwp) WRITE(numout,*) 'Reading bias fields for bias rlx from file ',cn_bias_tot
+               IF( iom_varid( numbias_tot, 'tbias_rlx' ) > 0 ) THEN
+                  ! Get the T and S bias data
+                  CALL iom_get( numbias_tot, jpdom_autoglo, 'tbias_rlx', tbias_rlx )
+                  CALL iom_get( numbias_tot, jpdom_autoglo, 'sbias_rlx', sbias_rlx )
+               ELSE
+                  CALL ctl_stop( 'Bias relaxation variables not found in ',cn_bias_tot )
+               ENDIF
+            ENDIF
+
+
+            !Search for bias from assim term if needed. Use same file
+            IF ( ln_bias_asm .and. .not.ln_bsyncro ) THEN
+               IF(lwp) WRITE(numout,*) 'Reading a-syncro bias fields for bias asm from file ',cn_bias_tot
+               IF( iom_varid( numbias_tot, 'tbias_asm' ) > 0 ) THEN
+                  ! Get the T and S bias data
+                  CALL iom_get( numbias_tot, jpdom_autoglo, 'tbias_asm', tbias_asm )
+                  CALL iom_get( numbias_tot, jpdom_autoglo, 'sbias_asm', sbias_asm )
+               ELSE
+                  CALL ctl_stop( 'Bias assim variables not found in ',cn_bias_tot )
+               ENDIF
+            ENDIF
+
+            IF ( ln_incpc .and. .not.ln_bsyncro ) THEN
+               IF(lwp) WRITE(numout,*) 'Reading short time scale bias correction fields for bias asm from file ',cn_bias_tot
+               IF( iom_varid( numbias_tot, 'tbias_asm_stscale' ) > 0 ) THEN
+                  ! Get the T and S bias data
+                  CALL iom_get( numbias_tot, jpdom_autoglo, 'tbias_asm_stscale', tbias_asm_stscale )
+                  CALL iom_get( numbias_tot, jpdom_autoglo, 'sbias_asm_stscale', sbias_asm_stscale )
+               ELSE
+                  CALL ctl_stop( 'Short time scale bias assim variables not found in ',cn_bias_tot )
+               ENDIF
+            ENDIF  
+
+
+
+            ! Close the file
+            CALL iom_close(numbias_tot)
+
+         ELSE 
+            IF(lwp) WRITE(numout,*) 'No bias file found so T and S bias fields are set to zero'
+         ENDIF
+
+      ENDIF
+
+     ! for the time being, the bias_asm is read in the same file as
+     ! bias_rlx
+     ! Implications: bias_asm is estimated/evolved in time in the second outer 
+     !               loop only, when the assimilation increments are ready.
+     !               bias_asm is kept cte during the first outer loop.
+     !              => Assyncronous bias correction.
+     ! Alternative: Syncronous bias correction:
+     !              bias_asm estimated/evolved in the first outer loop
+     !              with the asm incrments of the previous cycle.
+     !              bias_asm kept cte during the second outer loop.
+     !              Implication: bias_asm should be estimated really in the
+     !              inner loop.
+      IF ( ln_bsyncro ) THEN
+      ! Read bias from assimilation from a separate file
+      IF ( ln_bias_asm ) THEN
+         tbias_asm(:,:,:) = 0.0_wp
+         sbias_asm(:,:,:) = 0.0_wp
+         numbias_asm      = 0
+         ! Get bias from file and prevent fail if the file does not exist
+         IF(lwp) WRITE(numout,*) 'Opening file for syncro assim bias ',TRIM( cn_bias_asm ) 
+         CALL iom_open( cn_bias_asm, numbias_asm, ldstop=.FALSE. )
+         
+         IF ( numbias_asm > 0 ) THEN      
+            ! Could check validity time of bias fields here...
+            
+            ! Get the T and S bias data
+            IF(lwp) WRITE(numout,*) 'Reading syncro bias fields from asm from file ',cn_bias_asm
+            CALL iom_get( numbias_asm, jpdom_autoglo, 'tbias_asm', tbias_asm )
+            CALL iom_get( numbias_asm, jpdom_autoglo, 'sbias_asm', sbias_asm )
+           
+!  this is only applicable if tbias_asm were to be calculated in the inner loop
+            tbias_asm(:,:,:) = tbias_asm(:,:,:) * rdt / bias_time_unit_asm
+            sbias_asm(:,:,:) = sbias_asm(:,:,:) * rdt / bias_time_unit_asm
+            
+            ! Close the file
+            CALL iom_close(numbias_asm)
+            
+         ELSE 
+            IF(lwp) WRITE(numout,*) 'No bias file found from asm so T and S bias fields are set to zero'
+         ENDIF
+         
+      ENDIF
+
+      ENDIF
+
+      !latitudinal dependence of partition coeficients. Adhoc
+      IF ( nn_lat_ramp == 1 ) THEN
+         ! Use the inertial ramp.
+         lenscl_bias = ( rn_maxlat_bias - rn_minlat_bias )*2._wp
+         WHERE ( abs( gphit(:,:) ) <= rn_minlat_bias )         
+            fbcoef(:,:) = 0._wp          
+         ELSEWHERE ( abs( gphit(:,:) ) >= rn_maxlat_bias )         
+            fbcoef(:,:) = 1._wp                    
+         ELSEWHERE        
+            fbcoef(:,:) = 1._wp - exp( -( abs( gphit(:,:) ) - rn_minlat_bias ) &
+                           * ( abs( gphit(:,:) ) - rn_minlat_bias ) / lenscl_bias )                         
+         ENDWHERE 
+      ELSEIF ( nn_lat_ramp == 2 ) THEN   
+         ! Use a linear ramp consist with the geostrophic velocity balance ramp in NEMOVAR
+     
+         WHERE ( abs( gphit(:,:) ) <= rn_minlat_bias )
+            fbcoef(:,:) = 0._wp
+         ELSEWHERE ( abs( gphit(:,:) ) >= rn_maxlat_bias ) 
+            fbcoef(:,:) = 1._wp
+         ELSEWHERE
+            fbcoef(:,:) = 1._wp - ((rn_maxlat_bias - abs( gphit(:,:)))/(rn_maxlat_bias - rn_minlat_bias))
+         ENDWHERE
+      ELSE
+         fbcoef(:,:) = 0.0_wp
+         fctamp      = 0.0_wp
+         fbcoef_stscale(:,:) = 0.0_wp
+      ENDIF
+
+
+      IF ( ln_incpc) THEN
+         minlat_bias = 3.0_wp
+         maxlat_bias = 8.0_wp  
+         WHERE ( abs( gphit(:,:) ) <= minlat_bias )
+            fbcoef_stscale(:,:)=0._wp
+         ELSEWHERE ( abs( gphit(:,:) ) >= maxlat_bias ) 
+            fbcoef_stscale(:,:)=1._wp
+         ELSEWHERE
+            fbcoef_stscale(:,:)=1._wp - ((maxlat_bias - abs( gphit(:,:)))/(maxlat_bias-minlat_bias))
+         ENDWHERE   
+      ENDIF 
+
+
+   END SUBROUTINE bias_init
+
+   SUBROUTINE tra_bias ( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE tra_bias  ***
+      !!
+      !! ** Purpose : Update bias field every time step
+      !!
+      !! ** Method  : add contributions to bias from 3 terms
+      !!
+      !! ** Action  : Bias from assimilation (read in bias_init) 
+      !!              Bias from relaxation term is estimated according to
+      !!              the prescribed time evolution of the bias
+      !!              Bias from ofl term is read from external file
+      !!              The difference contributions are added and the partition
+      !!              into direct bias in T/S and pressure perfomed.
+      !!
+      !! History :  09-03  (M. Balmaseda) 
+      !!----------------------------------------------------------------------
+      !! called every timestep after dta_sst if ln_bias true.
+
+      IMPLICIT NONE
+
+      !! * Arguments
+      INTEGER, INTENT(IN) ::   kt             ! ocean time-step index
+      !! * Local variables
+      INTEGER             ::   ji,jj,jk, it   ! local loop index
+      REAL(wp)            ::   tsclf          ! time saling factor 
+      REAL(wp)            ::   fb_t_asm_max, fb_t_rlx_max, fb_t_ofl_max
+      REAL(wp)            ::   ztfrac, ztsday
+      REAL(wp)            ::   zfrac, zfrac1 ! temporal weights for inst pcbias (names could be changed)
+      REAL(wp)            ::   zdecay        ! used in inst pcorr
+      REAL(wp), DIMENSION(jpi,jpj) :: zcof1, zcof2
+
+      IF ( .NOT. ln_bias ) RETURN
+      fb_t_rlx_max   = MIN(fb_t_rlx*fctamp,1.0_wp)
+      fb_t_asm_max   = MIN(fb_t_asm*fctamp,1.0_wp)
+      fb_t_ofl_max   = MIN(fb_t_ofl*fctamp,1.0_wp)
+
+      tbias(:,:,:)   = 0.0_wp
+      sbias(:,:,:)   = 0.0_wp
+      tbias_p(:,:,:) = 0.0_wp
+      sbias_p(:,:,:) = 0.0_wp
+      tbias_i(:,:,:) = 0.0_wp
+      sbias_i(:,:,:) = 0.0_wp
+
+      IF ( ln_bias_asm ) THEN
+      
+         tsclf = 1
+         IF ( .NOT.ln_bsyncro ) tsclf = rdt / bias_time_unit_asm 
+         zcof1(:,:) = tsclf * ( ( 1.0_wp - fbcoef(:,:) ) * fb_t_asm + &
+            &                              fbcoef(:,:)   * fb_t_asm_max )
+         zcof2(:,:) = ( 1.0_wp - fbcoef(:,:) ) * fb_p_asm
+
+         IF ( ln_itdecay ) THEN   !decay the pressure correction at each time step
+	 
+	    ztsday  = rday / REAL(rdt,wp)
+
+            zdecay = (1-ztscale)**(1/REAL(ztsday,wp)) ! used in ipc
+            zfrac1 = zdecay**REAL(kt,wp) ! used in ipc
+            IF ( zfrac1 <= 0.0 ) zfrac1 = 0.0_wp
+
+            IF( ln_asmiau .and. ln_trainc ) THEN  ! nudge in increments and decay historical contribution
+               
+               IF ( kt <= nitiaufin ) THEN  ! During IAU calculate the fraction of increments to apply at each time step
+
+                  ztfrac = REAL(kt,wp) / REAL(nitiaufin,wp)  ! nudging factor during the IAU
+	       
+                  IF (lwp) THEN
+                     WRITE(numout,*) 'tra_bias : bias weights'
+                     WRITE(numout,*) '~~~~~~~~~~~~'
+                     WRITE(numout,* ) "proportion of  increment applied in pcbias ",ztfrac
+                     WRITE(numout,* ) "proportion of  historical pcbias applied ",t_asm_mem**(REAL(kt,wp)/ztsday)
+                  ENDIF
+
+                  DO jk = 1, jpkm1  
+                     tbias(:,:,jk) = tbias(:,:,jk) +                            &
+                     &                ( t_asm_mem**(REAL(kt,wp)/ztsday) * tbias_asm(:,:,jk)  +                    &
+                     &                ztfrac * t_asm_upd * t_bkginc(:,:,jk) * tmask(:,:,jk) ) * zcof1(:,:)
+                     sbias(:,:,jk) = sbias(:,:,jk) +                            &
+                     &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * sbias_asm(:,:,jk)  +                     &
+                     &               ztfrac * t_asm_upd * s_bkginc(:,:,jk) * tmask(:,:,jk) ) * zcof1(:,:)
+
+                     tbias_p(:,:,jk) = tbias_p(:,:,jk) +                        &
+                     &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * tbias_asm(:,:,jk)  +                     &
+                     &               ztfrac * t_asm_upd * t_bkginc(:,:,jk) * tmask(:,:,jk) ) * zcof2(:,:)
+                     sbias_p(:,:,jk) = sbias_p(:,:,jk) +                        &  
+                     &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * sbias_asm(:,:,jk)  +                     &
+                     &               ztfrac * t_asm_upd * s_bkginc(:,:,jk) * tmask(:,:,jk) ) * zcof2(:,:)
+                  ENDDO
+
+                  IF (ln_incpc) THEN
+
+                     IF (lwp) THEN
+                       WRITE(numout,*) 'tra_bias : bias weights'
+                       WRITE(numout,*) '~~~~~~~~~~~~'
+                       WRITE(numout,* ) "IPC - proportion of  increment applied in pcbias ",ztfrac
+                       WRITE(numout,* ) "IPC - proportion of  historical pcbias applied ",zfrac1
+                     ENDIF
+
+                     DO jk = 1, jpkm1
+
+                        tbias_i(:,:,jk) =  ( t_bkginc(:,:,jk) * tmask(:,:,jk)* zwgt * ztfrac * (1.0 - fbcoef_stscale(:,:)) )         &
+                        &                + ( tbias_asm_stscale(:,:,jk) * zfrac1 * (1.0 - fbcoef_stscale(:,:)) )
+                        sbias_i(:,:,jk) =  ( s_bkginc(:,:,jk) * tmask(:,:,jk)* zwgt * ztfrac * (1.0 - fbcoef_stscale(:,:)) )         &
+                        &                + ( sbias_asm_stscale(:,:,jk) * zfrac1 * (1.0 - fbcoef_stscale(:,:)) )
+
+                     ENDDO
+
+                  ENDIF
+
+                  IF ( .not.ln_bsyncro ) THEN 
+
+                     IF ( kt == nn_bias_itwrt ) THEN
+
+                        DO jk = 1, jpkm1
+                           tbias_asm_out(:,:,jk) =  t_asm_mem**(REAL(kt,wp)/ztsday) * tbias_asm(:,:,jk)  +       &
+                           &                     ztfrac * t_asm_upd * t_bkginc(:,:,jk) * tmask(:,:,jk)
+                           sbias_asm_out(:,:,jk) =  t_asm_mem**(REAL(kt,wp)/ztsday) * sbias_asm(:,:,jk)  +       &
+                           &                     ztfrac * t_asm_upd * s_bkginc(:,:,jk) * tmask(:,:,jk)
+                         END DO
+
+                        IF ( ln_incpc) THEN
+                           DO jk = 1, jpkm1
+                              tbias_asm_stscale_out(:,:,jk) = ( t_bkginc(:,:,jk) * tmask(:,:,jk) *  zwgt * ztfrac ) + ( tbias_asm_stscale(:,:,jk) * zfrac1 )
+                              sbias_asm_stscale_out(:,:,jk) = ( s_bkginc(:,:,jk) * tmask(:,:,jk) *  zwgt * ztfrac ) + ( sbias_asm_stscale(:,:,jk) * zfrac1 )
+                           ENDDO
+                        ENDIF
+
+                     ENDIF
+
+                  ENDIF
+
+                  ! update the historical component with the increments at the end of the IAU
+                  IF ( kt == nitiaufin ) THEN
+                     DO jk = 1, jpkm1
+                        tbias_asm(:,:,jk) =  t_asm_mem**(REAL(kt,wp)/ztsday) * tbias_asm(:,:,jk)  +       &
+                        &                     ztfrac * t_asm_upd * t_bkginc(:,:,jk) * tmask(:,:,jk)
+                        sbias_asm(:,:,jk) =  t_asm_mem**(REAL(kt,wp)/ztsday) * sbias_asm(:,:,jk)  +       &
+                        &                     ztfrac * t_asm_upd * s_bkginc(:,:,jk) * tmask(:,:,jk)
+                     END DO
+
+                     IF (ln_incpc) THEN
+                        DO jk = 1, jpkm1
+                           tbias_asm_stscale(:,:,jk) = ( t_bkginc(:,:,jk) * tmask(:,:,jk) * zwgt * ztfrac ) + ( tbias_asm_stscale(:,:,jk) * zfrac1 )
+                           sbias_asm_stscale(:,:,jk) = ( s_bkginc(:,:,jk) * tmask(:,:,jk) * zwgt * ztfrac ) + ( sbias_asm_stscale(:,:,jk) * zfrac1 )
+                        ENDDO
+                     ENDIF
+     
+                  ENDIF
+               
+               ELSE ! decay pressure correction from combined historical component and increments after IAU
+
+                  ztfrac=t_asm_mem**(REAL(kt-nitiaufin,wp)/REAL(nitiaufin,wp))  ! decay from end of IAU
+                  
+                  DO jk = 1, jpkm1
+                     tbias(:,:,jk) = tbias(:,:,jk) +                            &
+                     &                ( ztfrac * tbias_asm(:,:,jk) ) * zcof1(:,:)
+                     sbias(:,:,jk) = sbias(:,:,jk) +                            &
+                     &               (  ztfrac * sbias_asm(:,:,jk) ) * zcof1(:,:)
+                     tbias_p(:,:,jk) = tbias_p(:,:,jk) +                        &
+                     &               (  ztfrac * tbias_asm(:,:,jk) ) * zcof2(:,:)
+                     sbias_p(:,:,jk) = sbias_p(:,:,jk) +                        &  
+                     &               ( ztfrac * sbias_asm(:,:,jk) ) * zcof2(:,:)
+                  ENDDO
+
+                 IF (ln_incpc) THEN
+
+                   zfrac  = zdecay**REAL(kt-nitiaufin,wp) 
+                   IF ( zfrac <= 0.0 ) zfrac = 0.0_wp
+   
+                   DO jk = 1, jpkm1
+                      tbias_i(:,:,jk) =  tbias_asm_stscale(:,:,jk) * zfrac * (1.0 - fbcoef_stscale(:,:))
+                      sbias_i(:,:,jk) =  sbias_asm_stscale(:,:,jk) * zfrac * (1.0 - fbcoef_stscale(:,:))
+                   ENDDO
+
+                   IF (lwp) THEN
+                      WRITE(numout,*) 'tra_bias : bias weights'
+                      WRITE(numout,*) '~~~~~~~~~~~~'
+                      WRITE(numout,* ) "IPC - proportion of increments + historical pcbias applied ",zfrac
+                   ENDIF
+
+                 ENDIF
+
+                 IF (lwp) THEN
+                    WRITE(numout,*) 'tra_bias : bias weights'
+                    WRITE(numout,*) '~~~~~~~~~~~~'
+                    WRITE(numout,* ) "proportion of increments + historical pcbias applied ",ztfrac
+                 ENDIF
+
+                 IF ( ln_trainc .and. .not.ln_bsyncro ) THEN 
+                    IF ( kt == nn_bias_itwrt ) THEN
+                       DO jk = 1, jpkm1
+                          tbias_asm_out(:,:,jk) =  ztfrac * tbias_asm(:,:,jk) 
+                          sbias_asm_out(:,:,jk) =  ztfrac * sbias_asm(:,:,jk) 
+                       END DO
+
+                       IF ( ln_incpc ) THEN
+                          IF (lwp) WRITE(numout,*) 'after end of IAU - IPC - saving s/tbias_asm_stscale'
+                             DO jk = 1, jpkm1
+                                tbias_asm_stscale_out(:,:,jk) =  tbias_asm_stscale(:,:,jk) * zfrac
+                                sbias_asm_stscale_out(:,:,jk) =  sbias_asm_stscale(:,:,jk) * zfrac
+                             ENDDO
+                          ENDIF
+                       ENDIF
+                    ENDIF
+                 ENDIF
+
+            ELSE ! no assimilation increments, simply decay pressure correction (e.g for forecasts)
+                 ! this occurs at obsoper step as well ( ln_asmiau is false ) 
+
+               DO jk = 1, jpkm1
+                  tbias(:,:,jk) = tbias(:,:,jk) +                                                         &
+                  &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * tbias_asm(:,:,jk) ) * zcof1(:,:)
+                  sbias(:,:,jk) = sbias(:,:,jk) +                                                         &
+                  &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * sbias_asm(:,:,jk) ) * zcof1(:,:)
+                  tbias_p(:,:,jk) = tbias_p(:,:,jk) +                                                     &
+                  &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * tbias_asm(:,:,jk) ) * zcof2(:,:)
+                  sbias_p(:,:,jk) = sbias_p(:,:,jk) +                                                     &  
+                  &               ( t_asm_mem**(REAL(kt,wp)/ztsday) * sbias_asm(:,:,jk) ) * zcof2(:,:)
+               ENDDO
+
+               IF (lwp) THEN
+                  WRITE(numout,*) 'tra_bias : bias weights'
+                  WRITE(numout,*) '~~~~~~~~~~~~'
+                  WRITE(numout,* ) "proportion of historical pcbias applied ",t_asm_mem**(REAL(kt,wp)/ztsday)
+               ENDIF
+
+               IF (ln_incpc) THEN
+                   IF (lwp) WRITE(numout,*) 'obsoper or forecast mode - IPC - computing tbias_i and sbias_i'
+                   DO jk = 1, jpkm1
+                      tbias_i(:,:,jk) = tbias_i(:,:,jk) + ( tbias_asm_stscale(:,:,jk) * zfrac1 * (1.0 - fbcoef_stscale(:,:)) )
+                      sbias_i(:,:,jk) = sbias_i(:,:,jk) + ( sbias_asm_stscale(:,:,jk) * zfrac1 * (1.0 - fbcoef_stscale(:,:)) )
+                   ENDDO
+                   tbias_i(:,:,:) =tbias_i(:,:,:)*tmask(:,:,:)
+                   sbias_i(:,:,:) =sbias_i(:,:,:)*tmask(:,:,:)
+               ENDIF
+            ENDIF
+ 
+         ELSE ! maintain a constant pressure correction  
+
+            DO jk = 1, jpkm1
+               tbias(:,:,jk) = tbias(:,:,jk) + tbias_asm(:,:,jk) * zcof1(:,:)
+               sbias(:,:,jk) = sbias(:,:,jk) + sbias_asm(:,:,jk) * zcof1(:,:)
+               tbias_p(:,:,jk) = tbias_p(:,:,jk) + tbias_asm(:,:,jk) * zcof2(:,:)
+               sbias_p(:,:,jk) = sbias_p(:,:,jk) + sbias_asm(:,:,jk) * zcof2(:,:)
+            END DO     
+
+            IF( ln_asmiau .and. ln_trainc .and. .not.ln_bsyncro ) THEN   
+            ! if last outer loop (ln_asmiau=true and ln_trainc=true). t/sbias_asm
+            ! is updated, only once (end of run) taking into account units.
+               IF ( kt == nn_bias_itwrt ) THEN
+                 IF(lwp) WRITE(numout,*)' estimating asm bias at timestep: ',kt
+                 DO jk = 1, jpkm1
+                   tbias_asm_out(:,:,jk) = t_asm_mem * tbias_asm(:,:,jk)  +             &
+                   &                      t_asm_upd * t_bkginc(:,:,jk) * tmask(:,:,jk)
+                   sbias_asm_out(:,:,jk) = t_asm_mem * sbias_asm(:,:,jk) +             &
+                   &                      t_asm_upd * s_bkginc(:,:,jk) * tmask(:,:,jk)               
+                 END DO
+               ENDIF
+             ENDIF
+  
+         ENDIF
+
+      ENDIF
+
+
+#if   defined key_tradmp 
+      ! Time evolution of bias from relaxation
+      IF ( ln_bias_rlx ) THEN
+         tbias_rlx(:,:,:) = t_rlx_mem * tbias_rlx(:,:,:) + &
+            &               t_rlx_upd * ttrdmp(:,:,:) * rdt
+         sbias_rlx(:,:,:) = t_rlx_mem * sbias_rlx(:,:,:) + &
+            &               t_rlx_upd * strdmp(:,:,:) * rdt
+         zcof1(:,:) = ( 1.0_wp - fbcoef(:,:) ) * fb_t_rlx +      &
+            &                    fbcoef(:,:)   * fb_t_rlx_max
+         zcof2(:,:) = ( 1.0_wp - fbcoef(:,:) ) * fb_p_rlx
+         DO jk = 1, jpkm1
+            tbias(:,:,jk)   = tbias(:,:,jk) + tbias_rlx(:,:,jk) * zcof1(:,:)
+            sbias(:,:,jk)   = sbias(:,:,jk) + sbias_rlx(:,:,jk) * zcof1(:,:)
+            tbias_p(:,:,jk) = tbias_p(:,:,jk) + tbias_rlx(:,:,jk) * zcof2(:,:)
+            sbias_p(:,:,jk) = sbias_p(:,:,jk) + sbias_rlx(:,:,jk) * zcof2(:,:)
+         ENDDO
+         IF ( kt == nn_bias_itwrt ) THEN
+            tbias_rlx_out(:,:,:) = tbias_rlx(:,:,:)
+            sbias_rlx_out(:,:,:) = sbias_rlx(:,:,:)
+         ENDIF
+      ENDIF
+#endif
+      ! ofline bias
+      IF ( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*) ' tra_bias: ln_bias_ofl = ',ln_bias_ofl
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~'
+      ENDIF
+      IF ( ln_bias_ofl ) THEN
+         IF(lwp) WRITE(numout,*) 'reading offline bias'
+         CALL fld_read( kt, 1, sf_tbias_ofl ) 
+         CALL fld_read( kt, 1, sf_sbias_ofl ) 
+
+         zcof1(:,:) = ( 1.0_wp - fbcoef(:,:) ) * fb_t_ofl +           &
+            &                    fbcoef(:,:)   * fb_t_ofl_max
+         zcof2(:,:) = ( 1.0_wp - fbcoef(:,:) ) * fb_p_ofl
+         DO jk = 1, jpkm1
+            tbias(:,:,jk)   = tbias(:,:,jk) + sf_tbias_ofl(1)%fnow(:,:,jk) * zcof1(:,:)
+            sbias(:,:,jk)   = sbias(:,:,jk) + sf_sbias_ofl(1)%fnow(:,:,jk) * zcof1(:,:)
+            tbias_p(:,:,jk) = tbias_p(:,:,jk) + sf_tbias_ofl(1)%fnow(:,:,jk) * zcof2(:,:)
+            sbias_p(:,:,jk) = sbias_p(:,:,jk) + sf_sbias_ofl(1)%fnow(:,:,jk) * zcof2(:,:)
+         ENDDO
+      ENDIF
+
+
+      !apply bias on tracers if needed      
+      IF ( ln_bias_ts_app ) THEN
+         
+         ! Add the bias directely to T/s
+         tsa(:,:,:,jp_tem) = tsa(:,:,:,jp_tem) + tmask(:,:,:) * tbias(:,:,:) / rdt
+         tsa(:,:,:,jp_sal) = tsa(:,:,:,jp_sal) + tmask(:,:,:) * sbias(:,:,:) / rdt
+
+         ! lateral boundary conditions (is this needed?)
+         CALL lbc_lnk( tsa(:,:,:,jp_tem), 'T', 1.0_wp )
+         CALL lbc_lnk( tsa(:,:,:,jp_sal), 'T', 1.0_wp )   
+
+      ENDIF
+
+      IF ( kt == nn_bias_itwrt ) THEN
+            tbias_p_out(:,:,:)   = tbias_p(:,:,:)
+            sbias_p_out(:,:,:)   = sbias_p(:,:,:)
+            IF (ln_incpc) THEN
+               tbias_i_out(:,:,:)   = tbias_i(:,:,:)
+               sbias_i_out(:,:,:)   = sbias_i(:,:,:)            
+            ENDIF
+      ENDIF
+
+   END SUBROUTINE tra_bias
+
+   SUBROUTINE dyn_bias( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dyn_bias  ***
+      !!
+      !! ** Purpose :   Computes rhd_pc, gru/v_pc bias corrected
+      !!                for hydrostatic pressure gradient
+      !!                depending on time step (semi-implicit/centered)
+      !!                If partial steps computes bottom pressure gradient.
+      !!                These correction terms will affect only the dynamical
+      !!                component (pressure gradient calculation), but not
+      !!                the isopycnal calculation for the lateral mixing.
+      !! 
+      !! ** Method  :   At this stage of the computation, ta and sa are the 
+      !!                after temperature and salinity. If semi-implicit, these
+      !!                are used to compute rho and bottom pressure gradient.
+      !!                If centered, tb,sb are used instead.
+      !!                If bias key is activated, the temperature,salinity are
+      !!                bias corrected in the calculation of the density fields
+      !!                used in the pressure gradient calculation.
+      !!
+      !!
+      !! ** Action  : - rhd_pc ready. rhop will be overwriten later
+      !!              - if ln_zps, bottom density gradients gru/v_pc ready.
+      !!----------------------------------------------------------------------
+      !!
+      !! * Arguments
+      INTEGER, INTENT(IN) ::   kt    ! ocean time-step index
+      !! * Local variables
+      REAL(wp) :: tsw(jpi,jpj,jpk,jpts)
+      !!
+      !!----------------------------------------------------------------------
+      !
+      ! gtu,gsu,gtv,gsv rhop will be overwritten later in step.
+      ! 
+      IF( ln_dynhpg_imp  ) THEN                             ! semi-implicit hpg
+         tsw(:,:,:,jp_tem) = tsa(:,:,:,jp_tem) - tbias_p(:,:,:)
+         tsw(:,:,:,jp_sal) = tsa(:,:,:,jp_sal) - sbias_p(:,:,:)
+         IF ( ln_incpc ) THEN
+            tsw(:,:,:,jp_tem) = tsa(:,:,:,jp_tem) - tbias_p(:,:,:) - tbias_i(:,:,:)
+            tsw(:,:,:,jp_sal) = tsa(:,:,:,jp_sal) - sbias_p(:,:,:) - sbias_i(:,:,:)
+            IF ( ln_incpc_only ) THEN
+               IF(lwp) WRITE(numout,*) 'ln_incpc_only =', ln_incpc_only, 'tsw updated with IPC only and ln_dynhpg_imp = ',ln_dynhpg_imp
+               tsw(:,:,:,jp_tem) = tsa(:,:,:,jp_tem) - tbias_i(:,:,:)
+               tsw(:,:,:,jp_sal) = tsa(:,:,:,jp_sal) - sbias_i(:,:,:)
+            ENDIF
+         ENDIF
+      ELSE
+         tsw(:,:,:,jp_tem) = tsb(:,:,:,jp_tem) - tbias_p(:,:,:)
+         tsw(:,:,:,jp_sal) = tsb(:,:,:,jp_sal) - sbias_p(:,:,:)
+         IF ( ln_incpc ) THEN
+            tsw(:,:,:,jp_tem) = tsb(:,:,:,jp_tem) - tbias_p(:,:,:) - tbias_i(:,:,:)
+            tsw(:,:,:,jp_sal) = tsb(:,:,:,jp_sal) - sbias_p(:,:,:) - sbias_i(:,:,:)
+            IF ( ln_incpc_only ) THEN
+               IF(lwp) WRITE(numout,*) 'ln_incpc_only =', ln_incpc_only, 'tsw updated with IPC only and ln_dynhpg_imp = ',ln_dynhpg_imp
+               tsw(:,:,:,jp_tem) = tsb(:,:,:,jp_tem) - tbias_i(:,:,:)
+               tsw(:,:,:,jp_sal) = tsb(:,:,:,jp_sal) - sbias_i(:,:,:)
+            ENDIF
+         ENDIF
+      ENDIF
+
+      IF(lwp) WRITE(numout,*) 'dyn_bias( kt ) calculating rhd_pc, kt =', kt
+      CALL eos( tsw, rhd_pc, rhop, fsdept_n(:,:,:) )
+      
+      CALL lbc_lnk( rhd_pc, 'T', 1.0_wp )
+
+
+      ! Partial steps: now horizontal gradient of t,s,rd 
+      ! at the bottom ocean level
+
+      IF( ln_zps    )  THEN
+         CALL zps_hde( kt, jpts, tsw, gtsu, gtsv,  &
+            &          rhd_pc, gru_pc , grv_pc  )
+      ENDIF
+
+   END SUBROUTINE dyn_bias
+   
+   SUBROUTINE bias_opn( kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE bias_opn  ***
+      !!                     
+      !! ** Purpose :  open bias restart file following the same logic as the
+      !!               standard restarts.
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN) ::   kt     ! ocean time-step
+      !! * Local variables
+      CHARACTER(LEN=20)   ::   clbkt    ! ocean time-step deine as a character
+      CHARACTER(LEN=50)   ::   clbias_tot   ! total bias restart file name
+      !!----------------------------------------------------------------------
+      !
+      IF( lrst_oce .AND. .NOT.lrst_bias ) THEN       ! create bias file
+         IF( nitend > 999999999 ) THEN   ;   WRITE(clbkt, *       ) nitend
+         ELSE                            ;   WRITE(clbkt, '(i8.8)') nitend
+         ENDIF
+         clbias_tot = TRIM(cexper)//"_"//TRIM(ADJUSTL(clbkt))//"_"//TRIM(cn_bias_tot)
+         IF(lwp) THEN
+            WRITE(numout,*)
+            SELECT CASE ( jprstlib )
+            CASE ( jprstdimg )   ;   WRITE(numout,*) '             open tot bias restart binary file: '//clbias_tot
+            CASE DEFAULT         ;   WRITE(numout,*) '             open tot bias restart NetCDF file: '//clbias_tot
+            END SELECT
+         ENDIF
+         CALL iom_open( clbias_tot, numbias_tot , ldwrt = .TRUE., kiolib = jprstlib )
+         lrst_bias=.TRUE.
+
+      ENDIF
+      !
+   END SUBROUTINE bias_opn
+
+   SUBROUTINE bias_wrt( kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE bias_wrt  ***
+      !!                     
+      !! ** Purpose :   Write bias restart fields in the format corresponding to jprstlib
+      !!
+      !! ** Method  :   Write in numbias_tot when kt == nitend in output
+      !!                file, save fields which are necessary for restart.
+      !!
+      !! Changed the timestep for writing to nitend rather than nitrst as this causes a
+      !! problem if the nstock list is used to determine the restart output times and
+      !! means that the bias is not output at all. M. Martin. 08/2011.
+      !! Need to check with Magdalena that this is ok for ECMWF.
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN) ::   kt   ! ocean time-step
+      !!----------------------------------------------------------------------
+      !                                                                     ! the begining of the run [s]
+
+      IF ( ln_bias_rlx ) THEN
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'tbias_rlx' , tbias_rlx_out )   
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'sbias_rlx' , sbias_rlx_out )   
+      ENDIF
+      
+      IF ( ln_bias_asm ) THEN
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'tbias_asm' , tbias_asm_out )   
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'sbias_asm' , sbias_asm_out )   
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'tbias_p'   , tbias_p_out )
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'sbias_p'   , sbias_p_out )         
+      ENDIF
+
+      IF ( ln_incpc ) THEN
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'tbias_asm_stscale' , tbias_asm_stscale_out )   
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'sbias_asm_stscale' , sbias_asm_stscale_out ) 
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'tbias_i'   , tbias_i_out )
+         CALL iom_rstput( nn_bias_itwrt, nn_bias_itwrt, numbias_tot, 'sbias_i'   , sbias_i_out )   
+      ENDIF
+      
+      IF( kt == nitend ) THEN
+         CALL iom_close( numbias_tot )     ! close the restart file (only at last time step)
+         lrst_bias = .FALSE.
+      ENDIF
+      !
+   END SUBROUTINE bias_wrt
+
+END MODULE bias
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/biaspar.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/biaspar.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ASM/biaspar.F90	(revision 9987)
@@ -0,0 +1,42 @@
+MODULE biaspar
+   !! Variables relevant to bias module
+   !!======================================================================
+   !!                 *** Module biaspar ***
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY: &
+      & wp
+   USE par_oce, ONLY: &
+      & jpi, &
+      & jpj, &
+      & jpk
+
+   IMPLICIT NONE
+   PUBLIC
+
+   !! * Shared module variables
+   LOGICAL, PUBLIC :: ln_bias        = .FALSE. !: estimate (apply) bias arrays 
+   LOGICAL, PUBLIC :: ln_bias_asm    = .FALSE. !: estimate bias from assim incr
+   LOGICAL, PUBLIC :: ln_bias_rlx    = .FALSE. !: estimate bias from relaxation 
+   LOGICAL, PUBLIC :: ln_bias_ofl    = .FALSE. !: bias estimated offline
+   LOGICAL, PUBLIC :: ln_bias_ts_app = .FALSE. !: estimate (apply) bias arrays 
+   LOGICAL, PUBLIC :: ln_bias_pc_app = .FALSE. !: estimate bias from assim incr
+   LOGICAL, PUBLIC :: lrst_bias      = .FALSE. !: estimate bias from assim incr
+
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE :: &
+      & tbias, &       !: Temperature bias field for T correction
+      & tbias_p, &     !:  "           "    "    "   P correction
+      & tbias_i, &     !:  "           "    "    "   incremental P correction
+      & sbias, &       !: Salinity bias field    for S correction
+      & sbias_p, &     !:  "           "    "    "   P correction
+      & sbias_i, &     !:  "           "    "    "   incremental P correction
+      & rhd_pc         !: Press corrtd density from online to use in dyn_hpg
+
+
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE :: &
+      & gru_pc, &      !: Press corrtd bottom pressure gradient (x-dir)
+      & grv_pc         !: Press corrtd bottom pressure gradient (y-dir)
+
+
+
+END MODULE biaspar
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdydta.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdydta.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdydta.F90	(revision 9987)
@@ -430,4 +430,5 @@
       CHARACTER(len=100)                     ::   cn_dir        ! Root directory for location of data files
       CHARACTER(len=100), DIMENSION(nb_bdy)  ::   cn_dir_array  ! Root directory for location of data files
+      CHARACTER(len = 256)::   clname                           ! temporary file name
       LOGICAL                                ::   ln_full_vel   ! =T => full velocities in 3D boundary data
                                                                 ! =F => baroclinic velocities in 3D boundary data
@@ -669,12 +670,20 @@
             ! sea ice
             IF( nn_ice_lim_dta(ib_bdy) .eq. 1 ) THEN
-
-               ! Test for types of ice input (lim2 or lim3) 
-               CALL iom_open ( bn_a_i%clname, inum )
-               id1 = iom_varid ( inum, bn_a_i%clvar, kdimsz=zdimsz, kndims=zndims, ldstop = .FALSE. )
+               ! Test for types of ice input (lim2 or lim3)
+               ! Build file name to find dimensions 
+               clname=TRIM(bn_a_i%clname)
+               IF( .NOT. bn_a_i%ln_clim ) THEN   
+                                                  WRITE(clname, '(a,"_y",i4.4)' ) TRIM( bn_a_i%clname ), nyear    ! add year
+                  IF( bn_a_i%cltype /= 'yearly' ) WRITE(clname, '(a,"m" ,i2.2)' ) TRIM( clname        ), nmonth   ! add month
+               ELSE
+                  IF( bn_a_i%cltype /= 'yearly' ) WRITE(clname, '(a,"_m",i2.2)' ) TRIM( bn_a_i%clname ), nmonth   ! add month
+               ENDIF
+               IF( bn_a_i%cltype == 'daily' .OR. bn_a_i%cltype(1:4) == 'week' ) &
+               &                                  WRITE(clname, '(a,"d" ,i2.2)' ) TRIM( clname        ), nday     ! add day
+               !
+               CALL iom_open  ( clname, inum )
+               id1 = iom_varid( inum, bn_a_i%clvar, kdimsz=zdimsz, kndims=zndims, ldstop = .FALSE. )
                CALL iom_close ( inum )
-               !CALL fld_clopn ( bn_a_i, nyear, nmonth, nday, ldstop=.TRUE. )
-               !CALL iom_open ( bn_a_i%clname, inum )
-               !id1 = iom_varid ( bn_a_i%num, bn_a_i%clvar, kdimsz=zdimsz, kndims=zndims, ldstop = .FALSE. )
+
       	       IF ( zndims == 4 ) THEN
                  ll_bdylim3 = .TRUE.   ! lim3 input
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn2d.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn2d.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn2d.F90	(revision 9987)
@@ -49,8 +49,8 @@
       !!----------------------------------------------------------------------
       INTEGER,                      INTENT(in) ::   kt   ! Main time step counter
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d 
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: pub2d, pvb2d
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: phur, phvr
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: pssh
+      REAL(wp), DIMENSION(:,:), INTENT(inout) :: pua2d, pva2d 
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) :: pub2d, pvb2d
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) :: phur, phvr
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) :: pssh
       !!
       INTEGER                                  ::   ib_bdy ! Loop counter
@@ -92,5 +92,5 @@
       TYPE(OBC_DATA),  INTENT(in) ::   dta  ! OBC external data
       INTEGER,         INTENT(in) ::   ib_bdy  ! BDY set index
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d 
+      REAL(wp), DIMENSION(:,:), INTENT(inout) :: pua2d, pva2d 
       !!
       INTEGER  ::   jb, jk         ! dummy loop indices
@@ -147,6 +147,6 @@
       TYPE(OBC_DATA),               INTENT(in) ::   dta  ! OBC external data
       INTEGER,                      INTENT(in) ::   ib_bdy  ! BDY set index
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pssh, phur, phvr 
+      REAL(wp), DIMENSION(:,:), INTENT(inout) :: pua2d, pva2d
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pssh, phur, phvr 
 
       INTEGER  ::   jb, igrd                         ! dummy loop indices
@@ -237,6 +237,6 @@
       TYPE(OBC_DATA),               INTENT(in) ::   dta  ! OBC external data
       INTEGER,                      INTENT(in) ::   ib_bdy  ! number of current open boundary set
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pub2d, pvb2d 
+      REAL(wp), DIMENSION(:,:),     INTENT(inout) :: pua2d, pva2d
+      REAL(wp), DIMENSION(:,:),     INTENT(in) :: pub2d, pvb2d 
       LOGICAL,                      INTENT(in) ::   ll_npo  ! flag for NPO version
 
@@ -271,8 +271,8 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   zssh ! Sea level
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   zssh ! Sea level
       !!
       INTEGER  ::   ib_bdy, ib, igrd                        ! local integers
-      INTEGER  ::   ii, ij, zcoef, zcoef1, zcoef2, ip, jp   !   "       "
+      INTEGER  ::   ii, ij, zcoef, ip, jp   !   "       "
 
       igrd = 1                       ! Everything is at T-points here
@@ -283,19 +283,7 @@
             ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
             ! Set gradient direction:
-            zcoef1 = bdytmask(ii-1,ij  ) +  bdytmask(ii+1,ij  )
-            zcoef2 = bdytmask(ii  ,ij-1) +  bdytmask(ii  ,ij+1)
-            IF ( zcoef1+zcoef2 == 0 ) THEN
-               ! corner
-!               zcoef = tmask(ii-1,ij,1) + tmask(ii+1,ij,1) +  tmask(ii,ij-1,1) +  tmask(ii,ij+1,1)
-!               zssh(ii,ij) = zssh(ii-1,ij  ) * tmask(ii-1,ij  ,1) + &
-!                 &           zssh(ii+1,ij  ) * tmask(ii+1,ij  ,1) + &
-!                 &           zssh(ii  ,ij-1) * tmask(ii  ,ij-1,1) + &
-!                 &           zssh(ii  ,ij+1) * tmask(ii  ,ij+1,1)
-               zcoef = bdytmask(ii-1,ij) + bdytmask(ii+1,ij) +  bdytmask(ii,ij-1) +  bdytmask(ii,ij+1)
-               zssh(ii,ij) = zssh(ii-1,ij  ) * bdytmask(ii-1,ij  ) + &
-                 &           zssh(ii+1,ij  ) * bdytmask(ii+1,ij  ) + &
-                 &           zssh(ii  ,ij-1) * bdytmask(ii  ,ij-1) + &
-                 &           zssh(ii  ,ij+1) * bdytmask(ii  ,ij+1)
-               zssh(ii,ij) = ( zssh(ii,ij) / MAX( 1, zcoef) ) * tmask(ii,ij,1)
+            zcoef = bdytmask(ii-1,ij) + bdytmask(ii+1,ij) +  bdytmask(ii,ij-1) +  bdytmask(ii,ij+1)
+            IF ( zcoef == 0 ) THEN
+               zssh(ii,ij) = 0._wp
             ELSE
                ip = bdytmask(ii+1,ij  ) - bdytmask(ii-1,ij  )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyice_lim.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyice_lim.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyice_lim.F90	(revision 9987)
@@ -107,4 +107,8 @@
       REAL(wp) ::   zwgt, zwgt1        ! local scalar
       REAL(wp) ::   ztmelts, zdh
+#if  defined key_lim2 && ! defined key_lim2_vp && defined key_agrif
+     USE ice_2, vt_s => hsnm
+     USE ice_2, vt_i => hicm
+#endif
 
       !!------------------------------------------------------------------------------
@@ -115,5 +119,5 @@
       !
 #if defined key_lim2
-      DO jb = 1, idx%nblen(jgrd)
+      DO jb = 1, idx%nblenrim(jgrd)
          ji    = idx%nbi(jb,jgrd)
          jj    = idx%nbj(jb,jgrd)
@@ -135,5 +139,5 @@
 
       DO jl = 1, jpl
-         DO jb = 1, idx%nblen(jgrd)
+         DO jb = 1, idx%nblenrim(jgrd)
             ji    = idx%nbi(jb,jgrd)
             jj    = idx%nbj(jb,jgrd)
@@ -171,5 +175,5 @@
 
       DO jl = 1, jpl
-         DO jb = 1, idx%nblen(jgrd)
+         DO jb = 1, idx%nblenrim(jgrd)
             ji    = idx%nbi(jb,jgrd)
             jj    = idx%nbj(jb,jgrd)
@@ -324,5 +328,5 @@
                
                jgrd = 2      ! u velocity
-               DO jb = 1, idx_bdy(ib_bdy)%nblen(jgrd)
+               DO jb = 1, idx_bdy(ib_bdy)%nblenrim(jgrd)
                   ji    = idx_bdy(ib_bdy)%nbi(jb,jgrd)
                   jj    = idx_bdy(ib_bdy)%nbj(jb,jgrd)
@@ -353,5 +357,5 @@
                
                jgrd = 3      ! v velocity
-               DO jb = 1, idx_bdy(ib_bdy)%nblen(jgrd)
+               DO jb = 1, idx_bdy(ib_bdy)%nblenrim(jgrd)
                   ji    = idx_bdy(ib_bdy)%nbi(jb,jgrd)
                   jj    = idx_bdy(ib_bdy)%nbj(jb,jgrd)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyini.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyini.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyini.F90	(revision 9987)
@@ -76,5 +76,5 @@
       INTEGER  ::   ib_bdy, ii, ij, ik, igrd, ib, ir, iseg ! dummy loop indices
       INTEGER  ::   icount, icountr, ibr_max, ilen1, ibm1  ! local integers
-      INTEGER  ::   iw, ie, is, in, inum, id_dummy         !   -       -
+      INTEGER  ::   iwe, ies, iso, ino, inum, id_dummy         !   -       -
       INTEGER  ::   igrd_start, igrd_end, jpbdta           !   -       -
       INTEGER  ::   jpbdtau, jpbdtas                       !   -       -
@@ -777,8 +777,8 @@
 !      is = mjg(1) + 1            ! if monotasking and no zoom, is=2
 !      in = mjg(1) + nlcj-1 - 1   ! if monotasking and no zoom, in=jpjm1      
-      iw = mig(1) - jpizoom + 2         ! if monotasking and no zoom, iw=2
-      ie = mig(1) + nlci - jpizoom - 1  ! if monotasking and no zoom, ie=jpim1
-      is = mjg(1) - jpjzoom + 2         ! if monotasking and no zoom, is=2
-      in = mjg(1) + nlcj - jpjzoom - 1  ! if monotasking and no zoom, in=jpjm1
+      iwe = mig(1) - jpizoom + 2         ! if monotasking and no zoom, iw=2
+      ies = mig(1) + nlci - jpizoom - 1  ! if monotasking and no zoom, ie=jpim1
+      iso = mjg(1) - jpjzoom + 2         ! if monotasking and no zoom, is=2
+      ino = mjg(1) + nlcj - jpjzoom - 1  ! if monotasking and no zoom, in=jpjm1
 
       ALLOCATE( nbondi_bdy(nb_bdy))
@@ -853,6 +853,6 @@
                ENDIF
                ! check if point is in local domain
-               IF(  nbidta(ib,igrd,ib_bdy) >= iw .AND. nbidta(ib,igrd,ib_bdy) <= ie .AND.   &
-                  & nbjdta(ib,igrd,ib_bdy) >= is .AND. nbjdta(ib,igrd,ib_bdy) <= in       ) THEN
+               IF(  nbidta(ib,igrd,ib_bdy) >= iwe .AND. nbidta(ib,igrd,ib_bdy) <= ies .AND.   &
+                  & nbjdta(ib,igrd,ib_bdy) >= iso .AND. nbjdta(ib,igrd,ib_bdy) <= ino      ) THEN
                   !
                   icount = icount  + 1
@@ -890,4 +890,5 @@
          com_south_b = 0
          com_north_b = 0
+
          DO igrd = 1, jpbgrd
             icount  = 0
@@ -896,6 +897,6 @@
                DO ib = 1, nblendta(igrd,ib_bdy)
                   ! check if point is in local domain and equals ir
-                  IF(  nbidta(ib,igrd,ib_bdy) >= iw .AND. nbidta(ib,igrd,ib_bdy) <= ie .AND.   &
-                     & nbjdta(ib,igrd,ib_bdy) >= is .AND. nbjdta(ib,igrd,ib_bdy) <= in .AND.   &
+                  IF(  nbidta(ib,igrd,ib_bdy) >= iwe .AND. nbidta(ib,igrd,ib_bdy) <= ies .AND.   &
+                     & nbjdta(ib,igrd,ib_bdy) >= iso .AND. nbjdta(ib,igrd,ib_bdy) <= ino .AND.   &
                      & nbrdta(ib,igrd,ib_bdy) == ir  ) THEN
                      !
@@ -1594,5 +1595,5 @@
             ELSE
                ! This is a corner
-               WRITE(numout,*) 'Found a South-West corner at (i,j): ', jpiwob(ib), jpjwdt(ib)
+               IF(lwp) WRITE(numout,*) 'Found a South-West corner at (i,j): ', jpiwob(ib), jpjwdt(ib)
                CALL bdy_ctl_corn(npckgw(ib), icornw(ib,1))
                itest=itest+1
@@ -1608,5 +1609,5 @@
             ELSE
                ! This is a corner
-               WRITE(numout,*) 'Found a North-West corner at (i,j): ', jpiwob(ib), jpjwft(ib)
+               IF(lwp) WRITE(numout,*) 'Found a North-West corner at (i,j): ', jpiwob(ib), jpjwft(ib)
                CALL bdy_ctl_corn(npckgw(ib), icornw(ib,2))
                itest=itest+1
@@ -1638,5 +1639,5 @@
             ELSE
                ! This is a corner
-               WRITE(numout,*) 'Found a South-East corner at (i,j): ', jpieob(ib)+1, jpjedt(ib)
+               IF(lwp) WRITE(numout,*) 'Found a South-East corner at (i,j): ', jpieob(ib)+1, jpjedt(ib)
                CALL bdy_ctl_corn(npckge(ib), icorne(ib,1))
                itest=itest+1
@@ -1652,5 +1653,5 @@
             ELSE
                ! This is a corner
-               WRITE(numout,*) 'Found a North-East corner at (i,j): ', jpieob(ib)+1, jpjeft(ib)
+               IF(lwp) WRITE(numout,*) 'Found a North-East corner at (i,j): ', jpieob(ib)+1, jpjeft(ib)
                CALL bdy_ctl_corn(npckge(ib), icorne(ib,2))
                itest=itest+1
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdytides.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdytides.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdytides.F90	(revision 9987)
@@ -416,5 +416,5 @@
       ! Absolute time from model initialization:   
       IF( PRESENT(kit) ) THEN  
-         z_arg = ( kt + (kit+0.5_wp*(time_add-1)) / REAL(nn_baro,wp) ) * rdt
+         z_arg = ( kt + (kit+time_add-1) / REAL(nn_baro,wp) ) * rdt
       ELSE                              
          z_arg = ( kt + time_add ) * rdt
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyvol.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyvol.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/BDY/bdyvol.F90	(revision 9987)
@@ -91,5 +91,5 @@
       ! Calculate the cumulate surface Flux z_cflxemp (m3/s) over all the domain
       ! -----------------------------------------------------------------------
-      z_cflxemp = SUM ( ( emp(:,:)-rnf(:,:)+rdivisf*fwfisf(:,:) ) * bdytmask(:,:) * e1t(:,:) * e2t(:,:) ) / rau0
+      z_cflxemp = SUM ( ( emp(:,:)-rnf(:,:)+fwfisf(:,:) ) * bdytmask(:,:) * e1t(:,:) * e2t(:,:) ) / rau0
       IF( lk_mpp )   CALL mpp_sum( z_cflxemp )     ! sum over the global domain
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaar5.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaar5.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaar5.F90	(revision 9987)
@@ -24,4 +24,6 @@
    USE phycst         ! physical constant
    USE in_out_manager  ! I/O manager
+   USE zdfddm
+   USE zdf_oce
 
    IMPLICIT NONE
@@ -42,4 +44,5 @@
    !! * Substitutions
 #  include "domzgr_substitute.h90"
+#  include "zdfddm_substitute.h90"
    !!----------------------------------------------------------------------
    !! NEMO/OPA 3.3 , NEMO Consortium (2010)
@@ -75,12 +78,18 @@
       INTEGER  ::   ji, jj, jk                      ! dummy loop arguments
       REAL(wp) ::   zvolssh, zvol, zssh_steric, zztmp, zarho, ztemp, zsal, zmass
+      REAL(wp) ::   zaw, zbw, zrw
       !
       REAL(wp), POINTER, DIMENSION(:,:)     :: zarea_ssh , zbotpres       ! 2D workspace 
+      REAL(wp), POINTER, DIMENSION(:,:)     :: pe                         ! 2D workspace 
       REAL(wp), POINTER, DIMENSION(:,:,:)   :: zrhd , zrhop               ! 3D workspace
       REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztsn                       ! 4D workspace
       !!--------------------------------------------------------------------
       IF( nn_timing == 1 )   CALL timing_start('dia_ar5')
+
+      !Call to init moved to here so that we can call iom_use in the
+      !initialisation
+      IF( kt == nit000 )     CALL dia_ar5_init
  
-      CALL wrk_alloc( jpi , jpj              , zarea_ssh , zbotpres )
+      CALL wrk_alloc( jpi , jpj              , zarea_ssh , zbotpres, pe )
       CALL wrk_alloc( jpi , jpj , jpk        , zrhd      , zrhop    )
       CALL wrk_alloc( jpi , jpj , jpk , jpts , ztsn                 )
@@ -95,30 +104,33 @@
       CALL iom_put( 'voltot', zvol               )
       CALL iom_put( 'sshtot', zvolssh / area_tot )
+      CALL iom_put( 'sshdyn', sshn(:,:) - (zvolssh / area_tot) )
 
       !                     
-      ztsn(:,:,:,jp_tem) = tsn(:,:,:,jp_tem)                    ! thermosteric ssh
-      ztsn(:,:,:,jp_sal) = sn0(:,:,:)
-      CALL eos( ztsn, zrhd, fsdept_n(:,:,:) )                       ! now in situ density using initial salinity
-      !
-      zbotpres(:,:) = 0._wp                        ! no atmospheric surface pressure, levitating sea-ice
-      DO jk = 1, jpkm1
-         zbotpres(:,:) = zbotpres(:,:) + fse3t(:,:,jk) * zrhd(:,:,jk)
-      END DO
-      IF( .NOT.lk_vvl ) THEN
-         IF ( ln_isfcav ) THEN
-            DO ji=1,jpi
-               DO jj=1,jpj
-                  zbotpres(ji,jj) = zbotpres(ji,jj) + sshn(ji,jj) * zrhd(ji,jj,mikt(ji,jj)) + riceload(ji,jj)
+      IF( iom_use('sshthster')) THEN
+         ztsn(:,:,:,jp_tem) = tsn(:,:,:,jp_tem)                    ! thermosteric ssh
+         ztsn(:,:,:,jp_sal) = sn0(:,:,:)
+         CALL eos( ztsn, zrhd, fsdept_n(:,:,:) )                       ! now in situ density using initial salinity
+         !
+         zbotpres(:,:) = 0._wp                        ! no atmospheric surface pressure, levitating sea-ice
+         DO jk = 1, jpkm1
+            zbotpres(:,:) = zbotpres(:,:) + fse3t(:,:,jk) * zrhd(:,:,jk)
+         END DO
+         IF( .NOT.lk_vvl ) THEN
+            IF ( ln_isfcav ) THEN
+               DO ji=1,jpi
+                  DO jj=1,jpj
+                     zbotpres(ji,jj) = zbotpres(ji,jj) + sshn(ji,jj) * zrhd(ji,jj,mikt(ji,jj)) + riceload(ji,jj)
+                  END DO
                END DO
-            END DO
-         ELSE
-            zbotpres(:,:) = zbotpres(:,:) + sshn(:,:) * zrhd(:,:,1)
+            ELSE
+               zbotpres(:,:) = zbotpres(:,:) + sshn(:,:) * zrhd(:,:,1)
+            END IF
          END IF
-      END IF
       !                                         
-      zarho = SUM( area(:,:) * zbotpres(:,:) ) 
-      IF( lk_mpp )   CALL mpp_sum( zarho )
-      zssh_steric = - zarho / area_tot
-      CALL iom_put( 'sshthster', zssh_steric )
+         zarho = SUM( area(:,:) * zbotpres(:,:) ) 
+         IF( lk_mpp )   CALL mpp_sum( zarho )
+         zssh_steric = - zarho / area_tot
+         CALL iom_put( 'sshthster', zssh_steric )
+      ENDIF
       
       !                                         ! steric sea surface height
@@ -190,6 +202,40 @@
       CALL iom_put( 'temptot', ztemp )
       CALL iom_put( 'saltot' , zsal  )
-      !
-      CALL wrk_dealloc( jpi , jpj              , zarea_ssh , zbotpres )
+
+      IF( iom_use( 'tnpeo' )) THEN    
+      ! Work done against stratification by vertical mixing
+      ! Exclude points where rn2 is negative as convection kicks in here and
+      ! work is not being done against stratification
+          pe(:,:) = 0._wp
+          IF( lk_zdfddm ) THEN
+             DO ji=1,jpi
+                DO jj=1,jpj
+                   DO jk=1,jpk
+                      zrw =   ( fsdepw(ji,jj,jk  ) - fsdept(ji,jj,jk) )   &
+                         &  / ( fsdept(ji,jj,jk-1) - fsdept(ji,jj,jk) )
+                      !
+                      zaw = rab_n(ji,jj,jk,jp_tem) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_tem)* zrw
+                      zbw = rab_n(ji,jj,jk,jp_sal) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_sal)* zrw
+                      !
+                      pe(ji, jj) = pe(ji, jj) - MIN(0._wp, rn2(ji,jj,jk)) * &
+                           &       grav * (avt(ji,jj,jk) * zaw * (tsn(ji,jj,jk-1,jp_tem) - tsn(ji,jj,jk,jp_tem) )  &
+                           &       - fsavs(ji,jj,jk) * zbw * (tsn(ji,jj,jk-1,jp_sal) - tsn(ji,jj,jk,jp_sal) ) )
+
+                   ENDDO
+                ENDDO
+             ENDDO
+          ELSE
+             DO ji=1,jpi
+                DO jj=1,jpj
+                   DO jk=1,jpk
+                       pe(ji,jj) = pe(ji,jj) + avt(ji, jj, jk) * MIN(0._wp,rn2(ji, jj, jk)) * rau0 * fse3w(ji, jj, jk)
+                   ENDDO
+                ENDDO
+             ENDDO
+          ENDIF
+          CALL iom_put( 'tnpeo', pe )
+      ENDIF
+      !
+      CALL wrk_dealloc( jpi , jpj              , zarea_ssh , zbotpres, pe )
       CALL wrk_dealloc( jpi , jpj , jpk        , zrhd      , zrhop    )
       CALL wrk_dealloc( jpi , jpj , jpk , jpts , ztsn                 )
@@ -211,21 +257,4 @@
       REAL(wp) ::   zztmp  
       REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   zsaldta   ! Jan/Dec levitus salinity
-      ! reading initial file
-      LOGICAL  ::   ln_tsd_init      !: T & S data flag
-      LOGICAL  ::   ln_tsd_tradmp    !: internal damping toward input data flag
-      CHARACTER(len=100)            ::   cn_dir
-      TYPE(FLD_N)                   ::  sn_tem,sn_sal
-      INTEGER  ::   ios=0
-
-      NAMELIST/namtsd/ ln_tsd_init,ln_tsd_tradmp,cn_dir,sn_tem,sn_sal
-      !
-
-      REWIND( numnam_ref )              ! Namelist namtsd in reference namelist :
-      READ  ( numnam_ref, namtsd, IOSTAT = ios, ERR = 901)
-901   IF( ios /= 0 ) CALL ctl_nam ( ios , ' namtsd in reference namelist for dia_ar5', lwp )
-      REWIND( numnam_cfg )              ! Namelist namtsd in configuration namelist : Parameters of the run
-      READ  ( numnam_cfg, namtsd, IOSTAT = ios, ERR = 902 )
-902   IF( ios /= 0 ) CALL ctl_nam ( ios , ' namtsd in configuration namelist for dia_ar5', lwp )
-      IF(lwm) WRITE ( numond, namtsd )
       !
       !!----------------------------------------------------------------------
@@ -233,5 +262,5 @@
       IF( nn_timing == 1 )   CALL timing_start('dia_ar5_init')
       !
-      CALL wrk_alloc( jpi , jpj , jpk, jpts, zsaldta )
+      CALL wrk_alloc( jpi, jpj, jpk, 2, zsaldta )
       !                                      ! allocate dia_ar5 arrays
       IF( dia_ar5_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dia_ar5_init : unable to allocate arrays' )
@@ -249,23 +278,26 @@
       IF( lk_mpp )   CALL mpp_sum( vol0 )
 
-      CALL iom_open ( TRIM( cn_dir )//TRIM(sn_sal%clname), inum )
-      CALL iom_get  ( inum, jpdom_data, TRIM(sn_sal%clvar), zsaldta(:,:,:,1), 1  )
-      CALL iom_get  ( inum, jpdom_data, TRIM(sn_sal%clvar), zsaldta(:,:,:,2), 12 )
-      CALL iom_close( inum )
-      sn0(:,:,:) = 0.5_wp * ( zsaldta(:,:,:,1) + zsaldta(:,:,:,2) )        
-      sn0(:,:,:) = sn0(:,:,:) * tmask(:,:,:)
-      IF( ln_zps ) THEN               ! z-coord. partial steps
-         DO jj = 1, jpj               ! interpolation of salinity at the last ocean level (i.e. the partial step)
-            DO ji = 1, jpi
-               ik = mbkt(ji,jj)
-               IF( ik > 1 ) THEN
-                  zztmp = ( gdept_1d(ik) - gdept_0(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
-                  sn0(ji,jj,ik) = ( 1._wp - zztmp ) * sn0(ji,jj,ik) + zztmp * sn0(ji,jj,ik-1)
-               ENDIF
+      IF( iom_use('sshthster')) THEN
+         CALL iom_open ( 'sali_ref_clim_monthly', inum )
+         CALL iom_get  ( inum, jpdom_data, 'vosaline' , zsaldta(:,:,:,1), 1  )
+         CALL iom_get  ( inum, jpdom_data, 'vosaline' , zsaldta(:,:,:,2), 12 )
+         CALL iom_close( inum )
+
+         sn0(:,:,:) = 0.5_wp * ( zsaldta(:,:,:,1) + zsaldta(:,:,:,2) )        
+         sn0(:,:,:) = sn0(:,:,:) * tmask(:,:,:)
+         IF( ln_zps ) THEN               ! z-coord. partial steps
+            DO jj = 1, jpj               ! interpolation of salinity at the last ocean level (i.e. the partial step)
+               DO ji = 1, jpi
+                  ik = mbkt(ji,jj)
+                  IF( ik > 1 ) THEN
+                     zztmp = ( gdept_1d(ik) - gdept_0(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
+                     sn0(ji,jj,ik) = ( 1._wp - zztmp ) * sn0(ji,jj,ik) + zztmp * sn0(ji,jj,ik-1)
+                  ENDIF
+               END DO
             END DO
-         END DO
+         ENDIF
       ENDIF
       !
-      CALL wrk_dealloc( jpi , jpj , jpk, jpts, zsaldta )
+      CALL wrk_dealloc( jpi, jpj, jpk, 2, zsaldta )
       !
       IF( nn_timing == 1 )   CALL timing_stop('dia_ar5_init')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diadimg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diadimg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diadimg.F90	(revision 9987)
@@ -124,6 +124,7 @@
 
     CASE DEFAULT
-       IF(lwp) WRITE(numout,*) ' E R R O R : bad cd_type in dia_wri_dimg '
-       STOP 'dia_wri_dimg'
+    
+       WRITE(numout,*) 'dia_wri_dimg : E R R O R : bad cd_type in dia_wri_dimg'
+       CALL ctl_stop( 'STOP', 'dia_wri_dimg :bad cd_type in dia_wri_dimg ' )
 
     END SELECT
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaharm.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaharm.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaharm.F90	(revision 9987)
@@ -196,9 +196,7 @@
                   DO ji = 1,jpi
                      ! Elevation
-                     ana_temp(ji,jj,nhc,1) = ana_temp(ji,jj,nhc,1) + ztemp*sshn(ji,jj)           *tmask_i(ji,jj)        
-#if defined key_dynspg_ts
-                     ana_temp(ji,jj,nhc,2) = ana_temp(ji,jj,nhc,2) + ztemp*un_b(ji,jj)*hur(ji,jj)*umask_i(ji,jj)
-                     ana_temp(ji,jj,nhc,3) = ana_temp(ji,jj,nhc,3) + ztemp*vn_b(ji,jj)*hvr(ji,jj)*vmask_i(ji,jj)
-#endif
+                     ana_temp(ji,jj,nhc,1) = ana_temp(ji,jj,nhc,1) + ztemp*sshn(ji,jj)*tmask_i(ji,jj)        
+                     ana_temp(ji,jj,nhc,2) = ana_temp(ji,jj,nhc,2) + ztemp*un_b(ji,jj)*umask_i(ji,jj)
+                     ana_temp(ji,jj,nhc,3) = ana_temp(ji,jj,nhc,3) + ztemp*vn_b(ji,jj)*vmask_i(ji,jj)
                   END DO
                END DO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diahsb.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diahsb.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diahsb.F90	(revision 9987)
@@ -93,5 +93,5 @@
       ! 1 - Trends due to forcing !
       ! ------------------------- !
-      z_frc_trd_v = r1_rau0 * glob_sum( - ( emp(:,:) - rnf(:,:) + rdivisf * fwfisf(:,:) ) * surf(:,:) ) ! volume fluxes
+      z_frc_trd_v = r1_rau0 * glob_sum( - ( emp(:,:) - rnf(:,:) + fwfisf(:,:) ) * surf(:,:) ) ! volume fluxes
       z_frc_trd_t =           glob_sum( sbc_tsc(:,:,jp_tem) * surf(:,:) )                               ! heat fluxes
       z_frc_trd_s =           glob_sum( sbc_tsc(:,:,jp_sal) * surf(:,:) )                               ! salt fluxes
@@ -101,7 +101,6 @@
       ! Add ice shelf heat & salt input
       IF( nn_isf .GE. 1 )  THEN
-          z_frc_trd_t = z_frc_trd_t &
-              &   + glob_sum( ( risf_tsc(:,:,jp_tem) - rdivisf * fwfisf(:,:) * (-1.9) * r1_rau0 ) * surf(:,:) )
-          z_frc_trd_s = z_frc_trd_s + (1.0_wp - rdivisf) * glob_sum( risf_tsc(:,:,jp_sal) * surf(:,:) )
+          z_frc_trd_t = z_frc_trd_t + glob_sum( risf_tsc(:,:,jp_tem) * surf(:,:) )
+          z_frc_trd_s = z_frc_trd_s + glob_sum( risf_tsc(:,:,jp_sal) * surf(:,:) )
       ENDIF
 
@@ -200,5 +199,4 @@
 !      ENDIF
 !!gm end
-
 
       IF( lk_vvl ) THEN
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diainsitutem.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diainsitutem.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diainsitutem.F90	(revision 9987)
@@ -0,0 +1,117 @@
+MODULE insitu_tem
+
+  USE dom_oce  ! ocean space and time domain
+  USE oce,            ONLY: tsn
+  USE par_oce,        ONLY: jpi, jpj, jpk, jpkm1
+  USE lbclnk,         ONLY: lbc_lnk
+  USE lib_mpp         ! MPP library
+
+  IMPLICIT NONE
+  PRIVATE
+
+  PUBLIC theta2t
+
+  !! * Accessibility
+  PUBLIC insitu_tem_alloc          ! routines called by step.F90
+
+  REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) :: insitu_t
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+
+CONTAINS
+
+   REAL FUNCTION insitu_tem_alloc()
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(2) :: ierr
+      !!----------------------------------------------------------------------
+      !
+      ierr = 0
+      !
+      ALLOCATE( insitu_t(jpi,jpj,jpk), STAT=ierr(1) )
+         !
+      insitu_tem_alloc = MAXVAL(ierr)
+      IF( lk_mpp )   CALL mpp_sum( insitu_tem_alloc )
+      !
+  END FUNCTION insitu_tem_alloc
+
+!-----------------------------------------------------------------------------------
+!
+! Calculate the insitu temperature by integrating the adiabatic lapse rate from zero 
+! to pressure at depth of tracer level. Based on UM subroutine POTTEM and function ATG
+!
+! Initial version: D. Acreman June 2006
+!
+!-----------------------------------------------------------------------------------
+
+  SUBROUTINE theta2t()
+
+    INTEGER, PARAMETER :: num_steps=10                ! number of steps in integration
+    INTEGER            :: step                        ! iteration counter
+    INTEGER            :: ji, jj, jk                  ! loop indices
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zP            ! pressure (decibars)
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zT            ! temperature at pressure p
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zTB           ! temperature at p-dp
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zTA           ! temperature at p+dp
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zDP           ! pressure step
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zSS           ! salinity(PSU) - 35.0
+    REAL(wp), DIMENSION(jpi,jpj,jpk) :: zLAPSE        ! adiabatic lapse rate
+
+!CDIR IEXPAND (ATG)
+
+! Set the pressure interval for the integration. The integration is carried out from 
+! zero (pressure at the surface) to the pressure at the depth of the tracer point. The
+! pressure in decibars is represented by the depth in metres. Pressures are "Oceanographic"
+! pressures equal to absolute pressure minus one atmosphere
+     zDP(:,:,:) = 0.0
+     DO jk = 1, jpkm1
+        DO jj = 1, jpj
+           DO ji = 1, jpi
+              ! These loops expanded for case where fsdept may be 1D
+              zDP(ji,jj,jk) = fsdept(ji,jj,jk) / real(num_steps)
+           END DO
+        END DO
+     END DO
+
+! Salinity at each point
+     zSS(:,:,:)      = tsn(:,:,:,jp_sal) - 35.0 
+
+! Set initial values of temperature and pressure. zT is the temperature at pressure zP, 
+! zTB is the temperature at pressure zP-zdP and zTA is the temperature at pressure zP+zdP
+     zT(:,:,:)  = tsn(:,:,:,jp_tem)
+     zP(:,:,:)  = 0.0         ! Pressure at surface
+     CALL ATG(zP, zT, zSS, zLAPSE)
+     zTB(:,:,:) = zT(:,:,:)  - zLAPSE(:,:,:) * zDP(:,:,:)
+
+     interation: DO step=1, num_steps
+        ! Calculate lapse rate (dT/dP) and hence TA
+        CALL ATG(zP, zT, zSS, zLAPSE)
+        zTA(:,:,:) = zTB(:,:,:) + 2.0 * zLAPSE(:,:,:) * zDP(:,:,:)
+        ! Have calculated TB, T and TA for this pressure, now advance solution by dP
+        zP(:,:,:)  = zP(:,:,:)  + zDP
+        zTB(:,:,:) = zT(:,:,:)
+        zT(:,:,:)  = zTA(:,:,:)
+
+     END DO interation
+
+     insitu_t(:,:,:) = zT(:,:,:) * tmask(:,:,:)
+     CALL lbc_lnk( insitu_t,  'T', 1.0)
+
+   END SUBROUTINE theta2t
+
+   SUBROUTINE ATG(P,T,DS,zLAPSE)
+
+     REAL, INTENT(IN   ) :: P(jpi,jpj,jpk)        ! PRESSURE (DECIBARS)
+     REAL, INTENT(IN   ) :: T(jpi,jpj,jpk)        ! TEMPERATURE (DEG C)
+     REAL, INTENT(IN   ) :: DS(jpi,jpj,jpk)       ! SALINITY (PSU) -35.0
+     REAL, INTENT(  OUT) :: zLAPSE(jpi,jpj,jpk)   ! LAPSE RATE
+
+       zLAPSE = ((( -2.1687E-16*T+1.8676E-14)*T-4.6206E-13)*P &
+           + ((2.7759E-12*T-1.1351E-10)*DS+((-5.4481E-14*T    &
+           + 8.733E-12)*T-6.7795E-10)*T+1.8741E-8))*P         &
+           + (-4.2393E-8*T+1.8932E-6)*DS                      &
+           + ((6.6228E-10*T-6.836E-8)*T+8.5258E-6)*T+3.5803E-5 
+
+   END SUBROUTINE ATG
+
+END MODULE insitu_tem
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaprod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaprod.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaprod.F90	(revision 9987)
@@ -0,0 +1,248 @@
+MODULE diaprod
+! Requires key_iom_put
+# if defined key_iomput
+   !!======================================================================
+   !!                     ***  MODULE  diaprod  ***
+   !! Ocean diagnostics :  write ocean product diagnostics
+   !!=====================================================================
+   !! History :  3.4  ! 2012  (D. Storkey)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_prod      : calculate and write out product diagnostics
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain
+   USE domvvl          ! for thickness weighted diagnostics if key_vvl
+   USE eosbn2          ! equation of state  (eos call)
+   USE phycst          ! physical constants
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager  ! I/O manager
+   USE diadimg         ! dimg direct access file format output
+   USE iom
+   USE ioipsl
+   USE lib_mpp         ! MPP library
+   USE timing          ! preformance summary
+   USE wrk_nemo        ! working array
+   USE diaptr
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_prod                 ! routines called by step.F90
+
+   !! * Substitutions
+#  include "zdfddm_substitute.h90"
+#  include "domzgr_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.4 , NEMO Consortium (2012)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_prod( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_prod  ***
+      !!                   
+      !! ** Purpose :   Write out product diagnostics (uT, vS etc.)
+      !!
+      !! ** Method  :  use iom_put
+      !!               Product diagnostics are not thickness-weighted in this routine.
+      !!               They should be thickness-weighted using XIOS if key_vvl is set. 
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !!
+      INTEGER                      ::   ji, jj, jk              ! dummy loop indices
+      REAL(wp)                     ::   zztmp, zztmpx, zztmpy   ! 
+      !!
+      REAL(wp), POINTER, DIMENSION(:,:)   :: z2d      ! 2D workspace
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: z3d      ! 3D workspace
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zrhop    ! potential density
+      !!----------------------------------------------------------------------
+      ! 
+      IF( nn_timing == 1 )   CALL timing_start('dia_prod')
+      ! 
+      CALL wrk_alloc( jpi , jpj      , z2d )
+      CALL wrk_alloc( jpi , jpj, jpk , z3d )
+      CALL wrk_alloc( jpi , jpj, jpk , zrhop )
+      !
+
+      IF( iom_use("urhop") .OR. iom_use("vrhop") .OR. iom_use("wrhop") &
+#if ! defined key_diaar5
+     &  .OR. iom_use("rhop") &
+#endif
+     & ) THEN
+         CALL eos( tsn, z3d, zrhop )                 ! now in situ and potential density
+         zrhop(:,:,:) = zrhop(:,:,:)-1000.e0         ! reference potential density to 1000 to avoid precision issues in rhop2 calculation
+         zrhop(:,:,jpk) = 0._wp
+#if ! defined key_diaar5
+         CALL iom_put( 'rhop', zrhop )
+#else
+         ! If key_diaar5 set then there is already an iom_put call to output rhop.
+         ! Really should be a standard diagnostics option?
+#endif
+      ENDIF
+
+      IF( iom_use("ut") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = un(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_tem) + tsn(ji+1,jj,jk,jp_tem) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "ut", z3d )                  ! product of temperature and zonal velocity at U points
+      ENDIF
+
+      IF( iom_use("vt") .OR. iom_use("sopht_vt") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = vn(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_tem) + tsn(ji,jj+1,jk,jp_tem) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "vt", z3d )                  ! product of temperature and meridional velocity at V points
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = z3d(ji,jj,jk) * fse3v(ji,jj,jk) * e1v(ji,jj)
+               END DO
+            END DO
+         END DO
+         IF(ln_diaptr) CALL dia_ptr_ohst_components( jp_tem, 'vts', z3d)
+      ENDIF
+
+      IF( iom_use("wt") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               z3d(ji,jj,1) = wn(ji,jj,1) * tsn(ji,jj,1,jp_tem)
+            END DO
+         END DO
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = wn(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk-1,jp_tem) + tsn(ji,jj,jk,jp_tem) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "wt", z3d )                  ! product of temperature and vertical velocity at W points
+      ENDIF
+
+      IF( iom_use("us") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = un(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_sal) + tsn(ji+1,jj,jk,jp_sal) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "us", z3d )                  ! product of salinity and zonal velocity at U points
+      ENDIF
+
+      IF( iom_use("vs") .OR. iom_use("sopst_vs") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = vn(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_sal) + tsn(ji,jj+1,jk,jp_sal) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "vs", z3d )                  ! product of salinity and meridional velocity at V points
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = z3d(ji,jj,jk) * fse3v(ji,jj,jk) * e1v(ji,jj)
+               END DO
+            END DO
+         END DO
+         IF(ln_diaptr) CALL dia_ptr_ohst_components( jp_sal, 'vts', z3d)
+      ENDIF
+
+      IF( iom_use("ws") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               z3d(ji,jj,1) = wn(ji,jj,1) * tsn(ji,jj,1,jp_sal)
+            END DO
+         END DO
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = wn(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk-1,jp_sal) + tsn(ji,jj,jk,jp_sal) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "ws", z3d )                  ! product of salinity and vertical velocity at W points
+      ENDIF
+
+      IF( iom_use("urhop") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = un(ji,jj,jk) * 0.5 * ( zrhop(ji,jj,jk) + zrhop(ji+1,jj,jk) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "urhop", z3d )                  ! product of density and zonal velocity at U points
+      ENDIF
+
+      IF( iom_use("vrhop") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = vn(ji,jj,jk) * 0.5 * ( zrhop(ji,jj,jk) + zrhop(ji,jj+1,jk) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "vrhop", z3d )                  ! product of density and meridional velocity at V points
+      ENDIF
+
+      IF( iom_use("wrhop") ) THEN
+         z3d(:,:,:) = 0.e0 
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               z3d(ji,jj,1) = wn(ji,jj,1) * zrhop(ji,jj,1)
+            END DO
+         END DO
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = wn(ji,jj,jk) * 0.5 * ( zrhop(ji,jj,jk-1) + zrhop(ji,jj,jk) )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "wrhop", z3d )                  ! product of density and vertical velocity at W points
+      ENDIF
+
+      !
+      CALL wrk_dealloc( jpi , jpj      , z2d )
+      CALL wrk_dealloc( jpi , jpj, jpk , z3d )
+      CALL wrk_dealloc( jpi , jpj, jpk , zrhop )
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('dia_prod')
+      !
+   END SUBROUTINE dia_prod
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :                                         NO diaprod
+   !!----------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER :: lk_diaprod = .FALSE.   ! coupled flag
+CONTAINS
+   SUBROUTINE dia_prod( kt )   ! Empty routine
+      INTEGER ::   kt
+      WRITE(*,*) 'dia_prod: You should not have seen this print! error?', kt
+   END SUBROUTINE dia_prod
+#endif
+   !!======================================================================
+END MODULE diaprod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaptr.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaptr.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diaptr.F90	(revision 9987)
@@ -9,4 +9,5 @@
    !!            3.3  ! 2010-10  (G. Madec)  dynamical allocation
    !!            3.6  ! 2014-12  (C. Ethe) use of IOM
+   !!            3.6  ! 2016-06  (T. Graham) Addition of diagnostics for CMIP6
    !!----------------------------------------------------------------------
 
@@ -21,4 +22,5 @@
    USE dom_oce          ! ocean space and time domain
    USE phycst           ! physical constants
+   USE ldftra_oce 
    !
    USE iom              ! IOM library
@@ -38,13 +40,15 @@
    PUBLIC   dia_ptr_init   ! call in step module
    PUBLIC   dia_ptr        ! call in step module
+   PUBLIC   dia_ptr_ohst_components        ! called from tra_ldf/tra_adv routines
 
    !                                  !!** namelist  namptr  **
-   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:) ::   htr_adv, htr_ldf   !: Heat TRansports (adv, diff, overturn.)
-   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:) ::   str_adv, str_ldf   !: Salt TRansports (adv, diff, overturn.)
-   
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   htr_adv, htr_ldf, htr_eiv, htr_vt   !: Heat TRansports (adv, diff, Bolus.)
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   str_adv, str_ldf, str_eiv, str_vs   !: Salt TRansports (adv, diff, Bolus.)
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   htr_ove, str_ove   !: heat Salt TRansports ( overturn.)
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   htr_btr, str_btr   !: heat Salt TRansports ( barotropic )
 
    LOGICAL, PUBLIC ::   ln_diaptr   !  Poleward transport flag (T) or not (F)
    LOGICAL, PUBLIC ::   ln_subbas   !  Atlantic/Pacific/Indian basins calculation
-   INTEGER         ::   nptr        ! = 1 (l_subbas=F) or = 5 (glo, atl, pac, ind, ipc) (l_subbas=T) 
+   INTEGER, PUBLIC ::   nptr        ! = 1 (l_subbas=F) or = 5 (glo, atl, pac, ind, ipc) (l_subbas=T) 
 
    REAL(wp) ::   rc_sv    = 1.e-6_wp   ! conversion from m3/s to Sverdrup
@@ -77,10 +81,20 @@
       !
       INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp) ::   zv, zsfc               ! local scalar
+      REAL(wp) ::   zsfc,zvfc               ! local scalar
       REAL(wp), DIMENSION(jpi,jpj)     ::  z2d   ! 2D workspace
       REAL(wp), DIMENSION(jpi,jpj,jpk) ::  z3d   ! 3D workspace
       REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zmask   ! 3D workspace
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts) ::  zts   ! 3D workspace
-      CHARACTER( len = 10 )  :: cl1
+      REAL(wp), DIMENSION(jpj)     ::  vsum   ! 1D workspace
+      REAL(wp), DIMENSION(jpj,jpts)     ::  tssum   ! 1D workspace
+ 
+      !
+      !overturning calculation
+      REAL(wp), DIMENSION(jpj,jpk,nptr) ::   sjk  , r1_sjk ! i-mean i-k-surface and its inverse
+      REAL(wp), DIMENSION(jpj,jpk,nptr) ::   v_msf, sn_jk  , tn_jk ! i-mean T and S, j-Stream-Function
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zvn   ! 3D workspace
+
+
+      CHARACTER( len = 12 )  :: cl1
       !!----------------------------------------------------------------------
       !
@@ -88,9 +102,10 @@
 
       !
+      z3d(:,:,:) = 0._wp
       IF( PRESENT( pvtr ) ) THEN
          IF( iom_use("zomsfglo") ) THEN    ! effective MSF
             z3d(1,:,:) = ptr_sjk( pvtr(:,:,:) )  ! zonal cumulative effective transport
-            DO jk = 2, jpkm1 
-              z3d(1,:,jk) = z3d(1,:,jk-1) + z3d(1,:,jk)   ! effective j-Stream-Function (MSF)
+            DO jk = jpkm1,1,-1                   !Integrate from bottom up to get
+              z3d(1,:,jk) = z3d(1,:,jk+1) - z3d(1,:,jk)   ! effective j-Stream-Function (MSF)
             END DO
             DO ji = 1, jpi
@@ -100,7 +115,7 @@
             CALL iom_put( cl1, z3d * rc_sv )
             DO jn = 2, nptr                                    ! by sub-basins
-               z3d(1,:,:) =  ptr_sjk( pvtr(:,:,:), btmsk(:,:,jn)*btm30(:,:) ) 
-               DO jk = 2, jpkm1 
-                  z3d(1,:,jk) = z3d(1,:,jk-1) + z3d(1,:,jk)    ! effective j-Stream-Function (MSF)
+               z3d(1,:,:) =  ptr_sjk( pvtr(:,:,:), btmsk(:,:,jn) ) 
+               DO jk = jpkm1,1,-1
+                  z3d(1,:,jk) = z3d(1,:,jk+1) - z3d(1,:,jk)    ! effective j-Stream-Function (MSF)
                END DO
                DO ji = 1, jpi
@@ -111,4 +126,122 @@
             END DO
          ENDIF
+         IF( iom_use("sopstove") .OR. iom_use("sophtove") .OR. iom_use("sopstbtr") .OR. iom_use("sophtbtr") ) THEN
+            ! define fields multiplied by scalar
+            zmask(:,:,:) = 0._wp
+            zts(:,:,:,:) = 0._wp
+            zvn(:,:,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpi
+                     zvfc = e1v(ji,jj) * fse3v(ji,jj,jk)
+                     zmask(ji,jj,jk)      = vmask(ji,jj,jk)      * zvfc
+                     zts(ji,jj,jk,jp_tem) = (tsn(ji,jj,jk,jp_tem)+tsn(ji,jj+1,jk,jp_tem)) * 0.5 * zvfc  !Tracers averaged onto V grid
+                     zts(ji,jj,jk,jp_sal) = (tsn(ji,jj,jk,jp_sal)+tsn(ji,jj+1,jk,jp_sal)) * 0.5 * zvfc
+                     zvn(ji,jj,jk)        = vn(ji,jj,jk)         * zvfc
+                  ENDDO
+               ENDDO
+             ENDDO
+         ENDIF
+         IF( iom_use("sopstove") .OR. iom_use("sophtove") ) THEN
+             sjk(:,:,1) = ptr_sjk( zmask(:,:,:), btmsk(:,:,1) )
+             r1_sjk(:,:,1) = 0._wp
+             WHERE( sjk(:,:,1) /= 0._wp )   r1_sjk(:,:,1) = 1._wp / sjk(:,:,1)
+
+             ! i-mean T and S, j-Stream-Function, global
+             tn_jk(:,:,1) = ptr_sjk( zts(:,:,:,jp_tem) ) * r1_sjk(:,:,1)
+             sn_jk(:,:,1) = ptr_sjk( zts(:,:,:,jp_sal) ) * r1_sjk(:,:,1)
+             v_msf(:,:,1) = ptr_sjk( zvn(:,:,:) )
+
+             htr_ove(:,1) = SUM( v_msf(:,:,1)*tn_jk(:,:,1) ,2 )
+             str_ove(:,1) = SUM( v_msf(:,:,1)*sn_jk(:,:,1) ,2 )
+
+             z2d(1,:) = htr_ove(:,1) * rc_pwatt        !  (conversion in PW)
+             DO ji = 1, jpi
+               z2d(ji,:) = z2d(1,:)
+             ENDDO
+             cl1 = 'sophtove'
+             CALL iom_put( TRIM(cl1), z2d )
+             z2d(1,:) = str_ove(:,1) * rc_ggram        !  (conversion in Gg)
+             DO ji = 1, jpi
+               z2d(ji,:) = z2d(1,:)
+             ENDDO
+             cl1 = 'sopstove'
+             CALL iom_put( TRIM(cl1), z2d )
+             IF( ln_subbas ) THEN
+                DO jn = 2, nptr
+                    sjk(:,:,jn) = ptr_sjk( zmask(:,:,:), btmsk(:,:,jn) )
+                    r1_sjk(:,:,jn) = 0._wp
+                    WHERE( sjk(:,:,jn) /= 0._wp )   r1_sjk(:,:,jn) = 1._wp / sjk(:,:,jn)
+
+                    ! i-mean T and S, j-Stream-Function, basin
+                    tn_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) ) * r1_sjk(:,:,jn)
+                    sn_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) ) * r1_sjk(:,:,jn)
+                    v_msf(:,:,jn) = ptr_sjk( zvn(:,:,:), btmsk(:,:,jn) ) 
+                    htr_ove(:,jn) = SUM( v_msf(:,:,jn)*tn_jk(:,:,jn) ,2 )
+                    str_ove(:,jn) = SUM( v_msf(:,:,jn)*sn_jk(:,:,jn) ,2 )
+
+                    z2d(1,:) = htr_ove(:,jn) * rc_pwatt !  (conversion in PW)
+                    DO ji = 1, jpi
+                        z2d(ji,:) = z2d(1,:)
+                    ENDDO
+                    cl1 = TRIM('sophtove_'//clsubb(jn))
+                    CALL iom_put( cl1, z2d )
+                    z2d(1,:) = str_ove(:,jn) * rc_ggram        ! (conversion in Gg)
+                    DO ji = 1, jpi
+                        z2d(ji,:) = z2d(1,:)
+                    ENDDO
+                    cl1 = TRIM('sopstove_'//clsubb(jn))
+                    CALL iom_put( cl1, z2d )
+                END DO
+             ENDIF
+         ENDIF
+         IF( iom_use("sopstbtr") .OR. iom_use("sophtbtr") ) THEN
+         ! Calculate barotropic heat and salt transport here 
+             sjk(:,1,1) = ptr_sj( zmask(:,:,:), btmsk(:,:,1) )
+             r1_sjk(:,1,1) = 0._wp
+             WHERE( sjk(:,1,1) /= 0._wp )   r1_sjk(:,1,1) = 1._wp / sjk(:,1,1)
+            
+            vsum = ptr_sj( zvn(:,:,:), btmsk(:,:,1))
+            tssum(:,jp_tem) = ptr_sj( zts(:,:,:,jp_tem), btmsk(:,:,1) )
+            tssum(:,jp_sal) = ptr_sj( zts(:,:,:,jp_sal), btmsk(:,:,1) )
+            htr_btr(:,1) = vsum * tssum(:,jp_tem) * r1_sjk(:,1,1)
+            str_btr(:,1) = vsum * tssum(:,jp_sal) * r1_sjk(:,1,1)
+            z2d(1,:) = htr_btr(:,1) * rc_pwatt        !  (conversion in PW)
+            DO ji = 2, jpi
+               z2d(ji,:) = z2d(1,:)
+            ENDDO
+            cl1 = 'sophtbtr'
+            CALL iom_put( TRIM(cl1), z2d )
+            z2d(1,:) = str_btr(:,1) * rc_ggram        !  (conversion in Gg)
+            DO ji = 2, jpi
+              z2d(ji,:) = z2d(1,:)
+            ENDDO
+            cl1 = 'sopstbtr'
+            CALL iom_put( TRIM(cl1), z2d )
+            IF( ln_subbas ) THEN
+                DO jn = 2, nptr
+                    sjk(:,1,jn) = ptr_sj( zmask(:,:,:), btmsk(:,:,jn) )
+                    r1_sjk(:,1,jn) = 0._wp
+                    WHERE( sjk(:,1,jn) /= 0._wp )   r1_sjk(:,1,jn) = 1._wp / sjk(:,1,jn)
+                    vsum = ptr_sj( zvn(:,:,:), btmsk(:,:,jn))
+                    tssum(:,jp_tem) = ptr_sj( zts(:,:,:,jp_tem), btmsk(:,:,jn) )
+                    tssum(:,jp_sal) = ptr_sj( zts(:,:,:,jp_sal), btmsk(:,:,jn) )
+                    htr_btr(:,jn) = vsum * tssum(:,jp_tem) * r1_sjk(:,1,jn)
+                    str_btr(:,jn) = vsum * tssum(:,jp_sal) * r1_sjk(:,1,jn)
+                    z2d(1,:) = htr_btr(:,jn) * rc_pwatt !  (conversion in PW)
+                    DO ji = 1, jpi
+                        z2d(ji,:) = z2d(1,:)
+                    ENDDO
+                    cl1 = TRIM('sophtbtr_'//clsubb(jn))
+                    CALL iom_put( cl1, z2d )
+                    z2d(1,:) = str_btr(:,jn) * rc_ggram        ! (conversion in Gg)
+                    DO ji = 1, jpi
+                        z2d(ji,:) = z2d(1,:)
+                    ENDDO
+                    cl1 = TRIM('sopstbtr_'//clsubb(jn))
+                    CALL iom_put( cl1, z2d )
+               ENDDO
+            ENDIF !ln_subbas
+         ENDIF !iom_use("sopstbtr....)
          !
       ELSE
@@ -150,5 +283,5 @@
          !                                ! Advective and diffusive heat and salt transport
          IF( iom_use("sophtadv") .OR. iom_use("sopstadv") ) THEN   
-            z2d(1,:) = htr_adv(:) * rc_pwatt        !  (conversion in PW)
+            z2d(1,:) = htr_adv(:,1) * rc_pwatt        !  (conversion in PW)
             DO ji = 1, jpi
                z2d(ji,:) = z2d(1,:)
@@ -156,5 +289,5 @@
             cl1 = 'sophtadv'                 
             CALL iom_put( TRIM(cl1), z2d )
-            z2d(1,:) = str_adv(:) * rc_ggram        ! (conversion in Gg)
+            z2d(1,:) = str_adv(:,1) * rc_ggram        ! (conversion in Gg)
             DO ji = 1, jpi
                z2d(ji,:) = z2d(1,:)
@@ -162,8 +295,24 @@
             cl1 = 'sopstadv'
             CALL iom_put( TRIM(cl1), z2d )
+            IF( ln_subbas ) THEN
+              DO jn=2,nptr
+               z2d(1,:) = htr_adv(:,jn) * rc_pwatt        !  (conversion in PW)
+               DO ji = 1, jpi
+                 z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = TRIM('sophtadv_'//clsubb(jn))                 
+               CALL iom_put( cl1, z2d )
+               z2d(1,:) = str_adv(:,jn) * rc_ggram        ! (conversion in Gg)
+               DO ji = 1, jpi
+                  z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = TRIM('sopstadv_'//clsubb(jn))                 
+               CALL iom_put( cl1, z2d )              
+              ENDDO
+            ENDIF
          ENDIF
          !
          IF( iom_use("sophtldf") .OR. iom_use("sopstldf") ) THEN   
-            z2d(1,:) = htr_ldf(:) * rc_pwatt        !  (conversion in PW) 
+            z2d(1,:) = htr_ldf(:,1) * rc_pwatt        !  (conversion in PW) 
             DO ji = 1, jpi
                z2d(ji,:) = z2d(1,:)
@@ -171,5 +320,5 @@
             cl1 = 'sophtldf'
             CALL iom_put( TRIM(cl1), z2d )
-            z2d(1,:) = str_ldf(:) * rc_ggram        !  (conversion in Gg)
+            z2d(1,:) = str_ldf(:,1) * rc_ggram        !  (conversion in Gg)
             DO ji = 1, jpi
                z2d(ji,:) = z2d(1,:)
@@ -177,5 +326,111 @@
             cl1 = 'sopstldf'
             CALL iom_put( TRIM(cl1), z2d )
-         ENDIF
+            IF( ln_subbas ) THEN
+              DO jn=2,nptr
+               z2d(1,:) = htr_ldf(:,jn) * rc_pwatt        !  (conversion in PW)
+               DO ji = 1, jpi
+                 z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = TRIM('sophtldf_'//clsubb(jn))                 
+               CALL iom_put( cl1, z2d )
+               z2d(1,:) = str_ldf(:,jn) * rc_ggram        ! (conversion in Gg)
+               DO ji = 1, jpi
+                  z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = TRIM('sopstldf_'//clsubb(jn))                 
+               CALL iom_put( cl1, z2d )              
+              ENDDO
+            ENDIF
+         ENDIF
+
+         IF( iom_use("sopht_vt") .OR. iom_use("sopst_vs") ) THEN   
+            z2d(1,:) = htr_vt(:,1) * rc_pwatt        !  (conversion in PW) 
+            DO ji = 1, jpi
+               z2d(ji,:) = z2d(1,:)
+            ENDDO
+            cl1 = 'sopht_vt'
+            CALL iom_put( TRIM(cl1), z2d )
+            z2d(1,:) = str_vs(:,1) * rc_ggram        !  (conversion in Gg)
+            DO ji = 1, jpi
+               z2d(ji,:) = z2d(1,:)
+            ENDDO
+            cl1 = 'sopst_vs'
+            CALL iom_put( TRIM(cl1), z2d )
+            IF( ln_subbas ) THEN
+              DO jn=2,nptr
+               z2d(1,:) = htr_vt(:,jn) * rc_pwatt        !  (conversion in PW)
+               DO ji = 1, jpi
+                 z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = TRIM('sopht_vt_'//clsubb(jn))                 
+               CALL iom_put( cl1, z2d )
+               z2d(1,:) = str_vs(:,jn) * rc_ggram        ! (conversion in Gg)
+               DO ji = 1, jpi
+                  z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = TRIM('sopst_vs_'//clsubb(jn))                 
+               CALL iom_put( cl1, z2d )              
+              ENDDO
+            ENDIF
+         ENDIF
+
+#ifdef key_diaeiv
+         IF(lk_traldf_eiv) THEN
+            IF( iom_use("sophteiv") .OR. iom_use("sopsteiv") ) THEN 
+               z2d(1,:) = htr_eiv(:,1) * rc_pwatt        !  (conversion in PW) 
+               DO ji = 1, jpi
+                  z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = 'sophteiv'
+               CALL iom_put( TRIM(cl1), z2d )
+               z2d(1,:) = str_eiv(:,1) * rc_ggram        !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z2d(ji,:) = z2d(1,:)
+               ENDDO
+               cl1 = 'sopsteiv'
+               CALL iom_put( TRIM(cl1), z2d )
+               IF( ln_subbas ) THEN
+                  DO jn=2,nptr
+                     z2d(1,:) = htr_eiv(:,jn) * rc_pwatt        !  (conversion in PW)
+                     DO ji = 1, jpi
+                        z2d(ji,:) = z2d(1,:)
+                     ENDDO
+                     cl1 = TRIM('sophteiv_'//clsubb(jn))                 
+                     CALL iom_put( cl1, z2d )
+                     z2d(1,:) = str_eiv(:,jn) * rc_ggram        ! (conversion in Gg)
+                     DO ji = 1, jpi
+                        z2d(ji,:) = z2d(1,:)
+                     ENDDO
+                     cl1 = TRIM('sopsteiv_'//clsubb(jn)) 
+                     CALL iom_put( cl1, z2d )              
+                  ENDDO
+               ENDIF
+            ENDIF
+            IF( iom_use("zomsfeivglo") ) THEN
+               z3d(1,:,:) = ptr_sjk( v_eiv(:,:,:) )  ! zonal cumulative effective transport
+               DO jk = jpkm1,1,-1
+                 z3d(1,:,jk) = z3d(1,:,jk+1) - z3d(1,:,jk)   ! effective j-Stream-Function (MSF)
+               END DO
+               DO ji = 1, jpi
+                  z3d(ji,:,:) = z3d(1,:,:)
+               ENDDO
+               cl1 = TRIM('zomsfeiv'//clsubb(1) )
+               CALL iom_put( cl1, z3d * rc_sv )
+               IF( ln_subbas ) THEN
+                  DO jn = 2, nptr                                    ! by sub-basins
+                     z3d(1,:,:) =  ptr_sjk( v_eiv(:,:,:), btmsk(:,:,jn) ) 
+                     DO jk = jpkm1,1,-1
+                        z3d(1,:,jk) = z3d(1,:,jk+1) - z3d(1,:,jk)    ! effective j-Stream-Function (MSF)
+                     END DO
+                     DO ji = 1, jpi
+                        z3d(ji,:,:) = z3d(1,:,:)
+                     ENDDO
+                     cl1 = TRIM('zomsfeiv'//clsubb(jn) )
+                     CALL iom_put( cl1, z3d * rc_sv )
+                  END DO
+               ENDIF
+            ENDIF
+         ENDIF
+#endif
          !
       ENDIF
@@ -256,6 +511,10 @@
          ! Initialise arrays to zero because diatpr is called before they are first calculated
          ! Note that this means diagnostics will not be exactly correct when model run is restarted.
-         htr_adv(:) = 0._wp  ;  str_adv(:) =  0._wp  
-         htr_ldf(:) = 0._wp  ;  str_ldf(:) =  0._wp 
+         htr_adv(:,:) = 0._wp  ;  str_adv(:,:) =  0._wp 
+         htr_ldf(:,:) = 0._wp  ;  str_ldf(:,:) =  0._wp 
+         htr_eiv(:,:) = 0._wp  ;  str_eiv(:,:) =  0._wp 
+         htr_vt(:,:) = 0._wp  ;   str_vs(:,:) =  0._wp
+         htr_ove(:,:) = 0._wp  ;   str_ove(:,:) =  0._wp
+         htr_btr(:,:) = 0._wp  ;   str_btr(:,:) =  0._wp
          !
       ENDIF 
@@ -263,4 +522,87 @@
    END SUBROUTINE dia_ptr_init
 
+   SUBROUTINE dia_ptr_ohst_components( ktra, cptr, pva ) 
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ptr_ohst_components  ***
+      !!----------------------------------------------------------------------
+      !! Wrapper for heat and salt transport calculations to calculate them for each basin
+      !! Called from all advection and/or diffusion routines
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in )  :: ktra  ! tracer index
+      CHARACTER(len=3)                , INTENT(in)   :: cptr  ! transport type  'adv'/'ldf'/'eiv'
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: pva   ! 3D input array of advection/diffusion
+      INTEGER                                        :: jn    !
+
+      IF( cptr == 'adv' ) THEN
+         IF( ktra == jp_tem )  htr_adv(:,1) = ptr_sj( pva(:,:,:) )
+         IF( ktra == jp_sal )  str_adv(:,1) = ptr_sj( pva(:,:,:) )
+      ENDIF
+      IF( cptr == 'ldf' ) THEN
+         IF( ktra == jp_tem )  htr_ldf(:,1) = ptr_sj( pva(:,:,:) )
+         IF( ktra == jp_sal )  str_ldf(:,1) = ptr_sj( pva(:,:,:) )
+      ENDIF
+      IF( cptr == 'eiv' ) THEN
+         IF( ktra == jp_tem )  htr_eiv(:,1) = ptr_sj( pva(:,:,:) )
+         IF( ktra == jp_sal )  str_eiv(:,1) = ptr_sj( pva(:,:,:) )
+      ENDIF
+      IF( cptr == 'vts' ) THEN
+         IF( ktra == jp_tem )  htr_vt(:,1) = ptr_sj( pva(:,:,:) )
+         IF( ktra == jp_sal )  str_vs(:,1) = ptr_sj( pva(:,:,:) )
+      ENDIF
+      !
+      IF( ln_subbas ) THEN
+         !
+         IF( cptr == 'adv' ) THEN
+             IF( ktra == jp_tem ) THEN 
+                DO jn = 2, nptr
+                   htr_adv(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                END DO
+             ENDIF
+             IF( ktra == jp_sal ) THEN 
+                DO jn = 2, nptr
+                   str_adv(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                END DO
+             ENDIF
+         ENDIF
+         IF( cptr == 'ldf' ) THEN
+             IF( ktra == jp_tem ) THEN 
+                DO jn = 2, nptr
+                    htr_ldf(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                 END DO
+             ENDIF
+             IF( ktra == jp_sal ) THEN 
+                DO jn = 2, nptr
+                   str_ldf(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                END DO
+             ENDIF
+         ENDIF
+         IF( cptr == 'eiv' ) THEN
+             IF( ktra == jp_tem ) THEN 
+                DO jn = 2, nptr
+                    htr_eiv(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                 END DO
+             ENDIF
+             IF( ktra == jp_sal ) THEN 
+                DO jn = 2, nptr
+                   str_eiv(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                END DO
+             ENDIF
+         ENDIF
+         IF( cptr == 'vts' ) THEN
+             IF( ktra == jp_tem ) THEN 
+                DO jn = 2, nptr
+                    htr_vt(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                 END DO
+             ENDIF
+             IF( ktra == jp_sal ) THEN 
+                DO jn = 2, nptr
+                   str_vs(:,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+                END DO
+             ENDIF
+         ENDIF
+         !
+      ENDIF
+   END SUBROUTINE dia_ptr_ohst_components
+
 
    FUNCTION dia_ptr_alloc()
@@ -273,7 +615,11 @@
       ierr(:) = 0
       !
-      ALLOCATE( btmsk(jpi,jpj,nptr) ,           &
-         &      htr_adv(jpj) , str_adv(jpj) ,   &
-         &      htr_ldf(jpj) , str_ldf(jpj) , STAT=ierr(1)  )
+      ALLOCATE( btmsk(jpi,jpj,nptr) ,              &
+         &      htr_adv(jpj,nptr) , str_adv(jpj,nptr) ,   &
+         &      htr_eiv(jpj,nptr) , str_eiv(jpj,nptr) ,   &
+         &      htr_vt(jpj,nptr)  , str_vs(jpj,nptr)  ,   &
+         &      htr_ove(jpj,nptr) , str_ove(jpj,nptr) ,   &
+         &      htr_btr(jpj,nptr) , str_btr(jpj,nptr) ,   &
+         &      htr_ldf(jpj,nptr) , str_ldf(jpj,nptr) , STAT=ierr(1)  )
          !
       ALLOCATE( p_fval1d(jpj), p_fval2d(jpj,jpk), Stat=ierr(2))
@@ -402,5 +748,5 @@
 #endif
       !!--------------------------------------------------------------------
-      !
+     !
       p_fval => p_fval2d
 
@@ -434,4 +780,5 @@
 #endif
       !
+
    END FUNCTION ptr_sjk
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diawri.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diawri.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diawri.F90	(revision 9987)
@@ -39,4 +39,5 @@
    USE zdfmxl          ! mixed layer
    USE dianam          ! build name of file (routine)
+   USE zdftke          ! vertical physics: one-equation scheme 
    USE zdfddm          ! vertical  physics: double diffusion
    USE diahth          ! thermocline diagnostics
@@ -46,6 +47,6 @@
    USE iom
    USE ioipsl
-   USE dynspg_oce, ONLY: un_adv, vn_adv ! barotropic velocities     
-
+   USE dynspg_oce, ONLY: un_adv, vn_adv ! barotropic velocities    
+   USE insitu_tem, ONLY: insitu_t, theta2t
 #if defined key_lim2
    USE limwri_2 
@@ -145,15 +146,24 @@
       ENDIF
 
-      IF( .NOT.lk_vvl ) THEN
-         CALL iom_put( "e3t" , fse3t_n(:,:,:) )
-         CALL iom_put( "e3u" , fse3u_n(:,:,:) )
-         CALL iom_put( "e3v" , fse3v_n(:,:,:) )
-         CALL iom_put( "e3w" , fse3w_n(:,:,:) )
-      ENDIF
+      ! Output of initial vertical scale factor
+      CALL iom_put("e3t_0", e3t_0(:,:,:) )
+      CALL iom_put("e3u_0", e3t_0(:,:,:) )
+      CALL iom_put("e3v_0", e3t_0(:,:,:) )
+      !
+      CALL iom_put( "e3t" , fse3t_n(:,:,:) )
+      CALL iom_put( "e3u" , fse3u_n(:,:,:) )
+      CALL iom_put( "e3v" , fse3v_n(:,:,:) )
+      CALL iom_put( "e3w" , fse3w_n(:,:,:) )
+      IF( iom_use("e3tdef") )   &
+         CALL iom_put( "e3tdef"  , ( ( fse3t_n(:,:,:) - e3t_0(:,:,:) ) / e3t_0(:,:,:) * 100 * tmask(:,:,:) ) ** 2 )
+      CALL iom_put("tpt_dep", fsdept_n(:,:,:) )
+      CALL iom_put("wpt_dep", fsdepw_n(:,:,:) )
+
 
       CALL iom_put( "ssh" , sshn )                 ! sea surface height
-      if( iom_use('ssh2') )   CALL iom_put( "ssh2", sshn(:,:) * sshn(:,:) )   ! square of sea surface height
       
       CALL iom_put( "toce", tsn(:,:,:,jp_tem) )    ! 3D temperature
+      CALL theta2t ! in-situ temperature conversion
+      CALL iom_put( "tinsitu", insitu_t(:,:,:))    ! in-situ temperature
       CALL iom_put(  "sst", tsn(:,:,1,jp_tem) )    ! surface temperature
       IF ( iom_use("sbt") ) THEN
@@ -194,5 +204,5 @@
          CALL iom_put( "taubot", z2d )           
       ENDIF
-         
+      
       CALL iom_put( "uoce", un(:,:,:)         )    ! 3D i-current
       CALL iom_put(  "ssu", un(:,:,1)         )    ! surface i-current
@@ -242,5 +252,12 @@
       CALL iom_put( "avt" , avt                        )    ! T vert. eddy diff. coef.
       CALL iom_put( "avm" , avmu                       )    ! T vert. eddy visc. coef.
+      IF( lk_zdftke ) THEN   
+         CALL iom_put( "tke"      , en                               )    ! TKE budget: Turbulent Kinetic Energy   
+         CALL iom_put( "tke_niw"  , e_niw                            )    ! TKE budget: Near-inertial waves   
+      ENDIF 
       CALL iom_put( "avs" , fsavs(:,:,:)               )    ! S vert. eddy diff. coef. (useful only with key_zdfddm)
+                                                            ! Log of eddy diff coef
+      IF( iom_use('logavt') )   CALL iom_put( "logavt", LOG( MAX( 1.e-20_wp, avt  (:,:,:) ) ) )
+      IF( iom_use('logavs') )   CALL iom_put( "logavs", LOG( MAX( 1.e-20_wp, fsavs(:,:,:) ) ) )
 
       IF ( iom_use("sstgrad") .OR. iom_use("sstgrad2") ) THEN
@@ -307,11 +324,16 @@
          CALL iom_put( "eken", rke )           
       ENDIF
-         
-      IF( iom_use("u_masstr") .OR. iom_use("u_heattr") .OR. iom_use("u_salttr") ) THEN
+      !
+      CALL iom_put( "hdiv", hdivn )                  ! Horizontal divergence
+      !
+      IF( iom_use("u_masstr") .OR. iom_use("u_masstr_vint") .OR. iom_use("u_heattr") .OR. iom_use("u_salttr") ) THEN
          z3d(:,:,jpk) = 0.e0
+         z2d(:,:) = 0.e0
          DO jk = 1, jpkm1
             z3d(:,:,jk) = rau0 * un(:,:,jk) * e2u(:,:) * fse3u(:,:,jk) * umask(:,:,jk)
+            z2d(:,:) = z2d(:,:) + z3d(:,:,jk)
          END DO
          CALL iom_put( "u_masstr", z3d )                  ! mass transport in i-direction
+         CALL iom_put( "u_masstr_vint", z2d )             ! mass transport in i-direction vertical sum
       ENDIF
       
@@ -376,4 +398,34 @@
          CALL iom_put( "v_salttr", 0.5 * z2d )            !  heat transport in j-direction
       ENDIF
+
+      ! Vertical integral of temperature
+      IF( iom_use("tosmint") ) THEN
+         z2d(:,:)=0._wp
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z2d(ji,jj) = z2d(ji,jj) + rau0 * fse3t(ji,jj,jk) *  tsn(ji,jj,jk,jp_tem)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( z2d, 'T', -1. )
+         CALL iom_put( "tosmint", z2d ) 
+      ENDIF
+
+      ! Vertical integral of salinity
+      IF( iom_use("somint") ) THEN
+         z2d(:,:)=0._wp
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z2d(ji,jj) = z2d(ji,jj) + rau0 * fse3t(ji,jj,jk) * tsn(ji,jj,jk,jp_sal)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( z2d, 'T', -1. )
+         CALL iom_put( "somint", z2d ) 
+      ENDIF
+
+      CALL iom_put( "bn2", rn2 )  !Brunt-Vaisala buoyancy frequency (N^2)
       !
       CALL wrk_dealloc( jpi , jpj      , z2d )
@@ -438,7 +490,5 @@
       zdt = rdt
       IF( nacc == 1 ) zdt = rdtmin
-      IF( ln_mskland )   THEN   ;   clop = "only(x)"   ! put 1.e+20 on land (very expensive!!)
-      ELSE                      ;   clop = "x"         ! no use of the mask value (require less cpu time)
-      ENDIF
+      clop = "x"         ! no use of the mask value (require less cpu time, and otherwise the model crashes)
 #if defined key_diainstant
       zsto = nwrite * zdt
@@ -1020,4 +1070,6 @@
          CALL histdef( id_i, "vovvldep", "T point depth"         , "m"      ,   &   ! t-point depth
             &          jpi, jpj, nh_i, jpk, 1, jpk, nz_i, 32, clop, zsto, zout )
+         CALL histdef( id_i, "vovvle3t", "T point thickness"         , "m"      ,   &   ! t-point depth
+            &          jpi, jpj, nh_i, jpk, 1, jpk, nz_i, 32, clop, zsto, zout )
       END IF
 
@@ -1050,4 +1102,8 @@
       CALL histwrite( id_i, "sozotaux", kt, utau             , jpi*jpj    , idex )    ! i-wind stress
       CALL histwrite( id_i, "sometauy", kt, vtau             , jpi*jpj    , idex )    ! j-wind stress
+      IF( lk_vvl ) THEN
+         CALL histwrite( id_i, "vovvldep", kt, fsdept_n(:,:,:), jpi*jpj*jpk, idex )!  T-cell depth       
+         CALL histwrite( id_i, "vovvle3t", kt, fse3t_n (:,:,:), jpi*jpj*jpk, idex )!  T-cell thickness  
+      END IF
 
       ! 3. Close the file
@@ -1062,4 +1118,8 @@
       ENDIF
 #endif
+
+      IF (cdfile_name == "output.abort") THEN
+         CALL ctl_stop('MPPSTOP', 'NEMO abort from dia_wri_state')
+      END IF
        
 !     IF( nn_timing == 1 )   CALL timing_stop('dia_wri_state') ! not sure this works for routines not called in first timestep
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diawri_dimg.h90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diawri_dimg.h90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DIA/diawri_dimg.h90	(revision 9987)
@@ -112,5 +112,5 @@
     IF( inbsel >  jpk ) THEN
        IF(lwp) WRITE(numout,*)  ' STOP inbsel =',inbsel,' is larger than jpk=',jpk
-       STOP
+       CALL ctl_stop('STOP', 'NEMO aborted from dia_wri')
     ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/closea.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/closea.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/closea.F90	(revision 9987)
@@ -36,5 +36,5 @@
    PUBLIC clo_bat      ! routine called in domzgr module
 
-   INTEGER, PUBLIC, PARAMETER          ::   jpncs   = 4      !: number of closed sea
+   INTEGER, PUBLIC, PARAMETER          ::   jpncs   = 10      !: number of closed sea
    INTEGER, PUBLIC, DIMENSION(jpncs)   ::   ncstt            !: Type of closed sea
    INTEGER, PUBLIC, DIMENSION(jpncs)   ::   ncsi1, ncsj1     !: south-west closed sea limits (i,j)
@@ -155,16 +155,56 @@
             ncsi2(4)   = 76  ;  ncsj2(4)   = 61
             ncsir(4,1) = 84  ;  ncsjr(4,1) = 59 
-            !                                        ! =======================
-         CASE ( 025 )                                ! ORCA_R025 configuration
-            !                                        ! =======================
-            ncsnr(1)   = 1    ; ncstt(1)   = 0               ! Caspian + Aral sea
-            ncsi1(1)   = 1330 ; ncsj1(1)   = 645
-            ncsi2(1)   = 1400 ; ncsj2(1)   = 795
+            !                                        ! ================================
+         CASE ( 025 )                                ! ORCA_R025 extended configuration
+            !                                        ! ================================
+            ncsnr(1)   = 1    ; ncstt(1)   = 0               ! Caspian sea
+            ncsi1(1)   = 1330 ; ncsj1(1)   = 831
+            ncsi2(1)   = 1375 ; ncsj2(1)   = 981
             ncsir(1,1) = 1    ; ncsjr(1,1) = 1
             !                                        
-            ncsnr(2)   = 1    ; ncstt(2)   = 0               ! Azov Sea 
-            ncsi1(2)   = 1284 ; ncsj1(2)   = 722
-            ncsi2(2)   = 1304 ; ncsj2(2)   = 747
+            ncsnr(2)   = 1    ; ncstt(2)   = 0               ! Aral sea
+            ncsi1(2)   = 1376 ; ncsj1(2)   = 900
+            ncsi2(2)   = 1400 ; ncsj2(2)   = 981
             ncsir(2,1) = 1    ; ncsjr(2,1) = 1
+            !                                        
+            ncsnr(3)   = 1    ; ncstt(3)   = 0               ! Azov Sea 
+            ncsi1(3)   = 1284 ; ncsj1(3)   = 908
+            ncsi2(3)   = 1304 ; ncsj2(3)   = 933
+            ncsir(3,1) = 1    ; ncsjr(3,1) = 1
+            !
+            ncsnr(4)   = 1    ; ncstt(4)   = 0               ! Lake Superior  
+            ncsi1(4)   = 781  ; ncsj1(4)   = 904 
+            ncsi2(4)   = 815  ; ncsj2(4)   = 926 
+            ncsir(4,1) = 1    ; ncsjr(4,1) = 1 
+            ! 
+            ncsnr(5)   = 1    ; ncstt(5)   = 0               ! Lake Michigan
+            ncsi1(5)   = 795  ; ncsj1(5)   = 871             
+            ncsi2(5)   = 813  ; ncsj2(5)   = 905 
+            ncsir(5,1) = 1    ; ncsjr(5,1) = 1 
+            ! 
+            ncsnr(6)   = 1    ; ncstt(6)   = 0               ! Lake Huron part 1
+            ncsi1(6)   = 814  ; ncsj1(6)   = 882             
+            ncsi2(6)   = 825  ; ncsj2(6)   = 905 
+            ncsir(6,1) = 1    ; ncsjr(6,1) = 1 
+            ! 
+            ncsnr(7)   = 1    ; ncstt(7)   = 0               ! Lake Huron part 2
+            ncsi1(7)   = 826  ; ncsj1(7)   = 889             
+            ncsi2(7)   = 833  ; ncsj2(7)   = 905 
+            ncsir(7,1) = 1    ; ncsjr(7,1) = 1 
+            ! 
+            ncsnr(8)   = 1    ; ncstt(8)   = 0               ! Lake Erie
+            ncsi1(8)   = 816  ; ncsj1(8)   = 871             
+            ncsi2(8)   = 837  ; ncsj2(8)   = 881 
+            ncsir(8,1) = 1    ; ncsjr(8,1) = 1 
+            ! 
+            ncsnr(9)   = 1    ; ncstt(9)   = 0               ! Lake Ontario
+            ncsi1(9)   = 831  ; ncsj1(9)   = 882             
+            ncsi2(9)   = 847  ; ncsj2(9)   = 889 
+            ncsir(9,1) = 1    ; ncsjr(9,1) = 1 
+            ! 
+            ncsnr(10)   = 1    ; ncstt(10)   = 0               ! Lake Victoria  
+            ncsi1(10)   = 1274 ; ncsj1(10)   = 672 
+            ncsi2(10)   = 1289 ; ncsj2(10)   = 687 
+            ncsir(10,1) = 1    ; ncsjr(10,1) = 1 
             !
          END SELECT
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/daymod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/daymod.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/daymod.F90	(revision 9987)
@@ -73,4 +73,9 @@
       !!----------------------------------------------------------------------
       !
+      ! max number of seconds between each restart
+      IF( REAL( nitend - nit000 + 1 ) * rdt > REAL( HUGE( nsec1jan000 ) ) ) THEN
+         CALL ctl_stop( 'The number of seconds between each restart exceeds the integer 4 max value: 2^31-1. ',   &
+            &           'You must do a restart at higher frequency (or remove this stop and recompile the code in I8)' )
+      ENDIF
       ! all calendar staff is based on the fact that MOD( rday, rdttra(1) ) == 0
       IF( MOD( rday     , rdttra(1) ) /= 0. )   CALL ctl_stop( 'the time step must devide the number of second of in a day' )
@@ -238,9 +243,4 @@
                nday_year = 1
                nsec_year = ndt05
-               IF( nsec1jan000 >= 2 * (2**30 - nsecd * nyear_len(1) / 2 ) ) THEN   ! test integer 4 max value
-                  CALL ctl_stop( 'The number of seconds between Jan. 1st 00h of nit000 year and Jan. 1st 00h ',   &
-                     &           'of the current year is exceeding the INTEGER 4 max VALUE: 2^31-1 -> 68.09 years in seconds', &
-                     & 'You must do a restart at higher frequency (or remove this STOP and recompile everything in I8)' )
-               ENDIF
                nsec1jan000 = nsec1jan000 + nsecd * nyear_len(1)
                IF( nleapy == 1 )   CALL day_mth
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/dom_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/dom_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/dom_oce.F90	(revision 9987)
@@ -355,4 +355,7 @@
          &      gdept_0 (jpi,jpj,jpk) , e3t_0(jpi,jpj,jpk) , e3u_0 (jpi,jpj,jpk) ,                         &
          &      gdepw_0 (jpi,jpj,jpk) , e3w_0(jpi,jpj,jpk) , e3vw_0(jpi,jpj,jpk) , e3uw_0(jpi,jpj,jpk) , STAT=ierr(4) )
+
+      ! Initilaise key variables at risk of being intercepted before properly set up. 
+      e3t_0(:,:,:) = 0.0
          !
 #if defined key_vvl
@@ -368,4 +371,7 @@
          &      ehu_b    (jpi,jpj)    , ehv_b  (jpi,jpj),                                                     &
          &      ehur_b   (jpi,jpj)    , ehvr_b (jpi,jpj),                                  STAT=ierr(5) )                          
+
+      ! Initilaise key variables at risk of being intercepted before properly set up. 
+      e3t_n(:,:,:) = 0.0
 #endif
          !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domain.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domain.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domain.F90	(revision 9987)
@@ -136,5 +136,5 @@
       USE ioipsl
       NAMELIST/namrun/ cn_ocerst_indir, cn_ocerst_outdir, nn_stocklist, ln_rst_list,               &
-         &             nn_no   , cn_exp    , cn_ocerst_in, cn_ocerst_out, ln_rstart , nn_rstctl,   &
+         &             nn_no   , cn_exp    , cn_ocerst_in, cn_ocerst_out, ln_rstart , ln_rstdate, nn_rstctl,   &
          &             nn_it000, nn_itend  , nn_date0    , nn_leapy     , nn_istate , nn_stock ,   &
          &             nn_write, ln_dimgnnn, ln_mskland  , ln_cfmeta    , ln_clobber, nn_chunksz, nn_euler
@@ -173,5 +173,6 @@
          WRITE(numout,*) '      file prefix restart output      cn_ocerst_out= ', cn_ocerst_out
          WRITE(numout,*) '      restart output directory        cn_ocerst_outdir= ', cn_ocerst_outdir
-         WRITE(numout,*) '      restart logical                 ln_rstart  = ', ln_rstart
+         WRITE(numout,*) '      restart logical                 ln_rstart  = ' , ln_rstart
+         WRITE(numout,*) '      datestamping of restarts        ln_rstdate  = ', ln_rstdate
          WRITE(numout,*) '      start with forward time step    nn_euler   = ', nn_euler
          WRITE(numout,*) '      control of time step            nn_rstctl  = ', nn_rstctl
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domhgr.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domhgr.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domhgr.F90	(revision 9987)
@@ -169,40 +169,40 @@
             !
             ii0 = 282           ;   ii1 = 283        ! Gibraltar Strait (e2u = 20 km)
-            ij0 = 201 + isrow   ;   ij1 = 241 - isrow   ;   e2u( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  20.e3
+            ij0 = 241 - isrow   ;   ij1 = 241 - isrow   ;   e2u( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  20.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: Gibraltar : e2u reduced to 20 km'
 
             ii0 = 314           ;   ii1 = 315        ! Bhosporus Strait (e2u = 10 km)
-            ij0 = 208 + isrow   ;   ij1 = 248 - isrow   ;   e2u( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  10.e3
+            ij0 = 248 - isrow   ;   ij1 = 248 - isrow   ;   e2u( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  10.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: Bhosporus : e2u reduced to 10 km'
 
             ii0 =  44           ;   ii1 =  44        ! Lombok Strait (e1v = 13 km)
-            ij0 = 124 + isrow   ;   ij1 = 165 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  13.e3
+            ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  13.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: Lombok : e1v reduced to 10 km'
 
             ii0 =  48           ;   ii1 =  48        ! Sumba Strait (e1v = 8 km) [closed from bathy_11 on]
-            ij0 = 124 + isrow   ;   ij1 = 165 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  8.e3
+            ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  8.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: Sumba : e1v reduced to 8 km'
 
             ii0 =  53           ;   ii1 =  53        ! Ombai Strait (e1v = 13 km)
-            ij0 = 124 + isrow   ;   ij1 = 165 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 13.e3
+            ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 13.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: Ombai : e1v reduced to 13 km'
 
             ii0 =  56           ;   ii1 =  56        ! Timor Passage (e1v = 20 km)
-            ij0 = 124 + isrow   ;   ij1 = 145 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 20.e3
+            ij0 = 164 - isrow   ;   ij1 = 145 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 20.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: Timor Passage : e1v reduced to 20 km'
 
             ii0 =  55           ;   ii1 =  55        ! West Halmahera Strait (e1v = 30 km)
-            ij0 = 141 + isrow   ;   ij1 = 182 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 30.e3
+            ij0 = 181 - isrow   ;   ij1 = 182 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 30.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: W Halmahera : e1v reduced to 30 km'
 
             ii0 =  58           ;   ii1 =  58        ! East Halmahera Strait (e1v = 50 km)
-            ij0 = 141 + isrow   ;   ij1 = 182 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 50.e3
+            ij0 = 181 - isrow   ;   ij1 = 182 - isrow   ;   e1v( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) = 50.e3
             IF(lwp) WRITE(numout,*)
             IF(lwp) WRITE(numout,*) '             orca_r1: E Halmahera : e1v reduced to 50 km'
@@ -544,5 +544,6 @@
          IF ( cp_cfg == 'eel' .AND. jp_cfg == 6 ) THEN    ! for EEL6 configuration only
             IF( .NOT. Agrif_Root() ) THEN
-              zphi0 = ppgphi0 - FLOAT( Agrif_Parent(jpjglo)/2)*Agrif_Parent(ppe2_m) / (ra * rad)
+              zphi0 = ppgphi0 - FLOAT( Agrif_Parent(jpjglo)/2)*Agrif_Parent(ppe2_m)   & 
+                    &           / (ra * rad)
             ENDIF
          ENDIF
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/dommsk.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/dommsk.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/dommsk.F90	(revision 9987)
@@ -136,4 +136,5 @@
       INTEGER  ::   isrow                    ! index for ORCA1 starting row
       INTEGER , POINTER, DIMENSION(:,:) ::  imsk
+      REAL(wp) ::  zphi_drake_passage, zshlat_antarc
       REAL(wp), POINTER, DIMENSION(:,:) ::  zwf
       !!
@@ -413,35 +414,58 @@
          IF(lwp) WRITE(numout,*) '      Gibraltar '
          ii0 = 282           ;   ii1 = 283        ! Gibraltar Strait 
-         ij0 = 201 + isrow   ;   ij1 = 241 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+         ij0 = 241 - isrow   ;   ij1 = 241 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
 
          IF(lwp) WRITE(numout,*) '      Bhosporus '
          ii0 = 314           ;   ii1 = 315        ! Bhosporus Strait 
-         ij0 = 208 + isrow   ;   ij1 = 248 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+         ij0 = 248 - isrow   ;   ij1 = 248 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
 
          IF(lwp) WRITE(numout,*) '      Makassar (Top) '
          ii0 =  48           ;   ii1 =  48        ! Makassar Strait (Top) 
-         ij0 = 149 + isrow   ;   ij1 = 190 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
+         ij0 = 189 - isrow   ;   ij1 = 190 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
 
          IF(lwp) WRITE(numout,*) '      Lombok '
          ii0 =  44           ;   ii1 =  44        ! Lombok Strait 
-         ij0 = 124 + isrow   ;   ij1 = 165 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+         ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
 
          IF(lwp) WRITE(numout,*) '      Ombai '
          ii0 =  53           ;   ii1 =  53        ! Ombai Strait 
-         ij0 = 124 + isrow   ;   ij1 = 165 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+         ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
 
          IF(lwp) WRITE(numout,*) '      Timor Passage '
          ii0 =  56           ;   ii1 =  56        ! Timor Passage 
-         ij0 = 124 + isrow   ;   ij1 = 165 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+         ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
 
          IF(lwp) WRITE(numout,*) '      West Halmahera '
          ii0 =  58           ;   ii1 =  58        ! West Halmahera Strait 
-         ij0 = 141 + isrow   ;   ij1 = 182 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
+         ij0 = 181 - isrow   ;   ij1 = 182 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
 
          IF(lwp) WRITE(numout,*) '      East Halmahera '
          ii0 =  55           ;   ii1 =  55        ! East Halmahera Strait 
-         ij0 = 141 + isrow   ;   ij1 = 182 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
+         ij0 = 181 - isrow   ;   ij1 = 182 - isrow   ;   fmask( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
          !
       ENDIF
+      !
+      IF( cp_cfg == "orca" .AND. jp_cfg == 025 .AND. rn_shlat == 0.0 ) THEN   
+         !                                              ! ORCA_R025 configuration
+         !                                              ! Increased lateral friction on parts of Antarctic coastline
+         !                                              ! for increased stability
+         !                                              ! NB. This only works to do this here if we have free slip 
+         !                                              ! generally, so fmask is zero at coast points.
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   orca_r025: increase friction in following regions : '
+         IF(lwp) WRITE(numout,*) '      whole Antarctic coastline: partial slip shlat=1 '
+
+         zphi_drake_passage = -58.0_wp
+         zshlat_antarc = 1.0_wp
+         zwf(:,:) = fmask(:,:,1)         
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               IF( gphif(ji,jj) .lt. zphi_drake_passage .and. fmask(ji,jj,1) == 0._wp ) THEN
+                  fmask(ji,jj,:) = zshlat_antarc * MIN( 1._wp , MAX( zwf(ji+1,jj), zwf(ji,jj+1),   &
+                     &                                           zwf(ji-1,jj), zwf(ji,jj-1)  )  )
+               ENDIF
+            END DO
+         END DO
+      END IF
       !
       CALL lbc_lnk( fmask, 'F', 1._wp )      ! Lateral boundary conditions on fmask
@@ -526,5 +550,5 @@
       IF(lwp) WRITE(numout,*) 'dom_msk_nsa : noslip accurate boundary condition'
       IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   using Schchepetkin and O Brian scheme'
-      IF( lk_mpp )   CALL ctl_stop( ' mpp version is not yet implemented' )
+      IF( lk_mpp )   CALL ctl_stop('STOP', ' mpp version is not yet implemented' )
 
       ! mask for second order calculation of vorticity
@@ -548,5 +572,5 @@
          WRITE(numout,*) ' symetric boundary conditions need special'
          WRITE(numout,*) ' treatment not implemented. we stop.'
-         STOP
+         CALL ctl_stop('STOP', 'NEMO abort from dom_msk_nsa')
       ENDIF
       
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domvvl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domvvl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domvvl.F90	(revision 9987)
@@ -594,4 +594,5 @@
          IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   - interpolate scale factors and compute depths for next time step'
       ENDIF
+
       !
       ! Time filter and swap of scale factors
@@ -665,14 +666,4 @@
          ht(:,:) = ht(:,:) + fse3t_n(:,:,jk) * tmask(:,:,jk)
       END DO
-
-      ! Write outputs
-      ! =============
-      CALL iom_put(     "e3t" , fse3t_n  (:,:,:) )
-      CALL iom_put(     "e3u" , fse3u_n  (:,:,:) )
-      CALL iom_put(     "e3v" , fse3v_n  (:,:,:) )
-      CALL iom_put(     "e3w" , fse3w_n  (:,:,:) )
-      CALL iom_put( "tpt_dep" , fsde3w_n (:,:,:) )
-      IF( iom_use("e3tdef") )   &
-         CALL iom_put( "e3tdef"  , ( ( fse3t_n(:,:,:) - e3t_0(:,:,:) ) / e3t_0(:,:,:) * 100 * tmask(:,:,:) ) ** 2 )
 
       ! write restart file
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domwri.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domwri.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domwri.F90	(revision 9987)
@@ -215,4 +215,6 @@
          CALL iom_rstput( 0, 0, inum4, 'gdept_1d' , gdept_1d )  !    ! stretched system
          CALL iom_rstput( 0, 0, inum4, 'gdepw_1d' , gdepw_1d )
+         CALL iom_rstput( 0, 0, inum4, 'gdept_0', gdept_0, ktype = jp_r4 )     
+         CALL iom_rstput( 0, 0, inum4, 'gdepw_0', gdepw_0, ktype = jp_r4 )     
       ENDIF
       
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domzgr.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domzgr.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/domzgr.F90	(revision 9987)
@@ -219,7 +219,13 @@
          &  ppsur == pp_to_be_computed           ) THEN
          !
+#if defined key_agrif
+         za1  = (  ppdzmin - pphmax / FLOAT(jpkdta-1)  )                                                   &
+            & / ( TANH((1-ppkth)/ppacr) - ppacr/FLOAT(jpkdta-1) * (  LOG( COSH( (jpkdta - ppkth) / ppacr) )&
+            &                                                      - LOG( COSH( ( 1  - ppkth) / ppacr) )  )  )
+#else
          za1  = (  ppdzmin - pphmax / FLOAT(jpkm1)  )                                                      &
             & / ( TANH((1-ppkth)/ppacr) - ppacr/FLOAT(jpk-1) * (  LOG( COSH( (jpk - ppkth) / ppacr) )      &
             &                                                   - LOG( COSH( ( 1  - ppkth) / ppacr) )  )  )
+#endif
          za0  = ppdzmin - za1 *              TANH( (1-ppkth) / ppacr )
          zsur =   - za0 - za1 * ppacr * LOG( COSH( (1-ppkth) / ppacr )  )
@@ -236,5 +242,9 @@
               WRITE(numout,*) '            Uniform grid with ',jpk-1,' layers'
               WRITE(numout,*) '            Total depth    :', zhmax
+#if defined key_agrif
+              WRITE(numout,*) '            Layer thickness:', zhmax/(jpkdta-1)
+#else
               WRITE(numout,*) '            Layer thickness:', zhmax/(jpk-1)
+#endif
          ELSE
             IF( ppa1 == 0._wp .AND. ppa0 == 0._wp .AND. ppsur == 0._wp ) THEN
@@ -260,6 +270,10 @@
       ! Reference z-coordinate (depth - scale factor at T- and W-points)
       ! ======================
-      IF( ppkth == 0._wp ) THEN            !  uniform vertical grid       
+      IF( ppkth == 0._wp ) THEN            !  uniform vertical grid 
+#if defined key_agrif
+         za1 = zhmax / FLOAT(jpkdta-1) 
+#else
          za1 = zhmax / FLOAT(jpk-1) 
+#endif
          DO jk = 1, jpk
             zw = FLOAT( jk )
@@ -1870,7 +1884,8 @@
              iim1 = MAX( ji-1, 1 )
              ijm1 = MAX( jj-1, 1 )
-             IF( (bathy(iip1,jj) + bathy(iim1,jj) + bathy(ji,ijp1) + bathy(ji,ijm1) +              &
-        &         bathy(iip1,ijp1) + bathy(iim1,ijm1) + bathy(iip1,ijp1) + bathy(iim1,ijm1)) > 0._wp ) THEN
-               zenv(ji,jj) = rn_sbot_min
+             IF( ( + bathy(iim1,ijp1) + bathy(ji,ijp1) + bathy(iip1,ijp1)  &
+                &  + bathy(iim1,jj  )                  + bathy(iip1,jj  )  &
+                &  + bathy(iim1,ijm1) + bathy(ji,ijm1) + bathy(iip1,ijp1)  ) > 0._wp ) THEN
+                zenv(ji,jj) = rn_sbot_min
              ENDIF
            ENDIF
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/phycst.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/phycst.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DOM/phycst.F90	(revision 9987)
@@ -68,5 +68,9 @@
    REAL(wp), PUBLIC ::   rcdsn    =    0.31_wp       !: thermal conductivity of snow
    REAL(wp), PUBLIC ::   cpic     = 2067.0_wp        !: specific heat for ice 
+#if defined key_cice
+   REAL(wp), PUBLIC ::   lsub     =    2.835e+6_wp   !: pure ice latent heat of sublimation                   [J/kg]
+#else
    REAL(wp), PUBLIC ::   lsub     =    2.834e+6_wp   !: pure ice latent heat of sublimation                   [J/kg]
+#endif
    REAL(wp), PUBLIC ::   lfus     =    0.334e+6_wp   !: latent heat of fusion of fresh ice                    [J/kg]
    REAL(wp), PUBLIC ::   tmut     =    0.054_wp      !: decrease of seawater meltpoint with salinity
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/divcur.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/divcur.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/divcur.F90	(revision 9987)
@@ -97,6 +97,6 @@
       IF( nn_timing == 1 )  CALL timing_start('div_cur')
       !
-      CALL wrk_alloc( jpi  , jpj+2, zwu               )
-      CALL wrk_alloc( jpi+4, jpj  , zwv, kistart = -1 )
+      CALL wrk_alloc( jpi  , jpj+2, zwu  )
+      CALL wrk_alloc( jpi+2, jpj  , zwv  )
       !
       IF( kt == nit000 ) THEN
@@ -236,6 +236,6 @@
       CALL lbc_lnk( hdivn, 'T', 1. )   ;   CALL lbc_lnk( rotn , 'F', 1. )    ! lateral boundary cond. (no sign change)
       !
-      CALL wrk_dealloc( jpi  , jpj+2, zwu               )
-      CALL wrk_dealloc( jpi+4, jpj  , zwv, kistart = -1 )
+      CALL wrk_dealloc( jpi  , jpj+2, zwu )
+      CALL wrk_dealloc( jpi+2, jpj  , zwv )
       !
       IF( nn_timing == 1 )  CALL timing_stop('div_cur')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynhpg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynhpg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynhpg.F90	(revision 9987)
@@ -44,4 +44,5 @@
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
+   USE biaspar         ! bias correction variables
 
    IMPLICIT NONE
@@ -84,4 +85,7 @@
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrdu, ztrdv
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   z_rhd_st  ! tmp density storage for pressure corr
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     ::   z_gru_st  ! tmp ua trends storage for pressure corr
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     ::   z_grv_st  ! tmp va trends storage for pressure corr
       !!----------------------------------------------------------------------
       !
@@ -94,4 +98,20 @@
       ENDIF
       !
+      IF ( ln_bias .AND. ln_bias_pc_app ) THEN
+
+         !Allocate space for tempory variables
+         ALLOCATE( z_rhd_st(jpi,jpj,jpk), &
+            &      z_gru_st(jpi,jpj),     &
+            &      z_grv_st(jpi,jpj)      )
+
+         z_rhd_st(:,:,:) = rhd(:,:,:)     ! store orig density 
+         rhd(:,:,:)      = rhd_pc(:,:,:)  ! use pressure corrected density
+         z_gru_st(:,:)   = gru(:,:)
+         gru(:,:)        = gru_pc(:,:)
+         z_grv_st(:,:)   = grv(:,:)
+         grv(:,:)        = grv_pc(:,:)
+
+      ENDIF
+
       SELECT CASE ( nhpg )      ! Hydrostatic pressure gradient computation
       CASE (  0 )   ;   CALL hpg_zco    ( kt )      ! z-coordinate
@@ -112,4 +132,18 @@
       IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' hpg  - Ua: ', mask1=umask,   &
          &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      IF ( ln_bias .AND. ln_bias_pc_app )  THEN
+         IF(lwp) THEN 
+         WRITE(numout,*) " ! restore original density"
+         ENDIF
+         rhd(:,:,:) = z_rhd_st(:,:,:)     ! restore original density
+         gru(:,:)   = z_gru_st(:,:)
+         grv(:,:)   = z_grv_st(:,:)
+
+         !Deallocate tempory variables
+         DEALLOCATE( z_rhd_st,     &
+            &        z_gru_st,     &
+            &        z_grv_st      )
+      ENDIF
       !
       IF( nn_timing == 1 )  CALL timing_stop('dyn_hpg')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilapg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilapg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilapg.F90	(revision 9987)
@@ -465,7 +465,9 @@
             END DO
          ELSE
-            IF(lwp)WRITE(numout,*) ' ldfguv: kahm= 1 or 2, here =', kahm
-            IF(lwp)WRITE(numout,*) '         We stop'
-            STOP 'ldfguv'
+            
+            WRITE(numout,*) ' ldfguv: kahm= 1 or 2, here =', kahm
+            WRITE(numout,*) '         We stop'
+            CALL ctl_stop('STOP', 'ldfguv: Unexpected kahm value')
+
          ENDIF
          !                                             ! ===============
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynnxt.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynnxt.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynnxt.F90	(revision 9987)
@@ -266,6 +266,18 @@
                ! Add volume filter correction: compatibility with tracer advection scheme
                ! => time filter + conservation correction (only at the first level)
-               fse3t_b(:,:,1) = fse3t_b(:,:,1) - atfp * rdt * r1_rau0 * ( emp_b(:,:) - emp(:,:) &
-                              &                                          -rnf_b(:,:) + rnf(:,:) ) * tmask(:,:,1)
+               IF ( nn_isf == 0) THEN   ! if no ice shelf melting
+                  fse3t_b(:,:,1) = fse3t_b(:,:,1) - atfp * rdt * r1_rau0 * ( emp_b(:,:) - emp(:,:) &
+                                 &                                          -rnf_b(:,:) + rnf(:,:) ) * tmask(:,:,1)
+               ELSE                     ! if ice shelf melting
+                  DO jj = 1,jpj
+                     DO ji = 1,jpi
+                        jk = mikt(ji,jj)
+                        fse3t_b(ji,jj,jk) = fse3t_b(ji,jj,jk) - atfp * rdt * r1_rau0                       &
+                                          &                          * ( (emp_b(ji,jj)    - emp(ji,jj)   ) &
+                                          &                            - (rnf_b(ji,jj)    - rnf(ji,jj)   ) &
+                                          &                            + (fwfisf_b(ji,jj) - fwfisf(ji,jj)) ) * tmask(ji,jj,jk)
+                     END DO
+                  END DO
+               END IF
             ENDIF
             !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_flt.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_flt.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_flt.F90	(revision 9987)
@@ -166,4 +166,7 @@
             !
          ENDIF
+        IF( l_trddyn )   THEN                      ! Put here so code doesn't crash when doing KE trend but needs to be done properly
+            CALL wrk_alloc( jpi, jpj, jpk, ztrdu, ztrdv )
+         ENDIF
          !
       ELSE                       ! fixed volume  (add the surface pressure gradient + unweighted time stepping)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_ts.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_ts.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_ts.F90	(revision 9987)
@@ -187,5 +187,5 @@
       !
                                      	                ! time offset in steps for bdy data update
-      IF (.NOT.ln_bt_fw) THEN ; noffset=-2*nn_baro ; ELSE ;  noffset = 0 ; ENDIF
+      IF (.NOT.ln_bt_fw) THEN ; noffset=-nn_baro ; ELSE ;  noffset = 0 ; ENDIF
       !
       IF( kt == nit000 ) THEN             	!* initialisation
@@ -454,8 +454,8 @@
       !                                         ! Surface net water flux and rivers
       IF (ln_bt_fw) THEN
-         zssh_frc(:,:) = zraur * ( emp(:,:) - rnf(:,:) + rdivisf * fwfisf(:,:) )
+         zssh_frc(:,:) = zraur * ( emp(:,:) - rnf(:,:) + fwfisf(:,:) )
       ELSE
          zssh_frc(:,:) = zraur * z1_2 * (  emp(:,:) + emp_b(:,:) - rnf(:,:) - rnf_b(:,:)   &
-                &                        + rdivisf * ( fwfisf(:,:) + fwfisf_b(:,:) )       )
+                &                        + fwfisf(:,:) + fwfisf_b(:,:)                     )
       ENDIF
 #if defined key_asminc
@@ -523,6 +523,6 @@
          ! Update only tidal forcing at open boundaries
 #if defined key_tide
-         IF ( lk_bdy .AND. lk_tide )      CALL bdy_dta_tides( kt, kit=jn, time_offset=(noffset+1) )
-         IF ( ln_tide_pot .AND. lk_tide ) CALL upd_tide( kt, kit=jn, koffset=noffset )
+         IF ( lk_bdy .AND. lk_tide ) CALL bdy_dta_tides( kt, kit=jn, time_offset=(noffset+1) )
+         IF ( ln_tide_pot .AND. lk_tide ) CALL upd_tide( kt, kit=jn, time_offset=noffset )
 #endif
          !
@@ -900,6 +900,5 @@
 #if defined key_agrif
       ! Save time integrated fluxes during child grid integration
-      ! (used to update coarse grid transports)
-      ! Useless with 2nd order momentum schemes
+      ! (used to update coarse grid transports at next time step)
       !
       IF ( (.NOT.Agrif_Root()).AND.(ln_bt_fw) ) THEN
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynvor.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynvor.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynvor.F90	(revision 9987)
@@ -38,4 +38,5 @@
    USE wrk_nemo       ! Memory Allocation
    USE timing         ! Timing
+   USE lib_fortran
 
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf_imp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf_imp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf_imp.F90	(revision 9987)
@@ -323,9 +323,9 @@
             ze3va =  ( 1._wp - r_vvl ) * fse3v_n(ji,jj,1) + r_vvl   * fse3v_a(ji,jj,1) 
             va(ji,jj,1) = va(ji,jj,1) + p2dt * 0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
-               &                                      / ( ze3va * rau0 ) 
+               &                                      / ( ze3va * rau0 ) * vmask(ji,jj,1)
 #else
             va(ji,jj,1) = vb(ji,jj,1) &
                &                   + p2dt *(va(ji,jj,1) +  0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
-               &                                                       / ( fse3v(ji,jj,1) * rau0     )  )
+               &                                      / ( fse3v(ji,jj,1) * rau0     ) * vmask(ji,jj,1) )
 #endif
          END DO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/sshwzv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/sshwzv.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/DYN/sshwzv.F90	(revision 9987)
@@ -31,5 +31,4 @@
    USE bdydyn2d        ! bdy_ssh routine
 #if defined key_agrif
-   USE agrif_opa_update
    USE agrif_opa_interp
 #endif
@@ -75,5 +74,5 @@
       INTEGER, INTENT(in) ::   kt                      ! time step
       ! 
-      INTEGER             ::   jk                      ! dummy loop indice
+      INTEGER             ::   jk                      ! dummy loop indices
       REAL(wp)            ::   z2dt, z1_rau0           ! local scalars
       !!----------------------------------------------------------------------
@@ -95,4 +94,20 @@
       z2dt = 2._wp * rdt                              ! set time step size (Euler/Leapfrog)
       IF( neuler == 0 .AND. kt == nit000 )   z2dt = rdt
+
+
+#if defined key_asminc
+      !                                                ! Include the IAU weighted SSH increment
+      IF( lk_asminc .AND. ln_sshinc .AND. ln_asmiau ) THEN
+         CALL ssh_asm_inc( kt )
+#if defined key_vvl
+! Don't directly adjust ssh but change hdivn at all levels instead
+! In trasbc also add in the heat and salt content associated with these changes at each level  
+        DO jk = 1, jpkm1                                 
+                 hdivn(:,:,jk) = hdivn(:,:,jk) - ( ssh_iau(:,:) / ( ht_0(:,:) + 1.0 - ssmask(:,:) ) ) * ( e3t_0(:,:,jk) / fse3t_n(:,:,jk) ) * tmask(:,:,jk) 
+        END DO
+      ENDIF
+#endif
+#endif
+
 
       !                                           !------------------------------!
@@ -124,11 +139,4 @@
 #endif
 
-#if defined key_asminc
-      !                                                ! Include the IAU weighted SSH increment
-      IF( lk_asminc .AND. ln_sshinc .AND. ln_asmiau ) THEN
-         CALL ssh_asm_inc( kt )
-         ssha(:,:) = ssha(:,:) + z2dt * ssh_iau(:,:)
-      ENDIF
-#endif
 
       !                                           !------------------------------!
@@ -268,12 +276,9 @@
       ELSE                                         !** Leap-Frog time-stepping: Asselin filter + swap
          sshb(:,:) = sshn(:,:) + atfp * ( sshb(:,:) - 2 * sshn(:,:) + ssha(:,:) )     ! before <-- now filtered
-         IF( lk_vvl ) sshb(:,:) = sshb(:,:) - atfp * rdt / rau0 * ( emp_b(:,:) - emp(:,:) - rnf_b(:,:) + rnf(:,:) ) * ssmask(:,:)
+         IF( lk_vvl ) sshb(:,:) = sshb(:,:) - atfp * rdt / rau0 * ( emp_b(:,:)    - emp(:,:)    &
+                                &                                 - rnf_b(:,:)    + rnf(:,:)    &
+                                &                                 + fwfisf_b(:,:) - fwfisf(:,:) ) * ssmask(:,:)
          sshn(:,:) = ssha(:,:)                           ! now <-- after
       ENDIF
-      !
-      ! Update velocity at AGRIF zoom boundaries
-#if defined key_agrif
-      IF ( .NOT.Agrif_Root() ) CALL Agrif_Update_Dyn( kt )
-#endif
       !
       IF(ln_ctl)   CALL prt_ctl( tab2d_1=sshb, clinfo1=' sshb  - : ', mask1=tmask, ovlap=1 )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbclv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbclv.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbclv.F90	(revision 9987)
@@ -25,4 +25,8 @@
    USE icbutl         ! iceberg utility routines
 
+   USE sbc_oce        ! for icesheet freshwater input variables
+   USE in_out_manager
+   USE iom
+
    IMPLICIT NONE
    PRIVATE
@@ -48,4 +52,5 @@
       !
       REAL(wp)                        :: zcalving_used, zdist, zfact
+      REAL(wp)                        :: zgreenland_calving_sum, zantarctica_calving_sum
       INTEGER                         :: jn, ji, jj                    ! loop counters
       INTEGER                         :: imx                           ! temporary integer for max berg class
@@ -59,4 +64,41 @@
       zfact = ( (1000._wp)**3 / ( NINT(rday) * nyear_len(1) ) ) * 850._wp
       berg_grid%calving(:,:) = src_calving(:,:) * tmask_i(:,:) * zfact
+
+      IF( lk_oasis) THEN
+      ! nn_coupled_iceshelf_fluxes uninitialised unless lk_oasis=true
+      IF( nn_coupled_iceshelf_fluxes .gt. 0 ) THEN
+
+        ! Adjust total calving rates so that sum of iceberg calving and iceshelf melting in the northern
+        ! and southern hemispheres equals rate of increase of mass of greenland and antarctic ice sheets
+        ! to preserve total freshwater conservation in coupled models without an active ice sheet model.
+
+         zgreenland_calving_sum = SUM( berg_grid%calving(:,:) * greenland_icesheet_mask(:,:) )
+         IF( lk_mpp ) CALL mpp_sum( zgreenland_calving_sum )
+         WHERE( greenland_icesheet_mask(:,:) == 1.0 )                                                                                 &
+        &    berg_grid%calving(:,:) = berg_grid%calving(:,:) * greenland_icesheet_mass_rate_of_change * rn_greenland_calving_fraction &
+        &                                     / ( zgreenland_calving_sum + 1.0e-10_wp )
+
+         ! check
+         IF(lwp) WRITE(numout, *) 'Greenland iceberg calving climatology (kg/s) : ',zgreenland_calving_sum
+         zgreenland_calving_sum = SUM( berg_grid%calving(:,:) * greenland_icesheet_mask(:,:) )
+         IF( lk_mpp ) CALL mpp_sum( zgreenland_calving_sum )
+         IF(lwp) WRITE(numout, *) 'Greenland iceberg calving adjusted value (kg/s) : ',zgreenland_calving_sum
+
+         zantarctica_calving_sum = SUM( berg_grid%calving(:,:) * antarctica_icesheet_mask(:,:) )
+         IF( lk_mpp ) CALL mpp_sum( zantarctica_calving_sum )
+         WHERE( antarctica_icesheet_mask(:,:) == 1.0 )                                                                              &
+         berg_grid%calving(:,:) = berg_grid%calving(:,:) * antarctica_icesheet_mass_rate_of_change * rn_antarctica_calving_fraction &
+        &                           / ( zantarctica_calving_sum + 1.0e-10_wp )
+ 
+         ! check
+         IF(lwp) WRITE(numout, *) 'Antarctica iceberg calving climatology (kg/s) : ',zantarctica_calving_sum
+         zantarctica_calving_sum = SUM( berg_grid%calving(:,:) * antarctica_icesheet_mask(:,:) )
+         IF( lk_mpp ) CALL mpp_sum( zantarctica_calving_sum )
+         IF(lwp) WRITE(numout, *) 'Antarctica iceberg calving adjusted value (kg/s) : ',zantarctica_calving_sum
+
+      ENDIF
+      ENDIF
+   
+      CALL iom_put( 'berg_calve', berg_grid%calving(:,:) )
 
       ! Heat in units of W/m2, and mask (just in case)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbdia.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbdia.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbdia.F90	(revision 9987)
@@ -371,4 +371,6 @@
       IF( .NOT. ln_bergdia )   RETURN            !!gm useless iom will control whether it is output or not
       !
+      CALL iom_put( "berg_total_melt"      , berg_grid%floating_melt(:,:)   )   ! Total melt flux to ocean      [kg/m2/s]
+      CALL iom_put( "berg_total_heat_flux" , berg_grid%calving_hflx(:,:)    )   ! Total iceberg-ocean heat flux [W/m2]
       CALL iom_put( "berg_melt"        , berg_melt   (:,:)   )   ! Melt rate of icebergs                     [kg/m2/s]
       CALL iom_put( "berg_buoy_melt"   , buoy_melt   (:,:)   )   ! Buoyancy component of iceberg melt rate   [kg/m2/s]
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbini.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbini.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbini.F90	(revision 9987)
@@ -120,5 +120,5 @@
       ! first entry with narea for this processor is left hand interior index
       ! last  entry                               is right hand interior index
-      jj = jpj/2
+      jj = nlcj/2
       nicbdi = -1
       nicbei = -1
@@ -136,5 +136,5 @@
       !
       ! repeat for j direction
-      ji = jpi/2
+      ji = nlci/2
       nicbdj = -1
       nicbej = -1
@@ -153,9 +153,9 @@
       ! special for east-west boundary exchange we save the destination index
       i1 = MAX( nicbdi-1, 1)
-      i3 = INT( src_calving(i1,jpj/2) )
+      i3 = INT( src_calving(i1,nlcj/2) )
       jj = INT( i3/nicbpack )
       ricb_left = REAL( i3 - nicbpack*jj, wp )
       i1 = MIN( nicbei+1, jpi )
-      i3 = INT( src_calving(i1,jpj/2) )
+      i3 = INT( src_calving(i1,nlcj/2) )
       jj = INT( i3/nicbpack )
       ricb_right = REAL( i3 - nicbpack*jj, wp )
@@ -196,5 +196,5 @@
          WRITE(numicb,*) 'berg left       ', ricb_left
          WRITE(numicb,*) 'berg right      ', ricb_right
-         jj = jpj/2
+         jj = nlcj/2
          WRITE(numicb,*) "central j line:"
          WRITE(numicb,*) "i processor"
@@ -202,5 +202,5 @@
          WRITE(numicb,*) "i point"
          WRITE(numicb,*) (INT(src_calving(ji,jj)), ji=1,jpi)
-         ji = jpi/2
+         ji = nlci/2
          WRITE(numicb,*) "central i line:"
          WRITE(numicb,*) "j processor"
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbrst.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbrst.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbrst.F90	(revision 9987)
@@ -12,4 +12,6 @@
    !!            -    !                            Currently needs a fixed processor
    !!            -    !                            layout between restarts
+   !!            -    !  2015-11  Dave Storkey     Convert icb_rst_read to use IOM so can
+   !!                                              read single restart files
    !!----------------------------------------------------------------------
    !!----------------------------------------------------------------------
@@ -18,8 +20,11 @@
    !!----------------------------------------------------------------------
    USE par_oce        ! NEMO parameters
+   USE phycst         ! for rday
    USE dom_oce        ! NEMO domain
    USE in_out_manager ! NEMO IO routines
+   USE ioipsl, ONLY : ju2ymds    ! for calendar
    USE lib_mpp        ! NEMO MPI library, lk_mpp in particular
    USE netcdf         ! netcdf routines for IO
+   USE iom
    USE icb_oce        ! define iceberg arrays
    USE icbutl         ! iceberg utility routines
@@ -57,10 +62,6 @@
       INTEGER                      ::   idim, ivar, iatt
       INTEGER                      ::   jn, iunlim_dim, ibergs_in_file
-      INTEGER                      ::   iclass
-      INTEGER, DIMENSION(1)        ::   istrt, ilngth, idata
-      INTEGER, DIMENSION(2)        ::   istrt2, ilngth2
-      INTEGER, DIMENSION(nkounts)  ::   idata2
-      REAL(wp), DIMENSION(1)       ::   zdata                                         ! need 1d array to read in with
-                                                                                            ! start and count arrays
+      INTEGER                      ::   ii,ij,iclass
+      REAL(wp), DIMENSION(nkounts) ::   zdata      
       LOGICAL                      ::   ll_found_restart
       CHARACTER(len=256)           ::   cl_path
@@ -71,138 +72,62 @@
       !!----------------------------------------------------------------------
 
-      ! Find a restart file. Assume iceberg restarts in same directory as ocean restarts. 
+      ! Find a restart file. Assume iceberg restarts in same directory as ocean restarts
+      ! and are called TRIM(cn_ocerst)//'_icebergs'
       cl_path = TRIM(cn_ocerst_indir)
       IF( cl_path(LEN_TRIM(cl_path):) /= '/' ) cl_path = TRIM(cl_path) // '/'
-      cl_filename = ' '
-      IF ( lk_mpp ) THEN
-         cl_filename = ' '
-         WRITE( cl_filename, '("restart_icebergs_",I4.4,".nc")' ) narea-1
-         INQUIRE( file=TRIM(cl_path)//TRIM(cl_filename), exist=ll_found_restart )
-      ELSE
-         cl_filename = 'restart_icebergs.nc'
-         INQUIRE( file=TRIM(cl_path)//TRIM(cl_filename), exist=ll_found_restart )
-      ENDIF
-
-      IF ( .NOT. ll_found_restart) THEN                     ! only do the following if a file was found
-         CALL ctl_stop('icebergs: no restart file found')
-      ENDIF
-
-      IF (nn_verbose_level >= 0 .AND. lwp)  &
-         WRITE(numout,'(2a)') 'icebergs, read_restart_bergs: found restart file = ',TRIM(cl_path)//TRIM(cl_filename)
-
-      nret = NF90_OPEN(TRIM(cl_path)//TRIM(cl_filename), NF90_NOWRITE, ncid)
-      IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, read_restart_bergs: nf_open failed')
-
-      nret = nf90_inquire(ncid, idim, ivar, iatt, iunlim_dim)
-      IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, read_restart_bergs: nf_inquire failed')
-
-      IF( iunlim_dim .NE. -1) THEN
-
-         nret = nf90_inquire_dimension(ncid, iunlim_dim, cl_dname, ibergs_in_file)
-         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, read_restart_bergs: nf_inq_dimlen failed')
-
-         nret = NF90_INQ_VARID(ncid, 'number', numberid)
-         nret = NF90_INQ_VARID(ncid, 'mass_scaling', nscaling_id)
-         nret = NF90_INQ_VARID(ncid, 'xi', nxid)
-         nret = NF90_INQ_VARID(ncid, 'yj', nyid)
-         nret = NF90_INQ_VARID(ncid, 'lon', nlonid)
-         nret = NF90_INQ_VARID(ncid, 'lat', nlatid)
-         nret = NF90_INQ_VARID(ncid, 'uvel', nuvelid)
-         nret = NF90_INQ_VARID(ncid, 'vvel', nvvelid)
-         nret = NF90_INQ_VARID(ncid, 'mass', nmassid)
-         nret = NF90_INQ_VARID(ncid, 'thickness', nthicknessid)
-         nret = NF90_INQ_VARID(ncid, 'width', nwidthid)
-         nret = NF90_INQ_VARID(ncid, 'length', nlengthid)
-         nret = NF90_INQ_VARID(ncid, 'year', nyearid)
-         nret = NF90_INQ_VARID(ncid, 'day', ndayid)
-         nret = NF90_INQ_VARID(ncid, 'mass_of_bits', nmass_of_bits_id)
-         nret = NF90_INQ_VARID(ncid, 'heat_density', nheat_density_id)
-
-         ilngth(1) = 1
-         istrt2(1) = 1
-         ilngth2(1) = nkounts
-         ilngth2(2) = 1
-         DO jn=1, ibergs_in_file
-
-            istrt(1) = jn
-            istrt2(2) = jn
-
-            nret = NF90_GET_VAR(ncid, numberid, idata2, istrt2, ilngth2 )
-            localberg%number(:) = idata2(:)
-
-            nret = NF90_GET_VAR(ncid, nscaling_id, zdata, istrt, ilngth )
-            localberg%mass_scaling = zdata(1)
-
-            nret = NF90_GET_VAR(ncid, nlonid, zdata, istrt, ilngth)
-            localpt%lon = zdata(1)
-            nret = NF90_GET_VAR(ncid, nlatid, zdata, istrt, ilngth)
-            localpt%lat = zdata(1)
-            IF (nn_verbose_level >= 2 .AND. lwp) THEN
-               WRITE(numout,'(a,i5,a,2f10.4,a,i5)') 'icebergs, read_restart_bergs: berg ',jn,' is at ', &
-                                              localpt%lon,localpt%lat,' on PE ',narea-1
+      cl_filename = TRIM(cn_ocerst_in)//'_icebergs'
+      CALL iom_open( TRIM(cl_path)//cl_filename, ncid )
+
+      IF( iom_file(ncid)%iduld .GE. 0) THEN
+
+         ibergs_in_file = iom_file(ncid)%lenuld
+         DO jn = 1,ibergs_in_file
+
+            ! iom_get treats the unlimited dimension as time. Here the unlimited dimension 
+            ! is the iceberg index, but we can still use the ktime keyword to get the iceberg we want. 
+
+            CALL iom_get( ncid, 'xi'     ,localpt%xi  , ktime=jn )
+            CALL iom_get( ncid, 'yj'     ,localpt%yj  , ktime=jn )
+
+            ii = INT( localpt%xi + 0.5 )
+            ij = INT( localpt%yj + 0.5 )
+            ! Only proceed if this iceberg is on the local processor (excluding halos).
+            IF ( ii .GE. nldi+nimpp-1 .AND. ii .LE. nlei+nimpp-1 .AND. &
+           &     ij .GE. nldj+njmpp-1 .AND. ij .LE. nlej+njmpp-1 ) THEN           
+
+               CALL iom_get( ncid, jpdom_unknown, 'number'       , zdata(:) , ktime=jn, kstart=(/1/), kcount=(/nkounts/) )
+               localberg%number(:) = INT(zdata(:))
+               CALL iom_get( ncid, 'mass_scaling' , localberg%mass_scaling, ktime=jn )
+               CALL iom_get( ncid, 'lon'          , localpt%lon           , ktime=jn )
+               CALL iom_get( ncid, 'lat'          , localpt%lat           , ktime=jn )
+               CALL iom_get( ncid, 'uvel'         , localpt%uvel          , ktime=jn )
+               CALL iom_get( ncid, 'vvel'         , localpt%vvel          , ktime=jn )
+               CALL iom_get( ncid, 'mass'         , localpt%mass          , ktime=jn )
+               CALL iom_get( ncid, 'thickness'    , localpt%thickness     , ktime=jn )
+               CALL iom_get( ncid, 'width'        , localpt%width         , ktime=jn )
+               CALL iom_get( ncid, 'length'       , localpt%length        , ktime=jn )
+               CALL iom_get( ncid, 'year'         , zdata(1)              , ktime=jn )
+               localpt%year = INT(zdata(1))
+               CALL iom_get( ncid, 'day'          , localpt%day           , ktime=jn )
+               CALL iom_get( ncid, 'mass_of_bits' , localpt%mass_of_bits  , ktime=jn )
+               CALL iom_get( ncid, 'heat_density' , localpt%heat_density  , ktime=jn )
+
+               !
+               CALL icb_utl_add( localberg, localpt )
+
             ENDIF
-            nret = NF90_GET_VAR(ncid, nxid, zdata, istrt, ilngth)
-            localpt%xi = zdata(1)
-            nret = NF90_GET_VAR(ncid, nyid, zdata, istrt, ilngth)
-            localpt%yj = zdata(1)
-            nret = NF90_GET_VAR(ncid, nuvelid, zdata, istrt, ilngth )
-            localpt%uvel = zdata(1)
-            nret = NF90_GET_VAR(ncid, nvvelid, zdata, istrt, ilngth )
-            localpt%vvel = zdata(1)
-            nret = NF90_GET_VAR(ncid, nmassid, zdata, istrt, ilngth )
-            localpt%mass = zdata(1)
-            nret = NF90_GET_VAR(ncid, nthicknessid, zdata, istrt, ilngth )
-            localpt%thickness = zdata(1)
-            nret = NF90_GET_VAR(ncid, nwidthid, zdata, istrt, ilngth )
-            localpt%width = zdata(1)
-            nret = NF90_GET_VAR(ncid, nlengthid, zdata, istrt, ilngth )
-            localpt%length = zdata(1)
-            nret = NF90_GET_VAR(ncid, nyearid, idata, istrt, ilngth )
-            localpt%year = idata(1)
-            nret = NF90_GET_VAR(ncid, ndayid, zdata, istrt, ilngth )
-            localpt%day = zdata(1)
-            nret = NF90_GET_VAR(ncid, nmass_of_bits_id, zdata, istrt, ilngth )
-            localpt%mass_of_bits = zdata(1)
-            nret = NF90_GET_VAR(ncid, nheat_density_id, zdata, istrt, ilngth )
-            localpt%heat_density = zdata(1)
-            !
-            CALL icb_utl_add( localberg, localpt )
+
          END DO
-         !
-      ENDIF
-
-      nret = NF90_INQ_DIMID( ncid, 'c', nc_dim )
-      IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, read_restart: nf_inq_dimid c failed')
-
-      nret = NF90_INQUIRE_DIMENSION( ncid, nc_dim, cl_dname, iclass )
-      IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, read_restart: nf_inquire_dimension failed')
-
-      nret = NF90_INQ_VARID(ncid, 'kount'       , nkountid)
-      nret = NF90_INQ_VARID(ncid, 'calving'     , ncalvid)
-      nret = NF90_INQ_VARID(ncid, 'calving_hflx', ncalvhid)
-      nret = NF90_INQ_VARID(ncid, 'stored_ice'  , nsiceid)
-      nret = NF90_INQ_VARID(ncid, 'stored_heat' , nsheatid)
-
-      nstrt3(1) = 1
-      nstrt3(2) = 1
-      nlngth3(1) = jpi
-      nlngth3(2) = jpj
-      nlngth3(3) = 1
-
-      DO jn = 1, iclass
-         nstrt3(3) = jn
-         nret      = NF90_GET_VAR( ncid, nsiceid , griddata, nstrt3, nlngth3 )
-         berg_grid%stored_ice(:,:,jn) = griddata(:,:,1)
-      END DO
-
-      nret = NF90_GET_VAR( ncid, ncalvid , src_calving          (:,:) )
-      nret = NF90_GET_VAR( ncid, ncalvhid, src_calving_hflx     (:,:) )
-      nret = NF90_GET_VAR( ncid, nsheatid, berg_grid%stored_heat(:,:) )
-      nret = NF90_GET_VAR( ncid, nkountid, idata2(:) )
-      num_bergs(:) = idata2(:)
-
-      ! Finish up
-      nret = NF90_CLOSE(ncid)
-      IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, read_restart: nf_close failed')
+
+      ENDIF 
+
+      ! Gridded variables
+      CALL iom_get( ncid, jpdom_autoglo,    'calving'     , src_calving  )
+      CALL iom_get( ncid, jpdom_autoglo,    'calving_hflx', src_calving_hflx  )
+      CALL iom_get( ncid, jpdom_autoglo,    'stored_heat' , berg_grid%stored_heat  )
+      CALL iom_get( ncid, jpdom_autoglo_xy, 'stored_ice'  , berg_grid%stored_ice, kstart=(/1,1,1/), kcount=(/1,1,nclasses/) )
+      
+      CALL iom_get( ncid, jpdom_unknown, 'kount' , zdata(:) )
+      num_bergs(:) = INT(zdata(:))
 
       ! Sanity check
@@ -211,5 +136,6 @@
          WRITE(numout,'(2(a,i5))') 'icebergs, read_restart_bergs: # bergs =',jn,' on PE',narea-1
       IF( lk_mpp ) THEN
-         CALL mpp_sum(ibergs_in_file)
+         ! Only mpp_sum ibergs_in_file if we are reading from multiple restart files. 
+         IF( INDEX(iom_file(ncid)%name,'icebergs.nc' ) .EQ. 0 ) CALL mpp_sum(ibergs_in_file)
          CALL mpp_sum(jn)
       ENDIF
@@ -217,4 +143,7 @@
          &                                    ' bergs in the restart file and', jn,' bergs have been read'
       !
+      ! Finish up
+      CALL iom_close( ncid )
+      !
       IF( lwp .and. nn_verbose_level >= 0)  WRITE(numout,'(a)') 'icebergs, read_restart_bergs: completed'
       !
@@ -231,6 +160,10 @@
       INTEGER ::   jn   ! dummy loop index
       INTEGER ::   ix_dim, iy_dim, ik_dim, in_dim
-      CHARACTER(len=256)     :: cl_path
-      CHARACTER(len=256)     :: cl_filename
+      INTEGER             ::   iyear, imonth, iday
+      REAL (wp)           ::   zsec
+      REAL (wp)           ::   zfjulday
+      CHARACTER(len=256)  :: cl_path
+      CHARACTER(len=256)  :: cl_filename
+      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
       TYPE(iceberg), POINTER :: this
       TYPE(point)  , POINTER :: pt
@@ -240,8 +173,18 @@
       cl_path = TRIM(cn_ocerst_outdir)
       IF( cl_path(LEN_TRIM(cl_path):) /= '/' ) cl_path = TRIM(cl_path) // '/'
+      IF ( ln_rstdate ) THEN
+         zfjulday = fjulday + rdttra(1) / rday
+         IF( ABS(zfjulday - REAL(NINT(zfjulday),wp)) < 0.1 / rday )   zfjulday = REAL(NINT(zfjulday),wp)   ! avoid truncation error
+         CALL ju2ymds( zfjulday, iyear, imonth, iday, zsec )           
+         WRITE(clkt, '(i4.4,2i2.2)') iyear, imonth, iday
+      ELSE
+         IF( kt > 999999999 ) THEN   ;   WRITE(clkt, *       ) kt
+         ELSE                        ;   WRITE(clkt, '(i8.8)') kt
+         ENDIF
+      ENDIF
       IF( lk_mpp ) THEN
-         WRITE(cl_filename,'(A,"_icebergs_",I8.8,"_restart_",I4.4,".nc")') TRIM(cexper), kt, narea-1
+         WRITE(cl_filename,'(A,"_icebergs_",A,"_restart_",I4.4,".nc")') TRIM(cexper), TRIM(ADJUSTL(clkt)), narea-1
       ELSE
-         WRITE(cl_filename,'(A,"_icebergs_",I8.8,"_restart.nc")') TRIM(cexper), kt
+         WRITE(cl_filename,'(A,"_icebergs_",A,"_restart.nc")') TRIM(cexper), TRIM(ADJUSTL(clkt))
       ENDIF
       IF (nn_verbose_level >= 0) WRITE(numout,'(2a)') 'icebergs, write_restart: creating ',TRIM(cl_path)//TRIM(cl_filename)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbthm.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbthm.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbthm.F90	(revision 9987)
@@ -18,4 +18,5 @@
    USE dom_oce        ! NEMO domain
    USE in_out_manager ! NEMO IO routines, numout in particular
+   USE iom
    USE lib_mpp        ! NEMO MPI routines, ctl_stop in particular
    USE phycst         ! NEMO physical constants
@@ -160,5 +161,6 @@
             zmelt    = ( zdM - ( zdMbitsE - zdMbitsM ) ) * z1_dt   ! kg/s
             berg_grid%floating_melt(ii,ij) = berg_grid%floating_melt(ii,ij) + zmelt    * z1_e1e2    ! kg/m2/s
-            zheat = zmelt * pt%heat_density              ! kg/s x J/kg = J/s
+!            zheat = zmelt * pt%heat_density              ! kg/s x J/kg = J/s
+            zheat = zmelt * lfus                           !rma kg/s x J/kg (latent heat of fusion) = J/s
             berg_grid%calving_hflx (ii,ij) = berg_grid%calving_hflx (ii,ij) + zheat    * z1_e1e2    ! W/m2
             CALL icb_dia_melt( ii, ij, zMnew, zheat, this%mass_scaling,       &
@@ -208,5 +210,5 @@
       IF(.NOT. ln_passive_mode ) THEN
          emp (:,:) = emp (:,:) - berg_grid%floating_melt(:,:)
-!!       qns (:,:) = qns (:,:) + berg_grid%calving_hflx (:,:)  !!gm heat flux not yet properly coded ==>> need it, SOLVE that!
+         qns (:,:) = qns (:,:) - berg_grid%calving_hflx (:,:)  
       ENDIF
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbtrj.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbtrj.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ICB/icbtrj.F90	(revision 9987)
@@ -18,4 +18,5 @@
    USE lib_mpp        ! NEMO MPI library, lk_mpp in particular
    USE in_out_manager ! NEMO IO, numout in particular
+   USE ioipsl, ONLY : ju2ymds    ! for calendar
    USE netcdf
    !
@@ -60,11 +61,25 @@
       !
       INTEGER                               :: iret
+      INTEGER                               :: iyear, imonth, iday
+      REAL(wp)                              :: zfjulday, zsec
       CHARACTER(len=80)                     :: cl_filename
       TYPE(iceberg), POINTER                :: this
       TYPE(point)  , POINTER                :: pt
-      !!----------------------------------------------------------------------
-
-      IF( lk_mpp ) THEN   ;   WRITE(cl_filename,'("trajectory_icebergs_",I6.6,"_",I4.4,".nc")') ktend, narea-1
-      ELSE                ;   WRITE(cl_filename,'("trajectory_icebergs_",I6.6         ,".nc")') ktend
+      CHARACTER(LEN=20)                     :: cldate_ini, cldate_end
+      !!----------------------------------------------------------------------
+
+      ! compute initial time step date
+      CALL ju2ymds( fjulday, iyear, imonth, iday, zsec )
+      WRITE(cldate_ini, '(i4.4,2i2.2)') iyear, imonth, iday
+
+      ! compute end time step date
+      zfjulday = fjulday + rdttra(1) / rday * REAL( nitend - nit000 + 1 , wp)
+      IF( ABS(zfjulday - REAL(NINT(zfjulday),wp)) < 0.1 / rday )   zfjulday = REAL(NINT(zfjulday),wp)   ! avoid truncation error
+      CALL ju2ymds( zfjulday, iyear, imonth, iday, zsec )
+      WRITE(cldate_end, '(i4.4,2i2.2)') iyear, imonth, iday
+
+      ! define trajectory output name
+      IF( lk_mpp ) THEN   ;   WRITE(cl_filename,'("trajectory_icebergs_",A,"-",A,"_",I4.4,".nc")') TRIM(ADJUSTL(cldate_ini)), TRIM(ADJUSTL(cldate_end)), narea-1
+      ELSE                ;   WRITE(cl_filename,'("trajectory_icebergs_",A,"-",A         ,".nc")') TRIM(ADJUSTL(cldate_ini)), TRIM(ADJUSTL(cldate_end))
       ENDIF
       IF ( lwp .AND. nn_verbose_level >= 0) WRITE(numout,'(2a)') 'icebergs, icb_trj_init: creating ',TRIM(cl_filename)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/in_out_manager.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/in_out_manager.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/in_out_manager.F90	(revision 9987)
@@ -30,4 +30,5 @@
    CHARACTER(lc) ::   cn_ocerst_outdir !: restart output directory
    LOGICAL       ::   ln_rstart        !: start from (F) rest or (T) a restart file
+   LOGICAL       ::   ln_rstdate       !: datestamping of restarts
    LOGICAL       ::   ln_rst_list      !: output restarts at list of times (T) or by frequency (F)
    INTEGER       ::   nn_no            !: job number
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom.F90	(revision 9987)
@@ -94,13 +94,21 @@
       CHARACTER(len=*), INTENT(in)  :: cdname
 #if defined key_iomput
-      TYPE(xios_time)   :: dtime    = xios_time(0, 0, 0, 0, 0, 0)
-      CHARACTER(len=19) :: cldate 
-      CHARACTER(len=10) :: clname
-      INTEGER           ::   ji
+#if ! defined key_xios2
+      TYPE(xios_time)     :: dtime    = xios_time(0, 0, 0, 0, 0, 0)
+      CHARACTER(len=19)   :: cldate 
+#else
+      TYPE(xios_duration) :: dtime    = xios_duration(0, 0, 0, 0, 0, 0)
+      TYPE(xios_date)     :: start_date
+#endif
+      CHARACTER(len=10)   :: clname
+      INTEGER             :: ji
       !
       REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: z_bnds
       !!----------------------------------------------------------------------
-
+#if ! defined key_xios2
       ALLOCATE( z_bnds(jpk,2) )
+#else
+      ALLOCATE( z_bnds(2,jpk) )
+#endif
 
       clname = cdname
@@ -110,4 +118,5 @@
 
       ! calendar parameters
+#if ! defined key_xios2
       SELECT CASE ( nleapy )        ! Choose calendar for IOIPSL
       CASE ( 1)   ;   CALL xios_set_context_attr(TRIM(clname), calendar_type= "Gregorian")
@@ -117,6 +126,17 @@
       WRITE(cldate,"(i4.4,'-',i2.2,'-',i2.2,' 00:00:00')") nyear,nmonth,nday 
       CALL xios_set_context_attr(TRIM(clname), start_date=cldate )
-
+#else
+      ! Calendar type is now defined in xml file 
+      SELECT CASE ( nleapy )        ! Choose calendar for IOIPSL
+      CASE ( 1)   ; CALL xios_define_calendar( TYPE = "Gregorian", time_origin = xios_date(1900,01,01,00,00,00), &
+          &                                    start_date = xios_date(nyear,nmonth,nday,0,0,0) )
+      CASE ( 0)   ; CALL xios_define_calendar( TYPE = "NoLeap"   , time_origin = xios_date(1900,01,01,00,00,00), &
+          &                                    start_date = xios_date(nyear,nmonth,nday,0,0,0) )
+      CASE (30)   ; CALL xios_define_calendar( TYPE = "D360"     , time_origin = xios_date(1900,01,01,00,00,00), &
+          &                                    start_date = xios_date(nyear,nmonth,nday,0,0,0) )
+      END SELECT
+#endif
       ! horizontal grid definition
+
       CALL set_scalar
 
@@ -170,14 +190,29 @@
 
       ! Add vertical grid bounds
+#if ! defined key_xios2
       z_bnds(:      ,1) = gdepw_1d(:)
       z_bnds(1:jpkm1,2) = gdepw_1d(2:jpk)
       z_bnds(jpk:   ,2) = gdepw_1d(jpk) + e3t_1d(jpk)
+#else
+      z_bnds(1      ,:) = gdepw_1d(:)
+      z_bnds(2,1:jpkm1) = gdepw_1d(2:jpk)
+      z_bnds(2,jpk:   ) = gdepw_1d(jpk) + e3t_1d(jpk)
+#endif
+
       CALL iom_set_axis_attr( "deptht", bounds=z_bnds )
       CALL iom_set_axis_attr( "depthu", bounds=z_bnds )
       CALL iom_set_axis_attr( "depthv", bounds=z_bnds )
-      z_bnds(:    ,2) = gdept_1d(:)
-      z_bnds(2:jpk,1) = gdept_1d(1:jpkm1)
-      z_bnds(1    ,1) = gdept_1d(1) - e3w_1d(1)
+
+#if ! defined key_xios2
+      z_bnds(:    ,2)  = gdept_1d(:)
+      z_bnds(2:jpk,1)  = gdept_1d(1:jpkm1)
+      z_bnds(1    ,1)  = gdept_1d(1) - e3w_1d(1)
+#else
+      z_bnds(2,:    )  = gdept_1d(:)
+      z_bnds(1,2:jpk)  = gdept_1d(1:jpkm1)
+      z_bnds(1,1    )  = gdept_1d(1) - e3w_1d(1)
+#endif
       CALL iom_set_axis_attr( "depthw", bounds=z_bnds )
+
 
 # if defined key_floats
@@ -193,4 +228,6 @@
       ! automatic definitions of some of the xml attributs
       CALL set_xmlatt
+
+      CALL set_1point
 
       ! end file definition
@@ -673,4 +710,5 @@
       CHARACTER(LEN=256)             ::   clname      ! file name
       CHARACTER(LEN=1)               ::   clrankpv, cldmspc      ! 
+      LOGICAL                        ::   ll_depth_spec ! T => if kstart, kcount present then *only* use values for 3rd spatial dimension.
       !---------------------------------------------------------------------
       !
@@ -685,5 +723,6 @@
       IF( PRESENT(kcount) .AND. (.NOT. PRESENT(kstart)) ) CALL ctl_stop(trim(clinfo), 'kcount present needs kstart present')
       IF( PRESENT(kstart) .AND. (.NOT. PRESENT(kcount)) ) CALL ctl_stop(trim(clinfo), 'kstart present needs kcount present')
-      IF( PRESENT(kstart) .AND. idom /= jpdom_unknown   ) CALL ctl_stop(trim(clinfo), 'kstart present needs kdom = jpdom_unknown')
+      IF( PRESENT(kstart) .AND. idom /= jpdom_unknown .AND.  idom /= jpdom_autoglo_xy  ) &
+     &           CALL ctl_stop(trim(clinfo), 'kstart present needs kdom = jpdom_unknown or kdom = jpdom_autoglo_xy')
 
       luse_jattr = .false.
@@ -718,4 +757,10 @@
          ! update idom definition...
          ! Identify the domain in case of jpdom_auto(glo/dta) definition
+         IF( idom == jpdom_autoglo_xy ) THEN
+            ll_depth_spec = .TRUE.
+            idom = jpdom_autoglo
+         ELSE
+            ll_depth_spec = .FALSE.
+         ENDIF
          IF( idom == jpdom_autoglo .OR. idom == jpdom_autodta ) THEN            
             IF( idom == jpdom_autoglo ) THEN   ;   idom = jpdom_global 
@@ -771,7 +816,7 @@
          istart(idmspc+1) = itime
 
-         IF(              PRESENT(kstart)       ) THEN ; istart(1:idmspc) = kstart(1:idmspc) ; icnt(1:idmspc) = kcount(1:idmspc)
+         IF( PRESENT(kstart) .AND. .NOT. ll_depth_spec ) THEN ; istart(1:idmspc) = kstart(1:idmspc) ; icnt(1:idmspc) = kcount(1:idmspc)
          ELSE
-            IF(           idom == jpdom_unknown ) THEN                                       ; icnt(1:idmspc) = idimsz(1:idmspc)
+            IF(           idom == jpdom_unknown ) THEN                                                ; icnt(1:idmspc) = idimsz(1:idmspc)
             ELSE 
                IF( .NOT. PRESENT(pv_r1d) ) THEN   !   not a 1D array
@@ -796,6 +841,7 @@
                   ENDIF
                   IF( PRESENT(pv_r3d) ) THEN
-                     IF( idom == jpdom_data ) THEN   ; icnt(3) = jpkdta
-                     ELSE                            ; icnt(3) = jpk
+                     IF( idom == jpdom_data ) THEN                                  ; icnt(3) = jpkdta
+                     ELSE IF( ll_depth_spec .AND. PRESENT(kstart) ) THEN            ; istart(3) = kstart(3); icnt(3) = kcount(3)
+                     ELSE                                                           ; icnt(3) = jpk
                      ENDIF
                   ENDIF
@@ -988,5 +1034,5 @@
    !!----------------------------------------------------------------------
    SUBROUTINE iom_g0d_intatt( kiomid, cdatt, pvar )
-      INTEGER         , INTENT(in   )                 ::   kiomid    ! Identifier of the file
+      INTEGER         , INTENT(in   )                 ::   kiomid    !Identifier of the file
       CHARACTER(len=*), INTENT(in   )                 ::   cdatt     ! Name of the attribute
       INTEGER         , INTENT(  out)                 ::   pvar      ! read field
@@ -1104,9 +1150,14 @@
       CHARACTER(LEN=*), INTENT(in) ::   cdname
       REAL(wp)        , INTENT(in) ::   pfield0d
+#if ! defined key_xios2
       REAL(wp)        , DIMENSION(jpi,jpj) ::   zz     ! masson
+#endif
 #if defined key_iomput
+#if ! defined key_xios2
       zz(:,:)=pfield0d
       CALL xios_send_field(cdname, zz)
-      !CALL xios_send_field(cdname, (/pfield0d/)) 
+#else
+      CALL xios_send_field(cdname, (/pfield0d/)) 
+#endif
 #else
       IF( .FALSE. )   WRITE(numout,*) cdname, pfield0d   ! useless test to avoid compilation warnings
@@ -1156,6 +1207,11 @@
       REAL(wp), DIMENSION(:)   , OPTIONAL, INTENT(in) ::   lonvalue, latvalue
       REAL(wp), DIMENSION(:,:) , OPTIONAL, INTENT(in) ::   bounds_lon, bounds_lat, area
-      LOGICAL,  DIMENSION(:,:) , OPTIONAL, INTENT(in) ::   mask
-
+#if ! defined key_xios2
+     LOGICAL,  DIMENSION(:,:) , OPTIONAL, INTENT(in) ::   mask
+#else
+      LOGICAL,  DIMENSION(:) , OPTIONAL, INTENT(in) ::   mask
+#endif
+
+#if ! defined key_xios2
       IF ( xios_is_valid_domain     (cdid) ) THEN
          CALL xios_set_domain_attr     ( cdid, ni_glo=ni_glo, nj_glo=nj_glo, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj,   &
@@ -1164,6 +1220,5 @@
             &    lonvalue=lonvalue, latvalue=latvalue, mask=mask, nvertex=nvertex, bounds_lon=bounds_lon,                  &
             &    bounds_lat=bounds_lat, area=area )
-      ENDIF
-
+     ENDIF
       IF ( xios_is_valid_domaingroup(cdid) ) THEN
          CALL xios_set_domaingroup_attr( cdid, ni_glo=ni_glo, nj_glo=nj_glo, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj,   &
@@ -1173,7 +1228,34 @@
             &    bounds_lat=bounds_lat, area=area )
       ENDIF
+
+#else
+      IF ( xios_is_valid_domain     (cdid) ) THEN
+         CALL xios_set_domain_attr     ( cdid, ni_glo=ni_glo, nj_glo=nj_glo, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj,   &
+            &    data_dim=data_dim, data_ibegin=data_ibegin, data_ni=data_ni, data_jbegin=data_jbegin, data_nj=data_nj ,   &
+            &    lonvalue_1D=lonvalue, latvalue_1D=latvalue, mask_1D=mask, nvertex=nvertex, bounds_lon_1D=bounds_lon,                  &
+            &    bounds_lat_1D=bounds_lat, area=area, type='curvilinear')
+     ENDIF
+      IF ( xios_is_valid_domaingroup(cdid) ) THEN
+         CALL xios_set_domaingroup_attr( cdid, ni_glo=ni_glo, nj_glo=nj_glo, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj,   &
+            &    data_dim=data_dim, data_ibegin=data_ibegin, data_ni=data_ni, data_jbegin=data_jbegin, data_nj=data_nj ,   &
+            &    lonvalue_1D=lonvalue, latvalue_1D=latvalue, mask_1D=mask, nvertex=nvertex, bounds_lon_1D=bounds_lon,                  &
+            &    bounds_lat_1D=bounds_lat, area=area, type='curvilinear' )
+      ENDIF
+#endif
       CALL xios_solve_inheritance()
 
    END SUBROUTINE iom_set_domain_attr
+
+#if defined key_xios2
+  SUBROUTINE iom_set_zoom_domain_attr( cdid, ibegin, jbegin, ni, nj)
+     CHARACTER(LEN=*)                   , INTENT(in) ::   cdid
+     INTEGER                  , OPTIONAL, INTENT(in) ::   ibegin, jbegin, ni, nj
+
+     IF ( xios_is_valid_zoom_domain     (cdid) ) THEN
+         CALL xios_set_zoom_domain_attr     ( cdid, ibegin=ibegin, jbegin=jbegin, ni=ni,    &
+           &   nj=nj)
+    ENDIF
+  END SUBROUTINE iom_set_zoom_domain_attr
+#endif
 
 
@@ -1183,6 +1265,11 @@
       REAL(wp), DIMENSION(:,:), OPTIONAL, INTENT(in) ::   bounds
       IF ( PRESENT(paxis) ) THEN
+#if ! defined key_xios2
          IF ( xios_is_valid_axis     (cdid) )   CALL xios_set_axis_attr     ( cdid, size=SIZE(paxis), value=paxis )
          IF ( xios_is_valid_axisgroup(cdid) )   CALL xios_set_axisgroup_attr( cdid, size=SIZE(paxis), value=paxis )
+#else
+         IF ( xios_is_valid_axis     (cdid) )   CALL xios_set_axis_attr     ( cdid, n_glo=SIZE(paxis), value=paxis )
+         IF ( xios_is_valid_axisgroup(cdid) )   CALL xios_set_axisgroup_attr( cdid, n_glo=SIZE(paxis), value=paxis )
+#endif
       ENDIF
       IF ( xios_is_valid_axis     (cdid) )   CALL xios_set_axis_attr     ( cdid, bounds=bounds )
@@ -1191,14 +1278,19 @@
    END SUBROUTINE iom_set_axis_attr
 
-
    SUBROUTINE iom_set_field_attr( cdid, freq_op, freq_offset )
       CHARACTER(LEN=*)          , INTENT(in) ::   cdid
-      CHARACTER(LEN=*),OPTIONAL , INTENT(in) ::   freq_op
-      CHARACTER(LEN=*),OPTIONAL , INTENT(in) ::   freq_offset
-      IF ( xios_is_valid_field     (cdid) )   CALL xios_set_field_attr     ( cdid, freq_op=freq_op, freq_offset=freq_offset )
-      IF ( xios_is_valid_fieldgroup(cdid) )   CALL xios_set_fieldgroup_attr( cdid, freq_op=freq_op, freq_offset=freq_offset )
+#if ! defined key_xios2
+      CHARACTER(LEN=*)   ,OPTIONAL , INTENT(in) ::   freq_op
+      CHARACTER(LEN=*)   ,OPTIONAL , INTENT(in) ::   freq_offset
+#else
+      TYPE(xios_duration),OPTIONAL , INTENT(in) ::   freq_op
+      TYPE(xios_duration),OPTIONAL , INTENT(in) ::   freq_offset
+#endif
+      IF ( xios_is_valid_field     (cdid) )   CALL xios_set_field_attr       &
+    &     ( cdid, freq_op=freq_op, freq_offset=freq_offset )
+      IF ( xios_is_valid_fieldgroup(cdid) )   CALL xios_set_fieldgroup_attr  &
+    &                    ( cdid, freq_op=freq_op, freq_offset=freq_offset )
       CALL xios_solve_inheritance()
    END SUBROUTINE iom_set_field_attr
-
 
    SUBROUTINE iom_set_file_attr( cdid, name, name_suffix )
@@ -1213,10 +1305,19 @@
    SUBROUTINE iom_get_file_attr( cdid, name, name_suffix, output_freq )
       CHARACTER(LEN=*)          , INTENT(in ) ::   cdid
-      CHARACTER(LEN=*),OPTIONAL , INTENT(out) ::   name, name_suffix, output_freq
+      CHARACTER(LEN=*),OPTIONAL , INTENT(out) ::   name, name_suffix
+#if ! defined key_xios2
+      CHARACTER(LEN=*),OPTIONAL , INTENT(out) ::    output_freq
+#else
+      TYPE(xios_duration)   ,OPTIONAL , INTENT(out) :: output_freq
+#endif  
       LOGICAL                                 ::   llexist1,llexist2,llexist3
       !---------------------------------------------------------------------
       IF( PRESENT( name        ) )   name = ''          ! default values
       IF( PRESENT( name_suffix ) )   name_suffix = ''
+#if ! defined key_xios2
       IF( PRESENT( output_freq ) )   output_freq = ''
+#else
+      IF( PRESENT( output_freq ) )   output_freq = xios_duration(0,0,0,0,0,0)
+#endif
       IF ( xios_is_valid_file     (cdid) ) THEN
          CALL xios_solve_inheritance()
@@ -1239,6 +1340,11 @@
       CHARACTER(LEN=*)                   , INTENT(in) ::   cdid
       LOGICAL, DIMENSION(:,:,:), OPTIONAL, INTENT(in) ::   mask
+#if ! defined key_xios2
       IF ( xios_is_valid_grid     (cdid) )   CALL xios_set_grid_attr     ( cdid, mask=mask )
       IF ( xios_is_valid_gridgroup(cdid) )   CALL xios_set_gridgroup_attr( cdid, mask=mask )
+#else
+      IF ( xios_is_valid_grid     (cdid) )   CALL xios_set_grid_attr     ( cdid, mask_3D=mask )
+      IF ( xios_is_valid_gridgroup(cdid) )   CALL xios_set_gridgroup_attr( cdid, mask_3D=mask )
+#endif
       CALL xios_solve_inheritance()
    END SUBROUTINE iom_set_grid_attr
@@ -1282,5 +1388,9 @@
       ni=nlei-nldi+1 ; nj=nlej-nldj+1
 
-      CALL iom_set_domain_attr("grid_"//cdgrd, ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-1, jbegin=njmpp+nldj-1, ni=ni, nj=nj)
+#if ! defined key_xios2
+     CALL iom_set_domain_attr("grid_"//cdgrd, ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-1, jbegin=njmpp+nldj-1, ni=ni, nj=nj)
+#else
+     CALL iom_set_domain_attr("grid_"//cdgrd, ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-2, jbegin=njmpp+nldj-2, ni=ni, nj=nj)
+#endif     
       CALL iom_set_domain_attr("grid_"//cdgrd, data_dim=2, data_ibegin = 1-nldi, data_ni = jpi, data_jbegin = 1-nldj, data_nj = jpj)
       CALL iom_set_domain_attr("grid_"//cdgrd, lonvalue = RESHAPE(plon(nldi:nlei, nldj:nlej),(/ ni*nj /)),   &
@@ -1296,5 +1406,9 @@
          END SELECT
          !
+#if ! defined key_xios2
          CALL iom_set_domain_attr( "grid_"//cdgrd       , mask = RESHAPE(zmask(nldi:nlei,nldj:nlej,1),(/ni,nj    /)) /= 0. )
+#else
+         CALL iom_set_domain_attr( "grid_"//cdgrd       , mask = RESHAPE(zmask(nldi:nlei,nldj:nlej,1),(/ni*nj    /)) /= 0. )
+#endif  
          CALL iom_set_grid_attr  ( "grid_"//cdgrd//"_3D", mask = RESHAPE(zmask(nldi:nlei,nldj:nlej,:),(/ni,nj,jpk/)) /= 0. )
       ENDIF
@@ -1430,4 +1544,6 @@
       ALLOCATE( zlon(ni*nj) )       ;       zlon(:) = 0.
 
+      CALL dom_ngb( -168.7, 65.6, ix, iy, 'T' ) !  i-line that passes across Bering strait to avoid land processor (used in plots)
+#if ! defined key_xios2
       CALL iom_set_domain_attr("gznl", ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-1, jbegin=njmpp+nldj-1, ni=ni, nj=nj)
       CALL iom_set_domain_attr("gznl", data_dim=2, data_ibegin = 1-nldi, data_ni = jpi, data_jbegin = 1-nldj, data_nj = jpj)
@@ -1435,6 +1551,14 @@
          &                             latvalue = RESHAPE(plat(nldi:nlei, nldj:nlej),(/ ni*nj /)))  
       !
-      CALL dom_ngb( 180., 90., ix, iy, 'T' ) !  i-line that passes near the North Pole : Reference latitude (used in plots)
       CALL iom_set_domain_attr ('ptr', zoom_ibegin=ix, zoom_nj=jpjglo)
+#else
+! Pas teste : attention aux indices !
+      CALL iom_set_domain_attr("gznl", ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-2, jbegin=njmpp+nldj-2, ni=ni, nj=nj)
+      CALL iom_set_domain_attr("gznl", data_dim=2, data_ibegin = 1-nldi, data_ni = jpi, data_jbegin = 1-nldj, data_nj = jpj)
+      CALL iom_set_domain_attr("gznl", lonvalue = zlon,   &
+         &                             latvalue = RESHAPE(plat(nldi:nlei, nldj:nlej),(/ ni*nj /)))  
+       CALL iom_set_zoom_domain_attr ("ptr", ibegin=ix-1, jbegin=0, ni=1, nj=jpjglo)
+#endif
+
       CALL iom_update_file_name('ptr')
       !
@@ -1450,11 +1574,31 @@
       REAL(wp), DIMENSION(1)   ::   zz = 1.
       !!----------------------------------------------------------------------
+#if ! defined key_xios2
       CALL iom_set_domain_attr('scalarpoint', ni_glo=jpnij, nj_glo=1, ibegin=narea, jbegin=1, ni=1, nj=1)
+#else
+      CALL iom_set_domain_attr('scalarpoint', ni_glo=jpnij, nj_glo=1, ibegin=narea-1, jbegin=0, ni=1, nj=1)
+#endif
       CALL iom_set_domain_attr('scalarpoint', data_dim=2, data_ibegin = 1, data_ni = 1, data_jbegin = 1, data_nj = 1)
       
       zz=REAL(narea,wp)
       CALL iom_set_domain_attr('scalarpoint', lonvalue=zz, latvalue=zz)
-
+      
    END SUBROUTINE set_scalar
+
+   SUBROUTINE set_1point
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE set_1point  ***
+      !!
+      !! ** Purpose :   define zoom grid for scalar fields
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(1)   ::   zz = 1.
+      INTEGER  :: ix, iy
+      !!----------------------------------------------------------------------
+      CALL dom_ngb( 180., 90., ix, iy, 'T' ) !  Nearest point to north pole should be ocean
+      CALL iom_set_domain_attr('1point', zoom_ibegin=ix, zoom_jbegin=iy)
+
+   END SUBROUTINE set_1point
+
 
 
@@ -1479,12 +1623,28 @@
       REAL(wp)        ,DIMENSION( 3) ::   zlonpira                 ! longitudes of pirata moorings
       REAL(wp)        ,DIMENSION( 9) ::   zlatpira                 ! latitudes  of pirata moorings
+#if  defined key_xios2
+      TYPE(xios_duration)            ::   f_op, f_of
+#endif
+ 
       !!----------------------------------------------------------------------
       ! 
       ! frequency of the call of iom_put (attribut: freq_op)
-      WRITE(cl1,'(i1)')        1   ;   CALL iom_set_field_attr('field_definition', freq_op = cl1//'ts', freq_offset='0ts')
-      WRITE(cl1,'(i1)')  nn_fsbc   ;   CALL iom_set_field_attr('SBC'             , freq_op = cl1//'ts', freq_offset='0ts')
-      WRITE(cl1,'(i1)')  nn_fsbc   ;   CALL iom_set_field_attr('SBC_scalar'      , freq_op = cl1//'ts', freq_offset='0ts')
-      WRITE(cl1,'(i1)') nn_dttrc   ;   CALL iom_set_field_attr('ptrc_T'          , freq_op = cl1//'ts', freq_offset='0ts')
-      WRITE(cl1,'(i1)') nn_dttrc   ;   CALL iom_set_field_attr('diad_T'          , freq_op = cl1//'ts', freq_offset='0ts')
+#if ! defined key_xios2
+      WRITE(cl1,'(i1)')        1   ;   CALL iom_set_field_attr('field_definition', freq_op=cl1//'ts', freq_offset='0ts')
+      WRITE(cl1,'(i1)')        2   ;   CALL iom_set_field_attr('trendT_even'      , freq_op=cl1//'ts', freq_offset='0ts')
+      WRITE(cl1,'(i1)')        2   ;   CALL iom_set_field_attr('trendT_odd'       , freq_op=cl1//'ts', freq_offset='-1ts')
+      WRITE(cl1,'(i1)')  nn_fsbc   ;   CALL iom_set_field_attr('SBC'             , freq_op=cl1//'ts', freq_offset='0ts')
+      WRITE(cl1,'(i1)')  nn_fsbc   ;   CALL iom_set_field_attr('SBC_scalar'      , freq_op=cl1//'ts', freq_offset='0ts')
+      WRITE(cl1,'(i1)') nn_dttrc   ;   CALL iom_set_field_attr('ptrc_T'          , freq_op=cl1//'ts', freq_offset='0ts')
+      WRITE(cl1,'(i1)') nn_dttrc   ;   CALL iom_set_field_attr('diad_T'          , freq_op=cl1//'ts', freq_offset='0ts')
+#else
+      f_op%timestep = 1        ;  f_of%timestep = 0  ; CALL iom_set_field_attr('field_definition', freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = 2        ;  f_of%timestep = 0  ; CALL iom_set_field_attr('trendT_even'      , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = 2        ;  f_of%timestep = -1 ; CALL iom_set_field_attr('trendT_odd'       , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_fsbc  ;  f_of%timestep = 0  ; CALL iom_set_field_attr('SBC'             , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_fsbc  ;  f_of%timestep = 0  ; CALL iom_set_field_attr('SBC_scalar'      , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_dttrc ;  f_of%timestep = 0  ; CALL iom_set_field_attr('ptrc_T'          , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_dttrc ;  f_of%timestep = 0  ; CALL iom_set_field_attr('diad_T'          , freq_op=f_op, freq_offset=f_of)
+#endif
        
       ! output file names (attribut: name)
@@ -1508,5 +1668,9 @@
          ! Equatorial section (attributs: jbegin, ni, name_suffix)
          CALL dom_ngb( 0., 0., ix, iy, cl1 )
+#if ! defined key_xios2
          CALL iom_set_domain_attr ('Eq'//cl1, zoom_jbegin=iy, zoom_ni=jpiglo)
+#else
+         CALL iom_set_zoom_domain_attr ('Eq'//cl1, jbegin=iy-1, ni=jpiglo)
+#endif
          CALL iom_get_file_attr   ('Eq'//cl1, name_suffix = clsuff             )
          CALL iom_set_file_attr   ('Eq'//cl1, name_suffix = TRIM(clsuff)//'_Eq')
@@ -1588,5 +1752,9 @@
                ENDIF
                clname = TRIM(ADJUSTL(clat))//TRIM(ADJUSTL(clon))
+#if ! defined key_xios2
                CALL iom_set_domain_attr (TRIM(clname)//cl1, zoom_ibegin= ix, zoom_jbegin= iy)
+#else
+               CALL iom_set_zoom_domain_attr  (TRIM(clname)//cl1, ibegin= ix-1, jbegin= iy-1)
+#endif
                CALL iom_get_file_attr   (TRIM(clname)//cl1, name_suffix = clsuff                         )
                CALL iom_set_file_attr   (TRIM(clname)//cl1, name_suffix = TRIM(clsuff)//'_'//TRIM(clname))
@@ -1617,9 +1785,17 @@
       REAL(wp)           ::   zsec
       LOGICAL            ::   llexist
-      !!----------------------------------------------------------------------
+#if  defined key_xios2
+      TYPE(xios_duration)   ::   output_freq 
+#endif      
+      !!----------------------------------------------------------------------
+
 
       DO jn = 1,2
-
+#if ! defined key_xios2
          IF( jn == 1 )   CALL iom_get_file_attr( cdid, name        = clname, output_freq = clfreq )
+#else
+         output_freq = xios_duration(0,0,0,0,0,0)
+         IF( jn == 1 )   CALL iom_get_file_attr( cdid, name        = clname, output_freq = output_freq )
+#endif
          IF( jn == 2 )   CALL iom_get_file_attr( cdid, name_suffix = clname )
 
@@ -1632,4 +1808,5 @@
             END DO
 
+#if ! defined key_xios2
             idx = INDEX(clname,'@freq@') + INDEX(clname,'@FREQ@')
             DO WHILE ( idx /= 0 ) 
@@ -1644,5 +1821,30 @@
                idx = INDEX(clname,'@freq@') + INDEX(clname,'@FREQ@')
             END DO
-
+#else
+            idx = INDEX(clname,'@freq@') + INDEX(clname,'@FREQ@')
+            DO WHILE ( idx /= 0 ) 
+              IF ( output_freq%timestep /= 0) THEN
+                  WRITE(clfreq,'(I18,A2)')INT(output_freq%timestep),'ts' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%hour /= 0 ) THEN
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%hour),'h' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%day /= 0 ) THEN
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%day),'d' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%month /= 0 ) THEN   
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%month),'m' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%year /= 0 ) THEN   
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%year),'y' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE
+                  CALL ctl_stop('error in the name of file id '//TRIM(cdid),   &
+                     & ' attribute output_freq is undefined -> cannot replace @freq@ in '//TRIM(clname) )
+              ENDIF
+              clname = clname(1:idx-1)//TRIM(ADJUSTL(clfreq))//clname(idx+6:LEN_TRIM(clname))
+              idx = INDEX(clname,'@freq@') + INDEX(clname,'@FREQ@')
+            END DO
+#endif
             idx = INDEX(clname,'@startdate@') + INDEX(clname,'@STARTDATE@')
             DO WHILE ( idx /= 0 ) 
@@ -1673,4 +1875,5 @@
             END DO
 
+            IF( jn == 1 .AND. TRIM(Agrif_CFixed()) /= '0' )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
             IF( jn == 1 )   CALL iom_set_file_attr( cdid, name        = clname )
             IF( jn == 2 )   CALL iom_set_file_attr( cdid, name_suffix = clname )
@@ -1720,4 +1923,6 @@
       ENDIF
       
+!$AGRIF_DO_NOT_TREAT      
+! Should be fixed in the conv
       IF( llfull ) THEN 
          clfmt = TRIM(clfmt)//",'_',i2.2,':',i2.2,':',i2.2"
@@ -1730,4 +1935,5 @@
          WRITE(iom_sdate, '('//TRIM(clfmt)//')') iyear, imonth, iday                          ! date of the end of run
       ENDIF
+!$AGRIF_END_DO_NOT_TREAT      
 
    END FUNCTION iom_sdate
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom_def.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom_def.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom_def.F90	(revision 9987)
@@ -26,5 +26,6 @@
    INTEGER, PARAMETER, PUBLIC ::   jpdom_unknown       = 7   !: No dimension checking
    INTEGER, PARAMETER, PUBLIC ::   jpdom_autoglo       = 8   !: 
-   INTEGER, PARAMETER, PUBLIC ::   jpdom_autodta       = 9   !: 
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_autoglo_xy    = 9   !: Automatically set horizontal dimensions only
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_autodta       = 10  !: 
 
    INTEGER, PARAMETER, PUBLIC ::   jpioipsl    = 100      !: Use ioipsl (fliocom only) library
@@ -57,4 +58,5 @@
       INTEGER                                   ::   nvars    !: number of identified varibles in the file
       INTEGER                                   ::   iduld    !: id of the unlimited dimension
+      INTEGER                                   ::   lenuld   !: length of the unlimited dimension (number of records in file)
       INTEGER                                   ::   irec     !: writing record position  
       CHARACTER(LEN=32)                         ::   uldname  !: name of the unlimited dimension
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom_nf90.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom_nf90.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/iom_nf90.F90	(revision 9987)
@@ -154,6 +154,7 @@
          CALL iom_nf90_check(NF90_Inquire(if90id, unlimitedDimId = iom_file(kiomid)%iduld), clinfo)
          IF ( iom_file(kiomid)%iduld .GE. 0 ) THEN
-           CALL iom_nf90_check(NF90_Inquire_Dimension(if90id, iom_file(kiomid)%iduld,   &
-        &                                               name = iom_file(kiomid)%uldname), clinfo)
+           CALL iom_nf90_check(NF90_Inquire_Dimension(if90id, iom_file(kiomid)%iduld,     & 
+        &                                               name = iom_file(kiomid)%uldname,  &
+        &                                               len  = iom_file(kiomid)%lenuld ), clinfo )
          ENDIF
          IF(lwp) WRITE(numout,*) '                   ---> '//TRIM(cdname)//' OK'
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/restart.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/restart.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/IOM/restart.F90	(revision 9987)
@@ -21,7 +21,9 @@
    USE in_out_manager  ! I/O manager
    USE iom             ! I/O module
+   USE ioipsl, ONLY : ju2ymds    ! for calendar
    USE eosbn2          ! equation of state            (eos bn2 routine)
    USE trdmxl_oce      ! ocean active mixed layer tracers trends variables
    USE divcur          ! hor. divergence and curl      (div & cur routines)
+   USE sbc_oce         ! for icesheet freshwater input variables
 
    IMPLICIT NONE
@@ -54,8 +56,11 @@
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt     ! ocean time-step
+      INTEGER             ::   iyear, imonth, iday
+      REAL (wp)           ::   zsec
+      REAL (wp)           ::   zfjulday
       !!
       CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
       CHARACTER(LEN=50)   ::   clname   ! ocean output restart file name
-      CHARACTER(lc)       ::   clpath   ! full path to ocean output restart file
+      CHARACTER(LEN=150)  ::   clpath   ! full path to ocean output restart file
       !!----------------------------------------------------------------------
       !
@@ -81,7 +86,14 @@
       IF( kt == nitrst - 1 .OR. nstock == 1 .OR. ( kt == nitend .AND. .NOT. lrst_oce ) ) THEN
          IF( nitrst <= nitend .AND. nitrst > 0 ) THEN 
-            ! beware of the format used to write kt (default is i8.8, that should be large enough...)
-            IF( nitrst > 999999999 ) THEN   ;   WRITE(clkt, *       ) nitrst
-            ELSE                            ;   WRITE(clkt, '(i8.8)') nitrst
+            IF ( ln_rstdate ) THEN
+               zfjulday = fjulday + rdttra(1) / rday
+               IF( ABS(zfjulday - REAL(NINT(zfjulday),wp)) < 0.1 / rday )   zfjulday = REAL(NINT(zfjulday),wp)   ! avoid truncation error
+               CALL ju2ymds( zfjulday, iyear, imonth, iday, zsec )           
+               WRITE(clkt, '(i4.4,2i2.2)') iyear, imonth, iday
+            ELSE
+               ! beware of the format used to write kt (default is i8.8, that should be large enough...)
+               IF( nitrst > 999999999 ) THEN   ;   WRITE(clkt, *       ) nitrst
+               ELSE                            ;   WRITE(clkt, '(i8.8)') nitrst
+               ENDIF
             ENDIF
             ! create the file
@@ -145,4 +157,16 @@
                      CALL iom_rstput( kt, nitrst, numrow, 'rhd'    , rhd       )
 #endif
+                     IF( lk_oasis) THEN
+                     ! nn_coupled_iceshelf_fluxes uninitialised unless lk_oasis=true
+                     IF( nn_coupled_iceshelf_fluxes .eq. 1 ) THEN
+                        CALL iom_rstput( kt, nitrst, numrow, 'greenland_icesheet_mass', greenland_icesheet_mass )
+                        CALL iom_rstput( kt, nitrst, numrow, 'greenland_icesheet_timelapsed', greenland_icesheet_timelapsed )
+                        CALL iom_rstput( kt, nitrst, numrow, 'greenland_icesheet_mass_roc', greenland_icesheet_mass_rate_of_change )
+                        CALL iom_rstput( kt, nitrst, numrow, 'antarctica_icesheet_mass', antarctica_icesheet_mass )
+                        CALL iom_rstput( kt, nitrst, numrow, 'antarctica_icesheet_timelapsed', antarctica_icesheet_timelapsed )
+                        CALL iom_rstput( kt, nitrst, numrow, 'antarctica_icesheet_mass_roc', antarctica_icesheet_mass_rate_of_change )
+                     ENDIF
+                     ENDIF
+
       IF( kt == nitrst ) THEN
          CALL iom_close( numrow )     ! close the restart file (only at last time step)
@@ -258,4 +282,23 @@
 #endif
       !
+      IF( iom_varid( numror, 'greenland_icesheet_mass', ldstop = .FALSE. ) > 0 )   THEN
+         CALL iom_get( numror, 'greenland_icesheet_mass', greenland_icesheet_mass )
+         CALL iom_get( numror, 'greenland_icesheet_timelapsed', greenland_icesheet_timelapsed )
+         CALL iom_get( numror, 'greenland_icesheet_mass_roc', greenland_icesheet_mass_rate_of_change )
+      ELSE
+         greenland_icesheet_mass = 0.0 
+         greenland_icesheet_mass_rate_of_change = 0.0 
+         greenland_icesheet_timelapsed = 0.0
+      ENDIF
+      IF( iom_varid( numror, 'antarctica_icesheet_mass', ldstop = .FALSE. ) > 0 )   THEN
+         CALL iom_get( numror, 'antarctica_icesheet_mass', antarctica_icesheet_mass )
+         CALL iom_get( numror, 'antarctica_icesheet_timelapsed', antarctica_icesheet_timelapsed )
+         CALL iom_get( numror, 'antarctica_icesheet_mass_roc', antarctica_icesheet_mass_rate_of_change )
+      ELSE
+         antarctica_icesheet_mass = 0.0 
+         antarctica_icesheet_mass_rate_of_change = 0.0 
+         antarctica_icesheet_timelapsed = 0.0
+      ENDIF
+
       IF( neuler == 0 ) THEN                                  ! Euler restart (neuler=0)
          tsb  (:,:,:,:) = tsn  (:,:,:,:)                             ! all before fields set to now values
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/lbclnk.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/lbclnk.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/lbclnk.F90	(revision 9987)
@@ -11,4 +11,5 @@
    !!                            the BDY/OBC communications
    !!            3.4  ! 2012-12  (R. Bourdalle-Badie and G. Reffray)  add a C1D case  
+   !!            3.6  ! 2015-06  (O. Tintó and M. Castrillo)  add lbc_lnk_multi  
    !!----------------------------------------------------------------------
 #if defined key_mpp_mpi
@@ -24,5 +25,5 @@
 
    INTERFACE lbc_lnk_multi
-      MODULE PROCEDURE mpp_lnk_2d_9
+      MODULE PROCEDURE mpp_lnk_2d_9, mpp_lnk_2d_multiple
    END INTERFACE
 
@@ -80,4 +81,8 @@
    END INTERFACE
 
+   INTERFACE lbc_lnk_multi
+      MODULE PROCEDURE lbc_lnk_2d_9, lbc_lnk_2d_multiple
+   END INTERFACE
+
    INTERFACE lbc_bdy_lnk
       MODULE PROCEDURE lbc_bdy_lnk_2d, lbc_bdy_lnk_3d
@@ -87,7 +92,13 @@
       MODULE PROCEDURE lbc_lnk_2d_e
    END INTERFACE
+   
+   TYPE arrayptr
+      REAL , DIMENSION (:,:),  POINTER :: pt2d
+   END TYPE arrayptr
+   PUBLIC   arrayptr
 
    PUBLIC   lbc_lnk       ! ocean/ice  lateral boundary conditions
    PUBLIC   lbc_lnk_e 
+   PUBLIC   lbc_lnk_multi ! modified ocean lateral boundary conditions
    PUBLIC   lbc_bdy_lnk   ! ocean lateral BDY boundary conditions
    PUBLIC   lbc_lnk_icb
@@ -171,4 +182,61 @@
       !
    END SUBROUTINE lbc_lnk_2d
+   
+   SUBROUTINE lbc_lnk_2d_multiple( pt2d_array , type_array , psgn_array , num_fields )
+      !!
+      INTEGER :: num_fields
+      TYPE( arrayptr ), DIMENSION(:) :: pt2d_array
+      CHARACTER(len=1), DIMENSION(:), INTENT(in   ) ::   type_array   ! define the nature of ptab array grid-points
+      !                                                               ! = T , U , V , F , W and I points
+      REAL(wp)        , DIMENSION(:), INTENT(in   ) ::   psgn_array   ! =-1 the sign change across the north fold boundary
+      !                                                               ! =  1. , the sign is kept
+      !
+      INTEGER  ::   ii    !!MULTI SEND DUMMY LOOP INDICES
+      !
+      DO ii = 1, num_fields
+        CALL lbc_lnk_2d( pt2d_array(ii)%pt2d, type_array(ii), psgn_array(ii) )
+      END DO     
+      !
+   END SUBROUTINE lbc_lnk_2d_multiple
+
+   SUBROUTINE lbc_lnk_2d_9( pt2dA, cd_typeA, psgnA, pt2dB, cd_typeB, psgnB, pt2dC, cd_typeC, psgnC   &
+      &                   , pt2dD, cd_typeD, psgnD, pt2dE, cd_typeE, psgnE, pt2dF, cd_typeF, psgnF   &
+      &                   , pt2dG, cd_typeG, psgnG, pt2dH, cd_typeH, psgnH, pt2dI, cd_typeI, psgnI, cd_mpp, pval)
+      !!---------------------------------------------------------------------
+      ! Second 2D array on which the boundary condition is applied
+      REAL(wp), DIMENSION(jpi,jpj), TARGET          , INTENT(inout) ::   pt2dA
+      REAL(wp), DIMENSION(jpi,jpj), TARGET, OPTIONAL, INTENT(inout) ::   pt2dB , pt2dC , pt2dD , pt2dE
+      REAL(wp), DIMENSION(jpi,jpj), TARGET, OPTIONAL, INTENT(inout) ::   pt2dF , pt2dG , pt2dH , pt2dI
+      ! define the nature of ptab array grid-points
+      CHARACTER(len=1)                              , INTENT(in   ) ::   cd_typeA
+      CHARACTER(len=1)                    , OPTIONAL, INTENT(in   ) ::   cd_typeB , cd_typeC , cd_typeD , cd_typeE
+      CHARACTER(len=1)                    , OPTIONAL, INTENT(in   ) ::   cd_typeF , cd_typeG , cd_typeH , cd_typeI
+      ! =-1 the sign change across the north fold boundary
+      REAL(wp)                                      , INTENT(in   ) ::   psgnA
+      REAL(wp)                            , OPTIONAL, INTENT(in   ) ::   psgnB , psgnC , psgnD , psgnE
+      REAL(wp)                            , OPTIONAL, INTENT(in   ) ::   psgnF , psgnG , psgnH , psgnI
+      CHARACTER(len=3)                    , OPTIONAL, INTENT(in   ) ::   cd_mpp   ! fill the overlap area only
+      REAL(wp)                            , OPTIONAL, INTENT(in   ) ::   pval     ! background value (used at closed boundaries)
+      !!
+      !!---------------------------------------------------------------------
+
+      !!The first array
+      CALL lbc_lnk( pt2dA, cd_typeA, psgnA ) 
+
+      !! Look if more arrays to process
+      IF(PRESENT (psgnB) )CALL lbc_lnk( pt2dA, cd_typeA, psgnA ) 
+      IF(PRESENT (psgnC) )CALL lbc_lnk( pt2dC, cd_typeC, psgnC ) 
+      IF(PRESENT (psgnD) )CALL lbc_lnk( pt2dD, cd_typeD, psgnD ) 
+      IF(PRESENT (psgnE) )CALL lbc_lnk( pt2dE, cd_typeE, psgnE ) 
+      IF(PRESENT (psgnF) )CALL lbc_lnk( pt2dF, cd_typeF, psgnF ) 
+      IF(PRESENT (psgnG) )CALL lbc_lnk( pt2dG, cd_typeG, psgnG ) 
+      IF(PRESENT (psgnH) )CALL lbc_lnk( pt2dH, cd_typeH, psgnH ) 
+      IF(PRESENT (psgnI) )CALL lbc_lnk( pt2dI, cd_typeI, psgnI ) 
+
+   END SUBROUTINE lbc_lnk_2d_9
+
+
+
+
 
 #else
@@ -372,4 +440,58 @@
       !    
    END SUBROUTINE lbc_lnk_2d
+   
+   SUBROUTINE lbc_lnk_2d_multiple( pt2d_array , type_array , psgn_array , num_fields )
+      !!
+      INTEGER :: num_fields
+      TYPE( arrayptr ), DIMENSION(:) :: pt2d_array
+      CHARACTER(len=1), DIMENSION(:), INTENT(in   ) ::   type_array   ! define the nature of ptab array grid-points
+      !                                                               ! = T , U , V , F , W and I points
+      REAL(wp)        , DIMENSION(:), INTENT(in   ) ::   psgn_array   ! =-1 the sign change across the north fold boundary
+      !                                                               ! =  1. , the sign is kept
+      !
+      INTEGER  ::   ii    !!MULTI SEND DUMMY LOOP INDICES
+      !
+      DO ii = 1, num_fields
+        CALL lbc_lnk_2d( pt2d_array(ii)%pt2d, type_array(ii), psgn_array(ii) )
+      END DO     
+      !
+   END SUBROUTINE lbc_lnk_2d_multiple
+
+   SUBROUTINE lbc_lnk_2d_9( pt2dA, cd_typeA, psgnA, pt2dB, cd_typeB, psgnB, pt2dC, cd_typeC, psgnC   &
+      &                   , pt2dD, cd_typeD, psgnD, pt2dE, cd_typeE, psgnE, pt2dF, cd_typeF, psgnF   &
+      &                   , pt2dG, cd_typeG, psgnG, pt2dH, cd_typeH, psgnH, pt2dI, cd_typeI, psgnI, cd_mpp, pval)
+      !!---------------------------------------------------------------------
+      ! Second 2D array on which the boundary condition is applied
+      REAL(wp), DIMENSION(jpi,jpj), TARGET          , INTENT(inout) ::   pt2dA
+      REAL(wp), DIMENSION(jpi,jpj), TARGET, OPTIONAL, INTENT(inout) ::   pt2dB , pt2dC , pt2dD , pt2dE
+      REAL(wp), DIMENSION(jpi,jpj), TARGET, OPTIONAL, INTENT(inout) ::   pt2dF , pt2dG , pt2dH , pt2dI
+      ! define the nature of ptab array grid-points
+      CHARACTER(len=1)                              , INTENT(in   ) ::   cd_typeA
+      CHARACTER(len=1)                    , OPTIONAL, INTENT(in   ) ::   cd_typeB , cd_typeC , cd_typeD , cd_typeE
+      CHARACTER(len=1)                    , OPTIONAL, INTENT(in   ) ::   cd_typeF , cd_typeG , cd_typeH , cd_typeI
+      ! =-1 the sign change across the north fold boundary
+      REAL(wp)                                      , INTENT(in   ) ::   psgnA
+      REAL(wp)                            , OPTIONAL, INTENT(in   ) ::   psgnB , psgnC , psgnD , psgnE
+      REAL(wp)                            , OPTIONAL, INTENT(in   ) ::   psgnF , psgnG , psgnH , psgnI
+      CHARACTER(len=3)                    , OPTIONAL, INTENT(in   ) ::   cd_mpp   ! fill the overlap area only
+      REAL(wp)                            , OPTIONAL, INTENT(in   ) ::   pval     ! background value (used at closed boundaries)
+      !!
+      !!---------------------------------------------------------------------
+
+      !!The first array
+      CALL lbc_lnk( pt2dA, cd_typeA, psgnA ) 
+
+      !! Look if more arrays to process
+      IF(PRESENT (psgnB) )CALL lbc_lnk( pt2dA, cd_typeA, psgnA ) 
+      IF(PRESENT (psgnC) )CALL lbc_lnk( pt2dC, cd_typeC, psgnC ) 
+      IF(PRESENT (psgnD) )CALL lbc_lnk( pt2dD, cd_typeD, psgnD ) 
+      IF(PRESENT (psgnE) )CALL lbc_lnk( pt2dE, cd_typeE, psgnE ) 
+      IF(PRESENT (psgnF) )CALL lbc_lnk( pt2dF, cd_typeF, psgnF ) 
+      IF(PRESENT (psgnG) )CALL lbc_lnk( pt2dG, cd_typeG, psgnG ) 
+      IF(PRESENT (psgnH) )CALL lbc_lnk( pt2dH, cd_typeH, psgnH ) 
+      IF(PRESENT (psgnI) )CALL lbc_lnk( pt2dI, cd_typeI, psgnI ) 
+
+   END SUBROUTINE lbc_lnk_2d_9
+
 
 #endif
@@ -441,2 +563,3 @@
    !!======================================================================
 END MODULE lbclnk
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/lib_mpp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/lib_mpp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/lib_mpp.F90	(revision 9987)
@@ -24,4 +24,5 @@
    !!            3.5  !  2013  ( C. Ethe, G. Madec ) message passing arrays as local variables 
    !!            3.5  !  2013 (S.Mocavero, I.Epicoco - CMCC) north fold optimizations
+   !!            3.6  !  2015 (O. Tintó and M. Castrillo - BSC) Added 'mpp_lnk_2d_multiple', 'mpp_lbc_north_2d_multiple', 'mpp_max_multiple' 
    !!----------------------------------------------------------------------
 
@@ -62,4 +63,5 @@
    USE lbcnfd         ! north fold treatment
    USE in_out_manager ! I/O manager
+   USE wrk_nemo       ! work arrays
 
    IMPLICIT NONE
@@ -70,6 +72,7 @@
    PUBLIC   mpp_ini_north, mpp_lbc_north, mpp_lbc_north_e
    PUBLIC   mpp_min, mpp_max, mpp_sum, mpp_minloc, mpp_maxloc
+   PUBLIC   mpp_max_multiple
    PUBLIC   mpp_lnk_3d, mpp_lnk_3d_gather, mpp_lnk_2d, mpp_lnk_2d_e
-   PUBLIC   mpp_lnk_2d_9 
+   PUBLIC   mpp_lnk_2d_9 , mpp_lnk_2d_multiple 
    PUBLIC   mppscatter, mppgather
    PUBLIC   mpp_ini_ice, mpp_ini_znl
@@ -78,8 +81,10 @@
    PUBLIC   mpp_lnk_bdy_2d, mpp_lnk_bdy_3d
    PUBLIC   mpp_lbc_north_icb, mpp_lnk_2d_icb
+   PUBLIC   mpprank
 
    TYPE arrayptr
       REAL , DIMENSION (:,:),  POINTER :: pt2d
    END TYPE arrayptr
+   PUBLIC   arrayptr
    
    !! * Interfaces
@@ -105,4 +110,8 @@
    INTERFACE mpp_maxloc
       MODULE PROCEDURE mpp_maxloc2d ,mpp_maxloc3d
+   END INTERFACE
+
+   INTERFACE mpp_max_multiple
+      MODULE PROCEDURE mppmax_real_multiple
    END INTERFACE
 
@@ -298,4 +307,12 @@
       ENDIF
 
+#if defined key_agrif
+      IF (Agrif_Root()) THEN
+         CALL Agrif_MPI_Init(mpi_comm_opa)
+      ELSE
+         CALL Agrif_MPI_set_grid_comm(mpi_comm_opa)
+      ENDIF
+#endif
+
       CALL mpi_comm_rank( mpi_comm_opa, mpprank, ierr )
       CALL mpi_comm_size( mpi_comm_opa, mppsize, ierr )
@@ -724,16 +741,17 @@
       ! -----------------------
       !
-      DO ii = 1 , num_fields
          !First Array
-         IF( npolj /= 0 .AND. .NOT. PRESENT(cd_mpp) ) THEN
-            !
-            SELECT CASE ( jpni )
-            CASE ( 1 )     ;   CALL lbc_nfd      ( pt2d_array(ii)%pt2d( : , : ), type_array(ii) , psgn_array(ii) )   ! only 1 northern proc, no mpp
-            CASE DEFAULT   ;   CALL mpp_lbc_north( pt2d_array(ii)%pt2d( : , : ), type_array(ii), psgn_array(ii) )   ! for all northern procs.
-            END SELECT
-            !
-         ENDIF
-         !
-      END DO
+      IF( npolj /= 0 .AND. .NOT. PRESENT(cd_mpp) ) THEN
+         !
+         SELECT CASE ( jpni )
+         CASE ( 1 )     ;   
+             DO ii = 1 , num_fields  
+                       CALL lbc_nfd      ( pt2d_array(ii)%pt2d( : , : ), type_array(ii) , psgn_array(ii) )   ! only 1 northern proc, no mpp
+             END DO
+         CASE DEFAULT   ;   CALL mpp_lbc_north_2d_multiple( pt2d_array, type_array, psgn_array, num_fields )   ! for all northern procs.
+         END SELECT
+         !
+      ENDIF
+        !
       
       DEALLOCATE( zt2ns, zt2sn, zt2ew, zt2we )
@@ -1681,4 +1699,29 @@
    END SUBROUTINE mppmax_real
 
+   SUBROUTINE mppmax_real_multiple( ptab, NUM , kcom  )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mppmax_real  ***
+      !!
+      !! ** Purpose :   Maximum
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:) ,  INTENT(inout)           ::   ptab   ! ???
+      INTEGER , INTENT(in   )           ::   NUM
+      INTEGER , INTENT(in   ), OPTIONAL ::   kcom   ! ???
+      !!
+      INTEGER  ::   ierror, localcomm
+      REAL(wp) , POINTER , DIMENSION(:) ::   zwork
+      !!----------------------------------------------------------------------
+      !
+      CALL wrk_alloc(NUM , zwork)
+      localcomm = mpi_comm_opa
+      IF( PRESENT(kcom) )   localcomm = kcom
+      !
+      CALL mpi_allreduce( ptab, zwork, NUM, mpi_double_precision, mpi_max, localcomm, ierror )
+      ptab = zwork
+      CALL wrk_dealloc(NUM , zwork)
+      !
+   END SUBROUTINE mppmax_real_multiple
+
 
    SUBROUTINE mppmin_a_real( ptab, kdim, kcom )
@@ -2006,4 +2049,9 @@
 
    SUBROUTINE mppstop
+   
+#if defined key_oasis3
+   USE mod_oasis      ! coupling routines
+#endif
+
       !!----------------------------------------------------------------------
       !!                  ***  routine mppstop  ***
@@ -2015,6 +2063,19 @@
       !!----------------------------------------------------------------------
       !
+      
+#if defined key_oasis3
+      ! If we're trying to shut down cleanly then we need to consider the fact
+      ! that this could be part of an MPMD configuration - we don't want to
+      ! leave other components deadlocked.
+
+      CALL oasis_abort(nproc,"mppstop","NEMO initiated abort")
+
+
+#else
+      
       CALL mppsync
       CALL mpi_finalize( info )
+#endif
+
       !
    END SUBROUTINE mppstop
@@ -2575,4 +2636,166 @@
    END SUBROUTINE mpp_lbc_north_2d
 
+   SUBROUTINE mpp_lbc_north_2d_multiple( pt2d_array, cd_type, psgn, num_fields)
+      !!---------------------------------------------------------------------
+      !!                   ***  routine mpp_lbc_north_2d  ***
+      !!
+      !! ** Purpose :   Ensure proper north fold horizontal bondary condition
+      !!              in mpp configuration in case of jpn1 > 1
+      !!              (for multiple 2d arrays )
+      !!
+      !! ** Method  :   North fold condition and mpp with more than one proc
+      !!              in i-direction require a specific treatment. We gather
+      !!              the 4 northern lines of the global domain on 1 processor
+      !!              and apply lbc north-fold on this sub array. Then we
+      !!              scatter the north fold array back to the processors.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ,  INTENT (in   ) ::   num_fields  ! number of variables contained in pt2d
+      TYPE( arrayptr ), DIMENSION(:) :: pt2d_array
+      CHARACTER(len=1), DIMENSION(:), INTENT(in   ) ::   cd_type   ! nature of pt2d grid-points
+      !                                                          !   = T ,  U , V , F or W  gridpoints
+      REAL(wp), DIMENSION(:), INTENT(in   ) ::   psgn      ! = -1. the sign change across the north fold 
+      !!                                                             ! =  1. , the sign is kept
+      INTEGER ::   ji, jj, jr, jk
+      INTEGER ::   ierr, itaille, ildi, ilei, iilb
+      INTEGER ::   ijpj, ijpjm1, ij, iproc
+      INTEGER, DIMENSION (jpmaxngh)      ::   ml_req_nf          !for mpi_isend when avoiding mpi_allgather
+      INTEGER                            ::   ml_err             ! for mpi_isend when avoiding mpi_allgather
+      INTEGER, DIMENSION(MPI_STATUS_SIZE)::   ml_stat            ! for mpi_isend when avoiding mpi_allgather
+      !                                                              ! Workspace for message transfers avoiding mpi_allgather
+      REAL(wp), DIMENSION(:,:,:)  , ALLOCATABLE   :: ztab
+      REAL(wp), DIMENSION(:,:,:)  , ALLOCATABLE   :: znorthloc, zfoldwk
+      REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE   :: znorthgloio
+      REAL(wp), DIMENSION(:,:,:)  , ALLOCATABLE   :: ztabl, ztabr
+      INTEGER :: istatus(mpi_status_size)
+      INTEGER :: iflag
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( ztab(jpiglo,4,num_fields), znorthloc(jpi,4,num_fields), zfoldwk(jpi,4,num_fields),   & 
+            &   znorthgloio(jpi,4,num_fields,jpni) )   ! expanded to 3 dimensions
+      ALLOCATE( ztabl(jpi,4,num_fields), ztabr(jpi*jpmaxngh, 4,num_fields) )
+      !
+      ijpj   = 4
+      ijpjm1 = 3
+      !
+      
+      DO jk = 1, num_fields
+         DO jj = nlcj-ijpj+1, nlcj             ! put in znorthloc the last 4 jlines of pt2d (for every variable)
+            ij = jj - nlcj + ijpj
+            znorthloc(:,ij,jk) = pt2d_array(jk)%pt2d(:,jj)
+         END DO
+      END DO
+      !                                     ! Build in procs of ncomm_north the znorthgloio
+      itaille = jpi * ijpj
+                                                                  
+      IF ( l_north_nogather ) THEN
+         !
+         ! Avoid the use of mpi_allgather by exchanging only with the processes already identified 
+         ! (in nemo_northcomms) as being  involved in this process' northern boundary exchange
+         !
+         ztabr(:,:,:) = 0
+         ztabl(:,:,:) = 0
+
+         DO jk = 1, num_fields
+            DO jj = nlcj-ijpj+1, nlcj          ! First put local values into the global array
+               ij = jj - nlcj + ijpj
+               DO ji = nfsloop, nfeloop
+                  ztabl(ji,ij,jk) = pt2d_array(jk)%pt2d(ji,jj)
+               END DO
+            END DO
+         END DO
+
+         DO jr = 1,nsndto
+            IF ((nfipproc(isendto(jr),jpnj) .ne. (narea-1)) .and. (nfipproc(isendto(jr),jpnj) .ne. -1)) THEN
+               CALL mppsend(5, znorthloc, itaille*num_fields, nfipproc(isendto(jr),jpnj), ml_req_nf(jr)) ! Buffer expanded "num_fields" times
+            ENDIF
+         END DO
+         DO jr = 1,nsndto
+            iproc = nfipproc(isendto(jr),jpnj)
+            IF(iproc .ne. -1) THEN
+               ilei = nleit (iproc+1)
+               ildi = nldit (iproc+1)
+               iilb = nfiimpp(isendto(jr),jpnj) - nfiimpp(isendto(1),jpnj)
+            ENDIF
+            IF((iproc .ne. (narea-1)) .and. (iproc .ne. -1)) THEN
+              CALL mpprecv(5, zfoldwk, itaille*num_fields, iproc) ! Buffer expanded "num_fields" times
+              DO jk = 1 , num_fields
+                 DO jj = 1, ijpj
+                    DO ji = ildi, ilei
+                       ztabr(iilb+ji,jj,jk) = zfoldwk(ji,jj,jk)       ! Modified to 3D
+                    END DO
+                 END DO
+              END DO
+            ELSE IF (iproc .eq. (narea-1)) THEN
+              DO jk = 1, num_fields
+                 DO jj = 1, ijpj
+                    DO ji = ildi, ilei
+                          ztabr(iilb+ji,jj,jk) = pt2d_array(jk)%pt2d(ji,nlcj-ijpj+jj)       ! Modified to 3D
+                    END DO
+                 END DO
+              END DO
+            ENDIF
+         END DO
+         IF (l_isend) THEN
+            DO jr = 1,nsndto
+               IF ((nfipproc(isendto(jr),jpnj) .ne. (narea-1)) .and. (nfipproc(isendto(jr),jpnj) .ne. -1)) THEN
+                  CALL mpi_wait(ml_req_nf(jr), ml_stat, ml_err)
+               ENDIF
+            END DO
+         ENDIF
+         !
+         DO ji = 1, num_fields     ! Loop to manage 3D variables
+            CALL mpp_lbc_nfd( ztabl(:,:,ji), ztabr(:,:,ji), cd_type(ji), psgn(ji) )  ! North fold boundary condition
+         END DO
+         !
+         DO jk = 1, num_fields
+            DO jj = nlcj-ijpj+1, nlcj             ! Scatter back to pt2d
+               ij = jj - nlcj + ijpj
+               DO ji = 1, nlci
+                  pt2d_array(jk)%pt2d(ji,jj) = ztabl(ji,ij,jk)       ! Modified to 3D
+               END DO
+            END DO
+         END DO
+         
+         !
+      ELSE
+         !
+         CALL MPI_ALLGATHER( znorthloc  , itaille*num_fields, MPI_DOUBLE_PRECISION,        &
+            &                znorthgloio, itaille*num_fields, MPI_DOUBLE_PRECISION, ncomm_north, ierr )
+         !
+         ztab(:,:,:) = 0.e0
+         DO jk = 1, num_fields
+            DO jr = 1, ndim_rank_north            ! recover the global north array
+               iproc = nrank_north(jr) + 1
+               ildi = nldit (iproc)
+               ilei = nleit (iproc)
+               iilb = nimppt(iproc)
+               DO jj = 1, ijpj
+                  DO ji = ildi, ilei
+                     ztab(ji+iilb-1,jj,jk) = znorthgloio(ji,jj,jk,jr)
+                  END DO
+               END DO
+            END DO
+         END DO
+         
+         DO ji = 1, num_fields
+            CALL lbc_nfd( ztab(:,:,ji), cd_type(ji), psgn(ji) )   ! North fold boundary condition
+         END DO
+         !
+         DO jk = 1, num_fields
+            DO jj = nlcj-ijpj+1, nlcj             ! Scatter back to pt2d
+               ij = jj - nlcj + ijpj
+               DO ji = 1, nlci
+                  pt2d_array(jk)%pt2d(ji,jj) = ztab(ji+nimpp-1,ij,jk)
+               END DO
+            END DO
+         END DO
+         !
+         !
+      ENDIF
+      DEALLOCATE( ztab, znorthloc, zfoldwk, znorthgloio )
+      DEALLOCATE( ztabl, ztabr )
+      !
+   END SUBROUTINE mpp_lbc_north_2d_multiple
 
    SUBROUTINE mpp_lbc_north_e( pt2d, cd_type, psgn)
@@ -3680,4 +3903,8 @@
       IF( numevo_ice /= -1 )   CALL FLUSH(numevo_ice)
       !
+      IF( cd1 == 'MPPSTOP' ) THEN
+         IF(lwp) WRITE(numout,*)  'E R R O R: Calling mppstop'
+         CALL mppstop()
+      ENDIF
       IF( cd1 == 'STOP' ) THEN
          IF(lwp) WRITE(numout,*)  'huge E-R-R-O-R : immediate stop'
@@ -3784,5 +4011,5 @@
             WRITE(kout,*)
          ENDIF
-         STOP 'ctl_opn bad opening'
+         CALL ctl_stop ('STOP', 'NEMO abort ctl_opn bad opening')
       ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/mppini.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/mppini.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/mppini.F90	(revision 9987)
@@ -201,45 +201,4 @@
       
 #endif
-      IF(lwp) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) '           defines mpp subdomains'
-         WRITE(numout,*) '           ----------------------'
-         WRITE(numout,*) '           iresti=',iresti,' irestj=',irestj
-         WRITE(numout,*) '           jpni  =',jpni  ,' jpnj  =',jpnj
-         ifreq = 4
-         il1   = 1
-         DO jn = 1, (jpni-1)/ifreq+1
-            il2 = MIN( jpni, il1+ifreq-1 )
-            WRITE(numout,*)
-            WRITE(numout,9200) ('***',ji = il1,il2-1)
-            DO jj = jpnj, 1, -1
-               WRITE(numout,9203) ('   ',ji = il1,il2-1)
-               WRITE(numout,9202) jj, ( ilcit(ji,jj),ilcjt(ji,jj),ji = il1,il2 )
-               WRITE(numout,9203) ('   ',ji = il1,il2-1)
-               WRITE(numout,9200) ('***',ji = il1,il2-1)
-            END DO
-            WRITE(numout,9201) (ji,ji = il1,il2)
-            il1 = il1+ifreq
-         END DO
- 9200    FORMAT('     ***',20('*************',a3))
- 9203    FORMAT('     *     ',20('         *   ',a3))
- 9201    FORMAT('        ',20('   ',i3,'          '))
- 9202    FORMAT(' ',i3,' *  ',20(i3,'  x',i3,'   *   '))
-      ENDIF
-
-      zidom = nreci
-      DO ji = 1, jpni
-         zidom = zidom + ilcit(ji,1) - nreci
-      END DO
-      IF(lwp) WRITE(numout,*)
-      IF(lwp) WRITE(numout,*)' sum ilcit(i,1) = ', zidom, ' jpiglo = ', jpiglo
-      
-      zjdom = nrecj
-      DO jj = 1, jpnj
-         zjdom = zjdom + ilcjt(1,jj) - nrecj
-      END DO
-      IF(lwp) WRITE(numout,*)' sum ilcit(1,j) = ', zjdom, ' jpjglo = ', jpjglo
-      IF(lwp) WRITE(numout,*)
-      
 
       !  2. Index arrays for subdomains
@@ -304,7 +263,54 @@
          nlejt(jn) = nlej
       END DO
-      
-
-      ! 4. From global to local
+
+      ! 4. Subdomain print
+      ! ------------------
+      
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' mpp_init: defines mpp subdomains'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~  ----------------------'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'iresti=',iresti,' irestj=',irestj
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'jpni=',jpni,' jpnj=',jpnj
+      zidom = nreci
+      DO ji = 1, jpni
+         zidom = zidom + ilcit(ji,1) - nreci
+      END DO
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*)' sum ilcit(i,1)=', zidom, ' jpiglo=', jpiglo
+
+      zjdom = nrecj
+      DO jj = 1, jpnj
+         zjdom = zjdom + ilcjt(1,jj) - nrecj
+      END DO
+      IF(lwp) WRITE(numout,*)' sum ilcit(1,j)=', zjdom, ' jpjglo=', jpjglo
+      IF(lwp) WRITE(numout,*)
+
+      IF(lwp) THEN
+         ifreq = 4
+         il1   = 1
+         DO jn = 1, (jpni-1)/ifreq+1
+            il2 = MIN( jpni, il1+ifreq-1 )
+            WRITE(numout,*)
+            WRITE(numout,9200) ('***',ji = il1,il2-1)
+            DO jj = jpnj, 1, -1
+               WRITE(numout,9203) ('   ',ji = il1,il2-1)
+               WRITE(numout,9202) jj, ( ilcit(ji,jj),ilcjt(ji,jj),ji = il1,il2 )
+               WRITE(numout,9204) (nfipproc(ji,jj),ji=il1,il2)
+               WRITE(numout,9203) ('   ',ji = il1,il2-1)
+               WRITE(numout,9200) ('***',ji = il1,il2-1)
+            END DO
+            WRITE(numout,9201) (ji,ji = il1,il2)
+            il1 = il1+ifreq
+         END DO
+ 9200     FORMAT('     ***',20('*************',a3))
+ 9203     FORMAT('     *     ',20('         *   ',a3))
+ 9201     FORMAT('        ',20('   ',i3,'          '))
+ 9202     FORMAT(' ',i3,' *  ',20(i3,'  x',i3,'   *   '))
+ 9204     FORMAT('     *  ',20('      ',i3,'   *   '))
+      ENDIF
+
+      ! 5. From global to local
       ! -----------------------
 
@@ -313,5 +319,5 @@
 
 
-      ! 5. Subdomain neighbours
+      ! 6. Subdomain neighbours
       ! ----------------------
 
@@ -436,8 +442,9 @@
          WRITE(numout,*) ' nimpp  = ', nimpp
          WRITE(numout,*) ' njmpp  = ', njmpp
-         WRITE(numout,*) ' nbse   = ', nbse  , ' npse   = ', npse
-         WRITE(numout,*) ' nbsw   = ', nbsw  , ' npsw   = ', npsw
-         WRITE(numout,*) ' nbne   = ', nbne  , ' npne   = ', npne
-         WRITE(numout,*) ' nbnw   = ', nbnw  , ' npnw   = ', npnw
+         WRITE(numout,*) ' nreci  = ', nreci  , ' npse   = ', npse
+         WRITE(numout,*) ' nrecj  = ', nrecj  , ' npsw   = ', npsw
+         WRITE(numout,*) ' jpreci = ', jpreci , ' npne   = ', npne
+         WRITE(numout,*) ' jprecj = ', jprecj , ' npnw   = ', npnw
+         WRITE(numout,*)
       ENDIF
 
@@ -446,7 +453,8 @@
       ! Prepare mpp north fold
 
-      IF (jperio >= 3 .AND. jperio <= 6 .AND. jpni > 1 ) THEN
+      IF( jperio >= 3 .AND. jperio <= 6 .AND. jpni > 1 ) THEN
          CALL mpp_ini_north
-      END IF
+         IF(lwp) WRITE(numout,*) ' mpp_init : North fold boundary prepared for jpni >1'
+      ENDIF
 
       ! Prepare NetCDF output file (if necessary)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/mppini_2.h90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/mppini_2.h90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LBC/mppini_2.h90	(revision 9987)
@@ -318,10 +318,12 @@
          ENDIF
 
+         ! Check wet points over the entire domain to preserve the MPI communication stencil
          isurf = 0
-         DO jj = 1+jprecj, ilj-jprecj
-            DO  ji = 1+jpreci, ili-jpreci
+         DO jj = 1, ilj
+            DO  ji = 1, ili
                IF( imask(ji+iimppt(ii,ij)-1, jj+ijmppt(ii,ij)-1) == 1) isurf = isurf+1
             END DO
          END DO
+
          IF(isurf /= 0) THEN
             icont = icont + 1
@@ -333,5 +335,4 @@
 
       nfipproc(:,:) = ipproc(:,:)
-
 
       ! Control
@@ -441,4 +442,16 @@
       ii = iin(narea)
       ij = ijn(narea)
+
+      ! set default neighbours
+      noso = ioso(ii,ij)
+      nowe = iowe(ii,ij)
+      noea = ioea(ii,ij)
+      nono = iono(ii,ij) 
+      npse = iose(ii,ij)
+      npsw = iosw(ii,ij)
+      npne = ione(ii,ij)
+      npnw = ionw(ii,ij)
+
+      ! check neighbours location
       IF( ioso(ii,ij) >= 0 .AND. ioso(ii,ij) <= (jpni*jpnj-1) ) THEN 
          iiso = 1 + MOD(ioso(ii,ij),jpni)
@@ -511,4 +524,5 @@
       IF (lwp) THEN
          CALL ctl_opn( inum, 'layout.dat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE., narea )
+         WRITE(inum,'(a)') '   jpnij     jpi     jpj     jpk  jpiglo  jpjglo'
          WRITE(inum,'(6i8)') jpnij,jpi,jpj,jpk,jpiglo,jpjglo
          WRITE(inum,'(a)') 'NAREA nlci nlcj nldi nldj nlei nlej nimpp njmpp'
@@ -523,13 +537,4 @@
       END IF
 
-      IF( nperio == 1 .AND.jpni /= 1 ) CALL ctl_stop( ' mpp_init2:  error on cyclicity' )
-
-      ! Prepare mpp north fold
-
-      IF( jperio >= 3 .AND. jperio <= 6 .AND. jpni > 1 ) THEN
-         CALL mpp_ini_north
-         IF(lwp) WRITE(numout,*) ' mpp_init2 : North fold boundary prepared for jpni >1'
-      ENDIF
-
       ! Defined npolj, either 0, 3 , 4 , 5 , 6
       ! In this case the important thing is that npolj /= 0
@@ -548,28 +553,37 @@
       ENDIF
 
+      ! Periodicity : no corner if nbondi = 2 and nperio != 1
+
+      IF(lwp) THEN
+         WRITE(numout,*) ' nproc  = ', nproc
+         WRITE(numout,*) ' nowe   = ', nowe  , ' noea   =  ', noea
+         WRITE(numout,*) ' nono   = ', nono  , ' noso   =  ', noso
+         WRITE(numout,*) ' nbondi = ', nbondi
+         WRITE(numout,*) ' nbondj = ', nbondj
+         WRITE(numout,*) ' npolj  = ', npolj
+         WRITE(numout,*) ' nperio = ', nperio
+         WRITE(numout,*) ' nlci   = ', nlci
+         WRITE(numout,*) ' nlcj   = ', nlcj
+         WRITE(numout,*) ' nimpp  = ', nimpp
+         WRITE(numout,*) ' njmpp  = ', njmpp
+         WRITE(numout,*) ' nreci  = ', nreci  , ' npse   = ', npse
+         WRITE(numout,*) ' nrecj  = ', nrecj  , ' npsw   = ', npsw
+         WRITE(numout,*) ' jpreci = ', jpreci , ' npne   = ', npne
+         WRITE(numout,*) ' jprecj = ', jprecj , ' npnw   = ', npnw
+         WRITE(numout,*)
+      ENDIF
+
+      IF( nperio == 1 .AND. jpni /= 1 ) CALL ctl_stop( ' mpp_init2: error on cyclicity' )
+
+      ! Prepare mpp north fold
+
+      IF( jperio >= 3 .AND. jperio <= 6 .AND. jpni > 1 ) THEN
+         CALL mpp_ini_north
+         IF(lwp) WRITE(numout,*) ' mpp_init2 : North fold boundary prepared for jpni >1'
+      ENDIF
+
       ! Prepare NetCDF output file (if necessary)
       CALL mpp_init_ioipsl
 
-      ! Periodicity : no corner if nbondi = 2 and nperio != 1
-
-      IF(lwp) THEN
-         WRITE(numout,*) ' nproc=  ',nproc
-         WRITE(numout,*) ' nowe=   ',nowe
-         WRITE(numout,*) ' noea=   ',noea
-         WRITE(numout,*) ' nono=   ',nono
-         WRITE(numout,*) ' noso=   ',noso
-         WRITE(numout,*) ' nbondi= ',nbondi
-         WRITE(numout,*) ' nbondj= ',nbondj
-         WRITE(numout,*) ' npolj=  ',npolj
-         WRITE(numout,*) ' nperio= ',nperio
-         WRITE(numout,*) ' nlci=   ',nlci
-         WRITE(numout,*) ' nlcj=   ',nlcj
-         WRITE(numout,*) ' nimpp=  ',nimpp
-         WRITE(numout,*) ' njmpp=  ',njmpp
-         WRITE(numout,*) ' nbse=   ',nbse,' npse= ',npse
-         WRITE(numout,*) ' nbsw=   ',nbsw,' npsw= ',npsw
-         WRITE(numout,*) ' nbne=   ',nbne,' npne= ',npne
-         WRITE(numout,*) ' nbnw=   ',nbnw,' npnw= ',npnw
-      ENDIF
 
    END SUBROUTINE mpp_init2
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldfeiv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldfeiv.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldfeiv.F90	(revision 9987)
@@ -157,4 +157,14 @@
          END DO
       ENDIF
+
+      ! ORCA R1: Take the minimum between aeiw  and aeiv0
+      IF( cp_cfg == "orca" .AND. jp_cfg == 1 ) THEN
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               aeiw(ji,jj) = MIN( aeiw(ji,jj), aeiv0 )
+            END DO
+         END DO
+      ENDIF
+
       CALL lbc_lnk( aeiw, 'W', 1. )      ! lateral boundary condition on aeiw 
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldfslp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldfslp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldfslp.F90	(revision 9987)
@@ -188,10 +188,8 @@
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  IF (miku(ji,jj) .GT. miku(ji+1,jj)) zhmlpu(ji,jj) = MAX(hmlpt(ji  ,jj  ),                   5._wp)
-                  IF (miku(ji,jj) .LT. miku(ji+1,jj)) zhmlpu(ji,jj) = MAX(hmlpt(ji+1,jj  ),                   5._wp)
-                  IF (miku(ji,jj) .EQ. miku(ji+1,jj)) zhmlpu(ji,jj) = MAX(hmlpt(ji  ,jj  ), hmlpt(ji+1,jj  ), 5._wp)
-                  IF (mikv(ji,jj) .GT. miku(ji,jj+1)) zhmlpv(ji,jj) = MAX(hmlpt(ji  ,jj  ),                   5._wp)
-                  IF (mikv(ji,jj) .LT. miku(ji,jj+1)) zhmlpv(ji,jj) = MAX(hmlpt(ji  ,jj+1),                   5._wp)
-                  IF (mikv(ji,jj) .EQ. miku(ji,jj+1)) zhmlpv(ji,jj) = MAX(hmlpt(ji  ,jj  ), hmlpt(ji  ,jj+1), 5._wp)
+               zhmlpu(ji,jj) = ( MAX(hmlpt(ji,jj)  , hmlpt  (ji+1,jj  ), 5._wp)   &
+                  &            - MAX(risfdep(ji,jj), risfdep(ji+1,jj  )       )   )
+               zhmlpv(ji,jj) = ( MAX(hmlpt  (ji,jj), hmlpt  (ji  ,jj+1), 5._wp)   &
+                  &            - MAX(risfdep(ji,jj), risfdep(ji  ,jj+1)       )   )
                ENDDO
             ENDDO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldftra_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldftra_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldftra_oce.F90	(revision 9987)
@@ -41,4 +41,5 @@
 
    REAL(wp), PUBLIC ::   rldf                        !: multiplicative factor of diffusive coefficient
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   r_fact_lap
                                                      !: Needed to define the ratio between passive and active tracer diffusion coef. 
 
@@ -92,5 +93,5 @@
       !!                 ***  FUNCTION ldftra_oce_alloc  ***
      !!----------------------------------------------------------------------
-     INTEGER, DIMENSION(3) :: ierr
+     INTEGER, DIMENSION(4) :: ierr
      !!----------------------------------------------------------------------
      ierr(:) = 0
@@ -116,4 +117,5 @@
 # endif
 #endif
+      ALLOCATE( r_fact_lap(jpi,jpj,jpk), STAT=ierr(4) )
       ldftra_oce_alloc = MAXVAL( ierr )
       IF( ldftra_oce_alloc /= 0 )   CALL ctl_warn('ldftra_oce_alloc: failed to allocate arrays')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldftra_substitute.h90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldftra_substitute.h90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/LDF/ldftra_substitute.h90	(revision 9987)
@@ -13,5 +13,5 @@
 !   'key_traldf_c3d' :                 aht: 3D coefficient
 #       define   fsahtt(i,j,k)   rldf * ahtt(i,j,k)
-#       define   fsahtu(i,j,k)   rldf * ahtu(i,j,k)
+#       define   fsahtu(i,j,k)   rldf * ahtu(i,j,k) * r_fact_lap(i,j,k)
 #       define   fsahtv(i,j,k)   rldf * ahtv(i,j,k)
 #       define   fsahtw(i,j,k)   rldf * ahtw(i,j,k)
@@ -19,5 +19,5 @@
 !   'key_traldf_c2d' :                 aht: 2D coefficient
 #       define   fsahtt(i,j,k)   rldf * ahtt(i,j)
-#       define   fsahtu(i,j,k)   rldf * ahtu(i,j)
+#       define   fsahtu(i,j,k)   rldf * ahtu(i,j) * r_fact_lap(i,j,k)
 #       define   fsahtv(i,j,k)   rldf * ahtv(i,j)
 #       define   fsahtw(i,j,k)   rldf * ahtw(i,j)
@@ -25,5 +25,5 @@
 !   'key_traldf_c1d' :                aht: 1D coefficient
 #       define   fsahtt(i,j,k)   rldf * ahtt(k)
-#       define   fsahtu(i,j,k)   rldf * ahtu(k)
+#       define   fsahtu(i,j,k)   rldf * ahtu(k) * r_fact_lap(i,j,k)
 #       define   fsahtv(i,j,k)   rldf * ahtv(k)
 #       define   fsahtw(i,j,k)   rldf * ahtw(k)
@@ -31,5 +31,5 @@
 !   Default option :             aht: Constant coefficient
 #      define   fsahtt(i,j,k)   rldf * aht0
-#      define   fsahtu(i,j,k)   rldf * aht0
+#      define   fsahtu(i,j,k)   rldf * aht0 * r_fact_lap(i,j,k)
 #      define   fsahtv(i,j,k)   rldf * aht0
 #      define   fsahtw(i,j,k)   rldf * aht0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/albedo.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/albedo.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/albedo.F90	(revision 9987)
@@ -9,4 +9,5 @@
    !!             -   ! 2001-06  (M. Vancoppenolle) LIM 3.0
    !!             -   ! 2006-08  (G. Madec)  cleaning for surface module
+   !!            3.6  ! 2016-01  (C. Rousset) new parameterization for sea ice albedo
    !!----------------------------------------------------------------------
 
@@ -29,21 +30,14 @@
 
    INTEGER  ::   albd_init = 0      !: control flag for initialization
-   REAL(wp) ::   zzero     = 0.e0   ! constant values
-   REAL(wp) ::   zone      = 1.e0   !    "       "
-
-   REAL(wp) ::   c1     = 0.05    ! constants values
-   REAL(wp) ::   c2     = 0.10    !    "        "
-   REAL(wp) ::   rmue   = 0.40    !  cosine of local solar altitude
-
+  
+   REAL(wp) ::   rmue     = 0.40    !  cosine of local solar altitude
+   REAL(wp) ::   ralb_oce = 0.066   ! ocean or lead albedo (Pegau and Paulson, Ann. Glac. 2001)
+   REAL(wp) ::   c1       = 0.05    ! snow thickness (only for nn_ice_alb=0)
+   REAL(wp) ::   c2       = 0.10    !  "        "
+   REAL(wp) ::   rcloud   = 0.06    ! cloud effect on albedo (only-for nn_ice_alb=0)
+ 
    !                             !!* namelist namsbc_alb
-   REAL(wp) ::   rn_cloud         !  cloudiness effect on snow or ice albedo (Grenfell & Perovich, 1984)
-#if defined key_lim3
-   REAL(wp) ::   rn_albice        !  albedo of melting ice in the arctic and antarctic (Shine & Hendersson-Sellers)
-#else
-   REAL(wp) ::   rn_albice        !  albedo of melting ice in the arctic and antarctic (Shine & Hendersson-Sellers)
-#endif
-   REAL(wp) ::   rn_alphd         !  coefficients for linear interpolation used to compute
-   REAL(wp) ::   rn_alphdi        !  albedo between two extremes values (Pyane, 1972)
-   REAL(wp) ::   rn_alphc         ! 
+   INTEGER  ::   nn_ice_alb
+   REAL(wp) ::   rn_albice
 
    !!----------------------------------------------------------------------
@@ -59,11 +53,31 @@
       !!          
       !! ** Purpose :   Computation of the albedo of the snow/ice system 
-      !!                as well as the ocean one
       !!       
-      !! ** Method  : - Computation of the albedo of snow or ice (choose the 
-      !!                rignt one by a large number of tests
-      !!              - Computation of the albedo of the ocean
-      !!
-      !! References :   Shine and Hendersson-Sellers 1985, JGR, 90(D1), 2243-2250.
+      !! ** Method  :   Two schemes are available (from namelist parameter nn_ice_alb)
+      !!                  0: the scheme is that of Shine & Henderson-Sellers (JGR 1985) for clear-skies
+      !!                  1: the scheme is "home made" (for cloudy skies) and based on Brandt et al. (J. Climate 2005)
+      !!                                                                           and Grenfell & Perovich (JGR 2004)
+      !!                Description of scheme 1:
+      !!                  1) Albedo dependency on ice thickness follows the findings from Brandt et al (2005)
+      !!                     which are an update of Allison et al. (JGR 1993) ; Brandt et al. 1999
+      !!                     0-5cm  : linear function of ice thickness
+      !!                     5-150cm: log    function of ice thickness
+      !!                     > 150cm: constant
+      !!                  2) Albedo dependency on snow thickness follows the findings from Grenfell & Perovich (2004)
+      !!                     i.e. it increases as -EXP(-snw_thick/0.02) during freezing and -EXP(-snw_thick/0.03) during melting
+      !!                  3) Albedo dependency on clouds is speculated from measurements of Grenfell and Perovich (2004)
+      !!                     i.e. cloudy-clear albedo depend on cloudy albedo following a 2d order polynomial law
+      !!                  4) The needed 4 parameters are: dry and melting snow, freezing ice and bare puddled ice
+      !!
+      !! ** Note    :   The parameterization from Shine & Henderson-Sellers presents several misconstructions:
+      !!                  1) ice albedo when ice thick. tends to 0 is different than ocean albedo
+      !!                  2) for small ice thick. covered with some snow (<3cm?), albedo is larger 
+      !!                     under melting conditions than under freezing conditions
+      !!                  3) the evolution of ice albedo as a function of ice thickness shows  
+      !!                     3 sharp inflexion points (at 5cm, 100cm and 150cm) that look highly unrealistic
+      !!
+      !! References :   Shine & Henderson-Sellers 1985, JGR, 90(D1), 2243-2250.
+      !!                Brandt et al. 2005, J. Climate, vol 18
+      !!                Grenfell & Perovich 2004, JGR, vol 109 
       !!----------------------------------------------------------------------
       REAL(wp), INTENT(in   ), DIMENSION(:,:,:) ::   pt_ice      !  ice surface temperature (Kelvin)
@@ -73,99 +87,133 @@
       REAL(wp), INTENT(  out), DIMENSION(:,:,:) ::   pa_ice_os   !  albedo of ice under overcast sky
       !!
-      INTEGER  ::   ji, jj, jl    ! dummy loop indices
-      INTEGER  ::   ijpl          ! number of ice categories (3rd dim of ice input arrays)
-      REAL(wp) ::   zalbpsnm      ! albedo of ice under clear sky when snow is melting
-      REAL(wp) ::   zalbpsnf      ! albedo of ice under clear sky when snow is freezing
-      REAL(wp) ::   zalbpsn       ! albedo of snow/ice system when ice is coverd by snow
-      REAL(wp) ::   zalbpic       ! albedo of snow/ice system when ice is free of snow
-      REAL(wp) ::   zithsn        ! = 1 for hsn >= 0 ( ice is cov. by snow ) ; = 0 otherwise (ice is free of snow)
-      REAL(wp) ::   zitmlsn       ! = 1 freezinz snow (pt_ice >=rt0_snow) ; = 0 melting snow (pt_ice<rt0_snow)
-      REAL(wp) ::   zihsc1        ! = 1 hsn <= c1 ; = 0 hsn > c1
-      REAL(wp) ::   zihsc2        ! = 1 hsn >= c2 ; = 0 hsn < c2
-      !!
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zalbfz    ! = rn_alphdi for freezing ice ; = rn_albice for melting ice
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zficeth   !  function of ice thickness
+      INTEGER  ::   ji, jj, jl         ! dummy loop indices
+      INTEGER  ::   ijpl               ! number of ice categories (3rd dim of ice input arrays)
+      REAL(wp)            ::   ralb_im, ralb_sf, ralb_sm, ralb_if
+      REAL(wp)            ::   zswitch, z1_c1, z1_c2
+      REAL(wp)                            ::   zalb_sm, zalb_sf, zalb_st ! albedo of snow melting, freezing, total
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zalb, zalb_it             ! intermediate variable & albedo of ice (snow free)
       !!---------------------------------------------------------------------
-      
+
       ijpl = SIZE( pt_ice, 3 )                     ! number of ice categories
-
-      CALL wrk_alloc( jpi,jpj,ijpl, zalbfz, zficeth )
+      
+      CALL wrk_alloc( jpi,jpj,ijpl, zalb, zalb_it )
 
       IF( albd_init == 0 )   CALL albedo_init      ! initialization 
 
-      !---------------------------
-      !  Computation of  zficeth
-      !---------------------------
-      ! ice free of snow and melts
-      WHERE     ( ph_snw == 0._wp .AND. pt_ice >= rt0_ice )   ;   zalbfz(:,:,:) = rn_albice
-      ELSE WHERE                                              ;   zalbfz(:,:,:) = rn_alphdi
-      END  WHERE
-
-      WHERE     ( 1.5  < ph_ice                     )  ;  zficeth = zalbfz
-      ELSE WHERE( 1.0  < ph_ice .AND. ph_ice <= 1.5 )  ;  zficeth = 0.472  + 2.0 * ( zalbfz - 0.472 ) * ( ph_ice - 1.0 )
-      ELSE WHERE( 0.05 < ph_ice .AND. ph_ice <= 1.0 )  ;  zficeth = 0.2467 + 0.7049 * ph_ice              &
-         &                                                                 - 0.8608 * ph_ice * ph_ice     &
-         &                                                                 + 0.3812 * ph_ice * ph_ice * ph_ice
-      ELSE WHERE                                       ;  zficeth = 0.1    + 3.6    * ph_ice
-      END WHERE
-
-!!gm old code
-!      DO jl = 1, ijpl
-!         DO jj = 1, jpj
-!            DO ji = 1, jpi
-!               IF( ph_ice(ji,jj,jl) > 1.5 ) THEN
-!                  zficeth(ji,jj,jl) = zalbfz(ji,jj,jl)
-!               ELSEIF( ph_ice(ji,jj,jl) > 1.0  .AND. ph_ice(ji,jj,jl) <= 1.5 ) THEN
-!                  zficeth(ji,jj,jl) = 0.472 + 2.0 * ( zalbfz(ji,jj,jl) - 0.472 ) * ( ph_ice(ji,jj,jl) - 1.0 )
-!               ELSEIF( ph_ice(ji,jj,jl) > 0.05 .AND. ph_ice(ji,jj,jl) <= 1.0 ) THEN
-!                  zficeth(ji,jj,jl) = 0.2467 + 0.7049 * ph_ice(ji,jj,jl)                               &
-!                     &                    - 0.8608 * ph_ice(ji,jj,jl) * ph_ice(ji,jj,jl)                 &
-!                     &                    + 0.3812 * ph_ice(ji,jj,jl) * ph_ice(ji,jj,jl) * ph_ice (ji,jj,jl)
-!               ELSE
-!                  zficeth(ji,jj,jl) = 0.1 + 3.6 * ph_ice(ji,jj,jl) 
-!               ENDIF
-!            END DO
-!         END DO
-!      END DO
-!!gm end old code
-      
-      !----------------------------------------------- 
-      !    Computation of the snow/ice albedo system 
-      !-------------------------- ---------------------
-      
-      !    Albedo of snow-ice for clear sky.
-      !-----------------------------------------------    
-      DO jl = 1, ijpl
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               !  Case of ice covered by snow.             
-               !                                        !  freezing snow        
-               zihsc1   = 1.0 - MAX( zzero , SIGN( zone , - ( ph_snw(ji,jj,jl) - c1 ) ) )
-               zalbpsnf = ( 1.0 - zihsc1 ) * (  zficeth(ji,jj,jl)                                             &
-                  &                           + ph_snw(ji,jj,jl) * ( rn_alphd - zficeth(ji,jj,jl) ) / c1  )   &
-                  &     +         zihsc1   * rn_alphd  
-               !                                        !  melting snow                
-               zihsc2   = MAX( zzero , SIGN( zone , ph_snw(ji,jj,jl) - c2 ) )
-               zalbpsnm = ( 1.0 - zihsc2 ) * ( rn_albice + ph_snw(ji,jj,jl) * ( rn_alphc - rn_albice ) / c2 )   &
-                  &     +         zihsc2   *   rn_alphc 
-               !
-               zitmlsn  =  MAX( zzero , SIGN( zone , pt_ice(ji,jj,jl) - rt0_snow ) )   
-               zalbpsn  =  zitmlsn * zalbpsnm + ( 1.0 - zitmlsn ) * zalbpsnf
-            
-               !  Case of ice free of snow.
-               zalbpic  = zficeth(ji,jj,jl) 
-            
-               ! albedo of the system   
-               zithsn   = 1.0 - MAX( zzero , SIGN( zone , - ph_snw(ji,jj,jl) ) )
-               pa_ice_cs(ji,jj,jl) =  zithsn * zalbpsn + ( 1.0 - zithsn ) *  zalbpic
+      
+      SELECT CASE ( nn_ice_alb )
+
+      !------------------------------------------
+      !  Shine and Henderson-Sellers (1985)
+      !------------------------------------------
+      CASE( 0 )
+       
+         ralb_sf = 0.80       ! dry snow
+         ralb_sm = 0.65       ! melting snow
+         ralb_if = 0.72       ! bare frozen ice
+         ralb_im = rn_albice  ! bare puddled ice 
+         
+         !  Computation of ice albedo (free of snow)
+         WHERE     ( ph_snw == 0._wp .AND. pt_ice >= rt0_ice )   ;   zalb(:,:,:) = ralb_im
+         ELSE WHERE                                              ;   zalb(:,:,:) = ralb_if
+         END  WHERE
+      
+         WHERE     ( 1.5  < ph_ice                     )  ;  zalb_it = zalb
+         ELSE WHERE( 1.0  < ph_ice .AND. ph_ice <= 1.5 )  ;  zalb_it = 0.472  + 2.0 * ( zalb - 0.472 ) * ( ph_ice - 1.0 )
+         ELSE WHERE( 0.05 < ph_ice .AND. ph_ice <= 1.0 )  ;  zalb_it = 0.2467 + 0.7049 * ph_ice              &
+            &                                                                 - 0.8608 * ph_ice * ph_ice     &
+            &                                                                 + 0.3812 * ph_ice * ph_ice * ph_ice
+         ELSE WHERE                                       ;  zalb_it = 0.1    + 3.6    * ph_ice
+         END WHERE
+     
+         DO jl = 1, ijpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! freezing snow
+                  ! no effect of underlying ice layer IF snow thickness > c1. Albedo does not depend on snow thick if > c2
+                  !                                        !  freezing snow        
+                  zswitch   = 1._wp - MAX( 0._wp , SIGN( 1._wp , - ( ph_snw(ji,jj,jl) - c1 ) ) )
+                  zalb_sf   = ( 1._wp - zswitch ) * (  zalb_it(ji,jj,jl)  &
+                     &                           + ph_snw(ji,jj,jl) * ( ralb_sf - zalb_it(ji,jj,jl) ) / c1  )   &
+                     &        +         zswitch   * ralb_sf  
+
+                  ! melting snow
+                  ! no effect of underlying ice layer. Albedo does not depend on snow thick IF > c2
+                  zswitch   = MAX( 0._wp , SIGN( 1._wp , ph_snw(ji,jj,jl) - c2 ) )
+                  zalb_sm = ( 1._wp - zswitch ) * ( ralb_im + ph_snw(ji,jj,jl) * ( ralb_sm - ralb_im ) / c2 )   &
+                      &     +         zswitch   *   ralb_sm 
+                  !
+                  ! snow albedo
+                  zswitch  =  MAX( 0._wp , SIGN( 1._wp , pt_ice(ji,jj,jl) - rt0_snow ) )   
+                  zalb_st  =  zswitch * zalb_sm + ( 1._wp - zswitch ) * zalb_sf
+               
+                  ! Ice/snow albedo
+                  zswitch   = 1._wp - MAX( 0._wp , SIGN( 1._wp , - ph_snw(ji,jj,jl) ) )
+                  pa_ice_cs(ji,jj,jl) =  zswitch * zalb_st + ( 1._wp - zswitch ) * zalb_it(ji,jj,jl)
+                  !
+               END DO
             END DO
          END DO
-      END DO
-      
-      !    Albedo of snow-ice for overcast sky.
-      !----------------------------------------------  
-      pa_ice_os(:,:,:) = pa_ice_cs(:,:,:) + rn_cloud       ! Oberhuber correction
-      !
-      CALL wrk_dealloc( jpi,jpj,ijpl, zalbfz, zficeth )
+
+         pa_ice_os(:,:,:) = pa_ice_cs(:,:,:) + rcloud       ! Oberhuber correction for overcast sky
+
+      !------------------------------------------
+      !  New parameterization (2016)
+      !------------------------------------------
+      CASE( 1 ) 
+
+         ralb_im = rn_albice  ! bare puddled ice
+! compilation of values from literature
+         ralb_sf = 0.85      ! dry snow
+         ralb_sm = 0.75      ! melting snow
+         ralb_if = 0.60      ! bare frozen ice
+! Perovich et al 2002 (Sheba) => the only dataset for which all types of ice/snow were retrieved
+!         ralb_sf = 0.85       ! dry snow
+!         ralb_sm = 0.72       ! melting snow
+!         ralb_if = 0.65       ! bare frozen ice
+! Brandt et al 2005 (East Antarctica)
+!         ralb_sf = 0.87      ! dry snow
+!         ralb_sm = 0.82      ! melting snow
+!         ralb_if = 0.54      ! bare frozen ice
+! 
+         !  Computation of ice albedo (free of snow)
+         z1_c1 = 1. / ( LOG(1.5) - LOG(0.05) ) 
+         z1_c2 = 1. / 0.05
+         WHERE     ( ph_snw == 0._wp .AND. pt_ice >= rt0_ice )   ;   zalb = ralb_im
+         ELSE WHERE                                              ;   zalb = ralb_if
+         END  WHERE
+         
+         WHERE     ( 1.5  < ph_ice                     )  ;  zalb_it = zalb
+         ELSE WHERE( 0.05 < ph_ice .AND. ph_ice <= 1.5 )  ;  zalb_it = zalb     + ( 0.18 - zalb     ) * z1_c1 *  &
+            &                                                                     ( LOG(1.5) - LOG(ph_ice) )
+         ELSE WHERE                                       ;  zalb_it = ralb_oce + ( 0.18 - ralb_oce ) * z1_c2 * ph_ice
+         END WHERE
+
+         z1_c1 = 1. / 0.02
+         z1_c2 = 1. / 0.03
+         !  Computation of the snow/ice albedo
+         DO jl = 1, ijpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zalb_sf = ralb_sf - ( ralb_sf - zalb_it(ji,jj,jl)) * EXP( - ph_snw(ji,jj,jl) * z1_c1 );
+                  zalb_sm = ralb_sm - ( ralb_sm - zalb_it(ji,jj,jl)) * EXP( - ph_snw(ji,jj,jl) * z1_c2 );
+
+                   ! snow albedo
+                  zswitch = MAX( 0._wp , SIGN( 1._wp , pt_ice(ji,jj,jl) - rt0_snow ) )   
+                  zalb_st = zswitch * zalb_sm + ( 1._wp - zswitch ) * zalb_sf
+
+                  ! Ice/snow albedo   
+                  zswitch             = MAX( 0._wp , SIGN( 1._wp , - ph_snw(ji,jj,jl) ) )
+                  pa_ice_os(ji,jj,jl) = ( 1._wp - zswitch ) * zalb_st + zswitch *  zalb_it(ji,jj,jl)
+
+              END DO
+            END DO
+         END DO
+         ! Effect of the clouds (2d order polynomial)
+         pa_ice_cs = pa_ice_os - ( - 0.1010 * pa_ice_os * pa_ice_os + 0.1933 * pa_ice_os - 0.0148 ); 
+
+      END SELECT
+      
+      CALL wrk_dealloc( jpi,jpj,ijpl, zalb, zalb_it )
       !
    END SUBROUTINE albedo_ice
@@ -181,10 +229,10 @@
       REAL(wp), DIMENSION(:,:), INTENT(out) ::   pa_oce_cs   !  albedo of ocean under clear sky
       !!
-      REAL(wp) ::   zcoef   ! local scalar
-      !!----------------------------------------------------------------------
-      !
-      zcoef = 0.05 / ( 1.1 * rmue**1.4 + 0.15 )      ! Parameterization of Briegled and Ramanathan, 1982 
-      pa_oce_cs(:,:) = zcoef               
-      pa_oce_os(:,:)  = 0.06                         ! Parameterization of Kondratyev, 1969 and Payne, 1972
+      REAL(wp) :: zcoef 
+      !!----------------------------------------------------------------------
+      !
+      zcoef = 0.05 / ( 1.1 * rmue**1.4 + 0.15 )   ! Parameterization of Briegled and Ramanathan, 1982
+      pa_oce_cs(:,:) = zcoef 
+      pa_oce_os(:,:) = 0.06                       ! Parameterization of Kondratyev, 1969 and Payne, 1972
       !
    END SUBROUTINE albedo_oce
@@ -200,5 +248,5 @@
       !!----------------------------------------------------------------------
       INTEGER  ::   ios                 ! Local integer output status for namelist read
-      NAMELIST/namsbc_alb/ rn_cloud, rn_albice, rn_alphd, rn_alphdi, rn_alphc
+      NAMELIST/namsbc_alb/ nn_ice_alb, rn_albice 
       !!----------------------------------------------------------------------
       !
@@ -219,9 +267,6 @@
          WRITE(numout,*) '~~~~~~~'
          WRITE(numout,*) '   Namelist namsbc_alb : albedo '
-         WRITE(numout,*) '      correction for snow and ice albedo                  rn_cloud  = ', rn_cloud
-         WRITE(numout,*) '      albedo of melting ice in the arctic and antarctic   rn_albice = ', rn_albice
-         WRITE(numout,*) '      coefficients for linear                             rn_alphd  = ', rn_alphd
-         WRITE(numout,*) '      interpolation used to compute albedo                rn_alphdi = ', rn_alphdi
-         WRITE(numout,*) '      between two extremes values (Pyane, 1972)           rn_alphc  = ', rn_alphc
+         WRITE(numout,*) '      choose the albedo parameterization                  nn_ice_alb = ', nn_ice_alb
+         WRITE(numout,*) '      albedo of bare puddled ice                          rn_albice  = ', rn_albice
       ENDIF
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis3.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis3.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis3.F90	(revision 9987)
@@ -31,5 +31,5 @@
    USE in_out_manager               ! I/O manager
    USE lbclnk                       ! ocean lateral boundary conditions (or mpp link)
-
+   
    IMPLICIT NONE
    PRIVATE
@@ -41,4 +41,15 @@
    PUBLIC   cpl_freq
    PUBLIC   cpl_finalize
+#if defined key_mpp_mpi
+   INCLUDE 'mpif.h'
+#endif
+   
+   INTEGER, PARAMETER         :: localRoot  = 0
+   LOGICAL                    :: commRank            ! true for ranks doing OASIS communication
+#if defined key_cpl_rootexchg
+   LOGICAL                    :: rootexchg =.true.   ! logical switch 
+#else
+   LOGICAL                    :: rootexchg =.false.  ! logical switch 
+#endif 
 
    INTEGER, PUBLIC            ::   OASIS_Rcv  = 1    !: return code if received field
@@ -82,5 +93,6 @@
 
    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   exfld   ! Temporary buffer for receiving
-
+   INTEGER, PUBLIC :: localComm 
+      
    !!----------------------------------------------------------------------
    !! NEMO/OPA 3.3 , NEMO Consortium (2010)
@@ -120,4 +132,5 @@
       IF ( nerror /= OASIS_Ok ) &
          CALL oasis_abort (ncomp_id, 'cpl_init','Failure in oasis_get_localcomm' )
+      localComm = kl_comm 
       !
    END SUBROUTINE cpl_init
@@ -177,10 +190,10 @@
       IF( nerror > 0 ) THEN
          CALL oasis_abort ( ncomp_id, 'cpl_define', 'Failure in allocating exfld')   ;   RETURN
-      ENDIF
+      ENDIF      
       !
       ! -----------------------------------------------------------------
       ! ... Define the partition 
       ! -----------------------------------------------------------------
-      
+            
       paral(1) = 2                                              ! box partitioning
       paral(2) = jpiglo * (nldj-1+njmpp-1) + (nldi-1+nimpp-1)   ! NEMO lower left corner global offset    
@@ -196,5 +209,5 @@
       ENDIF
       
-      CALL oasis_def_partition ( id_part, paral, nerror )
+      CALL oasis_def_partition ( id_part, paral, nerror, jpiglo*jpjglo)
       !
       ! ... Announce send variables. 
@@ -241,5 +254,5 @@
             END DO
          ENDIF
-      END DO
+      END DO      
       !
       ! ... Announce received variables. 
@@ -373,5 +386,5 @@
             IF( srcv(kid)%nid(jc,jm) /= -1 ) THEN
 
-               CALL oasis_get ( srcv(kid)%nid(jc,jm), kstep, exfld, kinfo )         
+               CALL oasis_get ( srcv(kid)%nid(jc,jm), kstep, exfld, kinfo )   
                
                llaction =  kinfo == OASIS_Recvd   .OR. kinfo == OASIS_FromRest .OR.   &
@@ -384,5 +397,5 @@
                   kinfo = OASIS_Rcv
                   IF( llfisrt ) THEN 
-                     pdata(nldi:nlei,nldj:nlej,jc) =                                 exfld(:,:) * pmask(nldi:nlei,nldj:nlej,jm)
+                     pdata(nldi:nlei,nldj:nlej,jc) =                                 exfld(:,:) * pmask(nldi:nlei,nldj:nlej,jm) 
                      llfisrt = .FALSE.
                   ELSE
@@ -463,5 +476,9 @@
          CALL oasis_get_freqs(id, mop, 1, itmp, info)
 #else
+#if defined key_oasis3 
+         itmp(1) = namflddti( id )
+#else
          CALL oasis_get_freqs(id,      1, itmp, info)
+#endif
 #endif
          cpl_freq = itmp(1)
@@ -514,7 +531,8 @@
    END SUBROUTINE oasis_get_localcomm
 
-   SUBROUTINE oasis_def_partition(k1,k2,k3)
+   SUBROUTINE oasis_def_partition(k1,k2,k3,K4)
       INTEGER     , INTENT(  out) ::  k1,k3
       INTEGER     , INTENT(in   ) ::  k2(5)
+      INTEGER     , OPTIONAL, INTENT(in   ) ::  k4
       k1 = k2(1) ; k3 = k2(5)
       WRITE(numout,*) 'oasis_def_partition: Error you sould not be there...'
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/fldread.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/fldread.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/fldread.F90	(revision 9987)
@@ -32,4 +32,5 @@
    PUBLIC   fld_map    ! routine called by tides_init
    PUBLIC   fld_read, fld_fill   ! called by sbc... modules
+   PUBLIC   fld_clopn
 
    TYPE, PUBLIC ::   FLD_N      !: Namelist field informations
@@ -815,4 +816,12 @@
          imonth = kmonth
          iday = kday
+         IF ( sdjf%cltype(1:4) == 'week' ) THEN             ! find the day of the beginning of the week
+            isec_week = ksec_week( sdjf%cltype(6:8) )- (86400 * 8 )  
+            llprevmth  = isec_week > nsec_month             ! longer time since beginning of the week than the month
+            llprevyr   = llprevmth .AND. nmonth == 1
+            iyear  = nyear  - COUNT((/llprevyr /))
+            imonth = nmonth - COUNT((/llprevmth/)) + 12 * COUNT((/llprevyr /))
+            iday   = nday   + nmonth_len(nmonth-1) * COUNT((/llprevmth/)) - isec_week / NINT(rday)
+         ENDIF
       ELSE                                                  ! use current day values
          IF ( sdjf%cltype(1:4) == 'week' ) THEN             ! find the day of the beginning of the week
@@ -1281,5 +1290,5 @@
       CHARACTER(LEN=*)          , INTENT(in   ) ::   lsmfile ! land sea mask file name
       !! 
-      REAL(wp),DIMENSION(:,:,:),ALLOCATABLE     ::   ztmp_fly_dta,zfieldo                  ! temporary array of values on input grid
+      REAL(wp),DIMENSION(:,:,:),ALLOCATABLE     ::   ztmp_fly_dta                          ! temporary array of values on input grid
       INTEGER, DIMENSION(3)                     ::   rec1,recn                             ! temporary arrays for start and length
       INTEGER, DIMENSION(3)                     ::   rec1_lsm,recn_lsm                     ! temporary arrays for start and length in case of seaoverland
@@ -1347,6 +1356,6 @@
 
 
-         itmpi=SIZE(ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),1)
-         itmpj=SIZE(ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),2)
+         itmpi=jpi2_lsm-jpi1_lsm+1
+         itmpj=jpj2_lsm-jpj1_lsm+1
          itmpz=kk
          ALLOCATE(ztmp_fly_dta(itmpi,itmpj,itmpz))
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/geo2ocean.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/geo2ocean.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/geo2ocean.F90	(revision 9987)
@@ -51,5 +51,5 @@
 
    SUBROUTINE repcmo ( pxu1, pyu1, pxv1, pyv1,   &
-                       px2 , py2 )
+                       px2 , py2 , kchoix  )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE repcmo  ***
@@ -68,10 +68,25 @@
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   py2          ! j-componante (defined at v-point)
       !!----------------------------------------------------------------------
-      
-      ! Change from geographic to stretched coordinate
-      ! ----------------------------------------------
-      CALL rot_rep( pxu1, pyu1, 'U', 'en->i',px2 )
-      CALL rot_rep( pxv1, pyv1, 'V', 'en->j',py2 )
-      
+      INTEGER, INTENT( IN ) ::   &
+         kchoix   ! type of transformation
+                  ! = 1 change from geographic to model grid.
+                  ! =-1 change from model to geographic grid
+      !!----------------------------------------------------------------------
+ 
+      SELECT CASE (kchoix)
+      CASE ( 1)
+        ! Change from geographic to stretched coordinate
+        ! ----------------------------------------------
+     
+        CALL rot_rep( pxu1, pyu1, 'U', 'en->i',px2 )
+        CALL rot_rep( pxv1, pyv1, 'V', 'en->j',py2 )
+      CASE (-1)
+       ! Change from stretched to geographic coordinate
+       ! ----------------------------------------------
+     
+       CALL rot_rep( pxu1, pyu1, 'U', 'ij->e',px2 )
+       CALL rot_rep( pxv1, pyv1, 'V', 'ij->n',py2 )
+     END SELECT
+     
    END SUBROUTINE repcmo
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_ice.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_ice.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_ice.F90	(revision 9987)
@@ -80,5 +80,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qemp_oce       !: heat flux of precip and evap over ocean     [W/m2]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qemp_ice       !: heat flux of precip and evap over ice       [W/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qprec_ice      !: heat flux of precip over ice                [J/m3]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qevap_ice      !: heat flux of evap over ice                  [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qprec_ice      !: enthalpy of precip over ice                 [J/m3]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_oce        !: evap - precip over ocean                 [kg/m2/s]
 #endif
@@ -101,8 +102,22 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr_iu              !: ice fraction at NEMO U point
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr_iv              !: ice fraction at NEMO V point
-   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sstfrz             !: sea surface freezing temperature
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tsfc_ice           !: sea-ice surface skin temperature (on categories)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   kn_ice             !: sea-ice surface layer thermal conductivity (on cats)
+
    ! variables used in the coupled interface
    INTEGER , PUBLIC, PARAMETER ::   jpl = ncat
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   u_ice, v_ice          ! jpi, jpj
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  a_p, ht_p ! Meltpond fraction and depth
+   
+   !
+   
+   !
+#if defined key_asminc
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ndaice_da          !: NEMO fresh water flux to ocean due to data assim
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nfresh_da          !: NEMO salt flux to ocean due to data assim
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nfsalt_da          !: NEMO ice concentration change/second from data assim
+#endif
+      
 #endif
    
@@ -144,7 +159,7 @@
 #endif
 #if defined key_lim3
-         &      evap_ice(jpi,jpj,jpl) , devap_ice(jpi,jpj,jpl) , qprec_ice(jpi,jpj) ,  &
-         &      qemp_ice(jpi,jpj)     , qemp_oce(jpi,jpj)      ,                       &
-         &      qns_oce (jpi,jpj)     , qsr_oce (jpi,jpj)      , emp_oce (jpi,jpj)  ,  &
+         &      evap_ice(jpi,jpj,jpl) , devap_ice(jpi,jpj,jpl) , qprec_ice(jpi,jpj) ,   &
+         &      qemp_ice(jpi,jpj)     , qevap_ice(jpi,jpj,jpl) , qemp_oce (jpi,jpj) ,   &
+         &      qns_oce (jpi,jpj)     , qsr_oce  (jpi,jpj)     , emp_oce (jpi,jpj)  ,   &
 #endif
          &      emp_ice(jpi,jpj)      ,  STAT= ierr(1) )
@@ -152,14 +167,20 @@
 
 #if defined key_cice
-      ALLOCATE( qla_ice(jpi,jpj,1)    , qlw_ice(jpi,jpj,1)    , qsr_ice(jpi,jpj,1)    , &
+      ALLOCATE( qla_ice(jpi,jpj,ncat) , qlw_ice(jpi,jpj,1)    , qsr_ice(jpi,jpj,1)    , &
                 wndi_ice(jpi,jpj)     , tatm_ice(jpi,jpj)     , qatm_ice(jpi,jpj)     , &
                 wndj_ice(jpi,jpj)     , nfrzmlt(jpi,jpj)      , ss_iou(jpi,jpj)       , &
                 ss_iov(jpi,jpj)       , fr_iu(jpi,jpj)        , fr_iv(jpi,jpj)        , &
                 a_i(jpi,jpj,ncat)     , topmelt(jpi,jpj,ncat) , botmelt(jpi,jpj,ncat) , &
-                STAT= ierr(1) )
-      IF( ln_cpl )   ALLOCATE( u_ice(jpi,jpj)        , fr1_i0(jpi,jpj)       , tn_ice (jpi,jpj,1)    , &
+#if defined key_asminc
+                ndaice_da(jpi,jpj)    , nfresh_da(jpi,jpj)    , nfsalt_da(jpi,jpj)    , &
+#endif
+                sstfrz(jpi,jpj)       , STAT= ierr(1) )
+   ! Alex West: Allocating tn_ice with 5 categories.  When NEMO is used with CICE, this variable
+   ! represents top layer ice temperature, which is multi-category.
+      IF( ln_cpl )   ALLOCATE( u_ice(jpi,jpj)        , fr1_i0(jpi,jpj)       , tn_ice (jpi,jpj,jpl)  , &
          &                     v_ice(jpi,jpj)        , fr2_i0(jpi,jpj)       , alb_ice(jpi,jpj,1)    , &
          &                     emp_ice(jpi,jpj)      , qns_ice(jpi,jpj,1)    , dqns_ice(jpi,jpj,1)   , &
-         &                     STAT= ierr(2) )
+         &                     a_p(jpi,jpj,jpl)      , ht_p(jpi,jpj,jpl)     , tsfc_ice(jpi,jpj,jpl) , &
+         &                     kn_ice(jpi,jpj,jpl) ,    STAT=ierr(2) )
       
 #endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_oce.F90	(revision 9987)
@@ -125,4 +125,6 @@
 #endif
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: xcplmask          !: coupling mask for ln_mixcpl (warning: allocated in sbccpl)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   greenland_icesheet_mass_array, greenland_icesheet_mask
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   antarctica_icesheet_mass_array, antarctica_icesheet_mask
 
    !!----------------------------------------------------------------------
@@ -137,4 +139,31 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   e3t_m     !: mean (nn_fsbc time-step) sea surface layer thickness       [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   frq_m     !: mean (nn_fsbc time-step) fraction of solar net radiation absorbed in the 1st T level [-]
+   
+   !!----------------------------------------------------------------------
+   !!  Surface scalars of total ice sheet mass for Greenland and Antarctica, 
+   !! passed from atmosphere to be converted to dvol and hence a freshwater 
+   !! flux  by using old values. New values are saved in the dump, to become
+   !! old values next coupling timestep. Freshwater fluxes split between 
+   !! sub iceshelf melting and iceberg calving, scalled to flux per second
+   !!----------------------------------------------------------------------
+   
+   REAL(wp), PUBLIC  :: greenland_icesheet_mass, greenland_icesheet_mass_rate_of_change, greenland_icesheet_timelapsed 
+   REAL(wp), PUBLIC  :: antarctica_icesheet_mass, antarctica_icesheet_mass_rate_of_change, antarctica_icesheet_timelapsed
+
+   ! sbccpl namelist parameters associated with icesheet freshwater input code. Included here rather than in sbccpl.F90 to 
+   ! avoid circular dependencies.
+   INTEGER, PUBLIC     ::   nn_coupled_iceshelf_fluxes     ! =0 : total freshwater input from iceberg calving and ice shelf basal melting 
+                                                           ! taken from climatologies used (no action in coupling routines).
+                                                           ! =1 :  use rate of change of mass of Greenland and Antarctic icesheets to set the 
+                                                           ! combined magnitude of the iceberg calving and iceshelf melting freshwater fluxes.
+                                                           ! =2 :  specify constant freshwater inputs in this namelist to set the combined
+                                                           ! magnitude of iceberg calving and iceshelf melting freshwater fluxes.
+   LOGICAL, PUBLIC     ::   ln_iceshelf_init_atmos         ! If true force ocean to initialise iceshelf masses from atmospheric values rather
+                                                           ! than values in ocean restart (applicable if nn_coupled_iceshelf_fluxes=1).
+   REAL(wp), PUBLIC    ::   rn_greenland_total_fw_flux    ! Constant total rate of freshwater input (kg/s) for Greenland (if nn_coupled_iceshelf_fluxes=2) 
+   REAL(wp), PUBLIC    ::   rn_greenland_calving_fraction  ! Set fraction of total freshwater flux for iceberg calving - remainder goes to iceshelf melting.
+   REAL(wp), PUBLIC    ::   rn_antarctica_total_fw_flux   ! Constant total rate of freshwater input (kg/s) for Antarctica (if nn_coupled_iceshelf_fluxes=2) 
+   REAL(wp), PUBLIC    ::   rn_antarctica_calving_fraction ! Set fraction of total freshwater flux for iceberg calving - remainder goes to iceshelf melting.
+   REAL(wp), PUBLIC    ::   rn_iceshelf_fluxes_tolerance   ! Absolute tolerance for detecting differences in icesheet masses. 
 
    !! * Substitutions
@@ -172,4 +201,6 @@
          &      ssu_m  (jpi,jpj) , sst_m(jpi,jpj) , frq_m(jpi,jpj) ,      &
          &      ssv_m  (jpi,jpj) , sss_m(jpi,jpj) , ssh_m(jpi,jpj) , STAT=ierr(4) )
+      ALLOCATE( greenland_icesheet_mass_array(jpi,jpj) , antarctica_icesheet_mass_array(jpi,jpj) )
+      ALLOCATE( greenland_icesheet_mask(jpi,jpj) , antarctica_icesheet_mask(jpi,jpj) )
          !
 #if defined key_vvl
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_clio.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_clio.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_clio.F90	(revision 9987)
@@ -684,4 +684,10 @@
       qprec_ice(:,:) = rhosn * ( ( MIN( sf(jp_tair)%fnow(:,:,1), rt0_snow ) - rt0 ) * cpic * tmask(:,:,1) - lfus )
 
+      ! --- heat content of evap over ice in W/m2 (to be used in 1D-thermo) --- !
+      DO jl = 1, jpl
+         qevap_ice(:,:,jl) = 0._wp ! should be -evap_ice(:,:,jl)*( ( Tice - rt0 ) * cpic * tmask(:,:,1) - lfus )
+                                   ! but then qemp_ice should also include sublimation 
+      END DO
+
       CALL wrk_dealloc( jpi,jpj, zevap, zsnw ) 
 #endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_core.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_core.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_core.F90	(revision 9987)
@@ -91,4 +91,5 @@
    REAL(wp) ::   rn_zqt      ! z(q,t) : height of humidity and temperature measurements
    REAL(wp) ::   rn_zu       ! z(u)   : height of wind measurements
+   REAL(wp), PUBLIC :: rn_sfac ! multiplication factor for snow precipitation over sea-ice
 
    !! * Substitutions
@@ -151,5 +152,5 @@
          &                  sn_wndi, sn_wndj, sn_humi  , sn_qsr ,           &
          &                  sn_qlw , sn_tair, sn_prec  , sn_snow,           &
-         &                  sn_tdif, rn_zqt,  rn_zu
+         &                  sn_tdif, rn_zqt,  rn_zu, rn_sfac
       !!---------------------------------------------------------------------
       !
@@ -158,4 +159,5 @@
          !                                      ! ====================== !
          !
+         rn_sfac = 1._wp       ! Default to one if missing from namelist 
          REWIND( numnam_ref )              ! Namelist namsbc_core in reference namelist : CORE bulk parameters
          READ  ( numnam_ref, namsbc_core, IOSTAT = ios, ERR = 901)
@@ -206,5 +208,7 @@
       IF( MOD( kt - 1, nn_fsbc ) == 0 )   THEN
          qlw_ice(:,:,1)   = sf(jp_qlw)%fnow(:,:,1) 
-         qsr_ice(:,:,1)   = sf(jp_qsr)%fnow(:,:,1)
+         IF( ln_dm2dc ) THEN ; qsr_ice(:,:,1) = sbc_dcy( sf(jp_qsr)%fnow(:,:,1) )
+         ELSE                ; qsr_ice(:,:,1) =          sf(jp_qsr)%fnow(:,:,1)
+         ENDIF
          tatm_ice(:,:)    = sf(jp_tair)%fnow(:,:,1)         
          qatm_ice(:,:)    = sf(jp_humi)%fnow(:,:,1)
@@ -403,4 +407,8 @@
          CALL iom_put( "qsr_oce" ,   qsr  )                 ! output downward solar heat over the ocean
          CALL iom_put( "qt_oce"  ,   qns+qsr )              ! output total downward heat over the ocean
+         tprecip(:,:) = sf(jp_prec)%fnow(:,:,1) * rn_pfac   ! output total precipitation [kg/m2/s]
+         sprecip(:,:) = sf(jp_snow)%fnow(:,:,1) * rn_pfac   ! output solid precipitation [kg/m2/s]
+         CALL iom_put( 'snowpre', sprecip * 86400. )        ! Snow
+         CALL iom_put( 'precip' , tprecip * 86400. )        ! Total precipitation
       ENDIF
       !
@@ -608,7 +616,7 @@
       ! --- evaporation --- !
       z1_lsub = 1._wp / Lsub
-      evap_ice (:,:,:) = qla_ice (:,:,:) * z1_lsub ! sublimation
-      devap_ice(:,:,:) = dqla_ice(:,:,:) * z1_lsub
-      zevap    (:,:)   = emp(:,:) + tprecip(:,:)   ! evaporation over ocean
+      evap_ice (:,:,:) = rn_efac * qla_ice (:,:,:) * z1_lsub    ! sublimation
+      devap_ice(:,:,:) = rn_efac * dqla_ice(:,:,:) * z1_lsub    ! d(sublimation)/dT
+      zevap    (:,:)   = rn_efac * ( emp(:,:) + tprecip(:,:) )  ! evaporation over ocean
 
       ! --- evaporation minus precipitation --- !
@@ -633,4 +641,10 @@
       ! --- heat content of precip over ice in J/m3 (to be used in 1D-thermo) --- !
       qprec_ice(:,:) = rhosn * ( ( MIN( sf(jp_tair)%fnow(:,:,1), rt0_snow ) - rt0 ) * cpic * tmask(:,:,1) - lfus )
+
+      ! --- heat content of evap over ice in W/m2 (to be used in 1D-thermo) --- !
+      DO jl = 1, jpl
+         qevap_ice(:,:,jl) = 0._wp ! should be -evap_ice(:,:,jl)*( ( Tice - rt0 ) * cpic * tmask(:,:,1) )
+                                   ! But we do not have Tice => consider it at 0°C => evap=0 
+      END DO
 
       CALL wrk_dealloc( jpi,jpj, zevap, zsnw ) 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbccpl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbccpl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbccpl.F90	(revision 9987)
@@ -33,5 +33,8 @@
    USE cpl_oasis3      ! OASIS3 coupling
    USE geo2ocean       ! 
-   USE oce   , ONLY : tsn, un, vn, sshn, ub, vb, sshb, fraqsr_1lev
+   USE oce   , ONLY : tsn, un, vn, sshn, ub, vb, sshb, fraqsr_1lev,            &
+                      CO2Flux_out_cpl, DMS_out_cpl, chloro_out_cpl,            & 
+                      PCO2a_in_cpl, Dust_in_cpl, &
+                      ln_medusa
    USE albedo          !
    USE in_out_manager  ! I/O manager
@@ -46,10 +49,8 @@
    USE p4zflx, ONLY : oce_co2
 #endif
-#if defined key_cice
-   USE ice_domain_size, only: ncat
-#endif
 #if defined key_lim3
    USE limthd_dh       ! for CALL lim_thd_snwblow
 #endif
+   USE lib_fortran, ONLY: glob_sum
 
    IMPLICIT NONE
@@ -105,5 +106,10 @@
    INTEGER, PARAMETER ::   jpr_e3t1st = 41            ! first T level thickness 
    INTEGER, PARAMETER ::   jpr_fraqsr = 42            ! fraction of solar net radiation absorbed in the first ocean level
-   INTEGER, PARAMETER ::   jprcv      = 42            ! total number of fields received
+   INTEGER, PARAMETER ::   jpr_ts_ice = 43            ! skin temperature of sea-ice (used for melt-ponds)
+   INTEGER, PARAMETER ::   jpr_grnm   = 44            ! Greenland ice mass
+   INTEGER, PARAMETER ::   jpr_antm   = 45            ! Antarctic ice mass
+   INTEGER, PARAMETER ::   jpr_atm_pco2 = 46          ! Incoming atm CO2 flux
+   INTEGER, PARAMETER ::   jpr_atm_dust = 47          ! Incoming atm aggregate dust 
+   INTEGER, PARAMETER ::   jprcv      = 47            ! total number of fields received
 
    INTEGER, PARAMETER ::   jps_fice   =  1            ! ice fraction sent to the atmosphere
@@ -135,5 +141,16 @@
    INTEGER, PARAMETER ::   jps_e3t1st = 27            ! first level depth (vvl)
    INTEGER, PARAMETER ::   jps_fraqsr = 28            ! fraction of solar net radiation absorbed in the first ocean level
-   INTEGER, PARAMETER ::   jpsnd      = 28            ! total number of fields sended
+   INTEGER, PARAMETER ::   jps_a_p    = 29            ! meltpond fraction  
+   INTEGER, PARAMETER ::   jps_ht_p   = 30            ! meltpond depth (m) 
+   INTEGER, PARAMETER ::   jps_kice   = 31            ! ice surface layer thermal conductivity
+   INTEGER, PARAMETER ::   jps_sstfrz = 32            ! sea-surface freezing temperature
+   INTEGER, PARAMETER ::   jps_fice1  = 33            ! first-order ice concentration (for time-travelling ice coupling)
+   INTEGER, PARAMETER ::   jps_bio_co2 = 34           ! MEDUSA air-sea CO2 flux
+   INTEGER, PARAMETER ::   jps_bio_dms = 35           ! MEDUSA DMS surface concentration
+   INTEGER, PARAMETER ::   jps_bio_chloro = 36        ! MEDUSA chlorophyll surface concentration
+   INTEGER, PARAMETER ::   jpsnd      = 36            ! total number of fields sent
+
+   REAL(wp), PARAMETER :: dms_unit_conv = 1.0e+6      ! Coversion factor to get outgong DMS in standard units for coupling
+	                                              ! i.e. specifically nmol/L (= umol/m3)
 
    !                                                         !!** namelist namsbc_cpl **
@@ -146,8 +163,12 @@
    END TYPE FLD_C
    ! Send to the atmosphere                           !
-   TYPE(FLD_C) ::   sn_snd_temp, sn_snd_alb, sn_snd_thick, sn_snd_crt, sn_snd_co2                        
+   TYPE(FLD_C) ::   sn_snd_temp, sn_snd_alb, sn_snd_thick, sn_snd_crt, sn_snd_co2, sn_snd_cond, sn_snd_mpnd, sn_snd_sstfrz, sn_snd_thick1
+   TYPE(FLD_C) ::   sn_snd_bio_co2, sn_snd_bio_dms, sn_snd_bio_chloro                   
+
    ! Received from the atmosphere                     !
    TYPE(FLD_C) ::   sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau, sn_rcv_dqnsdt, sn_rcv_qsr, sn_rcv_qns, sn_rcv_emp, sn_rcv_rnf
-   TYPE(FLD_C) ::   sn_rcv_cal, sn_rcv_iceflx, sn_rcv_co2                        
+   TYPE(FLD_C) ::   sn_rcv_cal, sn_rcv_iceflx, sn_rcv_co2, sn_rcv_ts_ice, sn_rcv_grnm, sn_rcv_antm
+   TYPE(FLD_C) ::   sn_rcv_atm_pco2, sn_rcv_atm_dust                         
+
    ! Other namelist parameters                        !
    INTEGER     ::   nn_cplmodel            ! Maximum number of models to/from which NEMO is potentialy sending/receiving data
@@ -188,5 +209,8 @@
       ALLOCATE( a_i(jpi,jpj,1) , STAT=ierr(2) )  ! used in sbcice_if.F90 (done here as there is no sbc_ice_if_init)
 #endif
-      ALLOCATE( xcplmask(jpi,jpj,0:nn_cplmodel) , STAT=ierr(3) )
+      !ALLOCATE( xcplmask(jpi,jpj,0:nn_cplmodel) , STAT=ierr(3) )
+      ! Hardwire only two models as nn_cplmodel has not been read in
+      ! from the namelist yet.
+      ALLOCATE( xcplmask(jpi,jpj,0:2) , STAT=ierr(3) )   
       !
       sbc_cpl_alloc = MAXVAL( ierr )
@@ -216,9 +240,20 @@
       REAL(wp), POINTER, DIMENSION(:,:) ::   zacs, zaos
       !!
-      NAMELIST/namsbc_cpl/  sn_snd_temp, sn_snd_alb   , sn_snd_thick, sn_snd_crt   , sn_snd_co2,      &
-         &                  sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau  , sn_rcv_dqnsdt, sn_rcv_qsr,      &
-         &                  sn_rcv_qns , sn_rcv_emp   , sn_rcv_rnf  , sn_rcv_cal   , sn_rcv_iceflx,   &
-         &                  sn_rcv_co2 , nn_cplmodel  , ln_usecplmask
+      NAMELIST/namsbc_cpl/  sn_snd_temp, sn_snd_alb   , sn_snd_thick , sn_snd_crt   , sn_snd_co2,     &
+         &                  sn_snd_cond, sn_snd_mpnd  , sn_snd_sstfrz, sn_snd_thick1,                 &
+         &                  sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau   , sn_rcv_dqnsdt, sn_rcv_qsr,     &
+         &                  sn_rcv_qns , sn_rcv_emp   , sn_rcv_rnf   , sn_rcv_cal   , sn_rcv_iceflx,  &
+         &                  sn_rcv_co2 , sn_rcv_grnm  , sn_rcv_antm  , sn_rcv_ts_ice, nn_cplmodel  ,  &
+         &                  ln_usecplmask, nn_coupled_iceshelf_fluxes, ln_iceshelf_init_atmos,        &
+         &                  rn_greenland_total_fw_flux, rn_greenland_calving_fraction, &
+         &                  rn_antarctica_total_fw_flux, rn_antarctica_calving_fraction, rn_iceshelf_fluxes_tolerance
       !!---------------------------------------------------------------------
+
+      ! Add MEDUSA related fields to namelist
+      NAMELIST/namsbc_cpl/  sn_snd_bio_co2, sn_snd_bio_dms, sn_snd_bio_chloro,                        &
+         &                  sn_rcv_atm_pco2, sn_rcv_atm_dust
+
+      !!---------------------------------------------------------------------
+
       !
       IF( nn_timing == 1 )  CALL timing_start('sbc_cpl_init')
@@ -245,5 +280,5 @@
       ENDIF
       IF( lwp .AND. ln_cpl ) THEN                        ! control print
-         WRITE(numout,*)'  received fields (mutiple ice categogies)'
+         WRITE(numout,*)'  received fields (mutiple ice categories)'
          WRITE(numout,*)'      10m wind module                 = ', TRIM(sn_rcv_w10m%cldes  ), ' (', TRIM(sn_rcv_w10m%clcat  ), ')'
          WRITE(numout,*)'      stress module                   = ', TRIM(sn_rcv_taumod%cldes), ' (', TRIM(sn_rcv_taumod%clcat), ')'
@@ -258,6 +293,10 @@
          WRITE(numout,*)'      runoffs                         = ', TRIM(sn_rcv_rnf%cldes   ), ' (', TRIM(sn_rcv_rnf%clcat   ), ')'
          WRITE(numout,*)'      calving                         = ', TRIM(sn_rcv_cal%cldes   ), ' (', TRIM(sn_rcv_cal%clcat   ), ')'
+         WRITE(numout,*)'      Greenland ice mass              = ', TRIM(sn_rcv_grnm%cldes  ), ' (', TRIM(sn_rcv_grnm%clcat  ), ')'
+         WRITE(numout,*)'      Antarctica ice mass             = ', TRIM(sn_rcv_antm%cldes  ), ' (', TRIM(sn_rcv_antm%clcat  ), ')'
          WRITE(numout,*)'      sea ice heat fluxes             = ', TRIM(sn_rcv_iceflx%cldes), ' (', TRIM(sn_rcv_iceflx%clcat), ')'
          WRITE(numout,*)'      atm co2                         = ', TRIM(sn_rcv_co2%cldes   ), ' (', TRIM(sn_rcv_co2%clcat   ), ')'
+         WRITE(numout,*)'      atm pco2                        = ', TRIM(sn_rcv_atm_pco2%cldes), ' (', TRIM(sn_rcv_atm_pco2%clcat), ')'
+         WRITE(numout,*)'      atm dust                        = ', TRIM(sn_rcv_atm_dust%cldes), ' (', TRIM(sn_rcv_atm_dust%clcat), ')'
          WRITE(numout,*)'  sent fields (multiple ice categories)'
          WRITE(numout,*)'      surface temperature             = ', TRIM(sn_snd_temp%cldes  ), ' (', TRIM(sn_snd_temp%clcat  ), ')'
@@ -268,11 +307,25 @@
          WRITE(numout,*)'                      - orientation   = ', sn_snd_crt%clvor
          WRITE(numout,*)'                      - mesh          = ', sn_snd_crt%clvgrd
+         WRITE(numout,*)'      bio co2 flux                    = ', TRIM(sn_snd_bio_co2%cldes), ' (', TRIM(sn_snd_bio_co2%clcat), ')'
+         WRITE(numout,*)'      bio dms flux                    = ', TRIM(sn_snd_bio_dms%cldes), ' (', TRIM(sn_snd_bio_dms%clcat), ')'
+         WRITE(numout,*)'      bio dms chlorophyll             = ', TRIM(sn_snd_bio_chloro%cldes), ' (', TRIM(sn_snd_bio_chloro%clcat), ')'
          WRITE(numout,*)'      oce co2 flux                    = ', TRIM(sn_snd_co2%cldes   ), ' (', TRIM(sn_snd_co2%clcat   ), ')'
+         WRITE(numout,*)'      ice effective conductivity      = ', TRIM(sn_snd_cond%cldes   ), ' (', TRIM(sn_snd_cond%clcat   ), ')'
+         WRITE(numout,*)'      meltponds fraction & depth      = ', TRIM(sn_snd_mpnd%cldes  ), ' (', TRIM(sn_snd_mpnd%clcat   ), ')'
+         WRITE(numout,*)'      sea surface freezing temp       = ', TRIM(sn_snd_sstfrz%cldes   ), ' (', TRIM(sn_snd_sstfrz%clcat   ), ')'
+
          WRITE(numout,*)'  nn_cplmodel                         = ', nn_cplmodel
          WRITE(numout,*)'  ln_usecplmask                       = ', ln_usecplmask
+         WRITE(numout,*)'  nn_coupled_iceshelf_fluxes          = ', nn_coupled_iceshelf_fluxes
+         WRITE(numout,*)'  ln_iceshelf_init_atmos              = ', ln_iceshelf_init_atmos
+         WRITE(numout,*)'  rn_greenland_total_fw_flux         = ', rn_greenland_total_fw_flux
+         WRITE(numout,*)'  rn_antarctica_total_fw_flux        = ', rn_antarctica_total_fw_flux
+         WRITE(numout,*)'  rn_greenland_calving_fraction       = ', rn_greenland_calving_fraction
+         WRITE(numout,*)'  rn_antarctica_calving_fraction      = ', rn_antarctica_calving_fraction
+         WRITE(numout,*)'  rn_iceshelf_fluxes_tolerance        = ', rn_iceshelf_fluxes_tolerance
       ENDIF
 
       !                                   ! allocate sbccpl arrays
-      IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )
+      !IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )
      
       ! ================================ !
@@ -337,5 +390,9 @@
          srcv(jpr_otx2:jpr_otz2)%clgrid  = 'V'        !           and           V-point
          srcv(jpr_itx1:jpr_itz1)%clgrid  = 'F'        ! ice components given at F-point
-         srcv(jpr_otx1:jpr_otz2)%laction = .TRUE.     ! receive oce components on grid 1 & 2
+         !srcv(jpr_otx1:jpr_otz2)%laction = .TRUE.     ! receive oce components on grid 1 & 2
+! Currently needed for HadGEM3 - but shouldn't affect anyone else for the moment
+         srcv(jpr_otx1)%laction = .TRUE. 
+         srcv(jpr_oty1)%laction = .TRUE.
+!
          srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 only
       CASE( 'T,I' ) 
@@ -383,5 +440,5 @@
       srcv(jpr_snow)%clname = 'OTotSnow'      ! Snow = solid precipitation
       srcv(jpr_tevp)%clname = 'OTotEvap'      ! total evaporation (over oce + ice sublimation)
-      srcv(jpr_ievp)%clname = 'OIceEvap'      ! evaporation over ice = sublimation
+      srcv(jpr_ievp)%clname = 'OIceEvp'      ! evaporation over ice = sublimation
       srcv(jpr_sbpr)%clname = 'OSubMPre'      ! sublimation - liquid precipitation - solid precipitation 
       srcv(jpr_semp)%clname = 'OISubMSn'      ! ice solid water budget = sublimation - solid precipitation
@@ -396,5 +453,7 @@
       CASE default              ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_rcv_emp%cldes' )
       END SELECT
-
+      !Set the number of categories for coupling of sublimation
+      IF ( TRIM( sn_rcv_emp%clcat ) == 'yes' ) srcv(jpr_ievp)%nct = jpl
+      !
       !                                                      ! ------------------------- !
       !                                                      !     Runoffs & Calving     !   
@@ -410,4 +469,7 @@
       !
       srcv(jpr_cal   )%clname = 'OCalving'   ;   IF( TRIM( sn_rcv_cal%cldes ) == 'coupled' )   srcv(jpr_cal)%laction = .TRUE.
+      srcv(jpr_grnm  )%clname = 'OGrnmass'   ;   IF( TRIM( sn_rcv_grnm%cldes ) == 'coupled' )   srcv(jpr_grnm)%laction = .TRUE.
+      srcv(jpr_antm  )%clname = 'OAntmass'   ;   IF( TRIM( sn_rcv_antm%cldes ) == 'coupled' )   srcv(jpr_antm)%laction = .TRUE.
+
 
       !                                                      ! ------------------------- !
@@ -470,4 +532,20 @@
       !                                                      ! ------------------------- !
       srcv(jpr_co2 )%clname = 'O_AtmCO2'   ;   IF( TRIM(sn_rcv_co2%cldes   ) == 'coupled' )    srcv(jpr_co2 )%laction = .TRUE.
+
+
+      !                                                      ! --------------------------------------- !    
+      !                                                      ! Incoming CO2 and DUST fluxes for MEDUSA !
+      !                                                      ! --------------------------------------- !  
+      srcv(jpr_atm_pco2)%clname = 'OATMPCO2'
+
+      IF (TRIM(sn_rcv_atm_pco2%cldes) == 'medusa') THEN
+        srcv(jpr_atm_pco2)%laction = .TRUE.
+      END IF
+               
+      srcv(jpr_atm_dust)%clname = 'OATMDUST'   
+      IF (TRIM(sn_rcv_atm_dust%cldes) == 'medusa')  THEN
+        srcv(jpr_atm_dust)%laction = .TRUE.
+      END IF
+	 
       !                                                      ! ------------------------- !
       !                                                      !   topmelt and botmelt     !   
@@ -483,4 +561,17 @@
          srcv(jpr_topm:jpr_botm)%laction = .TRUE.
       ENDIF
+      
+#if defined key_cice && ! defined key_cice4
+      !                                                      ! ----------------------------- !
+      !                                                      !  sea-ice skin temperature     !   
+      !                                                      !  used in meltpond scheme      !
+      !                                                      !  May be calculated in Atm     !
+      !                                                      ! ----------------------------- !
+      srcv(jpr_ts_ice)%clname = 'OTsfIce'
+      IF ( TRIM( sn_rcv_ts_ice%cldes ) == 'ice' ) srcv(jpr_ts_ice)%laction = .TRUE.
+      IF ( TRIM( sn_rcv_ts_ice%clcat ) == 'yes' ) srcv(jpr_ts_ice)%nct = jpl
+      !TODO: Should there be a consistency check here?
+#endif
+
       !                                                      ! ------------------------------- !
       !                                                      !   OPA-SAS coupling - rcv by opa !   
@@ -600,10 +691,10 @@
       !                                                      ! ------------------------- !
       ssnd(jps_toce)%clname = 'O_SSTSST'
-      ssnd(jps_tice)%clname = 'O_TepIce'
+      ssnd(jps_tice)%clname = 'OTepIce'
       ssnd(jps_tmix)%clname = 'O_TepMix'
       SELECT CASE( TRIM( sn_snd_temp%cldes ) )
       CASE( 'none'                                 )       ! nothing to do
       CASE( 'oce only'                             )   ;   ssnd( jps_toce )%laction = .TRUE.
-      CASE( 'oce and ice' , 'weighted oce and ice' )
+      CASE( 'oce and ice' , 'weighted oce and ice' , 'oce and weighted ice')
          ssnd( (/jps_toce, jps_tice/) )%laction = .TRUE.
          IF ( TRIM( sn_snd_temp%clcat ) == 'yes' )  ssnd(jps_tice)%nct = jpl
@@ -634,13 +725,19 @@
 
       !                                                      ! ------------------------- !
-      !                                                      !  Ice fraction & Thickness ! 
+      !                                                      !  Ice fraction & Thickness 
       !                                                      ! ------------------------- !
       ssnd(jps_fice)%clname = 'OIceFrc'
       ssnd(jps_hice)%clname = 'OIceTck'
       ssnd(jps_hsnw)%clname = 'OSnwTck'
+      ssnd(jps_a_p)%clname  = 'OPndFrc'
+      ssnd(jps_ht_p)%clname = 'OPndTck'
+      ssnd(jps_fice1)%clname = 'OIceFrd'
       IF( k_ice /= 0 ) THEN
          ssnd(jps_fice)%laction = .TRUE.                  ! if ice treated in the ocean (even in climato case)
+         ssnd(jps_fice1)%laction = .TRUE.                 ! First-order regridded ice concentration, to be used
+	                                                  ! in producing atmos-to-ice fluxes
 ! Currently no namelist entry to determine sending of multi-category ice fraction so use the thickness entry for now
          IF ( TRIM( sn_snd_thick%clcat ) == 'yes' ) ssnd(jps_fice)%nct = jpl
+         IF ( TRIM( sn_snd_thick1%clcat ) == 'yes' ) ssnd(jps_fice1)%nct = jpl
       ENDIF
       
@@ -657,4 +754,41 @@
       CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_thick%cldes' )
       END SELECT
+
+      !                                                      ! ------------------------- !
+      !                                                      ! Ice Meltponds             !
+      !                                                      ! ------------------------- !
+#if defined key_cice && ! defined key_cice4
+      ! Meltponds only CICE5 
+      ssnd(jps_a_p)%clname = 'OPndFrc'   
+      ssnd(jps_ht_p)%clname = 'OPndTck'   
+      SELECT CASE ( TRIM( sn_snd_mpnd%cldes ) )
+      CASE ( 'none' )
+         ssnd(jps_a_p)%laction = .FALSE.
+         ssnd(jps_ht_p)%laction = .FALSE.
+      CASE ( 'ice only' ) 
+         ssnd(jps_a_p)%laction = .TRUE.
+         ssnd(jps_ht_p)%laction = .TRUE.
+         IF ( TRIM( sn_snd_mpnd%clcat ) == 'yes' ) THEN
+            ssnd(jps_a_p)%nct = jpl
+            ssnd(jps_ht_p)%nct = jpl
+         ELSE
+            IF ( jpl > 1 ) THEN
+               CALL ctl_stop( 'sbc_cpl_init: use weighted ice option for sn_snd_mpnd%cldes if not exchanging category fields' )
+            ENDIF
+         ENDIF
+      CASE ( 'weighted ice' ) 
+         ssnd(jps_a_p)%laction = .TRUE.
+         ssnd(jps_ht_p)%laction = .TRUE.
+         IF ( TRIM( sn_snd_mpnd%clcat ) == 'yes' ) THEN
+            ssnd(jps_a_p)%nct = jpl 
+            ssnd(jps_ht_p)%nct = jpl 
+         ENDIF
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_mpnd%cldes' )
+      END SELECT
+#else
+      IF( TRIM( sn_snd_mpnd%cldes ) /= 'none' ) THEN
+         CALL ctl_stop('Meltponds can only be used with CICEv5')
+      ENDIF
+#endif
 
       !                                                      ! ------------------------- !
@@ -689,4 +823,51 @@
       !                                                      ! ------------------------- !
       ssnd(jps_co2)%clname = 'O_CO2FLX' ;  IF( TRIM(sn_snd_co2%cldes) == 'coupled' )    ssnd(jps_co2 )%laction = .TRUE.
+      !
+
+      !                                                      ! ------------------------- !
+      !                                                      !   MEDUSA output fields    !
+      !                                                      ! ------------------------- !
+      ! Surface dimethyl sulphide from Medusa
+      ssnd(jps_bio_dms)%clname = 'OBioDMS'   
+      IF( TRIM(sn_snd_bio_dms%cldes) == 'medusa' )    ssnd(jps_bio_dms )%laction = .TRUE.
+
+      ! Surface CO2 flux from Medusa
+      ssnd(jps_bio_co2)%clname = 'OBioCO2'   
+      IF( TRIM(sn_snd_bio_co2%cldes) == 'medusa' )    ssnd(jps_bio_co2 )%laction = .TRUE.
+      
+      ! Surface chlorophyll from Medusa
+      ssnd(jps_bio_chloro)%clname = 'OBioChlo'   
+      IF( TRIM(sn_snd_bio_chloro%cldes) == 'medusa' )    ssnd(jps_bio_chloro )%laction = .TRUE.
+
+      !                                                      ! ------------------------- !
+      !                                                      ! Sea surface freezing temp !
+      !                                                      ! ------------------------- !
+      ssnd(jps_sstfrz)%clname = 'O_SSTFrz' ; IF( TRIM(sn_snd_sstfrz%cldes) == 'coupled' )  ssnd(jps_sstfrz)%laction = .TRUE.
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !    Ice conductivity       !
+      !                                                      ! ------------------------- !
+      ! Note that ultimately we will move to passing an ocean effective conductivity as well so there
+      ! will be some changes to the parts of the code which currently relate only to ice conductivity
+      ssnd(jps_kice )%clname = 'OIceKn'
+      SELECT CASE ( TRIM( sn_snd_cond%cldes ) )
+      CASE ( 'none' )
+         ssnd(jps_kice)%laction = .FALSE.
+      CASE ( 'ice only' )
+         ssnd(jps_kice)%laction = .TRUE.
+         IF ( TRIM( sn_snd_cond%clcat ) == 'yes' ) THEN
+            ssnd(jps_kice)%nct = jpl
+         ELSE
+            IF ( jpl > 1 ) THEN
+               CALL ctl_stop( 'sbc_cpl_init: use weighted ice option for sn_snd_cond%cldes if not exchanging category fields' )
+            ENDIF
+         ENDIF
+      CASE ( 'weighted ice' )
+         ssnd(jps_kice)%laction = .TRUE.
+         IF ( TRIM( sn_snd_cond%clcat ) == 'yes' ) ssnd(jps_kice)%nct = jpl
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_cond%cldes' )
+      END SELECT
+      !
+      
 
       !                                                      ! ------------------------------- !
@@ -785,4 +966,27 @@
       ncpl_qsr_freq = 86400 / ncpl_qsr_freq
 
+      IF( nn_coupled_iceshelf_fluxes .gt. 0 ) THEN
+          ! Crude masks to separate the Antarctic and Greenland icesheets. Obviously something
+          ! more complicated could be done if required.
+          greenland_icesheet_mask = 0.0
+          WHERE( gphit >= 0.0 ) greenland_icesheet_mask = 1.0
+          antarctica_icesheet_mask = 0.0
+          WHERE( gphit < 0.0 ) antarctica_icesheet_mask = 1.0
+
+          ! initialise other variables
+          greenland_icesheet_mass_array(:,:) = 0.0
+          antarctica_icesheet_mass_array(:,:) = 0.0
+
+          IF( .not. ln_rstart ) THEN
+             greenland_icesheet_mass = 0.0 
+             greenland_icesheet_mass_rate_of_change = 0.0 
+             greenland_icesheet_timelapsed = 0.0
+             antarctica_icesheet_mass = 0.0 
+             antarctica_icesheet_mass_rate_of_change = 0.0 
+             antarctica_icesheet_timelapsed = 0.0
+          ENDIF
+
+      ENDIF
+
       CALL wrk_dealloc( jpi,jpj, zacs, zaos )
       !
@@ -843,17 +1047,22 @@
       !!
       LOGICAL  ::   llnewtx, llnewtau      ! update wind stress components and module??
-      INTEGER  ::   ji, jj, jn             ! dummy loop indices
+      INTEGER  ::   ji, jj, jl, jn         ! dummy loop indices
       INTEGER  ::   isec                   ! number of seconds since nit000 (assuming rdttra did not change since nit000)
+      INTEGER  ::   ikchoix
       REAL(wp) ::   zcumulneg, zcumulpos   ! temporary scalars     
+      REAL(wp) ::   zgreenland_icesheet_mass_in, zantarctica_icesheet_mass_in
+      REAL(wp) ::   zgreenland_icesheet_mass_b, zantarctica_icesheet_mass_b
+      REAL(wp) ::   zmask_sum, zepsilon      
       REAL(wp) ::   zcoef                  ! temporary scalar
       REAL(wp) ::   zrhoa  = 1.22          ! Air density kg/m3
       REAL(wp) ::   zcdrag = 1.5e-3        ! drag coefficient
       REAL(wp) ::   zzx, zzy               ! temporary variables
-      REAL(wp), POINTER, DIMENSION(:,:) ::   ztx, zty, zmsk, zemp, zqns, zqsr
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztx, zty, zmsk, zemp, zqns, zqsr, ztx2, zty2
       !!----------------------------------------------------------------------
+
       !
       IF( nn_timing == 1 )  CALL timing_start('sbc_cpl_rcv')
       !
-      CALL wrk_alloc( jpi,jpj, ztx, zty, zmsk, zemp, zqns, zqsr )
+      CALL wrk_alloc( jpi,jpj, ztx, zty, zmsk, zemp, zqns, zqsr, ztx2, zty2 )
       !
       IF( ln_mixcpl )   zmsk(:,:) = 1. - xcplmask(:,:,0)
@@ -893,12 +1102,34 @@
             IF( TRIM( sn_rcv_tau%clvor ) == 'eastward-northward' ) THEN   ! 2 components oriented along the local grid
                !                                                       ! (geographical to local grid -> rotate the components)
-               CALL rot_rep( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), srcv(jpr_otx1)%clgrid, 'en->i', ztx )   
-               IF( srcv(jpr_otx2)%laction ) THEN
-                  CALL rot_rep( frcv(jpr_otx2)%z3(:,:,1), frcv(jpr_oty2)%z3(:,:,1), srcv(jpr_otx2)%clgrid, 'en->j', zty )   
-               ELSE	
-                  CALL rot_rep( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), srcv(jpr_otx1)%clgrid, 'en->j', zty )  
+               IF( srcv(jpr_otx1)%clgrid == 'U' .AND. (.NOT. srcv(jpr_otx2)%laction) ) THEN
+                  ! Temporary code for HadGEM3 - will be removed eventually.
+		  ! Only applies when we have only taux on U grid and tauy on V grid
+ 	          DO jj=2,jpjm1
+ 	             DO ji=2,jpim1
+ 	                  ztx(ji,jj)=0.25*vmask(ji,jj,1)                &
+ 	                     *(frcv(jpr_otx1)%z3(ji,jj,1)+frcv(jpr_otx1)%z3(ji-1,jj,1)    &
+ 	                     +frcv(jpr_otx1)%z3(ji,jj+1,1)+frcv(jpr_otx1)%z3(ji-1,jj+1,1))
+ 	                  zty(ji,jj)=0.25*umask(ji,jj,1)                &
+ 	                     *(frcv(jpr_oty1)%z3(ji,jj,1)+frcv(jpr_oty1)%z3(ji+1,jj,1)    &
+ 	                     +frcv(jpr_oty1)%z3(ji,jj-1,1)+frcv(jpr_oty1)%z3(ji+1,jj-1,1))
+ 	             ENDDO
+ 	          ENDDO
+ 	                
+ 	          ikchoix = 1
+ 	          CALL repcmo (frcv(jpr_otx1)%z3(:,:,1),zty,ztx,frcv(jpr_oty1)%z3(:,:,1),ztx2,zty2,ikchoix)
+ 	          CALL lbc_lnk (ztx2,'U', -1. )
+ 	          CALL lbc_lnk (zty2,'V', -1. )
+ 	          frcv(jpr_otx1)%z3(:,:,1)=ztx2(:,:)
+ 	          frcv(jpr_oty1)%z3(:,:,1)=zty2(:,:)
+ 	       ELSE
+ 	          CALL rot_rep( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), srcv(jpr_otx1)%clgrid, 'en->i', ztx )   
+ 	          frcv(jpr_otx1)%z3(:,:,1) = ztx(:,:)      ! overwrite 1st component on the 1st grid
+ 	          IF( srcv(jpr_otx2)%laction ) THEN
+ 	             CALL rot_rep( frcv(jpr_otx2)%z3(:,:,1), frcv(jpr_oty2)%z3(:,:,1), srcv(jpr_otx2)%clgrid, 'en->j', zty )   
+ 	          ELSE
+ 	             CALL rot_rep( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), srcv(jpr_otx1)%clgrid, 'en->j', zty ) 
+ 	          ENDIF
+          frcv(jpr_oty1)%z3(:,:,1) = zty(:,:)      ! overwrite 2nd component on the 2nd grid  
                ENDIF
-               frcv(jpr_otx1)%z3(:,:,1) = ztx(:,:)      ! overwrite 1st component on the 1st grid
-               frcv(jpr_oty1)%z3(:,:,1) = zty(:,:)      ! overwrite 2nd component on the 2nd grid
             ENDIF
             !                              
@@ -990,4 +1221,9 @@
       ENDIF
 
+      IF (ln_medusa) THEN
+        IF( srcv(jpr_atm_pco2)%laction) PCO2a_in_cpl(:,:) = frcv(jpr_atm_pco2)%z3(:,:,1)
+        IF( srcv(jpr_atm_dust)%laction) Dust_in_cpl(:,:) = frcv(jpr_atm_dust)%z3(:,:,1)
+      ENDIF
+
 #if defined key_cpl_carbon_cycle
       !                                                      ! ================== !
@@ -995,4 +1231,23 @@
       !                                                      ! ================== !
       IF( srcv(jpr_co2)%laction )   atm_co2(:,:) = frcv(jpr_co2)%z3(:,:,1)
+#endif
+
+#if defined key_cice && ! defined key_cice4
+      !  ! Sea ice surface skin temp:
+      IF( srcv(jpr_ts_ice)%laction ) THEN
+        DO jl = 1, jpl
+          DO jj = 1, jpj
+            DO ji = 1, jpi
+              IF (frcv(jpr_ts_ice)%z3(ji,jj,jl) > 0.0) THEN
+                tsfc_ice(ji,jj,jl) = 0.0
+              ELSE IF (frcv(jpr_ts_ice)%z3(ji,jj,jl) < -60.0) THEN
+                tsfc_ice(ji,jj,jl) = -60.0
+              ELSE
+                tsfc_ice(ji,jj,jl) = frcv(jpr_ts_ice)%z3(ji,jj,jl)
+              ENDIF
+            END DO
+          END DO
+        END DO
+      ENDIF
 #endif
 
@@ -1029,4 +1284,5 @@
          ssu_m(:,:) = frcv(jpr_ocx1)%z3(:,:,1)
          ub (:,:,1) = ssu_m(:,:)                             ! will be used in sbcice_lim in the call of lim_sbc_tau
+         un (:,:,1) = ssu_m(:,:)                             ! will be used in sbc_cpl_snd if atmosphere coupling
          CALL iom_put( 'ssu_m', ssu_m )
       ENDIF
@@ -1034,4 +1290,5 @@
          ssv_m(:,:) = frcv(jpr_ocy1)%z3(:,:,1)
          vb (:,:,1) = ssv_m(:,:)                             ! will be used in sbcice_lim in the call of lim_sbc_tau
+         vn (:,:,1) = ssv_m(:,:)                             ! will be used in sbc_cpl_snd if atmosphere coupling
          CALL iom_put( 'ssv_m', ssv_m )
       ENDIF
@@ -1110,6 +1367,89 @@
 
       ENDIF
-      !
-      CALL wrk_dealloc( jpi,jpj, ztx, zty, zmsk, zemp, zqns, zqsr )
+      
+      !                                                        ! land ice masses : Greenland
+      zepsilon = rn_iceshelf_fluxes_tolerance
+
+
+      ! See if we need zmask_sum...
+      IF ( srcv(jpr_grnm)%laction .OR. srcv(jpr_antm)%laction ) THEN
+         zmask_sum = glob_sum( tmask(:,:,1) )
+      ENDIF
+
+      IF( srcv(jpr_grnm)%laction .AND. nn_coupled_iceshelf_fluxes == 1 ) THEN
+         greenland_icesheet_mass_array(:,:) = frcv(jpr_grnm)%z3(:,:,1)
+         ! take average over ocean points of input array to avoid cumulative error over time
+         ! The following must be bit reproducible over different PE decompositions
+         zgreenland_icesheet_mass_in = glob_sum( greenland_icesheet_mass_array(:,:) * tmask(:,:,1) )
+
+         zgreenland_icesheet_mass_in = zgreenland_icesheet_mass_in / zmask_sum
+         greenland_icesheet_timelapsed = greenland_icesheet_timelapsed + rdt         
+
+         IF( ln_iceshelf_init_atmos .AND. kt == 1 ) THEN
+            ! On the first timestep (of an NRUN) force the ocean to ignore the icesheet masses in the ocean restart
+            ! and take them from the atmosphere to avoid problems with using inconsistent ocean and atmosphere restarts.
+            zgreenland_icesheet_mass_b = zgreenland_icesheet_mass_in
+            greenland_icesheet_mass = zgreenland_icesheet_mass_in
+         ENDIF
+
+         IF( ABS( zgreenland_icesheet_mass_in - greenland_icesheet_mass ) > zepsilon ) THEN
+            zgreenland_icesheet_mass_b = greenland_icesheet_mass
+            
+            ! Only update the mass if it has increased.
+            IF ( (zgreenland_icesheet_mass_in - greenland_icesheet_mass) > 0.0 ) THEN
+               greenland_icesheet_mass = zgreenland_icesheet_mass_in
+            ENDIF
+            
+            IF( zgreenland_icesheet_mass_b /= 0.0 ) &
+           &     greenland_icesheet_mass_rate_of_change = ( greenland_icesheet_mass - zgreenland_icesheet_mass_b ) / greenland_icesheet_timelapsed 
+            greenland_icesheet_timelapsed = 0.0_wp       
+         ENDIF
+         IF(lwp) WRITE(numout,*) 'Greenland icesheet mass (kg) read in is ', zgreenland_icesheet_mass_in
+         IF(lwp) WRITE(numout,*) 'Greenland icesheet mass (kg) used is    ', greenland_icesheet_mass
+         IF(lwp) WRITE(numout,*) 'Greenland icesheet mass rate of change (kg/s) is ', greenland_icesheet_mass_rate_of_change
+         IF(lwp) WRITE(numout,*) 'Greenland icesheet seconds lapsed since last change is ', greenland_icesheet_timelapsed
+      ELSE IF ( nn_coupled_iceshelf_fluxes == 2 ) THEN
+         greenland_icesheet_mass_rate_of_change = rn_greenland_total_fw_flux
+      ENDIF
+
+      !                                                        ! land ice masses : Antarctica
+      IF( srcv(jpr_antm)%laction .AND. nn_coupled_iceshelf_fluxes == 1 ) THEN
+         antarctica_icesheet_mass_array(:,:) = frcv(jpr_antm)%z3(:,:,1)
+         ! take average over ocean points of input array to avoid cumulative error from rounding errors over time
+         ! The following must be bit reproducible over different PE decompositions
+         zantarctica_icesheet_mass_in = glob_sum( antarctica_icesheet_mass_array(:,:) * tmask(:,:,1) )
+
+         zantarctica_icesheet_mass_in = zantarctica_icesheet_mass_in / zmask_sum
+         antarctica_icesheet_timelapsed = antarctica_icesheet_timelapsed + rdt         
+
+         IF( ln_iceshelf_init_atmos .AND. kt == 1 ) THEN
+            ! On the first timestep (of an NRUN) force the ocean to ignore the icesheet masses in the ocean restart
+            ! and take them from the atmosphere to avoid problems with using inconsistent ocean and atmosphere restarts.
+            zantarctica_icesheet_mass_b = zantarctica_icesheet_mass_in
+            antarctica_icesheet_mass = zantarctica_icesheet_mass_in
+         ENDIF
+
+         IF( ABS( zantarctica_icesheet_mass_in - antarctica_icesheet_mass ) > zepsilon ) THEN
+            zantarctica_icesheet_mass_b = antarctica_icesheet_mass
+            
+            ! Only update the mass if it has increased.
+            IF ( (zantarctica_icesheet_mass_in - antarctica_icesheet_mass) > 0.0 ) THEN
+               antarctica_icesheet_mass = zantarctica_icesheet_mass_in
+            END IF
+            
+            IF( zantarctica_icesheet_mass_b /= 0.0 ) &
+          &      antarctica_icesheet_mass_rate_of_change = ( antarctica_icesheet_mass - zantarctica_icesheet_mass_b ) / antarctica_icesheet_timelapsed 
+            antarctica_icesheet_timelapsed = 0.0_wp       
+         ENDIF
+         IF(lwp) WRITE(numout,*) 'Antarctica icesheet mass (kg) read in is ', zantarctica_icesheet_mass_in
+         IF(lwp) WRITE(numout,*) 'Antarctica icesheet mass (kg) used is    ', antarctica_icesheet_mass
+         IF(lwp) WRITE(numout,*) 'Antarctica icesheet mass rate of change (kg/s) is ', antarctica_icesheet_mass_rate_of_change
+         IF(lwp) WRITE(numout,*) 'Antarctica icesheet seconds lapsed since last change is ', antarctica_icesheet_timelapsed
+      ELSE IF ( nn_coupled_iceshelf_fluxes == 2 ) THEN
+         antarctica_icesheet_mass_rate_of_change = rn_antarctica_total_fw_flux
+      ENDIF
+
+      !
+      CALL wrk_dealloc( jpi,jpj, ztx, zty, zmsk, zemp, zqns, zqsr, ztx2, zty2 )
       !
       IF( nn_timing == 1 )  CALL timing_stop('sbc_cpl_rcv')
@@ -1333,39 +1673,48 @@
       !!             ***  ROUTINE sbc_cpl_ice_flx  ***
       !!
-      !! ** Purpose :   provide the heat and freshwater fluxes of the 
-      !!              ocean-ice system.
+      !! ** Purpose :   provide the heat and freshwater fluxes of the ocean-ice system
       !!
       !! ** Method  :   transform the fields received from the atmosphere into
       !!             surface heat and fresh water boundary condition for the 
       !!             ice-ocean system. The following fields are provided:
-      !!              * total non solar, solar and freshwater fluxes (qns_tot, 
+      !!               * total non solar, solar and freshwater fluxes (qns_tot, 
       !!             qsr_tot and emp_tot) (total means weighted ice-ocean flux)
       !!             NB: emp_tot include runoffs and calving.
-      !!              * fluxes over ice (qns_ice, qsr_ice, emp_ice) where
+      !!               * fluxes over ice (qns_ice, qsr_ice, emp_ice) where
       !!             emp_ice = sublimation - solid precipitation as liquid
       !!             precipitation are re-routed directly to the ocean and 
-      !!             runoffs and calving directly enter the ocean.
-      !!              * solid precipitation (sprecip), used to add to qns_tot 
+      !!             calving directly enter the ocean (runoffs are read but included in trasbc.F90)
+      !!               * solid precipitation (sprecip), used to add to qns_tot 
       !!             the heat lost associated to melting solid precipitation
       !!             over the ocean fraction.
-      !!       ===>> CAUTION here this changes the net heat flux received from
-      !!             the atmosphere
-      !!
-      !!                  - the fluxes have been separated from the stress as
-      !!                 (a) they are updated at each ice time step compare to
-      !!                 an update at each coupled time step for the stress, and
-      !!                 (b) the conservative computation of the fluxes over the
-      !!                 sea-ice area requires the knowledge of the ice fraction
-      !!                 after the ice advection and before the ice thermodynamics,
-      !!                 so that the stress is updated before the ice dynamics
-      !!                 while the fluxes are updated after it.
+      !!               * heat content of rain, snow and evap can also be provided,
+      !!             otherwise heat flux associated with these mass flux are
+      !!             guessed (qemp_oce, qemp_ice)
+      !!
+      !!             - the fluxes have been separated from the stress as
+      !!               (a) they are updated at each ice time step compare to
+      !!               an update at each coupled time step for the stress, and
+      !!               (b) the conservative computation of the fluxes over the
+      !!               sea-ice area requires the knowledge of the ice fraction
+      !!               after the ice advection and before the ice thermodynamics,
+      !!               so that the stress is updated before the ice dynamics
+      !!               while the fluxes are updated after it.
+      !!
+      !! ** Details
+      !!             qns_tot = pfrld * qns_oce + ( 1 - pfrld ) * qns_ice   => provided
+      !!                     + qemp_oce + qemp_ice                         => recalculated and added up to qns
+      !!
+      !!             qsr_tot = pfrld * qsr_oce + ( 1 - pfrld ) * qsr_ice   => provided
+      !!
+      !!             emp_tot = emp_oce + emp_ice                           => calving is provided and added to emp_tot (and emp_oce)
+      !!                                                                      river runoff (rnf) is provided but not included here
       !!
       !! ** Action  :   update at each nf_ice time step:
       !!                   qns_tot, qsr_tot  non-solar and solar total heat fluxes
       !!                   qns_ice, qsr_ice  non-solar and solar heat fluxes over the ice
-      !!                   emp_tot            total evaporation - precipitation(liquid and solid) (-runoff)(-calving)
-      !!                   emp_ice            ice sublimation - solid precipitation over the ice
-      !!                   dqns_ice           d(non-solar heat flux)/d(Temperature) over the ice
-      !!                   sprecip             solid precipitation over the ocean  
+      !!                   emp_tot           total evaporation - precipitation(liquid and solid) (-calving)
+      !!                   emp_ice           ice sublimation - solid precipitation over the ice
+      !!                   dqns_ice          d(non-solar heat flux)/d(Temperature) over the ice
+      !!                   sprecip           solid precipitation over the ocean  
       !!----------------------------------------------------------------------
       REAL(wp), INTENT(in   ), DIMENSION(:,:)   ::   p_frld     ! lead fraction                [0 to 1]
@@ -1376,14 +1725,16 @@
       !
       INTEGER ::   jl         ! dummy loop index
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zcptn, ztmp, zicefr, zmsk
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zemp_tot, zemp_ice, zsprecip, ztprecip, zqns_tot, zqsr_tot
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zqns_ice, zqsr_ice, zdqns_ice
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zevap, zsnw, zqns_oce, zqsr_oce, zqprec_ice, zqemp_oce ! for LIM3
+      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zcptn, ztmp, zicefr, zmsk, zsnw
+      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zemp_tot, zemp_ice, zemp_oce, ztprecip, zsprecip, zevap_oce, zevap_ice, zdevap_ice
+      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zqns_tot, zqns_oce, zqsr_tot, zqsr_oce, zqprec_ice, zqemp_oce, zqemp_ice
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zqns_ice, zqsr_ice, zdqns_ice, zqevap_ice
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('sbc_cpl_ice_flx')
       !
-      CALL wrk_alloc( jpi,jpj,     zcptn, ztmp, zicefr, zmsk, zemp_tot, zemp_ice, zsprecip, ztprecip, zqns_tot, zqsr_tot )
-      CALL wrk_alloc( jpi,jpj,jpl, zqns_ice, zqsr_ice, zdqns_ice )
+      CALL wrk_alloc( jpi,jpj,     zcptn, ztmp, zicefr, zmsk, zsnw )
+      CALL wrk_alloc( jpi,jpj,     zemp_tot, zemp_ice, zemp_oce, ztprecip, zsprecip, zevap_oce, zevap_ice, zdevap_ice )
+      CALL wrk_alloc( jpi,jpj,     zqns_tot, zqns_oce, zqsr_tot, zqsr_oce, zqprec_ice, zqemp_oce, zqemp_ice )
+      CALL wrk_alloc( jpi,jpj,jpl, zqns_ice, zqsr_ice, zdqns_ice, zqevap_ice )
 
       IF( ln_mixcpl )   zmsk(:,:) = 1. - xcplmask(:,:,0)
@@ -1392,38 +1743,121 @@
       !
       !                                                      ! ========================= !
-      !                                                      !    freshwater budget      !   (emp)
+      !                                                      !    freshwater budget      !   (emp_tot)
       !                                                      ! ========================= !
       !
-      !                                                           ! total Precipitation - total Evaporation (emp_tot)
-      !                                                           ! solid precipitation - sublimation       (emp_ice)
-      !                                                           ! solid Precipitation                     (sprecip)
-      !                                                           ! liquid + solid Precipitation            (tprecip)
+      !                                                           ! solid Precipitation                                (sprecip)
+      !                                                           ! liquid + solid Precipitation                       (tprecip)
+      !                                                           ! total Evaporation - total Precipitation            (emp_tot)
+      !                                                           ! sublimation - solid precipitation (cell average)   (emp_ice)
       SELECT CASE( TRIM( sn_rcv_emp%cldes ) )
       CASE( 'conservative'  )   ! received fields: jpr_rain, jpr_snow, jpr_ievp, jpr_tevp
          zsprecip(:,:) = frcv(jpr_snow)%z3(:,:,1)                  ! May need to ensure positive here
          ztprecip(:,:) = frcv(jpr_rain)%z3(:,:,1) + zsprecip(:,:)  ! May need to ensure positive here
-         zemp_tot(:,:) = frcv(jpr_tevp)%z3(:,:,1) - ztprecip(:,:)
-         zemp_ice(:,:) = frcv(jpr_ievp)%z3(:,:,1) - frcv(jpr_snow)%z3(:,:,1)
-            CALL iom_put( 'rain'         , frcv(jpr_rain)%z3(:,:,1)              )   ! liquid precipitation 
+         zemp_tot(:,:) = frcv(jpr_tevp)%z3(:,:,1) - ztprecip(:,:)         
+#if defined key_cice
+         IF ( TRIM(sn_rcv_emp%clcat) == 'yes' ) THEN
+            ! zemp_ice is the sum of frcv(jpr_ievp)%z3(:,:,1) over all layers - snow
+            zemp_ice(:,:) = - frcv(jpr_snow)%z3(:,:,1)
+            DO jl=1,jpl
+               zemp_ice(:,:   ) = zemp_ice(:,:) + frcv(jpr_ievp)%z3(:,:,jl)
+            ENDDO
+            ! latent heat coupled for each category in CICE
+            qla_ice(:,:,1:jpl) = - frcv(jpr_ievp)%z3(:,:,1:jpl) * lsub
+         ELSE
+            ! If CICE has multicategories it still expects coupling fields for
+            ! each even if we treat as a single field
+            ! The latent heat flux is split between the ice categories according
+            ! to the fraction of the ice in each category
+            zemp_ice(:,:) = frcv(jpr_ievp)%z3(:,:,1) - frcv(jpr_snow)%z3(:,:,1)
+            WHERE ( zicefr(:,:) /= 0._wp ) 
+               ztmp(:,:) = 1./zicefr(:,:)
+            ELSEWHERE 
+               ztmp(:,:) = 0.e0
+            END WHERE  
+            DO jl=1,jpl
+               qla_ice(:,:,jl) = - a_i(:,:,jl) * ztmp(:,:) * frcv(jpr_ievp)%z3(:,:,1) * lsub 
+            END DO
+            WHERE ( zicefr(:,:) == 0._wp )  qla_ice(:,:,1) = -frcv(jpr_ievp)%z3(:,:,1) * lsub 
+         ENDIF
+#else         
+         zemp_ice(:,:) = ( frcv(jpr_ievp)%z3(:,:,1) - frcv(jpr_snow)%z3(:,:,1) ) * zicefr(:,:)
+#endif                  
+         CALL iom_put( 'rain'         , frcv(jpr_rain)%z3(:,:,1) * tmask(:,:,1)      )   ! liquid precipitation 
+         CALL iom_put( 'rain_ao_cea'  , frcv(jpr_rain)%z3(:,:,1)* p_frld(:,:) * tmask(:,:,1)      )   ! liquid precipitation 
          IF( iom_use('hflx_rain_cea') )   &
-            CALL iom_put( 'hflx_rain_cea', frcv(jpr_rain)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from liq. precip. 
+            &  CALL iom_put( 'hflx_rain_cea', frcv(jpr_rain)%z3(:,:,1) * zcptn(:,:) * tmask(:,:,1))   ! heat flux from liq. precip. 
+         IF( iom_use('hflx_prec_cea') )   &
+            & CALL iom_put( 'hflx_prec_cea', ztprecip * zcptn(:,:) * tmask(:,:,1) * p_frld(:,:) )   ! heat content flux from all precip  (cell avg)
          IF( iom_use('evap_ao_cea') .OR. iom_use('hflx_evap_cea') )   &
-            ztmp(:,:) = frcv(jpr_tevp)%z3(:,:,1) - frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:)
+            & ztmp(:,:) = frcv(jpr_tevp)%z3(:,:,1) - frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:)
          IF( iom_use('evap_ao_cea'  ) )   &
-            CALL iom_put( 'evap_ao_cea'  , ztmp                   )   ! ice-free oce evap (cell average)
+            &  CALL iom_put( 'evap_ao_cea'  , ztmp * tmask(:,:,1)                  )   ! ice-free oce evap (cell average)
          IF( iom_use('hflx_evap_cea') )   &
-            CALL iom_put( 'hflx_evap_cea', ztmp(:,:) * zcptn(:,:) )   ! heat flux from from evap (cell average)
-      CASE( 'oce and ice'   )   ! received fields: jpr_sbpr, jpr_semp, jpr_oemp, jpr_ievp
+            &  CALL iom_put( 'hflx_evap_cea', ztmp(:,:) * zcptn(:,:) * tmask(:,:,1) )   ! heat flux from from evap (cell average)
+      CASE( 'oce and ice' )   ! received fields: jpr_sbpr, jpr_semp, jpr_oemp, jpr_ievp
          zemp_tot(:,:) = p_frld(:,:) * frcv(jpr_oemp)%z3(:,:,1) + zicefr(:,:) * frcv(jpr_sbpr)%z3(:,:,1)
-         zemp_ice(:,:) = frcv(jpr_semp)%z3(:,:,1)
+         zemp_ice(:,:) = frcv(jpr_semp)%z3(:,:,1) * zicefr(:,:)
          zsprecip(:,:) = frcv(jpr_ievp)%z3(:,:,1) - frcv(jpr_semp)%z3(:,:,1)
          ztprecip(:,:) = frcv(jpr_semp)%z3(:,:,1) - frcv(jpr_sbpr)%z3(:,:,1) + zsprecip(:,:)
       END SELECT
 
-      IF( iom_use('subl_ai_cea') )   &
-         CALL iom_put( 'subl_ai_cea', frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:) )   ! Sublimation over sea-ice         (cell average)
-      !   
-      !                                                           ! runoffs and calving (put in emp_tot)
+#if defined key_lim3
+      ! zsnw = snow fraction over ice after wind blowing
+      zsnw(:,:) = 0._wp  ;  CALL lim_thd_snwblow( p_frld, zsnw )
+      
+      ! --- evaporation minus precipitation corrected (because of wind blowing on snow) --- !
+      zemp_ice(:,:) = zemp_ice(:,:) + zsprecip(:,:) * ( zicefr(:,:) - zsnw(:,:) )  ! emp_ice = A * sublimation - zsnw * sprecip
+      zemp_oce(:,:) = zemp_tot(:,:) - zemp_ice(:,:)                                ! emp_oce = emp_tot - emp_ice
+
+      ! --- evaporation over ocean (used later for qemp) --- !
+      zevap_oce(:,:) = frcv(jpr_tevp)%z3(:,:,1) - frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:)
+
+      ! --- evaporation over ice (kg/m2/s) --- !
+      zevap_ice(:,:) = frcv(jpr_ievp)%z3(:,:,1)
+      ! since the sensitivity of evap to temperature (devap/dT) is not prescribed by the atmosphere, we set it to 0
+      ! therefore, sublimation is not redistributed over the ice categories in case no subgrid scale fluxes are provided by atm.
+      zdevap_ice(:,:) = 0._wp
+      
+      ! --- runoffs (included in emp later on) --- !
       IF( srcv(jpr_rnf)%laction )   rnf(:,:) = frcv(jpr_rnf)%z3(:,:,1)
+
+      ! --- calving (put in emp_tot and emp_oce) --- !
+      IF( srcv(jpr_cal)%laction ) THEN 
+         zemp_tot(:,:) = zemp_tot(:,:) - frcv(jpr_cal)%z3(:,:,1)
+         zemp_oce(:,:) = zemp_oce(:,:) - frcv(jpr_cal)%z3(:,:,1)
+         CALL iom_put( 'calving_cea', frcv(jpr_cal)%z3(:,:,1) )
+      ENDIF
+
+      IF( ln_mixcpl ) THEN
+         emp_tot(:,:) = emp_tot(:,:) * xcplmask(:,:,0) + zemp_tot(:,:) * zmsk(:,:)
+         emp_ice(:,:) = emp_ice(:,:) * xcplmask(:,:,0) + zemp_ice(:,:) * zmsk(:,:)
+         emp_oce(:,:) = emp_oce(:,:) * xcplmask(:,:,0) + zemp_oce(:,:) * zmsk(:,:)
+         sprecip(:,:) = sprecip(:,:) * xcplmask(:,:,0) + zsprecip(:,:) * zmsk(:,:)
+         tprecip(:,:) = tprecip(:,:) * xcplmask(:,:,0) + ztprecip(:,:) * zmsk(:,:)
+         DO jl=1,jpl
+            evap_ice (:,:,jl) = evap_ice (:,:,jl) * xcplmask(:,:,0) + zevap_ice (:,:) * zmsk(:,:)
+            devap_ice(:,:,jl) = devap_ice(:,:,jl) * xcplmask(:,:,0) + zdevap_ice(:,:) * zmsk(:,:)
+         ENDDO
+      ELSE
+         emp_tot(:,:) =         zemp_tot(:,:)
+         emp_ice(:,:) =         zemp_ice(:,:)
+         emp_oce(:,:) =         zemp_oce(:,:)     
+         sprecip(:,:) =         zsprecip(:,:)
+         tprecip(:,:) =         ztprecip(:,:)
+         DO jl=1,jpl
+            evap_ice (:,:,jl) = zevap_ice (:,:)
+            devap_ice(:,:,jl) = zdevap_ice(:,:)
+         ENDDO
+      ENDIF
+
+      IF( iom_use('subl_ai_cea') )   CALL iom_put( 'subl_ai_cea', zevap_ice(:,:) * zicefr(:,:)         )  ! Sublimation over sea-ice (cell average)
+                                     CALL iom_put( 'snowpre'    , sprecip(:,:)                         )  ! Snow
+      IF( iom_use('snow_ao_cea') )   CALL iom_put( 'snow_ao_cea', sprecip(:,:) * ( 1._wp - zsnw(:,:) ) )  ! Snow over ice-free ocean  (cell average)
+      IF( iom_use('snow_ai_cea') )   CALL iom_put( 'snow_ai_cea', sprecip(:,:) *           zsnw(:,:)   )  ! Snow over sea-ice         (cell average)
+#else
+      ! runoffs and calving (put in emp_tot)
+      IF( srcv(jpr_rnf)%laction )   rnf(:,:) = frcv(jpr_rnf)%z3(:,:,1)
+      IF( iom_use('hflx_rnf_cea') )   &
+         CALL iom_put( 'hflx_rnf_cea' , rnf(:,:) * zcptn(:,:) )
       IF( srcv(jpr_cal)%laction ) THEN 
          zemp_tot(:,:) = zemp_tot(:,:) - frcv(jpr_cal)%z3(:,:,1)
@@ -1443,27 +1877,26 @@
       ENDIF
 
-         CALL iom_put( 'snowpre'    , sprecip                                )   ! Snow
-      IF( iom_use('snow_ao_cea') )   &
-         CALL iom_put( 'snow_ao_cea', sprecip(:,:) * p_frld(:,:)             )   ! Snow        over ice-free ocean  (cell average)
-      IF( iom_use('snow_ai_cea') )   &
-         CALL iom_put( 'snow_ai_cea', sprecip(:,:) * zicefr(:,:)             )   ! Snow        over sea-ice         (cell average)
+      IF( iom_use('subl_ai_cea') )  CALL iom_put( 'subl_ai_cea', frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:) )  ! Sublimation over sea-ice (cell average)
+                                    CALL iom_put( 'snowpre'    , sprecip(:,:)               )   ! Snow
+      IF( iom_use('snow_ao_cea') )  CALL iom_put( 'snow_ao_cea', sprecip(:,:) * p_frld(:,:) )   ! Snow over ice-free ocean  (cell average)
+      IF( iom_use('snow_ai_cea') )  CALL iom_put( 'snow_ai_cea', sprecip(:,:) * zicefr(:,:) )   ! Snow over sea-ice         (cell average)
+#endif
 
       !                                                      ! ========================= !
       SELECT CASE( TRIM( sn_rcv_qns%cldes ) )                !   non solar heat fluxes   !   (qns)
       !                                                      ! ========================= !
-      CASE( 'oce only' )                                     ! the required field is directly provided
-         zqns_tot(:,:  ) = frcv(jpr_qnsoce)%z3(:,:,1)
-      CASE( 'conservative' )                                      ! the required fields are directly provided
-         zqns_tot(:,:  ) = frcv(jpr_qnsmix)%z3(:,:,1)
+      CASE( 'oce only' )         ! the required field is directly provided
+         zqns_tot(:,:) = frcv(jpr_qnsoce)%z3(:,:,1)
+      CASE( 'conservative' )     ! the required fields are directly provided
+         zqns_tot(:,:) = frcv(jpr_qnsmix)%z3(:,:,1)
          IF ( TRIM(sn_rcv_qns%clcat) == 'yes' ) THEN
             zqns_ice(:,:,1:jpl) = frcv(jpr_qnsice)%z3(:,:,1:jpl)
          ELSE
-            ! Set all category values equal for the moment
             DO jl=1,jpl
-               zqns_ice(:,:,jl) = frcv(jpr_qnsice)%z3(:,:,1)
+               zqns_ice(:,:,jl) = frcv(jpr_qnsice)%z3(:,:,1) ! Set all category values equal
             ENDDO
          ENDIF
-      CASE( 'oce and ice' )       ! the total flux is computed from ocean and ice fluxes
-         zqns_tot(:,:  ) =  p_frld(:,:) * frcv(jpr_qnsoce)%z3(:,:,1)
+      CASE( 'oce and ice' )      ! the total flux is computed from ocean and ice fluxes
+         zqns_tot(:,:) =  p_frld(:,:) * frcv(jpr_qnsoce)%z3(:,:,1)
          IF ( TRIM(sn_rcv_qns%clcat) == 'yes' ) THEN
             DO jl=1,jpl
@@ -1472,5 +1905,5 @@
             ENDDO
          ELSE
-            qns_tot(:,:   ) = qns_tot(:,:) + zicefr(:,:) * frcv(jpr_qnsice)%z3(:,:,1)
+            qns_tot(:,:) = qns_tot(:,:) + zicefr(:,:) * frcv(jpr_qnsice)%z3(:,:,1)
             DO jl=1,jpl
                zqns_tot(:,:   ) = zqns_tot(:,:) + zicefr(:,:) * frcv(jpr_qnsice)%z3(:,:,1)
@@ -1478,10 +1911,10 @@
             ENDDO
          ENDIF
-      CASE( 'mixed oce-ice' )     ! the ice flux is cumputed from the total flux, the SST and ice informations
+      CASE( 'mixed oce-ice' )    ! the ice flux is cumputed from the total flux, the SST and ice informations
 ! ** NEED TO SORT OUT HOW THIS SHOULD WORK IN THE MULTI-CATEGORY CASE - CURRENTLY NOT ALLOWED WHEN INTERFACE INITIALISED **
          zqns_tot(:,:  ) = frcv(jpr_qnsmix)%z3(:,:,1)
          zqns_ice(:,:,1) = frcv(jpr_qnsmix)%z3(:,:,1)    &
             &            + frcv(jpr_dqnsdt)%z3(:,:,1) * ( pist(:,:,1) - ( (rt0 + psst(:,:  ) ) * p_frld(:,:)   &
-            &                                                   +          pist(:,:,1)   * zicefr(:,:) ) )
+            &                                           + pist(:,:,1) * zicefr(:,:) ) )
       END SELECT
 !!gm
@@ -1493,29 +1926,11 @@
 !! similar job should be done for snow and precipitation temperature
       !                                     
-      IF( srcv(jpr_cal)%laction ) THEN                            ! Iceberg melting 
-         ztmp(:,:) = frcv(jpr_cal)%z3(:,:,1) * lfus               ! add the latent heat of iceberg melting 
-         zqns_tot(:,:) = zqns_tot(:,:) - ztmp(:,:)
-         IF( iom_use('hflx_cal_cea') )   &
-            CALL iom_put( 'hflx_cal_cea', ztmp + frcv(jpr_cal)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from calving
-      ENDIF
-
-      ztmp(:,:) = p_frld(:,:) * zsprecip(:,:) * lfus
-      IF( iom_use('hflx_snow_cea') )    CALL iom_put( 'hflx_snow_cea', ztmp + sprecip(:,:) * zcptn(:,:) )   ! heat flux from snow (cell average)
-
-#if defined key_lim3
-      CALL wrk_alloc( jpi,jpj, zevap, zsnw, zqns_oce, zqprec_ice, zqemp_oce ) 
-
-      ! --- evaporation --- !
-      ! clem: evap_ice is set to 0 for LIM3 since we still do not know what to do with sublimation
-      ! the problem is: the atm. imposes both mass evaporation and heat removed from the snow/ice
-      !                 but it is incoherent WITH the ice model  
-      DO jl=1,jpl
-         evap_ice(:,:,jl) = 0._wp  ! should be: frcv(jpr_ievp)%z3(:,:,1)
-      ENDDO
-      zevap(:,:) = zemp_tot(:,:) + ztprecip(:,:) ! evaporation over ocean
-
-      ! --- evaporation minus precipitation --- !
-      emp_oce(:,:) = emp_tot(:,:) - emp_ice(:,:)
-
+      IF( srcv(jpr_cal)%laction ) THEN   ! Iceberg melting 
+         zqns_tot(:,:) = zqns_tot(:,:) - frcv(jpr_cal)%z3(:,:,1) * lfus  ! add the latent heat of iceberg melting
+                                                                         ! we suppose it melts at 0deg, though it should be temp. of surrounding ocean
+         IF( iom_use('hflx_cal_cea') )   CALL iom_put( 'hflx_cal_cea', - frcv(jpr_cal)%z3(:,:,1) * lfus )   ! heat flux from calving
+      ENDIF
+
+#if defined key_lim3      
       ! --- non solar flux over ocean --- !
       !         note: p_frld cannot be = 0 since we limit the ice concentration to amax
@@ -1523,18 +1938,23 @@
       WHERE( p_frld /= 0._wp )  zqns_oce(:,:) = ( zqns_tot(:,:) - SUM( a_i * zqns_ice, dim=3 ) ) / p_frld(:,:)
 
-      ! --- heat flux associated with emp --- !
-      zsnw(:,:) = 0._wp
-      CALL lim_thd_snwblow( p_frld, zsnw )  ! snow distribution over ice after wind blowing
-      zqemp_oce(:,:) = -      zevap(:,:)                   * p_frld(:,:)      *   zcptn(:,:)   &      ! evap
-         &             + ( ztprecip(:,:) - zsprecip(:,:) )                    *   zcptn(:,:)   &      ! liquid precip
-         &             +   zsprecip(:,:)                   * ( 1._wp - zsnw ) * ( zcptn(:,:) - lfus ) ! solid precip over ocean
-      qemp_ice(:,:)  = -   frcv(jpr_ievp)%z3(:,:,1)        * zicefr(:,:)      *   zcptn(:,:)   &      ! ice evap
-         &             +   zsprecip(:,:)                   * zsnw             * ( zcptn(:,:) - lfus ) ! solid precip over ice
-
-      ! --- heat content of precip over ice in J/m3 (to be used in 1D-thermo) --- !
+      ! --- heat flux associated with emp (W/m2) --- !
+      zqemp_oce(:,:) = -  zevap_oce(:,:)                                      *   zcptn(:,:)   &       ! evap
+         &             + ( ztprecip(:,:) - zsprecip(:,:) )                    *   zcptn(:,:)   &       ! liquid precip
+         &             +   zsprecip(:,:)                   * ( 1._wp - zsnw ) * ( zcptn(:,:) - lfus )  ! solid precip over ocean + snow melting
+!      zqemp_ice(:,:) = -   frcv(jpr_ievp)%z3(:,:,1)        * zicefr(:,:)      *   zcptn(:,:)   &      ! ice evap
+!         &             +   zsprecip(:,:)                   * zsnw             * ( zcptn(:,:) - lfus ) ! solid precip over ice
+      zqemp_ice(:,:) =      zsprecip(:,:)                   * zsnw             * ( zcptn(:,:) - lfus ) ! solid precip over ice (only)
+                                                                                                       ! qevap_ice=0 since we consider Tice=0degC
+      
+      ! --- enthalpy of snow precip over ice in J/m3 (to be used in 1D-thermo) --- !
       zqprec_ice(:,:) = rhosn * ( zcptn(:,:) - lfus )
 
-      ! --- total non solar flux --- !
-      zqns_tot(:,:) = zqns_tot(:,:) + qemp_ice(:,:) + zqemp_oce(:,:)
+      ! --- heat content of evap over ice in W/m2 (to be used in 1D-thermo) --- !
+      DO jl = 1, jpl
+         zqevap_ice(:,:,jl) = 0._wp ! should be -evap * ( ( Tice - rt0 ) * cpic ) but we do not have Tice, so we consider Tice=0degC
+      END DO
+
+      ! --- total non solar flux (including evap/precip) --- !
+      zqns_tot(:,:) = zqns_tot(:,:) + zqemp_ice(:,:) + zqemp_oce(:,:)
 
       ! --- in case both coupled/forced are active, we must mix values --- ! 
@@ -1543,25 +1963,34 @@
          qns_oce(:,:) = qns_oce(:,:) * xcplmask(:,:,0) + zqns_oce(:,:)* zmsk(:,:)
          DO jl=1,jpl
-            qns_ice(:,:,jl) = qns_ice(:,:,jl) * xcplmask(:,:,0) +  zqns_ice(:,:,jl)* zmsk(:,:)
+            qns_ice  (:,:,jl) = qns_ice  (:,:,jl) * xcplmask(:,:,0) +  zqns_ice  (:,:,jl)* zmsk(:,:)
+            qevap_ice(:,:,jl) = qevap_ice(:,:,jl) * xcplmask(:,:,0) +  zqevap_ice(:,:,jl)* zmsk(:,:)
          ENDDO
          qprec_ice(:,:) = qprec_ice(:,:) * xcplmask(:,:,0) + zqprec_ice(:,:)* zmsk(:,:)
          qemp_oce (:,:) =  qemp_oce(:,:) * xcplmask(:,:,0) +  zqemp_oce(:,:)* zmsk(:,:)
-!!clem         evap_ice(:,:) = evap_ice(:,:) * xcplmask(:,:,0)
+         qemp_ice (:,:) =  qemp_ice(:,:) * xcplmask(:,:,0) +  zqemp_ice(:,:)* zmsk(:,:)
       ELSE
          qns_tot  (:,:  ) = zqns_tot  (:,:  )
          qns_oce  (:,:  ) = zqns_oce  (:,:  )
          qns_ice  (:,:,:) = zqns_ice  (:,:,:)
-         qprec_ice(:,:)   = zqprec_ice(:,:)
-         qemp_oce (:,:)   = zqemp_oce (:,:)
-      ENDIF
-
-      CALL wrk_dealloc( jpi,jpj, zevap, zsnw, zqns_oce, zqprec_ice, zqemp_oce ) 
+         qevap_ice(:,:,:) = zqevap_ice(:,:,:)
+         qprec_ice(:,:  ) = zqprec_ice(:,:  )
+         qemp_oce (:,:  ) = zqemp_oce (:,:  )
+         qemp_ice (:,:  ) = zqemp_ice (:,:  )
+      ENDIF
+
+      !! clem: we should output qemp_oce and qemp_ice (at least)
+      IF( iom_use('hflx_snow_cea') )   CALL iom_put( 'hflx_snow_cea', sprecip(:,:) * ( zcptn(:,:) - Lfus ) )   ! heat flux from snow (cell average)
+      !! these diags are not outputed yet
+!!      IF( iom_use('hflx_rain_cea') )   CALL iom_put( 'hflx_rain_cea', ( tprecip(:,:) - sprecip(:,:) ) * zcptn(:,:) )   ! heat flux from rain (cell average)
+!!      IF( iom_use('hflx_snow_ao_cea') ) CALL iom_put( 'hflx_snow_ao_cea', sprecip(:,:) * ( zcptn(:,:) - Lfus ) * (1._wp - zsnw(:,:)) ) ! heat flux from snow (cell average)
+!!      IF( iom_use('hflx_snow_ai_cea') ) CALL iom_put( 'hflx_snow_ai_cea', sprecip(:,:) * ( zcptn(:,:) - Lfus ) * zsnw(:,:) ) ! heat flux from snow (cell average)
+
 #else
-
       ! clem: this formulation is certainly wrong... but better than it was...
+      
       zqns_tot(:,:) = zqns_tot(:,:)                       &            ! zqns_tot update over free ocean with:
-         &          - ztmp(:,:)                           &            ! remove the latent heat flux of solid precip. melting
+         &          - (p_frld(:,:) * zsprecip(:,:) * lfus)  &          ! remove the latent heat flux of solid precip. melting
          &          - (  zemp_tot(:,:)                    &            ! remove the heat content of mass flux (assumed to be at SST)
-         &             - zemp_ice(:,:) * zicefr(:,:)  ) * zcptn(:,:) 
+         &             - zemp_ice(:,:) ) * zcptn(:,:) 
 
      IF( ln_mixcpl ) THEN
@@ -1575,5 +2004,4 @@
          qns_ice(:,:,:) = zqns_ice(:,:,:)
       ENDIF
-
 #endif
 
@@ -1626,5 +2054,4 @@
 
 #if defined key_lim3
-      CALL wrk_alloc( jpi,jpj, zqsr_oce ) 
       ! --- solar flux over ocean --- !
       !         note: p_frld cannot be = 0 since we limit the ice concentration to amax
@@ -1634,6 +2061,4 @@
       IF( ln_mixcpl ) THEN   ;   qsr_oce(:,:) = qsr_oce(:,:) * xcplmask(:,:,0) +  zqsr_oce(:,:)* zmsk(:,:)
       ELSE                   ;   qsr_oce(:,:) = zqsr_oce(:,:)   ;   ENDIF
-
-      CALL wrk_dealloc( jpi,jpj, zqsr_oce ) 
 #endif
 
@@ -1686,6 +2111,8 @@
       fr2_i0(:,:) = ( 0.82 * ( 1.0 - cldf_ice ) + 0.65 * cldf_ice )
 
-      CALL wrk_dealloc( jpi,jpj,     zcptn, ztmp, zicefr, zmsk, zemp_tot, zemp_ice, zsprecip, ztprecip, zqns_tot, zqsr_tot )
-      CALL wrk_dealloc( jpi,jpj,jpl, zqns_ice, zqsr_ice, zdqns_ice )
+      CALL wrk_dealloc( jpi,jpj,     zcptn, ztmp, zicefr, zmsk, zsnw )
+      CALL wrk_dealloc( jpi,jpj,     zemp_tot, zemp_ice, zemp_oce, ztprecip, zsprecip, zevap_oce, zevap_ice, zdevap_ice )
+      CALL wrk_dealloc( jpi,jpj,     zqns_tot, zqns_oce, zqsr_tot, zqsr_oce, zqprec_ice, zqemp_oce, zqemp_ice )
+      CALL wrk_dealloc( jpi,jpj,jpl, zqns_ice, zqsr_ice, zdqns_ice, zqevap_ice )
       !
       IF( nn_timing == 1 )  CALL timing_stop('sbc_cpl_ice_flx')
@@ -1706,7 +2133,9 @@
       !
       INTEGER ::   ji, jj, jl   ! dummy loop indices
+      INTEGER ::   ikchoix
       INTEGER ::   isec, info   ! local integer
       REAL(wp) ::   zumax, zvmax
       REAL(wp), POINTER, DIMENSION(:,:)   ::   zfr_l, ztmp1, ztmp2, zotx1, zoty1, zotz1, zitx1, zity1, zitz1
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   zotx1_in, zoty1_in
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmp3, ztmp4   
       !!----------------------------------------------------------------------
@@ -1715,4 +2144,5 @@
       !
       CALL wrk_alloc( jpi,jpj, zfr_l, ztmp1, ztmp2, zotx1, zoty1, zotz1, zitx1, zity1, zitz1 )
+      CALL wrk_alloc( jpi,jpj, zotx1_in, zoty1_in)
       CALL wrk_alloc( jpi,jpj,jpl, ztmp3, ztmp4 )
 
@@ -1743,5 +2173,5 @@
                      ztmp3(:,:,1) = SUM( tn_ice * a_i, dim=3 ) / SUM( a_i, dim=3 )
                   ELSEWHERE
-                     ztmp3(:,:,1) = rt0 ! TODO: Is freezing point a good default? (Maybe SST is better?)
+                     ztmp3(:,:,1) = rt0
                   END WHERE
                CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%clcat' )
@@ -1758,4 +2188,15 @@
                CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%clcat' )
                END SELECT
+            CASE( 'oce and weighted ice' )   ;   ztmp1(:,:) =   tsn(:,:,1,jp_tem) + rt0 
+               SELECT CASE( sn_snd_temp%clcat )
+               CASE( 'yes' )   
+        	  ztmp3(:,:,1:jpl) = tn_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
+               CASE( 'no' )
+        	  ztmp3(:,:,:) = 0.0
+        	  DO jl=1,jpl
+                     ztmp3(:,:,1) = ztmp3(:,:,1) + tn_ice(:,:,jl) * a_i(:,:,jl)
+        	  ENDDO
+               CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%clcat' )
+               END SELECT
             CASE( 'mixed oce-ice'        )   
                ztmp1(:,:) = ( ztmp1(:,:) + rt0 ) * zfr_l(:,:) 
@@ -1774,11 +2215,40 @@
       !                                                      ! ------------------------- !
       IF( ssnd(jps_albice)%laction ) THEN                         ! ice 
-         SELECT CASE( sn_snd_alb%cldes )
-         CASE( 'ice'          )   ; ztmp3(:,:,1:jpl) = alb_ice(:,:,1:jpl)
-         CASE( 'weighted ice' )   ; ztmp3(:,:,1:jpl) = alb_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
-         CASE default             ; CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_alb%cldes' )
+          SELECT CASE( sn_snd_alb%cldes )
+          CASE( 'ice' )
+             SELECT CASE( sn_snd_alb%clcat )
+             CASE( 'yes' )   
+                ztmp3(:,:,1:jpl) = alb_ice(:,:,1:jpl)
+             CASE( 'no' )
+                WHERE( SUM( a_i, dim=3 ) /= 0. )
+                   ztmp1(:,:) = SUM( alb_ice (:,:,1:jpl) * a_i(:,:,1:jpl), dim=3 ) / SUM( a_i(:,:,1:jpl), dim=3 )
+                ELSEWHERE
+                   ztmp1(:,:) = albedo_oce_mix(:,:)
+                END WHERE
+             CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_alb%clcat' )
+             END SELECT
+          CASE( 'weighted ice' )   ;
+             SELECT CASE( sn_snd_alb%clcat )
+             CASE( 'yes' )   
+                ztmp3(:,:,1:jpl) =  alb_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
+             CASE( 'no' )
+                WHERE( fr_i (:,:) > 0. )
+                   ztmp1(:,:) = SUM (  alb_ice(:,:,1:jpl) * a_i(:,:,1:jpl), dim=3 )
+                ELSEWHERE
+                   ztmp1(:,:) = 0.
+                END WHERE
+             CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_ice%clcat' )
+             END SELECT
+          CASE default      ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_alb%cldes' )
          END SELECT
-         CALL cpl_snd( jps_albice, isec, ztmp3, info )
-      ENDIF
+
+         SELECT CASE( sn_snd_alb%clcat )
+            CASE( 'yes' )   
+               CALL cpl_snd( jps_albice, isec, ztmp3, info )      !-> MV this has never been checked in coupled mode
+            CASE( 'no'  )   
+               CALL cpl_snd( jps_albice, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info ) 
+         END SELECT
+      ENDIF
+
       IF( ssnd(jps_albmix)%laction ) THEN                         ! mixed ice-ocean
          ztmp1(:,:) = albedo_oce_mix(:,:) * zfr_l(:,:)
@@ -1799,4 +2269,14 @@
          END SELECT
          IF( ssnd(jps_fice)%laction )   CALL cpl_snd( jps_fice, isec, ztmp3, info )
+      ENDIF
+      
+      ! Send ice fraction field (first order interpolation), for weighting UM fluxes to be passed to NEMO
+      IF (ssnd(jps_fice1)%laction) THEN
+         SELECT CASE (sn_snd_thick1%clcat)
+         CASE( 'yes' )   ;   ztmp3(:,:,1:jpl) =  a_i(:,:,1:jpl)
+         CASE( 'no' )    ;   ztmp3(:,:,1) = fr_i(:,:)
+         CASE default    ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick1%clcat' )
+	 END SELECT
+         CALL cpl_snd (jps_fice1, isec, ztmp3, info)
       ENDIF
       
@@ -1845,4 +2325,50 @@
       ENDIF
       !
+#if defined key_cice && ! defined key_cice4
+      ! Send meltpond fields 
+      IF( ssnd(jps_a_p)%laction .OR. ssnd(jps_ht_p)%laction ) THEN
+         SELECT CASE( sn_snd_mpnd%cldes) 
+         CASE( 'weighted ice' ) 
+            SELECT CASE( sn_snd_mpnd%clcat ) 
+            CASE( 'yes' ) 
+               ztmp3(:,:,1:jpl) =  a_p(:,:,1:jpl) * a_i(:,:,1:jpl) 
+               ztmp4(:,:,1:jpl) =  ht_p(:,:,1:jpl) * a_i(:,:,1:jpl) 
+            CASE( 'no' ) 
+               ztmp3(:,:,:) = 0.0 
+               ztmp4(:,:,:) = 0.0 
+               DO jl=1,jpl 
+                 ztmp3(:,:,1) = ztmp3(:,:,1) + a_p(:,:,jpl) * a_i(:,:,jpl) 
+                 ztmp4(:,:,1) = ztmp4(:,:,1) + ht_p(:,:,jpl) * a_i(:,:,jpl) 
+               ENDDO 
+            CASE default    ;   CALL ctl_stop( 'sbc_cpl_mpd: wrong definition of sn_snd_mpnd%clcat' ) 
+            END SELECT 
+         CASE( 'ice only' )    
+            ztmp3(:,:,1:jpl) = a_p(:,:,1:jpl) 
+            ztmp4(:,:,1:jpl) = ht_p(:,:,1:jpl) 
+         END SELECT 
+         IF( ssnd(jps_a_p)%laction )   CALL cpl_snd( jps_a_p, isec, ztmp3, info )    
+         IF( ssnd(jps_ht_p)%laction )   CALL cpl_snd( jps_ht_p, isec, ztmp4, info )    
+         !
+         ! Send ice effective conductivity
+         SELECT CASE( sn_snd_cond%cldes)
+         CASE( 'weighted ice' )   
+            SELECT CASE( sn_snd_cond%clcat )
+            CASE( 'yes' )   
+               ztmp3(:,:,1:jpl) =  kn_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
+            CASE( 'no' )
+               ztmp3(:,:,:) = 0.0
+               DO jl=1,jpl
+                 ztmp3(:,:,1) = ztmp3(:,:,1) + kn_ice(:,:,jl) * a_i(:,:,jl)
+               ENDDO
+            CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_cond%clcat' )
+            END SELECT
+         CASE( 'ice only' )   
+           ztmp3(:,:,1:jpl) = kn_ice(:,:,1:jpl)
+         END SELECT
+         IF( ssnd(jps_kice)%laction )   CALL cpl_snd( jps_kice, isec, ztmp3, info )
+      ENDIF
+#endif
+      !
+      !
 #if defined key_cpl_carbon_cycle
       !                                                      ! ------------------------- !
@@ -1852,4 +2378,24 @@
       !
 #endif
+
+
+
+      IF (ln_medusa) THEN
+      !                                                      ! ---------------------------------------------- !
+      !                                                      !  CO2 flux, DMS and chlorophyll from MEDUSA     ! 
+      !                                                      ! ---------------------------------------------- !
+         IF ( ssnd(jps_bio_co2)%laction ) THEN
+            CALL cpl_snd( jps_bio_co2, isec, RESHAPE( CO2Flux_out_cpl, (/jpi,jpj,1/) ), info )
+         ENDIF
+
+         IF ( ssnd(jps_bio_dms)%laction )  THEN
+            CALL cpl_snd( jps_bio_dms, isec, RESHAPE( DMS_out_cpl, (/jpi,jpj,1/) ), info )
+         ENDIF
+
+         IF ( ssnd(jps_bio_chloro)%laction )  THEN
+            CALL cpl_snd( jps_bio_chloro, isec, RESHAPE( chloro_out_cpl, (/jpi,jpj,1/) ), info )
+         ENDIF
+      ENDIF
+
       !                                                      ! ------------------------- !
       IF( ssnd(jps_ocx1)%laction ) THEN                      !      Surface current      !
@@ -1858,5 +2404,5 @@
          !                                                  j+1   j     -----V---F
          ! surface velocity always sent from T point                     !       |
-         !                                                        j      |   T   U
+         ! [except for HadGEM3]                                   j      |   T   U
          !                                                               |       |
          !                                                   j    j-1   -I-------|
@@ -1867,13 +2413,23 @@
             zotx1(:,:) = un(:,:,1)  
             zoty1(:,:) = vn(:,:,1)  
-         ELSE        
+         ELSE
             SELECT CASE( TRIM( sn_snd_crt%cldes ) )
             CASE( 'oce only'             )      ! C-grid ==> T
-               DO jj = 2, jpjm1
-                  DO ji = fs_2, fs_jpim1   ! vector opt.
-                     zotx1(ji,jj) = 0.5 * ( un(ji,jj,1) + un(ji-1,jj  ,1) )
-                     zoty1(ji,jj) = 0.5 * ( vn(ji,jj,1) + vn(ji  ,jj-1,1) ) 
+               IF ( TRIM( sn_snd_crt%clvgrd ) == 'T' ) THEN
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1   ! vector opt.
+                        zotx1(ji,jj) = 0.5 * ( un(ji,jj,1) + un(ji-1,jj  ,1) )
+                        zoty1(ji,jj) = 0.5 * ( vn(ji,jj,1) + vn(ji  ,jj-1,1) ) 
+                     END DO
                   END DO
-               END DO
+               ELSE
+! Temporarily Changed for UKV
+                  DO jj = 2, jpjm1
+                     DO ji = 2, jpim1
+                        zotx1(ji,jj) = un(ji,jj,1)
+                        zoty1(ji,jj) = vn(ji,jj,1)
+                     END DO
+                  END DO
+               ENDIF 
             CASE( 'weighted oce and ice' )   
                SELECT CASE ( cp_ice_msh )
@@ -1934,14 +2490,28 @@
                   END DO
                CASE( 'F' )                      ! Ocean on C grid, Ice on F-point (B-grid) ==> T
-                  DO jj = 2, jpjm1
-                     DO ji = 2, jpim1   ! NO vector opt.
-                        zotx1(ji,jj) = 0.5  * ( un(ji,jj,1)      + un(ji-1,jj  ,1) ) * zfr_l(ji,jj)   &   
-                           &         + 0.25 * ( u_ice(ji-1,jj-1) + u_ice(ji,jj-1)                     &
-                           &                  + u_ice(ji-1,jj  ) + u_ice(ji,jj  )  ) *  fr_i(ji,jj)
-                        zoty1(ji,jj) = 0.5  * ( vn(ji,jj,1)      + vn(ji  ,jj-1,1) ) * zfr_l(ji,jj)   & 
-                           &         + 0.25 * ( v_ice(ji-1,jj-1) + v_ice(ji,jj-1)                     &
-                           &                  + v_ice(ji-1,jj  ) + v_ice(ji,jj  )  ) *  fr_i(ji,jj)
+                  IF ( TRIM( sn_snd_crt%clvgrd ) == 'T' ) THEN
+                     DO jj = 2, jpjm1
+                        DO ji = 2, jpim1   ! NO vector opt.
+                           zotx1(ji,jj) = 0.5  * ( un(ji,jj,1)      + un(ji-1,jj,1) ) * zfr_l(ji,jj)   &   
+                                &         + 0.25 * ( u_ice(ji-1,jj-1) + u_ice(ji,jj-1)                     &
+                                &                  + u_ice(ji-1,jj  ) + u_ice(ji,jj  )  ) *  fr_i(ji,jj)
+                           zoty1(ji,jj) = 0.5  * ( vn(ji,jj,1)      + vn(ji,jj-1,1) ) * zfr_l(ji,jj)   &
+                                &         + 0.25 * ( v_ice(ji-1,jj-1) + v_ice(ji,jj-1)                     &
+                                &                  + v_ice(ji-1,jj  ) + v_ice(ji,jj  )  ) *  fr_i(ji,jj)
+                        END DO
                      END DO
-                  END DO
+#if defined key_cice
+                  ELSE
+! Temporarily Changed for HadGEM3
+                     DO jj = 2, jpjm1
+                        DO ji = 2, jpim1   ! NO vector opt.
+                           zotx1(ji,jj) = (1.0-fr_iu(ji,jj)) * un(ji,jj,1)             &
+                                &              + fr_iu(ji,jj) * 0.5 * ( u_ice(ji,jj-1) + u_ice(ji,jj) ) 
+                           zoty1(ji,jj) = (1.0-fr_iv(ji,jj)) * vn(ji,jj,1)             &
+                                &              + fr_iv(ji,jj) * 0.5 * ( v_ice(ji-1,jj) + v_ice(ji,jj) ) 
+                        END DO
+                     END DO
+#endif
+                  ENDIF
                END SELECT
             END SELECT
@@ -1953,14 +2523,42 @@
          IF( TRIM( sn_snd_crt%clvor ) == 'eastward-northward' ) THEN             ! Rotation of the components
             !                                                                     ! Ocean component
-            CALL rot_rep( zotx1, zoty1, ssnd(jps_ocx1)%clgrid, 'ij->e', ztmp1 )       ! 1st component 
-            CALL rot_rep( zotx1, zoty1, ssnd(jps_ocx1)%clgrid, 'ij->n', ztmp2 )       ! 2nd component 
-            zotx1(:,:) = ztmp1(:,:)                                                   ! overwrite the components 
-            zoty1(:,:) = ztmp2(:,:)
-            IF( ssnd(jps_ivx1)%laction ) THEN                                     ! Ice component
-               CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->e', ztmp1 )    ! 1st component 
-               CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->n', ztmp2 )    ! 2nd component 
-               zitx1(:,:) = ztmp1(:,:)                                                ! overwrite the components 
-               zity1(:,:) = ztmp2(:,:)
-            ENDIF
+            IF ( TRIM( sn_snd_crt%clvgrd ) == 'T' ) THEN
+               CALL rot_rep( zotx1, zoty1, ssnd(jps_ocx1)%clgrid, 'ij->e', ztmp1 )       ! 1st component
+               CALL rot_rep( zotx1, zoty1, ssnd(jps_ocx1)%clgrid, 'ij->n', ztmp2 )       ! 2nd component
+               zotx1(:,:) = ztmp1(:,:)                                                   ! overwrite the components
+               zoty1(:,:) = ztmp2(:,:)
+               IF( ssnd(jps_ivx1)%laction ) THEN                                  ! Ice component
+                  CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->e', ztmp1 )    ! 1st component
+                  CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->n', ztmp2 )    ! 2nd component
+                  zitx1(:,:) = ztmp1(:,:)                                                ! overwrite the components
+                  zity1(:,:) = ztmp2(:,:)
+               ENDIF
+            ELSE
+               ! Temporary code for HadGEM3 - will be removed eventually.
+               ! Only applies when we want uvel on U grid and vvel on V grid
+               ! Rotate U and V onto geographic grid before sending.
+
+               DO jj=2,jpjm1
+                  DO ji=2,jpim1
+                     ztmp1(ji,jj)=0.25*vmask(ji,jj,1)                  &
+                          *(zotx1(ji,jj)+zotx1(ji-1,jj)    &
+                          +zotx1(ji,jj+1)+zotx1(ji-1,jj+1))
+                     ztmp2(ji,jj)=0.25*umask(ji,jj,1)                  &
+                          *(zoty1(ji,jj)+zoty1(ji+1,jj)    &
+                          +zoty1(ji,jj-1)+zoty1(ji+1,jj-1))
+                  ENDDO
+               ENDDO
+
+               ! Ensure any N fold and wrap columns are updated
+               CALL lbc_lnk(ztmp1, 'V', -1.0)
+               CALL lbc_lnk(ztmp2, 'U', -1.0)
+                            
+               ikchoix = -1
+               ! We need copies of zotx1 and zoty2 in order to avoid problems 
+               ! caused by INTENTs used in the following subroutine. 
+               zotx1_in(:,:) = zotx1(:,:)
+               zoty1_in(:,:) = zoty1(:,:)
+               CALL repcmo (zotx1_in,ztmp2,ztmp1,zoty1_in,zotx1,zoty1,ikchoix)
+           ENDIF
          ENDIF
          !
@@ -2023,6 +2621,12 @@
       IF( ssnd(jps_rnf   )%laction )  CALL cpl_snd( jps_rnf   , isec, RESHAPE ( rnf , (/jpi,jpj,1/) ), info )
       IF( ssnd(jps_taum  )%laction )  CALL cpl_snd( jps_taum  , isec, RESHAPE ( taum, (/jpi,jpj,1/) ), info )
-
+      
+#if defined key_cice
+      ztmp1(:,:) = sstfrz(:,:) + rt0
+      IF( ssnd(jps_sstfrz)%laction )  CALL cpl_snd( jps_sstfrz, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
+#endif
+      !
       CALL wrk_dealloc( jpi,jpj, zfr_l, ztmp1, ztmp2, zotx1, zoty1, zotz1, zitx1, zity1, zitz1 )
+      CALL wrk_dealloc( jpi,jpj, zotx1_in, zoty1_in )
       CALL wrk_dealloc( jpi,jpj,jpl, ztmp3, ztmp4 )
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcfwb.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcfwb.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcfwb.F90	(revision 9987)
@@ -108,5 +108,5 @@
          !
          IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN
-            z_fwf = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + rdivisf * fwfisf(:,:) -  snwice_fmass(:,:) ) ) / area   ! sum over the global domain
+            z_fwf = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + fwfisf(:,:) - snwice_fmass(:,:) ) ) / area   ! sum over the global domain
             zcoef = z_fwf * rcp
             emp(:,:) = emp(:,:) - z_fwf              * tmask(:,:,1)
@@ -162,5 +162,5 @@
             zsurf_pos = glob_sum( e1e2t(:,:)*ztmsk_pos(:,:) )
             !                                                  ! fwf global mean (excluding ocean to ice/snow exchanges) 
-            z_fwf     = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + rdivisf * fwfisf(:,:) - snwice_fmass(:,:) ) ) / area
+            z_fwf     = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + fwfisf(:,:) - snwice_fmass(:,:) ) ) / area
             !            
             IF( z_fwf < 0._wp ) THEN         ! spread out over >0 erp area to increase evaporation
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_cice.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_cice.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_cice.F90	(revision 9987)
@@ -15,5 +15,6 @@
    USE dom_oce         ! ocean space and time domain
    USE domvvl
-   USE phycst, only : rcp, rau0, r1_rau0, rhosn, rhoic
+   USE eosbn2, only : eos_fzp ! Function to calculate freezing point of seawater
+   USE phycst, only : rcp, rau0, r1_rau0, rhosn, rhoic, rt0
    USE in_out_manager  ! I/O manager
    USE iom, ONLY : iom_put,iom_use              ! I/O manager library !!Joakim edit
@@ -37,6 +38,6 @@
    USE ice_gather_scatter
    USE ice_calendar, only: dt
+# if defined key_cice4
    USE ice_state, only: aice,aicen,uvel,vvel,vsno,vsnon,vice,vicen
-# if defined key_cice4
    USE ice_flux, only: strax,stray,strocnx,strocny,frain,fsnow,  &
                 strocnxT,strocnyT,                               & 
@@ -45,15 +46,27 @@
                 flatn_f,fsurfn_f,fcondtopn_f,                    &
                 uatm,vatm,wind,fsw,flw,Tair,potT,Qa,rhoa,zlvl,   &
-                swvdr,swvdf,swidr,swidf
+                swvdr,swvdf,swidr,swidf,Tf
    USE ice_therm_vertical, only: calc_Tsfc
 #else
+   USE ice_state, only: aice,aicen,uvel,nt_hpnd,trcrn,vvel,vsno,&
+                vsnon,vice,vicen,nt_Tsfc
    USE ice_flux, only: strax,stray,strocnx,strocny,frain,fsnow,  &
                 strocnxT,strocnyT,                               & 
-                sst,sss,uocn,vocn,ss_tltx,ss_tlty,fsalt_ai,     &
-                fresh_ai,fhocn_ai,fswthru_ai,frzmlt,          &
+                sst,sss,uocn,vocn,ss_tltx,ss_tlty,fsalt_ai,      &
+                fresh_ai,fhocn_ai,fswthru_ai,frzmlt,             &
                 flatn_f,fsurfn_f,fcondtopn_f,                    &
+#ifdef key_asminc
+                daice_da,fresh_da,fsalt_da,                    &
+#endif
                 uatm,vatm,wind,fsw,flw,Tair,potT,Qa,rhoa,zlvl,   &
-                swvdr,swvdf,swidr,swidf
-   USE ice_therm_shared, only: calc_Tsfc
+                swvdr,swvdf,swidr,swidf,Tf,                      &
+		!! When using NEMO with CICE, this change requires use of 
+		!! one of the following two CICE branches:
+		!! - at CICE5.0,   hadax/r1015_GSI8_with_GSI7
+		!! - at CICE5.1.2, hadax/vn5.1.2_GSI8
+                keffn_top,Tn_top
+
+   USE ice_therm_shared, only: calc_Tsfc, heat_capacity
+   USE ice_shortwave, only: apeffn
 #endif
    USE ice_forcing, only: frcvdr,frcvdf,frcidr,frcidf
@@ -161,5 +174,5 @@
       INTEGER, INTENT( in  ) ::   ksbc                ! surface forcing type
       REAL(wp), DIMENSION(:,:), POINTER :: ztmp1, ztmp2
-      REAL(wp) ::   zcoefu, zcoefv, zcoeff            ! local scalar
+      REAL(wp), DIMENSION(:,:,:), POINTER :: ztfrz3d
       INTEGER  ::   ji, jj, jl, jk                    ! dummy loop indices
       !!---------------------------------------------------------------------
@@ -174,17 +187,8 @@
       jj_off = INT ( (jpjglo - ny_global) / 2 )
 
-#if defined key_nemocice_decomp
-      ! Pass initial SST from NEMO to CICE so ice is initialised correctly if
-      ! there is no restart file.
-      ! Values from a CICE restart file would overwrite this
-      IF ( .NOT. ln_rstart ) THEN    
-         CALL nemo2cice( tsn(:,:,1,jp_tem) , sst , 'T' , 1.) 
-      ENDIF  
-#endif
-
-! Initialize CICE
+      ! Initialize CICE
       CALL CICE_Initialize
 
-! Do some CICE consistency checks
+      ! Do some CICE consistency checks
       IF ( (ksbc == jp_flx) .OR. (ksbc == jp_purecpl) ) THEN
          IF ( calc_strair .OR. calc_Tsfc ) THEN
@@ -198,16 +202,31 @@
 
 
-! allocate sbc_ice and sbc_cice arrays
-      IF( sbc_ice_alloc()      /= 0 )   CALL ctl_stop( 'STOP', 'sbc_ice_cice_alloc : unable to allocate arrays' )
+      ! allocate sbc_ice and sbc_cice arrays
+      IF( sbc_ice_alloc()      /= 0 )   CALL ctl_stop( 'STOP', 'sbc_ice_alloc : unable to allocate arrays' )
       IF( sbc_ice_cice_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_ice_cice_alloc : unable to allocate cice arrays' )
 
-! Ensure ocean temperatures are nowhere below freezing if not a NEMO restart
+      ! Ensure that no temperature points are below freezing if not a NEMO restart
       IF( .NOT. ln_rstart ) THEN
-         tsn(:,:,:,jp_tem) = MAX (tsn(:,:,:,jp_tem),Tocnfrz)
+
+         CALL wrk_alloc( jpi,jpj,jpk, ztfrz3d ) 
+         DO jk=1,jpk
+             CALL eos_fzp( tsn(:,:,jk,jp_sal), ztfrz3d(:,:,jk), fsdept_n(:,:,jk) )
+         ENDDO
+         tsn(:,:,:,jp_tem) = MAX( tsn(:,:,:,jp_tem), ztfrz3d )
          tsb(:,:,:,jp_tem) = tsn(:,:,:,jp_tem)
-      ENDIF
-
-      fr_iu(:,:)=0.0
-      fr_iv(:,:)=0.0
+         CALL wrk_dealloc( jpi,jpj,jpk, ztfrz3d ) 
+
+#if defined key_nemocice_decomp
+         ! Pass initial SST from NEMO to CICE so ice is initialised correctly if
+         ! there is no restart file.
+         ! Values from a CICE restart file would overwrite this
+         CALL nemo2cice( tsn(:,:,1,jp_tem) , sst , 'T' , 1.) 
+#endif
+
+      ENDIF  
+
+      ! calculate surface freezing temperature and send to CICE
+      CALL  eos_fzp(sss_m(:,:), sstfrz(:,:), fsdept_n(:,:,1)) 
+      CALL nemo2cice(sstfrz,Tf, 'T', 1. )
 
       CALL cice2nemo(aice,fr_i, 'T', 1. )
@@ -220,4 +239,6 @@
 ! T point to U point
 ! T point to V point
+      fr_iu(:,:)=0.0
+      fr_iv(:,:)=0.0
       DO jj=1,jpjm1
          DO ji=1,jpim1
@@ -283,5 +304,17 @@
  
       CALL wrk_dealloc( jpi,jpj, ztmp1, ztmp2 )
-      !
+
+#if defined key_asminc
+	   ! Initialize fresh water and salt fluxes from data assim   
+	   !  and data assimilation index to cice 
+	   nfresh_da(:,:) = 0.0   
+	   nfsalt_da(:,:) = 0.0   
+	   ndaice_da(:,:) = 0.0         
+#endif
+      !
+      ! In coupled mode get extra fields from CICE for passing back to atmosphere
+ 
+      IF ( ksbc == jp_purecpl ) CALL cice_sbc_hadgam(nit000)
+      ! 
       IF( nn_timing == 1 )  CALL timing_stop('cice_sbc_init')
       !
@@ -343,4 +376,16 @@
          CALL nemo2cice(ztmp,stray,'F', -1. )
 
+
+! Alex West: From configuration GSI8 onwards, when NEMO is used with CICE in
+! HadGEM3 the 'time-travelling ice' coupling approach is used, whereby 
+! atmosphere-ice fluxes are passed as pseudo-local values, formed by dividing
+! gridbox mean fluxes in the UM by future ice concentration obtained through 	
+! OASIS.  This allows for a much more realistic apportionment of energy through
+! the ice - and conserves energy.
+! Therefore the fluxes are now divided by ice concentration in the coupled
+! formulation (jp_purecpl) as well as for jp_flx.  This NEMO branch should only
+! be used at UM10.2 onwards (unless an explicit GSI8 UM branch is included), at
+! which point the GSI8 UM changes were committed.
+
 ! Surface downward latent heat flux (CI_5)
          IF (ksbc == jp_flx) THEN
@@ -348,24 +393,13 @@
                ztmpn(:,:,jl)=qla_ice(:,:,1)*a_i(:,:,jl)
             ENDDO
-         ELSE
-! emp_ice is set in sbc_cpl_ice_flx as sublimation-snow
-            qla_ice(:,:,1)= - ( emp_ice(:,:)+sprecip(:,:) ) * Lsub
-! End of temporary code
-            DO jj=1,jpj
-               DO ji=1,jpi
-                  IF (fr_i(ji,jj).eq.0.0) THEN
-                     DO jl=1,ncat
-                        ztmpn(ji,jj,jl)=0.0
-                     ENDDO
-                     ! This will then be conserved in CICE
-                     ztmpn(ji,jj,1)=qla_ice(ji,jj,1)
-                  ELSE
-                     DO jl=1,ncat
-                        ztmpn(ji,jj,jl)=qla_ice(ji,jj,1)*a_i(ji,jj,jl)/fr_i(ji,jj)
-                     ENDDO
-                  ENDIF
-               ENDDO
+         ELSE IF (ksbc == jp_purecpl) THEN
+            DO jl=1,ncat
+               ztmpn(:,:,jl)=qla_ice(:,:,jl)*a_i(:,:,jl)
             ENDDO
+	 ELSE
+           !In coupled mode - qla_ice calculated in sbc_cpl for each category
+           ztmpn(:,:,1:ncat)=qla_ice(:,:,1:ncat)
          ENDIF
+
          DO jl=1,ncat
             CALL nemo2cice(ztmpn(:,:,jl),flatn_f(:,:,jl,:),'T', 1. )
@@ -373,5 +407,5 @@
 ! GBM conductive flux through ice (CI_6)
 !  Convert to GBM
-            IF (ksbc == jp_flx) THEN
+            IF (ksbc == jp_flx .OR. ksbc == jp_purecpl) THEN
                ztmp(:,:) = botmelt(:,:,jl)*a_i(:,:,jl)
             ELSE
@@ -382,5 +416,5 @@
 ! GBM surface heat flux (CI_7)
 !  Convert to GBM
-            IF (ksbc == jp_flx) THEN
+            IF (ksbc == jp_flx .OR. ksbc == jp_purecpl) THEN
                ztmp(:,:) = (topmelt(:,:,jl)+botmelt(:,:,jl))*a_i(:,:,jl) 
             ELSE
@@ -431,8 +465,17 @@
       ENDIF
 
+#if defined key_asminc
+!Ice concentration change (from assimilation)
+      ztmp(:,:)=ndaice_da(:,:)*tmask(:,:,1)
+      Call nemo2cice(ztmp,daice_da,'T', 1. )
+#endif 
+
 ! Snowfall
 ! Ensure fsnow is positive (as in CICE routine prepare_forcing)
       IF( iom_use('snowpre') )   CALL iom_put('snowpre',MAX( (1.0-fr_i(:,:))*sprecip(:,:) ,0.0)) !!Joakim edit  
-      ztmp(:,:)=MAX(fr_i(:,:)*sprecip(:,:),0.0)  
+      IF( kt == nit000 .AND. lwp )  THEN
+         WRITE(numout,*) 'sprecip weight, rn_sfac=', rn_sfac
+      ENDIF
+      ztmp(:,:)=MAX(fr_i(:,:)*rn_sfac*sprecip(:,:),0.0)  
       CALL nemo2cice(ztmp,fsnow,'T', 1. ) 
 
@@ -442,10 +485,12 @@
       CALL nemo2cice(ztmp,frain,'T', 1. ) 
 
+! Recalculate freezing temperature and send to CICE 
+      CALL eos_fzp(sss_m(:,:), sstfrz(:,:), fsdept_n(:,:,1)) 
+      CALL nemo2cice(sstfrz,Tf,'T', 1. )
+
 ! Freezing/melting potential
 ! Calculated over NEMO leapfrog timestep (hence 2*dt)
-      nfrzmlt(:,:)=rau0*rcp*fse3t_m(:,:)*(Tocnfrz-sst_m(:,:))/(2.0*dt)
-
-      ztmp(:,:) = nfrzmlt(:,:)
-      CALL nemo2cice(ztmp,frzmlt,'T', 1. )
+      nfrzmlt(:,:)=rau0*rcp*fse3t_m(:,:)*(sstfrz(:,:)-sst_m(:,:))/(2.0*dt) 
+      CALL nemo2cice(nfrzmlt,frzmlt,'T', 1. )
 
 ! SST  and SSS
@@ -453,4 +498,11 @@
       CALL nemo2cice(sst_m,sst,'T', 1. )
       CALL nemo2cice(sss_m,sss,'T', 1. )
+
+      IF( ksbc == jp_purecpl ) THEN
+! Sea ice surface skin temperature
+         DO jl=1,ncat
+           CALL nemo2cice(tsfc_ice(:,:,jl), trcrn(:,:,nt_tsfc,jl,:),'T',1.)
+         ENDDO 
+      ENDIF
 
 ! x comp and y comp of surface ocean current
@@ -685,4 +737,10 @@
       ENDIF
 
+#if defined key_asminc
+! Import fresh water and salt flux due to seaice da
+      CALL cice2nemo(fresh_da, nfresh_da,'T',1.0)
+      CALL cice2nemo(fsalt_da, nfsalt_da,'T',1.0)
+#endif
+
 ! Release work space
 
@@ -708,9 +766,4 @@
       IF( nn_timing == 1 )  CALL timing_start('cice_sbc_hadgam')
       !
-      IF( kt == nit000 )  THEN
-         IF(lwp) WRITE(numout,*)'cice_sbc_hadgam'
-         IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )
-      ENDIF
-
       !                                         ! =========================== !
       !                                         !   Prepare Coupling fields   !
@@ -730,4 +783,32 @@
          CALL cice2nemo(vicen(:,:,jl,:),ht_i(:,:,jl),'T', 1. )
       ENDDO
+
+#if ! defined key_cice4
+! Meltpond fraction and depth
+      DO jl = 1,ncat
+         CALL cice2nemo(apeffn(:,:,jl,:),a_p(:,:,jl),'T', 1. )
+         CALL cice2nemo(trcrn(:,:,nt_hpnd,jl,:),ht_p(:,:,jl),'T', 1. )
+      ENDDO
+#endif
+
+
+! If using multilayers thermodynamics in CICE then get top layer temperature
+! and effective conductivity       
+!! When using NEMO with CICE, this change requires use of 
+!! one of the following two CICE branches:
+!! - at CICE5.0,   hadax/r1015_GSI8_with_GSI7
+!! - at CICE5.1.2, hadax/vn5.1.2_GSI8
+      IF (heat_capacity) THEN
+         DO jl = 1,ncat
+            CALL cice2nemo(Tn_top(:,:,jl,:),tn_ice(:,:,jl),'T', 1. )
+            CALL cice2nemo(keffn_top(:,:,jl,:),kn_ice(:,:,jl),'T', 1. )
+         ENDDO
+! Convert surface temperature to Kelvin
+         tn_ice(:,:,:)=tn_ice(:,:,:)+rt0
+      ELSE
+         tn_ice(:,:,:) = 0.0
+         kn_ice(:,:,:) = 0.0
+      ENDIF       
+
       !
       IF( nn_timing == 1 )  CALL timing_stop('cice_sbc_hadgam')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_if.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_if.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_if.F90	(revision 9987)
@@ -103,5 +103,6 @@
                                  ! ( d rho / dt ) / ( d rho / ds )      ( s = 34, t = -1.8 )
          
-         fr_i(:,:) = eos_fzp( sss_m ) * tmask(:,:,1)      ! sea surface freezing temperature [Celcius]
+         CALL eos_fzp( sss_m(:,:), fr_i(:,:) )       ! sea surface freezing temperature [Celcius]
+         fr_i(:,:) = fr_i(:,:) * tmask(:,:,1)
 
          IF( ln_cpl )   a_i(:,:,1) = fr_i(:,:)         
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim.F90	(revision 9987)
@@ -110,5 +110,4 @@
       INTEGER  ::   jl                 ! dummy loop index
       REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalb_os, zalb_cs  ! ice albedo under overcast/clear sky
-      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalb_ice          ! mean ice albedo (for coupled)
       REAL(wp), POINTER, DIMENSION(:,:  )   ::   zutau_ice, zvtau_ice 
       !!----------------------------------------------------------------------
@@ -126,6 +125,7 @@
          
          ! masked sea surface freezing temperature [Kelvin] (set to rt0 over land)
-         t_bo(:,:) = ( eos_fzp( sss_m ) + rt0 ) * tmask(:,:,1) + rt0 * ( 1._wp - tmask(:,:,1) )  
-         
+         CALL eos_fzp( sss_m(:,:) , t_bo(:,:) )
+         t_bo(:,:) = ( t_bo(:,:) + rt0 ) * tmask(:,:,1) + rt0 * ( 1._wp - tmask(:,:,1) )
+          
          ! Mask sea ice surface temperature (set to rt0 over land)
          DO jl = 1, jpl
@@ -196,5 +196,5 @@
          ! fr1_i0  , fr2_i0   : 1sr & 2nd fraction of qsr penetration in ice             [%]
          !----------------------------------------------------------------------------------------
-         CALL wrk_alloc( jpi,jpj,jpl, zalb_os, zalb_cs, zalb_ice )
+         CALL wrk_alloc( jpi,jpj,jpl, zalb_os, zalb_cs )
          CALL albedo_ice( t_su, ht_i, ht_s, zalb_cs, zalb_os ) ! cloud-sky and overcast-sky ice albedos
 
@@ -202,24 +202,21 @@
          CASE( jp_clio )                                       ! CLIO bulk formulation
             ! In CLIO the cloud fraction is read in the climatology and the all-sky albedo 
-            ! (zalb_ice) is computed within the bulk routine
-            CALL blk_ice_clio_flx( t_su, zalb_cs, zalb_os, zalb_ice )
-            IF( ln_mixcpl      ) CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=zalb_ice, psst=sst_m, pist=t_su )
-            IF( nn_limflx /= 2 ) CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_limflx )
+            ! (alb_ice) is computed within the bulk routine
+                                 CALL blk_ice_clio_flx( t_su, zalb_cs, zalb_os, alb_ice )
+            IF( ln_mixcpl      ) CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=alb_ice, psst=sst_m, pist=t_su )
+            IF( nn_limflx /= 2 ) CALL ice_lim_flx( t_su, alb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_limflx )
          CASE( jp_core )                                       ! CORE bulk formulation
             ! albedo depends on cloud fraction because of non-linear spectral effects
-            zalb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
-            CALL blk_ice_core_flx( t_su, zalb_ice )
-            IF( ln_mixcpl      ) CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=zalb_ice, psst=sst_m, pist=t_su )
-            IF( nn_limflx /= 2 ) CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_limflx )
+            alb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
+                                 CALL blk_ice_core_flx( t_su, alb_ice )
+            IF( ln_mixcpl      ) CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=alb_ice, psst=sst_m, pist=t_su )
+            IF( nn_limflx /= 2 ) CALL ice_lim_flx( t_su, alb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_limflx )
          CASE ( jp_purecpl )
             ! albedo depends on cloud fraction because of non-linear spectral effects
-            zalb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
-                                 CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=zalb_ice, psst=sst_m, pist=t_su )
-            ! clem: evap_ice is forced to 0 in coupled mode for now 
-            !       but it needs to be changed (along with modif in limthd_dh) once heat flux from evap will be avail. from atm. models
-            evap_ice  (:,:,:) = 0._wp   ;   devap_ice (:,:,:) = 0._wp
-            IF( nn_limflx == 2 ) CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_limflx )
+            alb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
+                                 CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=alb_ice, psst=sst_m, pist=t_su )
+            IF( nn_limflx == 2 ) CALL ice_lim_flx( t_su, alb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_limflx )
          END SELECT
-         CALL wrk_dealloc( jpi,jpj,jpl, zalb_os, zalb_cs, zalb_ice )
+         CALL wrk_dealloc( jpi,jpj,jpl, zalb_os, zalb_cs )
 
          !----------------------------!
@@ -264,4 +261,5 @@
       !!----------------------------------------------------------------------
       INTEGER :: ierr
+      INTEGER :: ji, jj
       !!----------------------------------------------------------------------
       IF(lwp) WRITE(numout,*)
@@ -320,4 +318,12 @@
       tn_ice(:,:,:) = t_su(:,:,:)       ! initialisation of surface temp for coupled simu
       !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( gphit(ji,jj) > 0._wp ) THEN  ;  rn_amax_2d(ji,jj) = rn_amax_n  ! NH
+            ELSE                             ;  rn_amax_2d(ji,jj) = rn_amax_s  ! SH
+            ENDIF
+        ENDDO
+      ENDDO 
+      !
       nstart = numit  + nn_fsbc      
       nitrun = nitend - nit000 + 1 
@@ -342,5 +348,5 @@
       INTEGER  ::   ios                 ! Local integer output status for namelist read
       NAMELIST/namicerun/ jpl, nlay_i, nlay_s, cn_icerst_in, cn_icerst_indir, cn_icerst_out, cn_icerst_outdir,  &
-         &                ln_limdyn, rn_amax, ln_limdiahsb, ln_limdiaout, ln_icectl, iiceprt, jiceprt  
+         &                ln_limdyn, rn_amax_n, rn_amax_s, ln_limdiahsb, ln_limdiaout, ln_icectl, iiceprt, jiceprt  
       !!-------------------------------------------------------------------
       !                    
@@ -363,5 +369,6 @@
          WRITE(numout,*) '   number of snow layers                                   = ', nlay_s
          WRITE(numout,*) '   switch for ice dynamics (1) or not (0)      ln_limdyn   = ', ln_limdyn
-         WRITE(numout,*) '   maximum ice concentration                               = ', rn_amax 
+         WRITE(numout,*) '   maximum ice concentration for NH                        = ', rn_amax_n 
+         WRITE(numout,*) '   maximum ice concentration for SH                        = ', rn_amax_s
          WRITE(numout,*) '   Diagnose heat/salt budget or not          ln_limdiahsb  = ', ln_limdiahsb
          WRITE(numout,*) '   Output   heat/salt budget or not          ln_limdiaout  = ', ln_limdiaout
@@ -578,5 +585,5 @@
       sfx_bog(:,:) = 0._wp   ;   sfx_dyn(:,:) = 0._wp
       sfx_bom(:,:) = 0._wp   ;   sfx_sum(:,:) = 0._wp
-      sfx_res(:,:) = 0._wp
+      sfx_res(:,:) = 0._wp   ;   sfx_sub(:,:) = 0._wp
       
       wfx_snw(:,:) = 0._wp   ;   wfx_ice(:,:) = 0._wp
@@ -594,6 +601,7 @@
       hfx_spr(:,:) = 0._wp   ;   hfx_dif(:,:) = 0._wp 
       hfx_err(:,:) = 0._wp   ;   hfx_err_rem(:,:) = 0._wp
-      hfx_err_dif(:,:) = 0._wp   ;
-
+      hfx_err_dif(:,:) = 0._wp
+      wfx_err_sub(:,:) = 0._wp
+      
       afx_tot(:,:) = 0._wp   ;
       afx_dyn(:,:) = 0._wp   ;   afx_thd(:,:) = 0._wp
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim_2.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim_2.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim_2.F90	(revision 9987)
@@ -150,5 +150,6 @@
 
          ! ... masked sea surface freezing temperature [Kelvin] (set to rt0 over land)
-         tfu(:,:) = eos_fzp( sss_m ) +  rt0 
+         CALL eos_fzp( sss_m(:,:), tfu(:,:) )
+         tfu(:,:) = tfu(:,:) + rt0
 
          zsist (:,:,1) = sist (:,:) + rt0 * ( 1. - tmask(:,:,1) )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcisf.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcisf.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcisf.F90	(revision 9987)
@@ -26,6 +26,5 @@
    USE zdfbfr
    USE fldread         ! read input field at current time step
-
-
+   USE lib_fortran, ONLY: glob_sum
 
    IMPLICIT NONE
@@ -53,11 +52,5 @@
    REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  risfLeff               !:effective length (Leff) BG03 nn_isf==2
    REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  ttbl, stbl, utbl, vtbl !:top boundary layer variable at T point
-#if defined key_agrif
-   ! AGRIF can not handle these arrays as integers. The reason is a mystery but problems avoided by declaring them as reals
-   REAL(wp),    PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  misfkt, misfkb         !:Level of ice shelf base
-                                                                                          !: (first wet level and last level include in the tbl)
-#else
    INTEGER,    PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  misfkt, misfkb         !:Level of ice shelf base
-#endif
 
 
@@ -90,10 +83,15 @@
     INTEGER                      ::   ji, jj, jk, ijkmin, inum, ierror
     INTEGER                      ::   ikt, ikb   ! top and bottom level of the isf boundary layer
+    REAL(wp)                     ::   zgreenland_fwfisf_sum, zantarctica_fwfisf_sum
     REAL(wp)                     ::   rmin
     REAL(wp)                     ::   zhk
-    CHARACTER(len=256)           ::   cfisf, cvarzisf, cvarhisf   ! name for isf file
+    REAL(wp)                     ::   zt_frz, zpress
+    CHARACTER(len=256)           ::   cfisf , cvarzisf, cvarhisf   ! name for isf file
     CHARACTER(LEN=256)           :: cnameis                     ! name of iceshelf file
     CHARACTER (LEN=32)           :: cvarLeff                    ! variable name for efficient Length scale
     INTEGER           ::   ios           ! Local integer output status for namelist read
+
+    REAL(wp), DIMENSION(:,:,:), POINTER :: zfwfisf3d, zqhcisf3d, zqlatisf3d
+    REAL(wp), DIMENSION(:,:  ), POINTER :: zqhcisf2d
       !
       !!---------------------------------------------------------------------
@@ -176,5 +174,5 @@
               DO jj = 1, jpj
                   jk = 2
-                  DO WHILE ( jk .LE. mbkt(ji,jj) .AND. fsdepw(ji,jj,jk) < rzisf_tbl(ji,jj) ) ;  jk = jk + 1 ;  END DO
+                  DO WHILE ( jk .LE. mbkt(ji,jj) .AND. gdepw_0(ji,jj,jk) < rzisf_tbl(ji,jj) ) ;  jk = jk + 1 ;  END DO
                   misfkt(ji,jj) = jk-1
                END DO
@@ -194,5 +192,18 @@
          END IF
          
+         ! save initial top boundary layer thickness         
          rhisf_tbl_0(:,:) = rhisf_tbl(:,:)
+
+      END IF
+
+      !                                            ! ---------------------------------------- !
+      IF( kt /= nit000 ) THEN                      !          Swap of forcing fields          !
+         !                                         ! ---------------------------------------- !
+         fwfisf_b  (:,:  ) = fwfisf  (:,:  )               ! Swap the ocean forcing fields except at nit000
+         risf_tsc_b(:,:,:) = risf_tsc(:,:,:)               ! where before fields are set at the end of the routine
+         !
+      ENDIF
+
+      IF( MOD( kt-1, nn_fsbc) == 0 ) THEN
 
          ! compute bottom level of isf tbl and thickness of tbl below the ice shelf
@@ -205,5 +216,4 @@
 
                ! determine the deepest level influenced by the boundary layer
-               ! test on tmask useless ?????
                DO jk = ikt, mbkt(ji,jj)
                   IF ( (SUM(fse3t_n(ji,jj,ikt:jk-1)) .LT. rhisf_tbl(ji,jj)) .AND. (tmask(ji,jj,jk) == 1) ) ikb = jk
@@ -217,17 +227,4 @@
             END DO
          END DO
-         
-      END IF
-
-      !                                            ! ---------------------------------------- !
-      IF( kt /= nit000 ) THEN                      !          Swap of forcing fields          !
-         !                                         ! ---------------------------------------- !
-         fwfisf_b  (:,:  ) = fwfisf  (:,:  )               ! Swap the ocean forcing fields except at nit000
-         risf_tsc_b(:,:,:) = risf_tsc(:,:,:)               ! where before fields are set at the end of the routine
-         !
-      ENDIF
-
-      IF( MOD( kt-1, nn_fsbc) == 0 ) THEN
-
 
          ! compute salf and heat flux
@@ -256,4 +253,45 @@
             CALL fld_read ( kt, nn_fsbc, sf_rnfisf   )
             fwfisf(:,:) = - sf_rnfisf(1)%fnow(:,:,1)         ! fresh water flux from the isf (fwfisf <0 mean melting) 
+
+            IF( lk_oasis) THEN
+            ! nn_coupled_iceshelf_fluxes uninitialised unless lk_oasis=true
+            IF( nn_coupled_iceshelf_fluxes .gt. 0 ) THEN
+
+              ! Adjust total iceshelf melt rates so that sum of iceberg calving and iceshelf melting in the northern
+              ! and southern hemispheres equals rate of increase of mass of greenland and antarctic ice sheets
+              ! to preserve total freshwater conservation in coupled models without an active ice sheet model.
+ 
+              ! All related global sums must be done bit reproducibly
+               zgreenland_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * greenland_icesheet_mask(:,:) )
+
+               ! use ABS function because we need to preserve the sign of fwfisf
+               WHERE( greenland_icesheet_mask(:,:) == 1.0 )                                                                  &
+              &    fwfisf(:,:) = fwfisf(:,:)  * ABS( greenland_icesheet_mass_rate_of_change * (1.0-rn_greenland_calving_fraction) &
+              &                           / ( zgreenland_fwfisf_sum + 1.0e-10_wp ) )
+
+               ! check
+               IF(lwp) WRITE(numout, *) 'Greenland iceshelf melting climatology (kg/s) : ',zgreenland_fwfisf_sum
+
+               zgreenland_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * greenland_icesheet_mask(:,:) )
+
+               IF(lwp) WRITE(numout, *) 'Greenland iceshelf melting adjusted value (kg/s) : ',zgreenland_fwfisf_sum
+
+               zantarctica_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * antarctica_icesheet_mask(:,:) )
+
+               ! use ABS function because we need to preserve the sign of fwfisf
+               WHERE( antarctica_icesheet_mask(:,:) == 1.0 ) &
+              &    fwfisf(:,:) = fwfisf(:,:)  * ABS( antarctica_icesheet_mass_rate_of_change * (1.0-rn_antarctica_calving_fraction) &
+              &                           / ( zantarctica_fwfisf_sum + 1.0e-10_wp ) )
+      
+               ! check
+               IF(lwp) WRITE(numout, *) 'Antarctica iceshelf melting climatology (kg/s) : ',zantarctica_fwfisf_sum
+
+               zantarctica_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * antarctica_icesheet_mask(:,:) )
+
+               IF(lwp) WRITE(numout, *) 'Antarctica iceshelf melting adjusted value (kg/s) : ',zantarctica_fwfisf_sum
+
+            ENDIF
+            ENDIF
+
             qisf(:,:)   = fwfisf(:,:) * lfusisf              ! heat        flux
             stbl(:,:)   = soce
@@ -264,4 +302,45 @@
             !CALL fld_read ( kt, nn_fsbc, sf_qisf   )
             fwfisf(:,:) = sf_fwfisf(1)%fnow(:,:,1)            ! fwf
+
+            IF( lk_oasis) THEN
+            ! nn_coupled_iceshelf_fluxes uninitialised unless lk_oasis=true
+            IF( nn_coupled_iceshelf_fluxes .gt. 0 ) THEN
+
+              ! Adjust total iceshelf melt rates so that sum of iceberg calving and iceshelf melting in the northern
+              ! and southern hemispheres equals rate of increase of mass of greenland and antarctic ice sheets
+              ! to preserve total freshwater conservation in coupled models without an active ice sheet model.
+
+              ! All related global sums must be done bit reproducibly
+               zgreenland_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * greenland_icesheet_mask(:,:) )
+
+               ! use ABS function because we need to preserve the sign of fwfisf
+               WHERE( greenland_icesheet_mask(:,:) == 1.0 )                                                                  &
+              &    fwfisf(:,:) = fwfisf(:,:)  * ABS( greenland_icesheet_mass_rate_of_change * (1.0-rn_greenland_calving_fraction) &
+              &                           / ( zgreenland_fwfisf_sum + 1.0e-10_wp ) )
+
+               ! check
+               IF(lwp) WRITE(numout, *) 'Greenland iceshelf melting climatology (kg/s) : ',zgreenland_fwfisf_sum
+
+               zgreenland_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * greenland_icesheet_mask(:,:) )
+
+               IF(lwp) WRITE(numout, *) 'Greenland iceshelf melting adjusted value (kg/s) : ',zgreenland_fwfisf_sum
+
+               zantarctica_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * antarctica_icesheet_mask(:,:) )
+
+               ! use ABS function because we need to preserve the sign of fwfisf
+               WHERE( antarctica_icesheet_mask(:,:) == 1.0 ) &
+              &    fwfisf(:,:) = fwfisf(:,:)  * ABS( antarctica_icesheet_mass_rate_of_change * (1.0-rn_antarctica_calving_fraction) &
+              &                           / ( zantarctica_fwfisf_sum + 1.0e-10_wp ) )
+      
+               ! check
+               IF(lwp) WRITE(numout, *) 'Antarctica iceshelf melting climatology (kg/s) : ',zantarctica_fwfisf_sum
+
+               zantarctica_fwfisf_sum = glob_sum( fwfisf(:,:) * e1t(:,:) * e2t(:,:) * antarctica_icesheet_mask(:,:) )
+
+               IF(lwp) WRITE(numout, *) 'Antarctica iceshelf melting adjusted value (kg/s) : ',zantarctica_fwfisf_sum
+
+            ENDIF
+            ENDIF
+
             qisf(:,:)   = fwfisf(:,:) * lfusisf              ! heat        flux
             !qisf(:,:)   = sf_qisf(1)%fnow(:,:,1)              ! heat flux
@@ -270,10 +349,19 @@
          END IF
          ! compute tsc due to isf
-         ! WARNING water add at temp = 0C, correction term is added in trasbc, maybe better here but need a 3D variable).
-         risf_tsc(:,:,jp_tem) = qisf(:,:) * r1_rau0_rcp !
+         ! WARNING water add at temp = 0C, correction term is added, maybe better here but need a 3D variable).
+!         zpress = grav*rau0*fsdept(ji,jj,jk)*1.e-04
+         zt_frz = -1.9 !eos_fzp( tsn(ji,jj,jk,jp_sal), zpress )
+         risf_tsc(:,:,jp_tem) = qisf(:,:) * r1_rau0_rcp - rdivisf * fwfisf(:,:) * zt_frz * r1_rau0 !
          
          ! salt effect already take into account in vertical advection
          risf_tsc(:,:,jp_sal) = (1.0_wp-rdivisf) * fwfisf(:,:) * stbl(:,:) * r1_rau0
-          
+
+         ! output
+         IF( iom_use('qlatisf' ) )   CALL iom_put('qlatisf', qisf)
+         IF( iom_use('fwfisf'  ) )   CALL iom_put('fwfisf' , fwfisf * stbl(:,:) / soce )
+
+         ! if apply only on the trend and not as a volume flux (rdivisf = 0), fwfisf have to be set to 0 now
+         fwfisf(:,:) = rdivisf * fwfisf(:,:)         
+ 
          ! lbclnk
          CALL lbc_lnk(risf_tsc(:,:,jp_tem),'T',1.)
@@ -281,4 +369,39 @@
          CALL lbc_lnk(fwfisf(:,:)   ,'T',1.)
          CALL lbc_lnk(qisf(:,:)     ,'T',1.)
+
+!=============================================================================================================================================
+         IF ( iom_use('fwfisf3d') .OR. iom_use('qlatisf3d') .OR. iom_use('qhcisf3d') .OR. iom_use('qhcisf')) THEN
+            CALL wrk_alloc( jpi,jpj,jpk, zfwfisf3d, zqhcisf3d, zqlatisf3d )
+            CALL wrk_alloc( jpi,jpj,     zqhcisf2d                        )
+
+            zfwfisf3d(:,:,:) = 0.0_wp                         ! 3d ice shelf melting (kg/m2/s)
+            zqhcisf3d(:,:,:) = 0.0_wp                         ! 3d heat content flux (W/m2)
+            zqlatisf3d(:,:,:)= 0.0_wp                         ! 3d ice shelf melting latent heat flux (W/m2)
+            zqhcisf2d(:,:)   = fwfisf(:,:) * zt_frz * rcp     ! 2d heat content flux (W/m2)
+
+            DO jj = 1,jpj
+               DO ji = 1,jpi
+                  ikt = misfkt(ji,jj)
+                  ikb = misfkb(ji,jj)
+                  DO jk = ikt, ikb - 1
+                     zfwfisf3d (ji,jj,jk) = zfwfisf3d (ji,jj,jk) + fwfisf   (ji,jj) * r1_hisf_tbl(ji,jj) * fse3t(ji,jj,jk)
+                     zqhcisf3d (ji,jj,jk) = zqhcisf3d (ji,jj,jk) + zqhcisf2d(ji,jj) * r1_hisf_tbl(ji,jj) * fse3t(ji,jj,jk)
+                     zqlatisf3d(ji,jj,jk) = zqlatisf3d(ji,jj,jk) + qisf     (ji,jj) * r1_hisf_tbl(ji,jj) * fse3t(ji,jj,jk)
+                  END DO
+                  zfwfisf3d (ji,jj,jk) = zfwfisf3d (ji,jj,jk) + fwfisf   (ji,jj) * r1_hisf_tbl(ji,jj) * ralpha(ji,jj) * fse3t(ji,jj,jk)
+                  zqhcisf3d (ji,jj,jk) = zqhcisf3d (ji,jj,jk) + zqhcisf2d(ji,jj) * r1_hisf_tbl(ji,jj) * ralpha(ji,jj) * fse3t(ji,jj,jk)
+                  zqlatisf3d(ji,jj,jk) = zqlatisf3d(ji,jj,jk) + qisf     (ji,jj) * r1_hisf_tbl(ji,jj) * ralpha(ji,jj) * fse3t(ji,jj,jk)
+               END DO
+            END DO
+
+            CALL iom_put('fwfisf3d' , zfwfisf3d (:,:,:))
+            CALL iom_put('qlatisf3d', zqlatisf3d(:,:,:))
+            CALL iom_put('qhcisf3d' , zqhcisf3d (:,:,:))
+            CALL iom_put('qhcisf'   , zqhcisf2d (:,:  ))
+
+            CALL wrk_dealloc( jpi,jpj,jpk, zfwfisf3d, zqhcisf3d, zqlatisf3d )
+            CALL wrk_dealloc( jpi,jpj,     zqhcisf2d                        )
+         END IF
+!=============================================================================================================================================
 
          IF( kt == nit000 ) THEN                          !   set the forcing field at nit000 - 1    !
@@ -295,7 +418,4 @@
          ENDIF
          ! 
-         ! output
-         CALL iom_put('qisf'  , qisf)
-         IF( iom_use('fwfisf') )   CALL iom_put('fwfisf', fwfisf * stbl(:,:) / soce )
       END IF
   
@@ -370,5 +490,5 @@
              ! Calculate freezing temperature
                 zpress = grav*rau0*fsdept(ji,jj,ik)*1.e-04 
-                zt_frz = eos_fzp(tsb(ji,jj,ik,jp_sal), zpress) 
+                CALL eos_fzp(tsb(ji,jj,ik,jp_sal), zt_frz, zpress) 
                 zt_sum = zt_sum + (tsn(ji,jj,ik,jp_tem)-zt_frz) * fse3t(ji,jj,ik) * tmask(ji,jj,ik)  ! sum temp
              ENDDO
@@ -452,5 +572,5 @@
       zti(:,:)=tinsitu( ttbl, stbl, zpress )
 ! Calculate freezing temperature
-      zfrz(:,:)=eos_fzp( sss_m(:,:), zpress )
+      CALL eos_fzp( sss_m(:,:), zfrz(:,:), zpress )
 
       
@@ -472,9 +592,6 @@
 
                      nit = nit + 1
-                     IF (nit .GE. 100) THEN
-                        !WRITE(numout,*) "sbcisf : too many iteration ... ", zhtflx, zhtflx_b,zgammat, rn_gammat0, rn_tfri2, nn_gammablk, ji,jj
-                        !WRITE(numout,*) "sbcisf : too many iteration ... ", (zhtflx - zhtflx_b)/zhtflx
-                        CALL ctl_stop( 'STOP', 'sbc_isf_hol99 : too many iteration ...' )
-                     END IF
+                     IF (nit .GE. 100) CALL ctl_stop( 'STOP', 'sbc_isf_hol99 : too many iteration ...' )
+
 ! save gammat and compute zhtflx_b
                      zgammat2d(ji,jj)=zgammat
@@ -794,5 +911,5 @@
                ! test on tmask useless ?????
                DO jk = ikt, mbkt(ji,jj)
-!                  IF ( (SUM(fse3t(ji,jj,ikt:jk-1)) .LT. rhisf_tbl(ji,jj)) .AND. (tmask(ji,jj,jk) == 1) ) ikb = jk
+                  IF ( (SUM(fse3t(ji,jj,ikt:jk-1)) .LT. rhisf_tbl(ji,jj)) .AND. (tmask(ji,jj,jk) == 1) ) ikb = jk
                END DO
                rhisf_tbl(ji,jj) = MIN(rhisf_tbl(ji,jj), SUM(fse3t(ji,jj,ikt:ikb)))  ! limit the tbl to water thickness.
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcmod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcmod.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcmod.F90	(revision 9987)
@@ -179,8 +179,9 @@
 
       !                          ! Checks:
-      IF( nn_isf .EQ. 0 ) THEN                      ! no specific treatment in vicinity of ice shelf 
+      IF( nn_isf .EQ. 0 ) THEN                      ! variable initialisation if no ice shelf 
          IF( sbc_isf_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_init : unable to allocate sbc_isf arrays' )
-         fwfisf  (:,:) = 0.0_wp
-         fwfisf_b(:,:) = 0.0_wp
+         fwfisf  (:,:)   = 0.0_wp ; fwfisf_b  (:,:)   = 0.0_wp
+         risf_tsc(:,:,:) = 0.0_wp ; risf_tsc_b(:,:,:) = 0.0_wp
+         rdivisf       = 0.0_wp
       END IF
       IF( nn_ice == 0 .AND. nn_components /= jp_iam_opa )   fr_i(:,:) = 0.e0 ! no ice in the domain, ice fraction is always zero
@@ -265,6 +266,9 @@
       ENDIF
       !
-      IF( lk_oasis )   CALL sbc_cpl_init (nn_ice)   ! OASIS initialisation. must be done before: (1) first time step
-      !                                                     !                                            (2) the use of nn_fsbc
+      IF( lk_oasis ) THEN
+         IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )         
+         CALL sbc_cpl_init (nn_ice)   ! OASIS initialisation. must be done before: (1) first time step
+                                      !                                            (2) the use of nn_fsbc
+      ENDIF
 
 !     nn_fsbc initialization if OPA-SAS coupling via OASIS
@@ -339,4 +343,8 @@
          emp_b(:,:) = emp(:,:)
          sfx_b(:,:) = sfx(:,:)
+         IF ( ln_rnf ) THEN
+            rnf_b    (:,:  ) = rnf    (:,:  )
+            rnf_tsc_b(:,:,:) = rnf_tsc(:,:,:)
+         ENDIF
       ENDIF
       !                                            ! ---------------------------------------- !
@@ -455,5 +463,6 @@
       !                                                ! ---------------------------------------- !
       IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN
-         CALL iom_put( "empmr" , emp  - rnf )                   ! upward water flux
+         CALL iom_put( "empmr"  , emp    - rnf )                ! upward water flux
+         CALL iom_put( "empbmr" , emp_b  - rnf )                ! before upward water flux ( needed to recalculate the time evolution of ssh in offline )
          CALL iom_put( "saltflx", sfx  )                        ! downward salt flux  
                                                                 ! (includes virtual salt flux beneath ice 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcrnf.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcrnf.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/sbcrnf.F90	(revision 9987)
@@ -52,5 +52,5 @@
    REAL(wp)                   ::   rn_hrnf         !: runoffs, depth over which enhanced vertical mixing is used
    REAL(wp)          , PUBLIC ::   rn_avt_rnf      !: runoffs, value of the additional vertical mixing coef. [m2/s]
-   REAL(wp)                   ::   rn_rfact        !: multiplicative factor for runoff
+   REAL(wp)          , PUBLIC ::   rn_rfact        !: multiplicative factor for runoff
 
    LOGICAL           , PUBLIC ::   l_rnfcpl = .false.       ! runoffs recieved from oasis
@@ -109,13 +109,5 @@
       !
       CALL wrk_alloc( jpi,jpj, ztfrz)
-
-      !                                            ! ---------------------------------------- !
-      IF( kt /= nit000 ) THEN                      !          Swap of forcing fields          !
-         !                                         ! ---------------------------------------- !
-         rnf_b    (:,:  ) = rnf    (:,:  )               ! Swap the ocean forcing fields except at nit000
-         rnf_tsc_b(:,:,:) = rnf_tsc(:,:,:)               ! where before fields are set at the end of the routine
-         !
-      ENDIF
-
+      !
       !                                            !-------------------!
       !                                            !   Update runoff   !
@@ -126,15 +118,8 @@
       IF(   ln_rnf_sal   )   CALL fld_read ( kt, nn_fsbc, sf_s_rnf )    ! idem for runoffs salinity    if required
       !
-      ! Runoff reduction only associated to the ORCA2_LIM configuration
-      ! when reading the NetCDF file runoff_1m_nomask.nc
-      IF( cp_cfg == 'orca' .AND. jp_cfg == 2 .AND. .NOT. l_rnfcpl )   THEN
-         WHERE( 40._wp < gphit(:,:) .AND. gphit(:,:) < 65._wp )
-            sf_rnf(1)%fnow(:,:,1) = 0.85 * sf_rnf(1)%fnow(:,:,1)
-         END WHERE
-      ENDIF
-      !
       IF( MOD( kt - 1, nn_fsbc ) == 0 ) THEN
          !
          IF( .NOT. l_rnfcpl )   rnf(:,:) = rn_rfact * ( sf_rnf(1)%fnow(:,:,1) )       ! updated runoff value at time step kt
+         CALL lbc_lnk(rnf(:,:), 'T', 1._wp)
          !
          !                                                     ! set temperature & salinity content of runoffs
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/updtide.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/updtide.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SBC/updtide.F90	(revision 9987)
@@ -31,5 +31,5 @@
 CONTAINS
 
-   SUBROUTINE upd_tide( kt, kit, kbaro, koffset )
+   SUBROUTINE upd_tide( kt, kit, time_offset )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE upd_tide  ***
@@ -42,8 +42,8 @@
       !!----------------------------------------------------------------------      
       INTEGER, INTENT(in)           ::   kt      ! ocean time-step index
-      INTEGER, INTENT(in), OPTIONAL ::   kit     ! external mode sub-time-step index (lk_dynspg_ts=T only)
-      INTEGER, INTENT(in), OPTIONAL ::   kbaro   ! number of sub-time-step           (lk_dynspg_ts=T only)
-      INTEGER, INTENT(in), OPTIONAL ::   koffset ! time offset in number 
-                                                 ! of sub-time-steps                 (lk_dynspg_ts=T only)
+      INTEGER, INTENT(in), OPTIONAL ::   kit     ! external mode sub-time-step index (lk_dynspg_ts=T)
+      INTEGER, INTENT(in), OPTIONAL ::   time_offset ! time offset in number 
+                                                     ! of internal steps             (lk_dynspg_ts=F)
+                                                     ! of external steps             (lk_dynspg_ts=T)
       !
       INTEGER  ::   joffset      ! local integer
@@ -57,8 +57,8 @@
       !
       joffset = 0
-      IF( PRESENT( koffset ) )   joffset = koffset
+      IF( PRESENT( time_offset ) )   joffset = time_offset
       !
-      IF( PRESENT( kit ) .AND. PRESENT( kbaro ) )   THEN
-         zt = zt + ( kit + 0.5_wp * ( joffset - 1 ) ) * rdt / REAL( kbaro, wp )
+      IF( PRESENT( kit ) )   THEN
+         zt = zt + ( kit +  joffset - 1 ) * rdt / REAL( nn_baro, wp )
       ELSE
          zt = zt + joffset * rdt
@@ -74,5 +74,5 @@
       IF( ln_tide_ramp ) THEN         ! linear increase if asked
          zt = ( kt - nit000 ) * rdt
-         IF( PRESENT( kit ) .AND. PRESENT( kbaro ) )   zt = zt + kit * rdt / REAL( kbaro, wp )
+         IF( PRESENT( kit ) )   zt = zt + ( kit + joffset -1) * rdt / REAL( nn_baro, wp )
          zramp = MIN(  MAX( zt / (rdttideramp*rday) , 0._wp ) , 1._wp  )
          pot_astro(:,:) = zramp * pot_astro(:,:)
@@ -86,9 +86,8 @@
   !!----------------------------------------------------------------------
 CONTAINS
-  SUBROUTINE upd_tide( kt, kit, kbaro, koffset )          ! Empty routine
+  SUBROUTINE upd_tide( kt, kit, time_offset )  ! Empty routine
     INTEGER, INTENT(in)           ::   kt      !  integer  arg, dummy routine
     INTEGER, INTENT(in), OPTIONAL ::   kit     !  optional arg, dummy routine
-    INTEGER, INTENT(in), OPTIONAL ::   kbaro   !  optional arg, dummy routine
-    INTEGER, INTENT(in), OPTIONAL ::   koffset !  optional arg, dummy routine
+    INTEGER, INTENT(in), OPTIONAL ::   time_offset !  optional arg, dummy routine
     WRITE(*,*) 'upd_tide: You should not have seen this print! error?', kt
   END SUBROUTINE upd_tide
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SOL/solpcg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SOL/solpcg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SOL/solpcg.F90	(revision 9987)
@@ -93,10 +93,10 @@
       REAL(wp) ::   zgcad        ! temporary scalars
       REAL(wp), DIMENSION(2) ::   zsum
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zgcr
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zgcr
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('sol_pcg')
       !
-      CALL wrk_alloc( jpi, jpj, zgcr )
+      ALLOCATE( zgcr(1:jpi,1:jpj) )
       !
       ! Initialization of the algorithm with standard PCG
@@ -210,5 +210,5 @@
       CALL lbc_lnk( gcx, c_solver_pt, 1. )      ! Output in gcx with lateral b.c. applied
       ! 
-      CALL wrk_dealloc( jpi, jpj, zgcr )
+      DEALLOCATE ( zgcr )
       !
       IF( nn_timing == 1 )  CALL timing_stop('sol_pcg')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SOL/solver.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SOL/solver.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/SOL/solver.F90	(revision 9987)
@@ -92,4 +92,6 @@
       IF( .NOT. lk_agrif .OR. .NOT. ln_rstart) THEN
          IF( sol_oce_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'solver_init : unable to allocate sol_oce arrays' )
+         gcx (:,:) = 0.e0
+         gcxb(:,:) = 0.e0
       ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/STO/stopar.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/STO/stopar.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/STO/stopar.F90	(revision 9987)
@@ -849,5 +849,5 @@
 
 
-   REAL(wp) FUNCTION sto_par_flt_fac( kpasses )
+   FUNCTION sto_par_flt_fac( kpasses )
       !!----------------------------------------------------------------------
       !!                  ***  FUNCTION sto_par_flt_fac  ***
@@ -858,4 +858,5 @@
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) :: kpasses
+      REAL(wp) :: sto_par_flt_fac
       !!
       INTEGER :: jpasses, ji, jj, jflti, jfltj
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/eosbn2.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/eosbn2.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/eosbn2.F90	(revision 9987)
@@ -22,4 +22,5 @@
    !!             -   ! 2013-04  (F. Roquet, G. Madec)  add eos_rab, change bn2 computation and reorganize the module
    !!             -   ! 2014-09  (F. Roquet)  add TEOS-10, S-EOS, and modify EOS-80
+   !!             -   ! 2015-06  (P.A. Bouttier) eos_fzp functions changed to subroutines for AGRIF
    !!----------------------------------------------------------------------
 
@@ -311,6 +312,6 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celcius]
       !                                                                ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd    ! in situ density            [-]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(inout) ::   prd    ! in situ density            [-]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(inout) ::   prhop  ! potential density (surface referenced)
       REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep   ! depth                      [m]
       !
@@ -456,4 +457,6 @@
       END SELECT
       !
+      CALL lbc_lnk( prd, 'T', 1.0_wp )
+      !
       IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-pot: ', tab3d_2=prhop, clinfo2=' pot : ', ovlap=1, kdim=jpk )
       !
@@ -901,5 +904,5 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celcius,psu]
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celcius-1,psu-1]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(inout) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
       !
       INTEGER  ::   ji, jj, jk      ! dummy loop indices
@@ -991,5 +994,5 @@
 
 
-   FUNCTION eos_fzp_2d( psal, pdep ) RESULT( ptf )
+   SUBROUTINE  eos_fzp_2d( psal, ptf, pdep )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE eos_fzp  ***
@@ -1005,5 +1008,5 @@
       REAL(wp), DIMENSION(jpi,jpj), INTENT(in   )           ::   psal   ! salinity   [psu]
       REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
-      REAL(wp), DIMENSION(jpi,jpj)                          ::   ptf   ! freezing temperature [Celcius]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(out  )           ::   ptf    ! freezing temperature [Celcius]
       !
       INTEGER  ::   ji, jj   ! dummy loop indices
@@ -1017,5 +1020,5 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               zs= SQRT( ABS( psal(ji,jj) ) * r1_S0 )           ! square root salinity
+               zs= SQRT( ABS( psal(ji,jj) ) / 35.16504_wp )           ! square root salinity
                ptf(ji,jj) = ((((1.46873e-03_wp*zs-9.64972e-03_wp)*zs+2.28348e-02_wp)*zs &
                   &          - 3.12775e-02_wp)*zs+2.07679e-02_wp)*zs-5.87701e-02_wp
@@ -1038,9 +1041,9 @@
          nstop = nstop + 1
          !
-      END SELECT
-      !
-   END FUNCTION eos_fzp_2d
-
-  FUNCTION eos_fzp_0d( psal, pdep ) RESULT( ptf )
+      END SELECT      
+      !
+  END SUBROUTINE eos_fzp_2d
+
+  SUBROUTINE eos_fzp_0d( psal, ptf, pdep )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE eos_fzp  ***
@@ -1054,7 +1057,7 @@
       !! Reference  :   UNESCO tech. papers in the marine science no. 28. 1978
       !!----------------------------------------------------------------------
-      REAL(wp), INTENT(in)           ::   psal   ! salinity   [psu]
-      REAL(wp), INTENT(in), OPTIONAL ::   pdep   ! depth      [m]
-      REAL(wp)                       ::   ptf   ! freezing temperature [Celcius]
+      REAL(wp), INTENT(in )           ::   psal         ! salinity   [psu]
+      REAL(wp), INTENT(in ), OPTIONAL ::   pdep         ! depth      [m]
+      REAL(wp), INTENT(out)           ::   ptf          ! freezing temperature [Celcius]
       !
       REAL(wp) :: zs   ! local scalars
@@ -1065,5 +1068,5 @@
       CASE ( -1, 1 )                !==  CT,SA (TEOS-10 formulation) ==!
          !
-         zs  = SQRT( ABS( psal ) * r1_S0 )           ! square root salinity
+         zs  = SQRT( ABS( psal ) / 35.16504_wp )           ! square root salinity
          ptf = ((((1.46873e-03_wp*zs-9.64972e-03_wp)*zs+2.28348e-02_wp)*zs &
                   &          - 3.12775e-02_wp)*zs+2.07679e-02_wp)*zs-5.87701e-02_wp
@@ -1086,5 +1089,5 @@
       END SELECT
       !
-   END FUNCTION eos_fzp_0d
+   END SUBROUTINE eos_fzp_0d
 
 
@@ -1255,4 +1258,11 @@
             WRITE(numout,*) '             model does not use Conservative Temperature'
          ENDIF
+      ENDIF
+      !
+      ! Consistency check on ln_useCT and nn_eos
+      IF ((nn_eos .EQ. -1) .AND. (.NOT. ln_useCT)) THEN
+         CALL ctl_stop("ln_useCT should be set to True if using TEOS-10 (nn_eos=-1)")
+      ELSE IF ((nn_eos .NE. -1) .AND. (ln_useCT)) THEN
+         CALL ctl_stop("ln_useCT should be set to False if using TEOS-80 or simplified equation of state (nn_eos=0 or nn_eos=1)")
       ENDIF
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv.F90	(revision 9987)
@@ -26,4 +26,6 @@
    USE cla             ! cross land advection      (cla_traadv     routine)
    USE ldftra_oce      ! lateral diffusion coefficient on tracers
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
    !
    USE in_out_manager  ! I/O manager
@@ -78,10 +80,13 @@
       !
       INTEGER ::   jk   ! dummy loop index
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zun, zvn, zwn
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zun, zvn, zwn
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: ztrdt, ztrds   ! 3D workspace
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zun, zvn, zwn )
+      ALLOCATE(zun(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zvn(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zwn(1:jpi, 1:jpj, 1:jpk))
       !                                          ! set time step
       IF( neuler == 0 .AND. kt == nit000 ) THEN     ! at nit000
@@ -120,5 +125,11 @@
       IF( ln_diaptr )   CALL dia_ptr( zvn )                                     ! diagnose the effective MSF 
       !
-   
+      IF( l_trdtra )   THEN                    !* Save ta and sa trends
+         ALLOCATE(ztrdt( 1:jpi, 1:jpj, 1:jpk) )
+         ALLOCATE(ztrds( 1:jpi, 1:jpj, 1:jpk) )
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+      !
       SELECT CASE ( nadv )                            !==  compute advection trend and add it to general trend  ==!
       CASE ( 1 )   ;    CALL tra_adv_cen2   ( kt, nit000, 'TRA',         zun, zvn, zwn, tsb, tsn, tsa, jpts )   !  2nd order centered
@@ -151,4 +162,14 @@
       END SELECT
       !
+      IF( l_trdtra )   THEN                      ! save the advective trends for further diagnostics
+         DO jk = 1, jpkm1
+            ztrdt(:,:,jk) = tsa(:,:,jk,jp_tem) - ztrdt(:,:,jk)
+            ztrds(:,:,jk) = tsa(:,:,jk,jp_sal) - ztrds(:,:,jk)
+         END DO
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_totad, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_totad, ztrds )
+         DEALLOCATE (ztrdt)
+         DEALLOCATE (ztrds)
+      ENDIF
       !                                              ! print mean trends (used for debugging)
       IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' adv  - Ta: ', mask1=tmask,               &
@@ -157,5 +178,7 @@
       IF( nn_timing == 1 )  CALL timing_stop( 'tra_adv' )
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zun, zvn, zwn )
+      DEALLOCATE(zun)
+      DEALLOCATE(zvn)
+      DEALLOCATE(zwn)
       !                                          
    END SUBROUTINE tra_adv
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_cen2.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_cen2.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_cen2.F90	(revision 9987)
@@ -173,5 +173,5 @@
          END DO 
       END DO 
-      zfzp(:,:) = eos_fzp( tsn(:,:,1,jp_sal), zpres(:,:) )
+      CALL eos_fzp( tsn(:,:,1,jp_sal), zfzp(:,:), zpres(:,:) )
       DO jk = 1, jpk
          DO jj = 1, jpj
@@ -279,8 +279,5 @@
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )   htr_adv(:) = ptr_sj( zwy(:,:,:) )
-           IF( jn == jp_sal )   str_adv(:) = ptr_sj( zwy(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr ) CALL dia_ptr_ohst_components( jn, 'adv', zwy(:,:,:) )
          !
       END DO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_eiv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_eiv.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_eiv.F90	(revision 9987)
@@ -28,4 +28,7 @@
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
+   USE diaptr         ! Heat/Salt transport diagnostics
+   USE trddyn
+   USE trd_oce
 
    IMPLICIT NONE
@@ -78,4 +81,5 @@
 # endif  
       REAL(wp), POINTER, DIMENSION(:,:) :: zu_eiv, zv_eiv, zw_eiv, z2d
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: z3d, z3d_T
       !!----------------------------------------------------------------------
       !
@@ -84,4 +88,5 @@
 # if defined key_diaeiv 
       CALL wrk_alloc( jpi, jpj, zu_eiv, zv_eiv, zw_eiv, z2d )
+      CALL wrk_alloc( jpi, jpj, jpk, z3d, z3d_T )
 # else
       CALL wrk_alloc( jpi, jpj, zu_eiv, zv_eiv, zw_eiv )
@@ -160,38 +165,184 @@
          CALL iom_put( "voce_eiv", v_eiv )    ! j-eiv current
          CALL iom_put( "woce_eiv", w_eiv )    ! vert. eiv current
-         IF( iom_use('ueiv_heattr') ) THEN
-            zztmp = 0.5 * rau0 * rcp 
+         IF( iom_use('weiv_masstr') ) THEN   ! vertical mass transport & its square value
+           z2d(:,:) = rau0 * e12t(:,:)
+           DO jk = 1, jpk
+              z3d(:,:,jk) = w_eiv(:,:,jk) * z2d(:,:)
+           END DO
+           CALL iom_put( "weiv_masstr" , z3d )  
+         ENDIF
+         IF( iom_use("ueiv_masstr") .OR. iom_use("ueiv_heattr") .OR. iom_use('ueiv_heattr3d')        &
+                                    .OR. iom_use("ueiv_salttr") .OR. iom_use('ueiv_salttr3d') ) THEN
+            z3d(:,:,jpk) = 0.e0
+            z2d(:,:) = 0.e0
+            DO jk = 1, jpkm1
+               z3d(:,:,jk) = rau0 * u_eiv(:,:,jk) * e2u(:,:) * fse3u(:,:,jk) * umask(:,:,jk)
+               z2d(:,:) = z2d(:,:) + z3d(:,:,jk)
+            END DO
+            CALL iom_put( "ueiv_masstr", z3d )                  ! mass transport in i-direction
+         ENDIF
+
+         IF( iom_use('ueiv_heattr') .OR. iom_use('ueiv_heattr3d') ) THEN
+            zztmp = 0.5 * rcp 
             z2d(:,:) = 0.e0 
-            DO jk = 1, jpkm1
-               DO jj = 2, jpjm1
-                  DO ji = fs_2, fs_jpim1   ! vector opt.
-                     z2d(ji,jj) = z2d(ji,jj) + u_eiv(ji,jj,jk) &
-                       &         * (tsn(ji,jj,jk,jp_tem)+tsn(ji+1,jj,jk,jp_tem)) * e2u(ji,jj) * fse3u(ji,jj,jk) 
-                  END DO
-               END DO
-            END DO
-            CALL lbc_lnk( z2d, 'U', -1. )
-            CALL iom_put( "ueiv_heattr", zztmp * z2d )                  ! heat transport in i-direction
+            z3d_T(:,:,:) = 0.e0 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z3d_T(ji,jj,jk) = z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_tem) + tsn(ji+1,jj,jk,jp_tem) )
+                     z2d(ji,jj) = z2d(ji,jj) + z3d_T(ji,jj,jk) 
+                  END DO
+               END DO
+            END DO
+            IF (iom_use('ueiv_heattr') ) THEN
+               CALL lbc_lnk( z2d, 'U', -1. )
+               CALL iom_put( "ueiv_heattr", zztmp * z2d )                  ! 2D heat transport in i-direction
+            ENDIF
+            IF (iom_use('ueiv_heattr3d') ) THEN
+               CALL lbc_lnk( z3d_T, 'U', -1. )
+               CALL iom_put( "ueiv_heattr3d", zztmp * z3d_T )              ! 3D heat transport in i-direction
+            ENDIF
+         ENDIF
+
+         IF( iom_use('ueiv_salttr') .OR. iom_use('ueiv_salttr3d') ) THEN
+            zztmp = 0.5 * 0.001
+            z2d(:,:) = 0.e0 
+            z3d_T(:,:,:) = 0.e0 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z3d_T(ji,jj,jk) = z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji+1,jj,jk,jp_sal) )
+                     z2d(ji,jj) = z2d(ji,jj) + z3d_T(ji,jj,jk) 
+                  END DO
+               END DO
+            END DO
+            IF (iom_use('ueiv_salttr') ) THEN
+               CALL lbc_lnk( z2d, 'U', -1. )
+               CALL iom_put( "ueiv_salttr", zztmp * z2d )                  ! 2D salt transport in i-direction
+            ENDIF
+            IF (iom_use('ueiv_salttr3d') ) THEN
+               CALL lbc_lnk( z3d_T, 'U', -1. )
+               CALL iom_put( "ueiv_salttr3d", zztmp * z3d_T )              ! 3D salt transport in i-direction
+            ENDIF
+         ENDIF
+
+         IF( iom_use("veiv_masstr") .OR. iom_use("veiv_heattr") .OR. iom_use('veiv_heattr3d')       &
+                                    .OR. iom_use("veiv_salttr") .OR. iom_use('veiv_salttr3d') ) THEN
+            z3d(:,:,jpk) = 0.e0
+            DO jk = 1, jpkm1
+               z3d(:,:,jk) = rau0 * v_eiv(:,:,jk) * e1v(:,:) * fse3v(:,:,jk) * vmask(:,:,jk)
+            END DO
+            CALL iom_put( "veiv_masstr", z3d )                  ! mass transport in j-direction
          ENDIF
             
-         IF( iom_use('veiv_heattr') ) THEN
-            zztmp = 0.5 * rau0 * rcp 
+         IF( iom_use('veiv_heattr') .OR. iom_use('veiv_heattr3d') ) THEN
+            zztmp = 0.5 * rcp 
             z2d(:,:) = 0.e0 
-            DO jk = 1, jpkm1
-               DO jj = 2, jpjm1
-                  DO ji = fs_2, fs_jpim1   ! vector opt.
-                     z2d(ji,jj) = z2d(ji,jj) + v_eiv(ji,jj,jk) &
-                     &           * (tsn(ji,jj,jk,jp_tem)+tsn(ji,jj+1,jk,jp_tem)) * e1v(ji,jj) * fse3v(ji,jj,jk) 
-                  END DO
-               END DO
-            END DO
-            CALL lbc_lnk( z2d, 'V', -1. )
-            CALL iom_put( "veiv_heattr", zztmp * z2d )                  !  heat transport in i-direction
-         ENDIF
+            z3d_T(:,:,:) = 0.e0 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z3d_T(ji,jj,jk) = z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_tem) + tsn(ji,jj+1,jk,jp_tem) )
+                     z2d(ji,jj) = z2d(ji,jj) + z3d_T(ji,jj,jk) 
+                  END DO
+               END DO
+            END DO
+            IF (iom_use('veiv_heattr') ) THEN
+               CALL lbc_lnk( z2d, 'V', -1. )
+               CALL iom_put( "veiv_heattr", zztmp * z2d )                  ! 2D heat transport in j-direction
+            ENDIF
+            IF (iom_use('veiv_heattr3d') ) THEN
+               CALL lbc_lnk( z3d_T, 'V', -1. )
+               CALL iom_put( "veiv_heattr3d", zztmp * z3d_T )              ! 3D heat transport in j-direction
+            ENDIF
+         ENDIF
+
+         IF( iom_use('veiv_salttr') .OR. iom_use('veiv_salttr3d') ) THEN
+            zztmp = 0.5 * 0.001
+            z2d(:,:) = 0.e0 
+            z3d_T(:,:,:) = 0.e0 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z3d_T(ji,jj,jk) = z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji,jj+1,jk,jp_sal) )
+                     z2d(ji,jj) = z2d(ji,jj) + z3d_T(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            IF (iom_use('veiv_salttr') ) THEN
+               CALL lbc_lnk( z2d, 'V', -1. )
+               CALL iom_put( "veiv_salttr", zztmp * z2d )                  ! 2D salt transport in i-direction
+            ENDIF
+            IF (iom_use('veiv_salttr3d') ) THEN
+               CALL lbc_lnk( z3d_T, 'V', -1. )
+               CALL iom_put( "veiv_salttr3d", zztmp * z3d_T )              ! 3D salt transport in i-direction
+            ENDIF
+         ENDIF
+
+         IF( iom_use('weiv_masstr') .OR. iom_use('weiv_heattr3d') .OR. iom_use('weiv_salttr3d')) THEN   ! vertical mass transport & its square value
+           z2d(:,:) = rau0 * e12t(:,:)
+           DO jk = 1, jpk
+              z3d(:,:,jk) = w_eiv(:,:,jk) * z2d(:,:)
+           END DO
+           CALL iom_put( "weiv_masstr" , z3d )                  ! mass transport in k-direction
+         ENDIF
+
+         IF( iom_use('weiv_heattr3d') ) THEN
+            zztmp = 0.5 * rcp 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z3d_T(ji,jj,jk) = z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_tem) + tsn(ji,jj,jk+1,jp_tem) )
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk( z3d_T, 'T', 1. )
+            CALL iom_put( "weiv_heattr3d", zztmp * z3d_T )                 ! 3D heat transport in k-direction
+         ENDIF
+
+         IF( iom_use('weiv_salttr3d') ) THEN
+            zztmp = 0.5 * 0.001 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z3d_T(ji,jj,jk) = z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji,jj,jk+1,jp_sal) )
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk( z3d_T, 'T', 1. )
+            CALL iom_put( "weiv_salttr3d", zztmp * z3d_T )                 ! 3D salt transport in k-direction
+         ENDIF
+
     END IF
+!
+    IF( ln_diaptr .AND. cdtype == 'TRA' ) THEN
+       z3d(:,:,:) = 0._wp
+       DO jk = 1, jpkm1
+          DO jj = 2, jpjm1
+             DO ji = fs_2, fs_jpim1   ! vector opt.
+                z3d(ji,jj,jk) = v_eiv(ji,jj,jk) * 0.5 * (tsn(ji,jj,jk,jp_tem)+tsn(ji,jj+1,jk,jp_tem)) &
+                &             * e1v(ji,jj) * fse3v(ji,jj,jk)
+             END DO
+          END DO
+       END DO
+       CALL dia_ptr_ohst_components( jp_tem, 'eiv', z3d )
+       z3d(:,:,:) = 0._wp
+       DO jk = 1, jpkm1
+          DO jj = 2, jpjm1
+             DO ji = fs_2, fs_jpim1   ! vector opt.
+                z3d(ji,jj,jk) = v_eiv(ji,jj,jk) * 0.5 * (tsn(ji,jj,jk,jp_sal)+tsn(ji,jj+1,jk,jp_sal)) &
+                &             * e1v(ji,jj) * fse3v(ji,jj,jk)
+             END DO
+          END DO
+       END DO
+       CALL dia_ptr_ohst_components( jp_sal, 'eiv', z3d )
+    ENDIF
+
+    IF( ln_KE_trd ) CALL trd_dyn(u_eiv, v_eiv, jpdyn_eivke, kt )
 # endif  
-      ! 
+
 # if defined key_diaeiv 
       CALL wrk_dealloc( jpi, jpj, zu_eiv, zv_eiv, zw_eiv, z2d )
+      CALL wrk_dealloc( jpi, jpj, jpk, z3d, z3d_T )
 # else
       CALL wrk_dealloc( jpi, jpj, zu_eiv, zv_eiv, zw_eiv )
@@ -212,5 +363,6 @@
       CHARACTER(len=3) ::   cdtype
       REAL, DIMENSION(:,:,:) ::   pun, pvn, pwn
-      WRITE(*,*) 'tra_adv_eiv: You should not have seen this print! error?', kt, cdtype, pun(1,1,1), pvn(1,1,1), pwn(1,1,1)
+      WRITE(*,*) 'tra_adv_eiv: You should not have seen this print! error?', &
+          &  kt, cdtype, pun(1,1,1), pvn(1,1,1), pwn(1,1,1)
    END SUBROUTINE tra_adv_eiv
 #endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl.F90	(revision 9987)
@@ -82,11 +82,14 @@
       REAL(wp) ::   zv, z0v, zzwy, z0w        !   -      -
       REAL(wp) ::   ztra, zbtr, zdt, zalpha   !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zslpx, zslpy   ! 3D workspace
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zwx  , zwy     ! -      - 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   zslpx, zslpy   ! 3D workspace
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   zwx  , zwy     ! -      - 
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_muscl')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zslpx, zslpy, zwx, zwy )
+      ALLOCATE( zslpx(1:jpi, 1:jpj, 1:jpk) )
+      ALLOCATE( zslpy(1:jpi, 1:jpj, 1:jpk) )
+      ALLOCATE( zwx  (1:jpi, 1:jpj, 1:jpk) )
+      ALLOCATE( zwy  (1:jpi, 1:jpj, 1:jpk) )
       !
       IF( kt == kit000 )  THEN
@@ -219,8 +222,5 @@
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-            IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) )
-            IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )  CALL dia_ptr_ohst_components( jn, 'adv', zwy(:,:,:)  )
 
          ! II. Vertical advective fluxes
@@ -291,5 +291,8 @@
       END DO
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zslpx, zslpy, zwx, zwy )
+      DEALLOCATE( zslpx )
+      DEALLOCATE( zslpy )
+      DEALLOCATE( zwx   )
+      DEALLOCATE( zwy   )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_adv_muscl')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl2.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl2.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl2.F90	(revision 9987)
@@ -200,8 +200,5 @@
 
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN
-            IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) )
-            IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr ) CALL dia_ptr_ohst_components( jn, 'adv', zwy(:,:,:)  )
 
          ! II. Vertical advective fluxes
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_qck.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_qck.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_qck.F90	(revision 9987)
@@ -355,8 +355,5 @@
          IF( l_trd )   CALL trd_tra( kt, cdtype, jn, jptra_yad, zwy, pvn, ptn(:,:,:,jn) )
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) )
-           IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )  CALL dia_ptr_ohst_components( jn, 'adv', zwy(:,:,:) )
          !
       END DO
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_tvd.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_tvd.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_tvd.F90	(revision 9987)
@@ -34,4 +34,5 @@
    USE timing         ! Timing
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+   USE iom
 
    IMPLICIT NONE
@@ -42,4 +43,5 @@
 
    LOGICAL ::   l_trd   ! flag to compute trends
+   LOGICAL ::   l_trans   ! flag to output vertically integrated transports
 
    !! * Substitutions
@@ -84,11 +86,14 @@
       REAL(wp) ::   zfp_ui, zfp_vj, zfp_wk   !   -      -
       REAL(wp) ::   zfm_ui, zfm_vj, zfm_wk   !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwi, zwz
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztrdx, ztrdy, ztrdz
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zwi, zwz
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: ztrdx, ztrdy, ztrdz, zptry
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   :: z2d
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_tvd')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zwi, zwz )
+      ALLOCATE(zwi(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zwz(1:jpi, 1:jpj, 1:jpk))
+
       !
       IF( kt == kit000 )  THEN
@@ -97,11 +102,21 @@
          IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
          !
-         l_trd = .FALSE.
-         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
       ENDIF
-      !
-      IF( l_trd )  THEN
-         CALL wrk_alloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
+      l_trd = .FALSE.
+      l_trans = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
+      IF( cdtype == 'TRA' .AND. (iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") ) ) l_trans = .TRUE.
+      !
+      IF( l_trd .OR. l_trans )  THEN
+         ALLOCATE(ztrdx(1:jpi, 1:jpj, 1:jpk))
+         ALLOCATE(ztrdy(1:jpi, 1:jpj, 1:jpk))
+         ALLOCATE(ztrdz(1:jpi, 1:jpj, 1:jpk))
          ztrdx(:,:,:) = 0.e0   ;    ztrdy(:,:,:) = 0.e0   ;   ztrdz(:,:,:) = 0.e0
+         ALLOCATE(z2d(1:jpi, 1:jpj))
+      ENDIF
+      !
+      IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
+         ALLOCATE(zptry(1:jpi, 1:jpj, 1:jpk))
+         zptry(:,:,:) = 0._wp
       ENDIF
       !
@@ -173,12 +188,11 @@
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zbtr = 1. / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
                   ! total intermediate advective trends
-                  ztra = - zbtr * (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
-                     &             + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
-                     &             + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) )
+                  ztra = - (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
+                     &      + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
+                     &      + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) ) / e1e2t(ji,jj)
                   ! update and guess with monotonic sheme
-                  pta(ji,jj,jk,jn) =   pta(ji,jj,jk,jn)         + ztra   * tmask(ji,jj,jk)
-                  zwi(ji,jj,jk)    = ( ptb(ji,jj,jk,jn) + z2dtt * ztra ) * tmask(ji,jj,jk)
+                  pta(ji,jj,jk,jn) =                       pta(ji,jj,jk,jn) +         ztra   / fse3t_n(ji,jj,jk) * tmask(ji,jj,jk)
+                  zwi(ji,jj,jk)    = ( fse3t_b(ji,jj,jk) * ptb(ji,jj,jk,jn) + z2dtt * ztra ) / fse3t_a(ji,jj,jk) * tmask(ji,jj,jk)
                END DO
             END DO
@@ -188,13 +202,10 @@
 
          !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd )  THEN 
+         IF( l_trd .OR. l_trans )  THEN 
             ! store intermediate advective trends
             ztrdx(:,:,:) = zwx(:,:,:)   ;    ztrdy(:,:,:) = zwy(:,:,:)  ;   ztrdz(:,:,:) = zwz(:,:,:)
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) )
-           IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )    zptry(:,:,:) = zwy(:,:,:) 
 
          ! 3. antidiffusive flux : high order minus low order
@@ -254,23 +265,56 @@
 
          !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd )  THEN 
+         IF( l_trd .OR. l_trans )  THEN 
             ztrdx(:,:,:) = ztrdx(:,:,:) + zwx(:,:,:)  ! <<< Add to previously computed
             ztrdy(:,:,:) = ztrdy(:,:,:) + zwy(:,:,:)  ! <<< Add to previously computed
             ztrdz(:,:,:) = ztrdz(:,:,:) + zwz(:,:,:)  ! <<< Add to previously computed
-            
-            CALL trd_tra( kt, cdtype, jn, jptra_xad, ztrdx, pun, ptn(:,:,:,jn) )   
-            CALL trd_tra( kt, cdtype, jn, jptra_yad, ztrdy, pvn, ptn(:,:,:,jn) )  
-            CALL trd_tra( kt, cdtype, jn, jptra_zad, ztrdz, pwn, ptn(:,:,:,jn) ) 
+         ENDIF
+         
+         IF( l_trd ) THEN 
+            CALL trd_tra( kt, cdtype, jn, jptra_xad, ztrdx, pun, ptn(:,:,:,jn) )
+            CALL trd_tra( kt, cdtype, jn, jptra_yad, ztrdy, pvn, ptn(:,:,:,jn) )
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, ztrdz, pwn, ptn(:,:,:,jn) )
          END IF
-         !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
+
+         IF( l_trans .AND. jn==jp_tem ) THEN
+            z2d(:,:) = 0._wp 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z2d(ji,jj) = z2d(ji,jj) + ztrdx(ji,jj,jk) 
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk( z2d, 'U', -1. )
+            CALL iom_put( "uadv_heattr", rau0_rcp * z2d )       ! heat transport in i-direction
+              !
+            z2d(:,:) = 0._wp 
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     z2d(ji,jj) = z2d(ji,jj) + ztrdy(ji,jj,jk) 
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk( z2d, 'V', -1. )
+            CALL iom_put( "vadv_heattr", rau0_rcp * z2d )       ! heat transport in j-direction
+         ENDIF
+         ! "Poleward" heat and salt transports (contribution of upstream fluxes)
          IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) ) + htr_adv(:)
-           IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) ) + str_adv(:)
+            zptry(:,:,:) = zptry(:,:,:) + zwy(:,:,:)  ! <<< Add to previously computed
+            CALL dia_ptr_ohst_components( jn, 'adv', zptry(:,:,:) )
          ENDIF
          !
       END DO
       !
-                   CALL wrk_dealloc( jpi, jpj, jpk, zwi, zwz )
-      IF( l_trd )  CALL wrk_dealloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
+      DEALLOCATE( zwi )
+      DEALLOCATE( zwz )
+      IF( l_trd .OR. l_trans )  THEN 
+         DEALLOCATE( ztrdx )
+         DEALLOCATE( ztrdy )
+         DEALLOCATE( ztrdz )
+         DEALLOCATE( z2d )
+      ENDIF
+      IF( cdtype == 'TRA' .AND. ln_diaptr ) DEALLOCATE( zptry )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_adv_tvd')
@@ -316,15 +360,21 @@
       REAL(wp) ::   zfp_ui, zfp_vj, zfp_wk   !   -      -
       REAL(wp) ::   zfm_ui, zfm_vj, zfm_wk   !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:  ) :: zwx_sav , zwy_sav
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwi, zwz, zhdiv, zwz_sav, zwzts
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztrdx, ztrdy, ztrdz
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztrs
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:  ) :: zwx_sav , zwy_sav
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zwi, zwz, zhdiv, zwz_sav, zwzts
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: ztrdx, ztrdy, ztrdz
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zptry
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) :: ztrs
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_tvd_zts')
       !
-      CALL wrk_alloc( jpi, jpj, zwx_sav, zwy_sav )
-      CALL wrk_alloc( jpi, jpj, jpk, zwi, zwz , zhdiv, zwz_sav, zwzts )
-      CALL wrk_alloc( jpi, jpj, jpk, 3, ztrs )
+      ALLOCATE(zwx_sav(1:jpi, 1:jpj))
+      ALLOCATE(zwy_sav(1:jpi, 1:jpj))
+      ALLOCATE(zwi(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zwz(1:jpi, 1:jpj, 1:jpk))        
+      ALLOCATE(zhdiv(1:jpi, 1:jpj, 1:jpk))       
+      ALLOCATE(zwz_sav(1:jpi, 1:jpj, 1:jpk))       
+      ALLOCATE(zwzts(1:jpi, 1:jpj, 1:jpk)) 
+      ALLOCATE(ztrs(1:jpi, 1:jpj, 1:jpk, 1:kjpt+1))
       !
       IF( kt == kit000 )  THEN
@@ -338,6 +388,13 @@
       !
       IF( l_trd )  THEN
-         CALL wrk_alloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
+         ALLOCATE(ztrdx(1:jpi, 1:jpj, 1:jpk))       
+         ALLOCATE(ztrdy(1:jpi, 1:jpj, 1:jpk))       
+         ALLOCATE(ztrdz(1:jpi, 1:jpj, 1:jpk))       
          ztrdx(:,:,:) = 0._wp  ;    ztrdy(:,:,:) = 0._wp  ;   ztrdz(:,:,:) = 0._wp
+      ENDIF
+      !
+      IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
+         ALLOCATE(zptry(1:jpi, 1:jpj, 1:jpk))       
+         zptry(:,:,:) = 0._wp
       ENDIF
       !
@@ -410,12 +467,11 @@
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zbtr = 1._wp / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
                   ! total intermediate advective trends
-                  ztra = - zbtr * (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
-                     &             + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
-                     &             + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) )
+                  ztra = - (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
+                     &      + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
+                     &      + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) ) / e1e2t(ji,jj)
                   ! update and guess with monotonic sheme
-                  pta(ji,jj,jk,jn) =   pta(ji,jj,jk,jn)         + ztra
-                  zwi(ji,jj,jk)    = ( ptb(ji,jj,jk,jn) + z2dtt * ztra ) * tmask(ji,jj,jk)
+                  pta(ji,jj,jk,jn) =                       pta(ji,jj,jk,jn) +         ztra   / fse3t_n(ji,jj,jk) * tmask(ji,jj,jk)
+                  zwi(ji,jj,jk)    = ( fse3t_b(ji,jj,jk) * ptb(ji,jj,jk,jn) + z2dtt * ztra ) / fse3t_a(ji,jj,jk) * tmask(ji,jj,jk)
                END DO
             END DO
@@ -430,16 +486,12 @@
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) )
-           IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )  zptry(:,:,:) = zwy(:,:,:)
 
          ! 3. antidiffusive flux : high order minus low order
          ! --------------------------------------------------
          ! antidiffusive flux on i and j
-
-
+         !
          DO jk = 1, jpkm1
-
+            !
             DO jj = 1, jpjm1
                DO ji = 1, fs_jpim1   ! vector opt.
@@ -472,4 +524,6 @@
          !
          ztrs(:,:,:,1) = ptb(:,:,:,jn)
+         ztrs(:,:,1,2) = ptb(:,:,1,jn)
+         ztrs(:,:,1,3) = ptb(:,:,1,jn)
          zwzts(:,:,:) = 0._wp
 
@@ -557,18 +611,31 @@
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
          IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )  htr_adv(:) = ptr_sj( zwy(:,:,:) ) + htr_adv(:)
-           IF( jn == jp_sal )  str_adv(:) = ptr_sj( zwy(:,:,:) ) + str_adv(:)
+            zptry(:,:,:) = zptry(:,:,:) + zwy(:,:,:) 
+            CALL dia_ptr_ohst_components( jn, 'adv', zptry(:,:,:) )
          ENDIF
          !
       END DO
       !
-                   CALL wrk_dealloc( jpi, jpj, jpk, zwi, zwz, zhdiv, zwz_sav, zwzts )
-                   CALL wrk_dealloc( jpi, jpj, jpk, 3, ztrs )
-                   CALL wrk_dealloc( jpi, jpj, zwx_sav, zwy_sav )
-      IF( l_trd )  CALL wrk_dealloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
+      DEALLOCATE(zwi) 
+      DEALLOCATE(zwz) 
+      DEALLOCATE(zhdiv) 
+      DEALLOCATE(zwz_sav) 
+      DEALLOCATE(zwzts)
+      DEALLOCATE(ztrs )
+      DEALLOCATE(zwx_sav) 
+      DEALLOCATE(zwy_sav )
+
+      IF( l_trd )  THEN
+          DEALLOCATE(ztrdx) 
+          DEALLOCATE(ztrdy) 
+          DEALLOCATE(ztrdz)
+      END IF
+
+      IF( cdtype == 'TRA' .AND. ln_diaptr ) DEALLOCATE(zptry )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_adv_tvd_zts')
       !
    END SUBROUTINE tra_adv_tvd_zts
+
 
    SUBROUTINE nonosc( pbef, paa, pbb, pcc, paft, p2dt )
@@ -593,10 +660,13 @@
       REAL(wp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn, z2dtt   ! local scalars
       REAL(wp) ::   zau, zbu, zcu, zav, zbv, zcv, zup, zdo            !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zbetup, zbetdo, zbup, zbdo
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zbetup, zbetdo, zbup, zbdo
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('nonosc')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zbetup, zbetdo, zbup, zbdo )
+      ALLOCATE(zbetup(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zbetdo(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zbup(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE(zbdo(1:jpi, 1:jpj, 1:jpk))
       !
       zbig  = 1.e+40_wp
@@ -675,5 +745,8 @@
       CALL lbc_lnk( paa, 'U', -1. )   ;   CALL lbc_lnk( pbb, 'V', -1. )   ! lateral boundary condition (changed sign)
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zbetup, zbetdo, zbup, zbdo )
+      DEALLOCATE(zbetup)
+      DEALLOCATE(zbetdo) 
+      DEALLOCATE(zbup)
+      DEALLOCATE(zbdo)
       !
       IF( nn_timing == 1 )  CALL timing_stop('nonosc')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_ubs.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_ubs.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_ubs.F90	(revision 9987)
@@ -177,8 +177,5 @@
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-            IF( jn == jp_tem )  htr_adv(:) = ptr_sj( ztv(:,:,:) )
-            IF( jn == jp_sal )  str_adv(:) = ptr_sj( ztv(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr ) CALL dia_ptr_ohst_components( jn, 'adv', ztv(:,:,:) )
          
          ! TVD scheme for the vertical direction  
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trabbl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trabbl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trabbl.F90	(revision 9987)
@@ -107,5 +107,5 @@
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step
       !
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrdt, ztrds
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  ztrdt, ztrds
       !!----------------------------------------------------------------------
       !
@@ -113,5 +113,6 @@
       !
       IF( l_trdtra )   THEN                         !* Save ta and sa trends
-         CALL wrk_alloc( jpi, jpj, jpk, ztrdt, ztrds )
+         ALLOCATE( ztrdt (1:jpi, 1:jpj, 1:jpk))
+         ALLOCATE( ztrds (1:jpi, 1:jpj, 1:jpk))
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
          ztrds(:,:,:) = tsa(:,:,:,jp_sal)
@@ -151,5 +152,5 @@
          CALL trd_tra( kt, 'TRA', jp_tem, jptra_bbl, ztrdt )
          CALL trd_tra( kt, 'TRA', jp_sal, jptra_bbl, ztrds )
-         CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
+         DEALLOCATE( ztrdt, ztrds )
       ENDIF
       !
@@ -187,10 +188,10 @@
       INTEGER  ::   ik           ! local integers
       REAL(wp) ::   zbtr         ! local scalars
-      REAL(wp), POINTER, DIMENSION(:,:) :: zptb
+      REAL(wp), ALLOCATABLE , DIMENSION(:,:) :: zptb
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_bbl_dif')
       !
-      CALL wrk_alloc( jpi, jpj, zptb )
+      ALLOCATE(zptb(1:jpi, 1:jpj))
       !
       DO jn = 1, kjpt                                     ! tracer loop
@@ -217,5 +218,5 @@
       END DO                                                ! end tracer
       !                                                     ! ===========
-      CALL wrk_dealloc( jpi, jpj, zptb )
+      DEALLOCATE( zptb )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_bbl_dif')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf.F90	(revision 9987)
@@ -68,4 +68,5 @@
       !
       rldf = 1     ! For active tracers the 
+      r_fact_lap(:,:,:) = 1.0
 
       IF( l_trdtra )   THEN                    !* Save ta and sa trends
@@ -214,4 +215,6 @@
       IF( ierr == 1 )   CALL ctl_stop( ' iso-level in z-coordinate - partial step, not allowed' )
       IF( ierr == 2 )   CALL ctl_stop( ' isoneutral bilaplacian operator does not exist' )
+      IF( ln_traldf_grif .AND. ln_isfcav         )   &
+           CALL ctl_stop( ' ice shelf and traldf_grif not tested')
       IF( lk_traldf_eiv .AND. .NOT.ln_traldf_iso )   &
            CALL ctl_stop( '          eddy induced velocity on tracers',   &
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilap.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilap.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilap.F90	(revision 9987)
@@ -173,8 +173,5 @@
          !                                                
          ! "zonal" mean lateral diffusive heat and salt transport
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN  
-           IF( jn == jp_tem )  htr_ldf(:) = ptr_sj( ztv(:,:,:) )
-           IF( jn == jp_sal )  str_ldf(:) = ptr_sj( ztv(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )   CALL dia_ptr_ohst_components( jn, 'ldf', ztv(:,:,:) )
          !                                                ! ===========
       END DO                                              ! tracer loop
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilapg.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilapg.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilapg.F90	(revision 9987)
@@ -247,9 +247,6 @@
          !                                                ! ===============
          ! "Poleward" diffusive heat or salt transport
-         IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( kaht == 2 ) ) THEN
-            ! note sign is reversed to give down-gradient diffusive transports (#1043)
-            IF( jn == jp_tem)   htr_ldf(:) = ptr_sj( -zftv(:,:,:) )
-            IF( jn == jp_sal)   str_ldf(:) = ptr_sj( -zftv(:,:,:) )
-         ENDIF
+        ! note sign is reversed to give down-gradient diffusive transports (#1043)
+         IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( kaht == 2 ) ) CALL dia_ptr_ohst_components( jn, 'ldf', -zftv(:,:,:) )
 
          !                             ! ************ !   ! ===============
@@ -330,7 +327,7 @@
                END DO
             ELSE
-               IF(lwp) WRITE(numout,*) ' ldfght: kaht= 1 or 2, here =', kaht
-               IF(lwp) WRITE(numout,*) '         We stop'
-               STOP 'ldfght'
+               WRITE(numout,*) ' ldfght: kaht= 1 or 2, here =', kaht
+               WRITE(numout,*) '         We stop'
+               CALL ctl_stop( 'STOP', 'ldfght : unexpected kaht value')
             ENDIF
             !                                             ! ===============
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso.F90	(revision 9987)
@@ -26,9 +26,10 @@
    USE ldfslp          ! iso-neutral slopes
    USE diaptr          ! poleward transport diagnostics
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
    USE in_out_manager  ! I/O manager
    USE iom             ! I/O library
    USE phycst          ! physical constants
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
-   USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
 
@@ -105,15 +106,29 @@
       INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
       INTEGER  ::  ikt
-      REAL(wp) ::  zmsku, zabe1, zcof1, zcoef3   ! local scalars
-      REAL(wp) ::  zmskv, zabe2, zcof2, zcoef4   !   -      -
-      REAL(wp) ::  zcoef0, zbtr, ztra            !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::  z2d
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zdkt, zdk1t, zdit, zdjt, ztfw 
+      REAL(wp) ::  zmsku, zabe1, zcof1, zcoef3       ! local scalars
+      REAL(wp) ::  zmskv, zabe2, zcof2, zcoef4       !   -      -
+      REAL(wp) ::  zcoef0, zbtr                      !   -      -
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:  ) ::  z2d
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  zdkt, zdk1t, zdit, zdjt, ztfw 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:), TARGET ::  ztrax, ztray, ztraz 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:), TARGET ::  ztrax_T, ztray_T, ztraz_T
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_ldf_iso')
       !
-      CALL wrk_alloc( jpi, jpj,      z2d ) 
-      CALL wrk_alloc( jpi, jpj, jpk, zdit, zdjt, ztfw, zdkt, zdk1t ) 
+      ALLOCATE( z2d(1:jpi, 1:jpj)) 
+      ALLOCATE( zdit(1:jpi, 1:jpj, 1:jpk))
+      ALLOCATE( zdjt(1:jpi, 1:jpj, 1:jpk)) 
+      ALLOCATE( ztfw(1:jpi, 1:jpj, 1:jpk)) 
+      ALLOCATE( zdkt(1:jpi, 1:jpj, 1:jpk)) 
+      ALLOCATE( zdk1t(1:jpi, 1:jpj, 1:jpk)) 
+      ALLOCATE( ztrax(1:jpi,1:jpj,1:jpk)) 
+      ALLOCATE( ztray(1:jpi,1:jpj,1:jpk))
+      ALLOCATE( ztraz(1:jpi,1:jpj,1:jpk) ) 
+      IF( l_trdtra .and. cdtype == 'TRA' ) THEN
+         ALLOCATE( ztrax_T(1:jpi,1:jpj,1:jpk)) 
+         ALLOCATE( ztray_T(1:jpi,1:jpj,1:jpk)) 
+         ALLOCATE( ztraz_T(1:jpi,1:jpj,1:jpk)) 
+      ENDIF
       !
 
@@ -127,4 +142,5 @@
       DO jn = 1, kjpt                                            ! tracer loop
          !                                                       ! ===========
+         ztrax(:,:,:) = 0._wp ; ztray(:,:,:) = 0._wp ; ztraz(:,:,:) = 0._wp ; 
          !                                               
          !!----------------------------------------------------------------------
@@ -226,6 +242,6 @@
                DO ji = fs_2, fs_jpim1   ! vector opt.
                   zbtr = 1.0 / ( e12t(ji,jj) * fse3t_n(ji,jj,jk) )
-                  ztra = zbtr * ( zftu(ji,jj,jk) - zftu(ji-1,jj,jk) + zftv(ji,jj,jk) - zftv(ji,jj-1,jk)  )
-                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra
+                  ztrax(ji,jj,jk) = zbtr * ( zftu(ji,jj,jk) - zftu(ji-1,jj,jk) )
+                  ztray(ji,jj,jk) = zbtr * ( zftv(ji,jj,jk) - zftv(ji,jj-1,jk) )
                END DO
             END DO
@@ -234,10 +250,9 @@
          !                                             ! ===============
          !
+         pta(:,:,:,jn) = pta(:,:,:,jn) + ztrax(:,:,:) + ztray(:,:,:)
+         !
          ! "Poleward" diffusive heat or salt transports (T-S case only)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN
             ! note sign is reversed to give down-gradient diffusive transports (#1043)
-            IF( jn == jp_tem)   htr_ldf(:) = ptr_sj( -zftv(:,:,:) )
-            IF( jn == jp_sal)   str_ldf(:) = ptr_sj( -zftv(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr ) CALL dia_ptr_ohst_components( jn, 'ldf', -zftv(:,:,:)  )
  
          IF( iom_use("udiff_heattr") .OR. iom_use("vdiff_heattr") ) THEN
@@ -314,14 +329,39 @@
                DO ji = fs_2, fs_jpim1   ! vector opt.
                   zbtr = 1.0 / ( e12t(ji,jj) * fse3t_n(ji,jj,jk) )
-                  ztra = (  ztfw(ji,jj,jk) - ztfw(ji,jj,jk+1)  ) * zbtr
-                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra
+                  ztraz(ji,jj,jk) = (  ztfw(ji,jj,jk) - ztfw(ji,jj,jk+1)  ) * zbtr
                END DO
             END DO
          END DO
+         pta(:,:,:,jn) = pta(:,:,:,jn) + ztraz(:,:,:)
          !
+         IF( l_trdtra .AND. cdtype == "TRA" .AND. jn .eq. 1 )  THEN      ! save the temperature trends
+            ztrax_T(:,:,:) = ztrax(:,:,:)
+            ztray_T(:,:,:) = ztray(:,:,:)
+            ztraz_T(:,:,:) = ztraz(:,:,:)
+         ENDIF
+         IF( l_trdtrc .AND. cdtype == "TRC" )   THEN      ! save the horizontal component of diffusive trends for further diagnostics
+            CALL trd_tra( kt, cdtype, jn, jptra_iso_x, ztrax )
+            CALL trd_tra( kt, cdtype, jn, jptra_iso_y, ztray ) 
+            CALL trd_tra( kt, cdtype, jn, jptra_iso_z1, ztraz )  ! This is the first part of the vertical component.
+         ENDIF
       END DO
       !
-      CALL wrk_dealloc( jpi, jpj, z2d ) 
-      CALL wrk_dealloc( jpi, jpj, jpk, zdit, zdjt, ztfw, zdkt, zdk1t ) 
+      IF( l_trdtra .AND. cdtype == "TRA" )   THEN      ! save the horizontal component of diffusive trends for further diagnostics
+         CALL trd_tra( kt, cdtype, jp_tem, jptra_iso_x, ztrax_T )
+         CALL trd_tra( kt, cdtype, jp_sal, jptra_iso_x, ztrax )
+         CALL trd_tra( kt, cdtype, jp_tem, jptra_iso_y, ztray_T )
+         CALL trd_tra( kt, cdtype, jp_sal, jptra_iso_y, ztray )
+         CALL trd_tra( kt, cdtype, jp_tem, jptra_iso_z1, ztraz_T )  ! This is the first part of the vertical component
+         CALL trd_tra( kt, cdtype, jp_sal, jptra_iso_z1, ztraz )    !
+      ENDIF
+      !
+      DEALLOCATE( z2d ) 
+      DEALLOCATE( zdit) 
+      DEALLOCATE( zdjt)
+      DEALLOCATE( ztfw) 
+      DEALLOCATE( zdkt )
+      DEALLOCATE( zdk1t ) 
+      DEALLOCATE( ztrax, ztray, ztraz ) 
+      IF( l_trdtra  .and. cdtype == 'TRA' ) DEALLOCATE( ztrax_T, ztray_T, ztraz_T ) 
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_ldf_iso')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso_grif.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso_grif.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso_grif.F90	(revision 9987)
@@ -386,8 +386,5 @@
          !
          !                             ! "Poleward" diffusive heat or salt transports (T-S case only)
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN
-            IF( jn == jp_tem)   htr_ldf(:) = ptr_sj( zftv(:,:,:) )        ! 3.3  names
-            IF( jn == jp_sal)   str_ldf(:) = ptr_sj( zftv(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )  CALL dia_ptr_ohst_components( jn, 'ldf', zftv(:,:,:) )
 
          IF( iom_use("udiff_heattr") .OR. iom_use("vdiff_heattr") ) THEN
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_lap.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_lap.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_lap.F90	(revision 9987)
@@ -154,8 +154,5 @@
          !
          ! "Poleward" diffusive heat or salt transports
-         IF( cdtype == 'TRA' .AND. ln_diaptr ) THEN
-            IF( jn  == jp_tem)   htr_ldf(:) = ptr_sj( ztv(:,:,:) )
-            IF( jn  == jp_sal)   str_ldf(:) = ptr_sj( ztv(:,:,:) )
-         ENDIF
+         IF( cdtype == 'TRA' .AND. ln_diaptr )    CALL dia_ptr_ohst_components( jn, 'ldf', ztv(:,:,:) )
          !                                                  ! ==================
       END DO                                                ! end of tracer loop
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/tranxt.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/tranxt.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/tranxt.F90	(revision 9987)
@@ -28,4 +28,5 @@
    USE sbc_oce         ! surface boundary condition: ocean
    USE sbcrnf          ! river runoffs
+   USE sbcisf          ! ice shelf melting/freezing
    USE zdf_oce         ! ocean vertical mixing
    USE domvvl          ! variable volume
@@ -46,5 +47,4 @@
    USE timing          ! Timing
 #if defined key_agrif
-   USE agrif_opa_update
    USE agrif_opa_interp
 #endif
@@ -110,4 +110,8 @@
       ! Update after tracer on domain lateral boundaries
       ! 
+#if defined key_agrif
+      CALL Agrif_tra                     ! AGRIF zoom boundaries
+#endif
+      !
       CALL lbc_lnk( tsa(:,:,:,jp_tem), 'T', 1._wp )      ! local domain boundaries  (T-point, unchanged sign)
       CALL lbc_lnk( tsa(:,:,:,jp_sal), 'T', 1._wp )
@@ -115,7 +119,4 @@
 #if defined key_bdy 
       IF( lk_bdy )   CALL bdy_tra( kt )  ! BDY open boundaries
-#endif
-#if defined key_agrif
-      CALL Agrif_tra                     ! AGRIF zoom boundaries
 #endif
  
@@ -126,12 +127,35 @@
 
       ! trends computation initialisation
-      IF( l_trdtra )   THEN                    ! store now fields before applying the Asselin filter
+      IF( l_trdtra )   THEN                    
          CALL wrk_alloc( jpi, jpj, jpk, ztrdt, ztrds )
-         ztrdt(:,:,:) = tsn(:,:,:,jp_tem) 
-         ztrds(:,:,:) = tsn(:,:,:,jp_sal)
+         ztrdt(:,:,jpk) = 0._wp
+         ztrds(:,:,jpk) = 0._wp
          IF( ln_traldf_iso ) THEN              ! diagnose the "pure" Kz diffusive trend 
             CALL trd_tra( kt, 'TRA', jp_tem, jptra_zdfp, ztrdt )
             CALL trd_tra( kt, 'TRA', jp_sal, jptra_zdfp, ztrds )
          ENDIF
+         ! total trend for the non-time-filtered variables.
+         ! G Nurser 23 Mar 2017. Recalculate trend as Delta(e3t*T)/e3tn; e3tn cancel from tsn terms
+         IF( lk_vvl ) THEN
+            DO jk = 1, jpkm1
+               zfact = 1.0 / rdttra(jk)
+               ztrdt(:,:,jk) = ( tsa(:,:,jk,jp_tem)*fse3t_a(:,:,jk) / fse3t_n(:,:,jk) - tsn(:,:,jk,jp_tem)) * zfact
+               ztrds(:,:,jk) = ( tsa(:,:,jk,jp_sal)*fse3t_a(:,:,jk) / fse3t_n(:,:,jk) - tsn(:,:,jk,jp_sal)) * zfact
+            END DO
+         ELSE
+            DO jk = 1, jpkm1
+               zfact = 1.0 / rdttra(jk)
+               ztrdt(:,:,jk) = ( tsa(:,:,jk,jp_tem) - tsn(:,:,jk,jp_tem) ) * zfact 
+               ztrds(:,:,jk) = ( tsa(:,:,jk,jp_sal) - tsn(:,:,jk,jp_sal) ) * zfact 
+            END DO
+         END IF
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_tot, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_tot, ztrds )
+         IF( .NOT.lk_vvl )  THEN
+            ! Store now fields before applying the Asselin filter 
+            ! in order to calculate Asselin filter trend later.
+            ztrdt(:,:,:) = tsn(:,:,:,jp_tem) 
+            ztrds(:,:,:) = tsn(:,:,:,jp_sal)
+         END IF
       ENDIF
 
@@ -142,4 +166,11 @@
             END DO
          END DO
+         IF (l_trdtra.AND.lk_vvl) THEN      ! Zero Asselin filter contribution must be explicitly written out since for vvl
+                                            ! Asselin filter is output by tra_nxt_vvl that is not called on this time step
+            ztrdt(:,:,:) = 0._wp
+            ztrds(:,:,:) = 0._wp
+            CALL trd_tra( kt, 'TRA', jp_tem, jptra_atf, ztrdt )
+            CALL trd_tra( kt, 'TRA', jp_sal, jptra_atf, ztrds )
+         END IF
       ELSE                                            ! Leap-Frog + Asselin filter time stepping
          !
@@ -148,13 +179,8 @@
          ELSE                 ;   CALL tra_nxt_fix( kt, nit000,         'TRA', tsb, tsn, tsa, jpts )  ! fixed    volume level 
          ENDIF
-      ENDIF 
-      !
-#if defined key_agrif
-      ! Update tracer at AGRIF zoom boundaries
-      IF( .NOT.Agrif_Root() )    CALL Agrif_Update_Tra( kt )      ! children only
-#endif      
-      !
-      ! trends computation
-      IF( l_trdtra ) THEN      ! trend of the Asselin filter (tb filtered - tb)/dt     
+      ENDIF     
+      !
+     ! trends computation
+      IF( l_trdtra.AND..NOT.lk_vvl) THEN      ! trend of the Asselin filter (tb filtered - tb)/dt     
          DO jk = 1, jpkm1
             zfact = 1._wp / r2dtra(jk)             
@@ -164,6 +190,6 @@
          CALL trd_tra( kt, 'TRA', jp_tem, jptra_atf, ztrdt )
          CALL trd_tra( kt, 'TRA', jp_sal, jptra_atf, ztrds )
-         CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
       END IF
+      IF( l_trdtra) CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
       !
       !                        ! control print
@@ -279,8 +305,9 @@
 
       !!     
-      LOGICAL  ::   ll_tra_hpg, ll_traqsr, ll_rnf   ! local logical
+      LOGICAL  ::   ll_tra_hpg, ll_traqsr, ll_rnf, ll_isf   ! local logical
       INTEGER  ::   ji, jj, jk, jn              ! dummy loop indices
-      REAL(wp) ::   zfact1, ztc_a , ztc_n , ztc_b , ztc_f , ztc_d    ! local scalar
+      REAL(wp) ::   zfact, zfact1, ztc_a , ztc_n , ztc_b , ztc_f , ztc_d    ! local scalar
       REAL(wp) ::   zfact2, ze3t_b, ze3t_n, ze3t_a, ze3t_f, ze3t_d   !   -      -
+      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztrd_atf
       !!----------------------------------------------------------------------
       !
@@ -295,12 +322,23 @@
          ll_traqsr  = ln_traqsr        ! active  tracers case  and  solar penetration
          ll_rnf     = ln_rnf           ! active  tracers case  and  river runoffs
+         IF (nn_isf .GE. 1) THEN 
+            ll_isf = .TRUE.            ! active  tracers case  and  ice shelf melting/freezing
+         ELSE
+            ll_isf = .FALSE.
+         END IF
       ELSE                          
          ll_tra_hpg = .FALSE.          ! passive tracers case or NO semi-implicit hpg
          ll_traqsr  = .FALSE.          ! active  tracers case and NO solar penetration
          ll_rnf     = .FALSE.          ! passive tracers or NO river runoffs
-      ENDIF
-      !
+         ll_isf     = .FALSE.          ! passive tracers or NO ice shelf melting/freezing
+      ENDIF
+      !
+      IF( ( l_trdtra .and. cdtype == 'TRA' ) .OR. ( l_trdtrc .and. cdtype == 'TRC' ) )   THEN
+         CALL wrk_alloc( jpi, jpj, jpk, kjpt, ztrd_atf )
+         ztrd_atf(:,:,:,:) = 0.0_wp
+      ENDIF
       DO jn = 1, kjpt      
          DO jk = 1, jpkm1
+            zfact = 1._wp / r2dtra(jk)
             zfact1 = atfp * p2dt(jk)
             zfact2 = zfact1 / rau0
@@ -321,15 +359,31 @@
                   ztc_f  = ztc_n  + atfp * ztc_d
                   !
-                  IF( jk == 1 ) THEN           ! first level 
-                     ze3t_f = ze3t_f - zfact2 * ( emp_b(ji,jj) - emp(ji,jj) + rnf(ji,jj) - rnf_b(ji,jj) )
+                  IF( jk == mikt(ji,jj) ) THEN           ! first level 
+                     ze3t_f = ze3t_f - zfact2 * ( (emp_b(ji,jj)    - emp(ji,jj)   )  &
+                            &                   - (rnf_b(ji,jj)    - rnf(ji,jj)   )  &
+                            &                   + (fwfisf_b(ji,jj) - fwfisf(ji,jj))  )
                      ztc_f  = ztc_f  - zfact1 * ( psbc_tc(ji,jj,jn) - psbc_tc_b(ji,jj,jn) )
                   ENDIF
 
-                  IF( ll_traqsr .AND. jn == jp_tem .AND. jk <= nksr )   &     ! solar penetration (temperature only)
+                  ! solar penetration (temperature only)
+                  IF( ll_traqsr .AND. jn == jp_tem .AND. jk <= nksr )                            & 
                      &     ztc_f  = ztc_f  - zfact1 * ( qsr_hc(ji,jj,jk) - qsr_hc_b(ji,jj,jk) ) 
 
-                  IF( ll_rnf .AND. jk <= nk_rnf(ji,jj) )   & 		      ! river runoffs
+                  ! river runoff
+                  IF( ll_rnf .AND. jk <= nk_rnf(ji,jj) )                                          &
                      &     ztc_f  = ztc_f  - zfact1 * ( rnf_tsc(ji,jj,jn) - rnf_tsc_b(ji,jj,jn) ) & 
                      &                              * fse3t_n(ji,jj,jk) / h_rnf(ji,jj)
+
+                  ! ice shelf
+                  IF( ll_isf ) THEN
+                     ! level fully include in the Losch_2008 ice shelf boundary layer
+                     IF ( jk >= misfkt(ji,jj) .AND. jk < misfkb(ji,jj) )                          &
+                        ztc_f  = ztc_f  - zfact1 * ( risf_tsc(ji,jj,jn) - risf_tsc_b(ji,jj,jn) )  &
+                               &                 * fse3t_n(ji,jj,jk) * r1_hisf_tbl (ji,jj)
+                     ! level partially include in Losch_2008 ice shelf boundary layer 
+                     IF ( jk == misfkb(ji,jj) )                                                   &
+                        ztc_f  = ztc_f  - zfact1 * ( risf_tsc(ji,jj,jn) - risf_tsc_b(ji,jj,jn) )  &
+                               &                 * fse3t_n(ji,jj,jk) * r1_hisf_tbl (ji,jj) * ralpha(ji,jj)
+                  END IF
 
                   ze3t_f = 1.e0 / ze3t_f
@@ -340,4 +394,7 @@
                      ze3t_d           = 1.e0   / ( ze3t_n + rbcp * ze3t_d )
                      pta(ji,jj,jk,jn) = ze3t_d * ( ztc_n  + rbcp * ztc_d  )   ! ta <-- Brown & Campana average
+                  ENDIF
+                  IF( ( l_trdtra .and. cdtype == 'TRA' ) .OR. ( l_trdtrc .and. cdtype == 'TRC' ) ) THEN
+                     ztrd_atf(ji,jj,jk,jn) = (ztc_f - ztc_n) * zfact/ze3t_n
                   ENDIF
                END DO
@@ -347,4 +404,16 @@
       END DO
       !
+      IF( l_trdtra .and. cdtype == 'TRA' ) THEN 
+         CALL trd_tra( kt, cdtype, jp_tem, jptra_atf, ztrd_atf(:,:,:,jp_tem) )
+         CALL trd_tra( kt, cdtype, jp_sal, jptra_atf, ztrd_atf(:,:,:,jp_sal) )
+         CALL wrk_dealloc( jpi, jpj, jpk, kjpt, ztrd_atf )
+      ENDIF
+      IF( l_trdtrc .and. cdtype == 'TRC' ) THEN
+         DO jn = 1, kjpt
+            CALL trd_tra( kt, cdtype, jn, jptra_atf, ztrd_atf(:,:,:,jn) )
+         END DO
+         CALL wrk_dealloc( jpi, jpj, jpk, kjpt, ztrd_atf )
+      ENDIF
+
    END SUBROUTINE tra_nxt_vvl
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traqsr.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traqsr.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/traqsr.F90	(revision 9987)
@@ -10,5 +10,6 @@
    !!             -   !  2005-11  (G. Madec) zco, zps, sco coordinate
    !!            3.2  !  2009-04  (G. Madec & NEMO team) 
-   !!            4.0  !  2012-05  (C. Rousset) store attenuation coef for use in ice model 
+   !!            3.4  !  2012-05  (C. Rousset) store attenuation coef for use in ice model 
+   !!            3.6  !  2015-12  (O. Aumont, J. Jouanno, C. Ethe) use vertical profile of chlorophyll
    !!----------------------------------------------------------------------
 
@@ -93,4 +94,5 @@
       !! Reference  : Jerlov, N. G., 1968 Optical Oceanography, Elsevier, 194pp.
       !!              Lengaigne et al. 2007, Clim. Dyn., V28, 5, 503-516.
+      !!              Morel, A. et Berthon, JF, 1989, Limnol Oceanogr 34(8), 1545-1562
       !!----------------------------------------------------------------------
       !
@@ -101,14 +103,15 @@
       REAL(wp) ::   zchl, zcoef, zfact   ! local scalars
       REAL(wp) ::   zc0, zc1, zc2, zc3   !    -         -
-      REAL(wp) ::   zzc0, zzc1, zzc2, zzc3   !    -         -
       REAL(wp) ::   zz0, zz1, z1_e3t     !    -         -
+      REAL(wp) ::   zCb, zCmax, zze, zpsi, zpsimax, zdelpsi, zCtot, zCze
+      REAL(wp) ::   zlogc, zlogc2, zlogc3 
       REAL(wp), POINTER, DIMENSION(:,:  ) :: zekb, zekg, zekr
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ze0, ze1, ze2, ze3, zea, ztrdt
-      !!----------------------------------------------------------------------
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: ze0, ze1, ze2, ze3, zea, ztrdt, zchl3d
+      !!--------------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_qsr')
       !
       CALL wrk_alloc( jpi, jpj,      zekb, zekg, zekr        ) 
-      CALL wrk_alloc( jpi, jpj, jpk, ze0, ze1, ze2, ze3, zea ) 
+      CALL wrk_alloc( jpi, jpj, jpk, ze0, ze1, ze2, ze3, zea, zchl3d ) 
       !
       IF( kt == nit000 ) THEN
@@ -183,31 +186,47 @@
             !                                             ! ------------------------- !
             ! Set chlorophyl concentration
-            IF( nn_chldta == 1 .OR. lk_vvl ) THEN            !*  Variable Chlorophyll or ocean volume
-               !
-               IF( nn_chldta == 1 ) THEN                             !*  Variable Chlorophyll
-                  !
-                  CALL fld_read( kt, 1, sf_chl )                         ! Read Chl data and provides it at the current time step
-                  !         
-!CDIR COLLAPSE
+            IF( nn_chldta == 1 .OR. nn_chldta == 2 .OR. lk_vvl ) THEN    !*  Variable Chlorophyll or ocean volume
+               !
+               IF( nn_chldta == 1 ) THEN        !*  2D Variable Chlorophyll
+                  !
+                  CALL fld_read( kt, 1, sf_chl )            ! Read Chl data and provides it at the current time step
+                  DO jk = 1, nksr + 1
+                     zchl3d(:,:,jk) = sf_chl(1)%fnow(:,:,1) 
+                  ENDDO
+                  !
+               ELSE IF( nn_chldta == 2 ) THEN    !*   -3-D Variable Chlorophyll
+                  !
+                  CALL fld_read( kt, 1, sf_chl )            ! Read Chl data and provides it at the current time step
+!CDIR NOVERRCHK   !
+                  DO jj = 1, jpj
 !CDIR NOVERRCHK
-                  DO jj = 1, jpj                                         ! Separation in R-G-B depending of the surface Chl
-!CDIR NOVERRCHK
-                     DO ji = 1, jpi
-                        zchl = MIN( 10. , MAX( 0.03, sf_chl(1)%fnow(ji,jj,1) ) )
-                        irgb = NINT( 41 + 20.*LOG10(zchl) + 1.e-15 )
-                        zekb(ji,jj) = rkrgb(1,irgb)
-                        zekg(ji,jj) = rkrgb(2,irgb)
-                        zekr(ji,jj) = rkrgb(3,irgb)
-                     END DO
-                  END DO
-               ELSE                                            ! Variable ocean volume but constant chrlorophyll
-                  zchl = 0.05                                     ! constant chlorophyll
-                  irgb = NINT( 41 + 20.*LOG10( zchl ) + 1.e-15 )
-                  zekb(:,:) = rkrgb(1,irgb)                       ! Separation in R-G-B depending of the chlorophyll 
-                  zekg(:,:) = rkrgb(2,irgb)
-                  zekr(:,:) = rkrgb(3,irgb)
+                     DO ji = 1, jpi
+                        zchl    = sf_chl(1)%fnow(ji,jj,1)
+                        zCtot   = 40.6  * zchl**0.459
+                        zze     = 568.2 * zCtot**(-0.746)
+                        IF( zze > 102. ) zze = 200.0 * zCtot**(-0.293)
+                        zlogc   = LOG( zchl )
+                        zlogc2  = zlogc * zlogc
+                        zlogc3  = zlogc * zlogc * zlogc
+                        zCb     = 0.768 + 0.087 * zlogc - 0.179 * zlogc2 - 0.025 * zlogc3
+                        zCmax   = 0.299 - 0.289 * zlogc + 0.579 * zlogc2
+                        zpsimax = 0.6   - 0.640 * zlogc + 0.021 * zlogc2 + 0.115 * zlogc3
+                        zdelpsi = 0.710 + 0.159 * zlogc + 0.021 * zlogc2
+                        zCze    = 1.12  * (zchl)**0.803 
+                        DO jk = 1, nksr + 1
+                           zpsi = fsdept(ji,jj,jk) / zze
+                           zchl3d(ji,jj,jk) = zCze * ( zCb + zCmax * EXP( -( (zpsi - zpsimax) / zdelpsi )**2 ) )
+                        END DO
+                        !
+                      END DO
+                   END DO
+                     !
+               ELSE                              !* Variable ocean volume but constant chrlorophyll
+                  DO jk = 1, nksr + 1
+                     zchl3d(:,:,jk) = 0.05 
+                  ENDDO
                ENDIF
                !
-               zcoef  = ( 1. - rn_abs ) / 3.e0                        ! equi-partition in R-G-B
+               zcoef  = ( 1. - rn_abs ) / 3.e0                        !  equi-partition in R-G-B
                ze0(:,:,1) = rn_abs  * qsr(:,:)
                ze1(:,:,1) = zcoef * qsr(:,:)
@@ -217,4 +236,15 @@
                !
                DO jk = 2, nksr+1
+                  !
+                  DO jj = 1, jpj                                         ! Separation in R-G-B depending of vertical profile of Chl
+!CDIR NOVERRCHK
+                     DO ji = 1, jpi
+                        zchl = MIN( 10. , MAX( 0.03, zchl3d(ji,jj,jk) ) )
+                        irgb = NINT( 41 + 20.*LOG10(zchl) + 1.e-15 )
+                        zekb(ji,jj) = rkrgb(1,irgb)
+                        zekg(ji,jj) = rkrgb(2,irgb)
+                        zekr(ji,jj) = rkrgb(3,irgb)
+                     END DO
+                  END DO
 !CDIR NOVERRCHK
                   DO jj = 1, jpj
@@ -233,16 +263,4 @@
                   END DO
                END DO
-               ! clem: store attenuation coefficient of the first ocean level
-               IF ( ln_qsr_ice ) THEN
-                  DO jj = 1, jpj
-                     DO ji = 1, jpi
-                        zzc0 = rn_abs * EXP( - fse3t(ji,jj,1) * xsi0r     )
-                        zzc1 = zcoef  * EXP( - fse3t(ji,jj,1) * zekb(ji,jj) )
-                        zzc2 = zcoef  * EXP( - fse3t(ji,jj,1) * zekg(ji,jj) )
-                        zzc3 = zcoef  * EXP( - fse3t(ji,jj,1) * zekr(ji,jj) )
-                        fraqsr_1lev(ji,jj) = 1.0 - ( zzc0 + zzc1 + zzc2  + zzc3  ) * tmask(ji,jj,2) 
-                     END DO
-                  END DO
-               ENDIF
                !
                DO jk = 1, nksr                                        ! compute and add qsr trend to ta
@@ -251,4 +269,29 @@
                zea(:,:,nksr+1:jpk) = 0.e0     ! below 400m set to zero
                CALL iom_put( 'qsr3d', zea )   ! Shortwave Radiation 3D distribution
+               !
+               IF ( ln_qsr_ice ) THEN    ! store attenuation coefficient of the first ocean level
+!CDIR NOVERRCHK
+                  DO jj = 1, jpj                                         ! Separation in R-G-B depending of the surface Chl
+!CDIR NOVERRCHK
+                     DO ji = 1, jpi
+                        zchl = MIN( 10. , MAX( 0.03, zchl3d(ji,jj,1) ) )
+                        irgb = NINT( 41 + 20.*LOG10(zchl) + 1.e-15 )
+                        zekb(ji,jj) = rkrgb(1,irgb)
+                        zekg(ji,jj) = rkrgb(2,irgb)
+                        zekr(ji,jj) = rkrgb(3,irgb)
+                     END DO
+                  END DO
+                  ! 
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi
+                        zc0 = rn_abs * EXP( - fse3t(ji,jj,1) * xsi0r     )
+                        zc1 = zcoef  * EXP( - fse3t(ji,jj,1) * zekb(ji,jj) )
+                        zc2 = zcoef  * EXP( - fse3t(ji,jj,1) * zekg(ji,jj) )
+                        zc3 = zcoef  * EXP( - fse3t(ji,jj,1) * zekr(ji,jj) )
+                        fraqsr_1lev(ji,jj) = 1.0 - ( zc0 + zc1 + zc2  + zc3  ) * tmask(ji,jj,2) 
+                     END DO
+                  END DO
+                  !
+               ENDIF
                !
             ELSE                                                 !*  Constant Chlorophyll
@@ -256,6 +299,6 @@
                   qsr_hc(:,:,jk) =  etot3(:,:,jk) * qsr(:,:)
                END DO
-               ! clem: store attenuation coefficient of the first ocean level
-               IF ( ln_qsr_ice ) THEN
+               !  store attenuation coefficient of the first ocean level
+               IF( ln_qsr_ice ) THEN
                   fraqsr_1lev(:,:) = etot3(:,:,1) / r1_rau0_rcp
                ENDIF
@@ -339,5 +382,5 @@
       !
       CALL wrk_dealloc( jpi, jpj,      zekb, zekg, zekr        ) 
-      CALL wrk_dealloc( jpi, jpj, jpk, ze0, ze1, ze2, ze3, zea ) 
+      CALL wrk_dealloc( jpi, jpj, jpk, ze0, ze1, ze2, ze3, zea, zchl3d ) 
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_qsr')
@@ -405,5 +448,5 @@
          WRITE(numout,*) '      bio-model            light penetration   ln_qsr_bio = ', ln_qsr_bio
          WRITE(numout,*) '      light penetration for ice-model LIM3     ln_qsr_ice = ', ln_qsr_ice
-         WRITE(numout,*) '      RGB : Chl data (=1) or cst value (=0)    nn_chldta  = ', nn_chldta
+         WRITE(numout,*) '      RGB : Chl data (=1/2) or cst value (=0)  nn_chldta  = ', nn_chldta
          WRITE(numout,*) '      RGB & 2 bands: fraction of light (rn_si1)    rn_abs = ', rn_abs
          WRITE(numout,*) '      RGB & 2 bands: shortess depth of extinction  rn_si0 = ', rn_si0
@@ -429,13 +472,15 @@
          IF( ln_qsr_rgb .AND. nn_chldta == 0 )   nqsr =  1 
          IF( ln_qsr_rgb .AND. nn_chldta == 1 )   nqsr =  2
-         IF( ln_qsr_2bd                      )   nqsr =  3
-         IF( ln_qsr_bio                      )   nqsr =  4
+         IF( ln_qsr_rgb .AND. nn_chldta == 2 )   nqsr =  3
+         IF( ln_qsr_2bd                      )   nqsr =  4
+         IF( ln_qsr_bio                      )   nqsr =  5
          !
          IF(lwp) THEN                   ! Print the choice
             WRITE(numout,*)
             IF( nqsr ==  1 )   WRITE(numout,*) '         R-G-B   light penetration - Constant Chlorophyll'
-            IF( nqsr ==  2 )   WRITE(numout,*) '         R-G-B   light penetration - Chl data '
-            IF( nqsr ==  3 )   WRITE(numout,*) '         2 bands light penetration'
-            IF( nqsr ==  4 )   WRITE(numout,*) '         bio-model light penetration'
+            IF( nqsr ==  2 )   WRITE(numout,*) '         R-G-B   light penetration - 2D Chl data '
+            IF( nqsr ==  3 )   WRITE(numout,*) '         R-G-B   light penetration - 3D Chl data '
+            IF( nqsr ==  4 )   WRITE(numout,*) '         2 bands light penetration'
+            IF( nqsr ==  5 )   WRITE(numout,*) '         bio-model light penetration'
          ENDIF
          !
@@ -460,5 +505,5 @@
             IF(lwp) WRITE(numout,*) '        level of light extinction = ', nksr, ' ref depth = ', gdepw_1d(nksr+1), ' m'
             !
-            IF( nn_chldta == 1 ) THEN           !* Chl data : set sf_chl structure
+            IF( nn_chldta == 1  .OR. nn_chldta == 2 ) THEN           !* Chl data : set sf_chl structure
                IF(lwp) WRITE(numout,*)
                IF(lwp) WRITE(numout,*) '        Chlorophyll read in a file'
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trasbc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trasbc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trasbc.F90	(revision 9987)
@@ -33,4 +33,7 @@
    USE timing          ! Timing
    USE eosbn2
+#if defined key_asminc   
+   USE asminc          ! Assimilation increment
+#endif
 
    IMPLICIT NONE
@@ -159,4 +162,5 @@
          ELSE                                         ! No restart or restart not found: Euler forward time stepping
             zfact = 1._wp
+            sbc_tsc(:,:,:) = 0._wp
             sbc_tsc_b(:,:,:) = 0._wp
          ENDIF
@@ -232,11 +236,7 @@
                DO jk = ikt, ikb - 1
                ! compute tfreez for the temperature correction (we add water at freezing temperature)
-!                  zpress = grav*rau0*fsdept(ji,jj,jk)*1.e-04
-                  zt_frz = -1.9 !eos_fzp( tsn(ji,jj,jk,jp_sal), zpress )
                ! compute trend
                   tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)                                          &
-                     &           + zfact * (risf_tsc_b(ji,jj,jp_tem) + risf_tsc(ji,jj,jp_tem)          &
-                     &               - rdivisf * (fwfisf(ji,jj) + fwfisf_b(ji,jj)) * zt_frz * r1_rau0) &
-                     &           * r1_hisf_tbl(ji,jj)
+                     &           + zfact * (risf_tsc_b(ji,jj,jp_tem) + risf_tsc(ji,jj,jp_tem)) * r1_hisf_tbl(ji,jj)
                   tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal)                                          &
                      &           + zfact * (risf_tsc_b(ji,jj,jp_sal) + risf_tsc(ji,jj,jp_sal)) * r1_hisf_tbl(ji,jj)
@@ -245,11 +245,7 @@
                ! level partially include in ice shelf boundary layer 
                ! compute tfreez for the temperature correction (we add water at freezing temperature)
-!               zpress = grav*rau0*fsdept(ji,jj,ikb)*1.e-04
-               zt_frz = -1.9 !eos_fzp( tsn(ji,jj,ikb,jp_sal), zpress )
                ! compute trend
                tsa(ji,jj,ikb,jp_tem) = tsa(ji,jj,ikb,jp_tem)                                           &
-                  &              + zfact * (risf_tsc_b(ji,jj,jp_tem) + risf_tsc(ji,jj,jp_tem)          &
-                  &                  - rdivisf * (fwfisf(ji,jj) + fwfisf_b(ji,jj)) * zt_frz * r1_rau0) & 
-                  &              * r1_hisf_tbl(ji,jj) * ralpha(ji,jj)
+                  &              + zfact * (risf_tsc_b(ji,jj,jp_tem) + risf_tsc(ji,jj,jp_tem)) * r1_hisf_tbl(ji,jj) * ralpha(ji,jj)
                tsa(ji,jj,ikb,jp_sal) = tsa(ji,jj,ikb,jp_sal)                                           &
                   &              + zfact * (risf_tsc_b(ji,jj,jp_sal) + risf_tsc(ji,jj,jp_sal)) * r1_hisf_tbl(ji,jj) * ralpha(ji,jj) 
@@ -287,4 +283,26 @@
          END DO  
       ENDIF
+
+      IF( iom_use('rnf_x_sst') )   CALL iom_put( "rnf_x_sst", rnf*tsn(:,:,1,jp_tem) )   ! runoff term on sst
+      IF( iom_use('rnf_x_sss') )   CALL iom_put( "rnf_x_sss", rnf*tsn(:,:,1,jp_sal) )   ! runoff term on sss
+
+#if defined key_asminc
+! WARNING: THIS MAY WELL NOT BE REQUIRED - WE DON'T WANT TO CHANGE T&S BUT THIS MAY COMPENSATE ANOTHER TERM...
+! Rate of change in e3t for each level is ssh_iau*e3t_0/ht_0
+! Contribution to tsa should be rate of change in level / per m of ocean? (hence the division by fse3t_n)
+      IF( ln_sshinc ) THEN         ! input of heat and salt due to assimilation
+         DO jj = 2, jpj 
+            DO ji = fs_2, fs_jpim1
+               zdep = ssh_iau(ji,jj) / ( ht_0(ji,jj) + 1.0 - ssmask(ji, jj) )
+               DO jk = 1, jpkm1
+                  tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)   &
+                                        &            + tsn(ji,jj,jk,jp_tem) * zdep * ( e3t_0(ji,jj,jk) / fse3t_n(ji,jj,jk) )
+                  tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal)   &
+                                        &            + tsn(ji,jj,jk,jp_sal) * zdep * ( e3t_0(ji,jj,jk) / fse3t_n(ji,jj,jk) )
+               END DO
+            END DO  
+         END DO  
+      ENDIF
+#endif
  
       IF( l_trdtra )   THEN                      ! send trends for further diagnostics
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf.F90	(revision 9987)
@@ -94,8 +94,18 @@
 
       IF( l_trdtra )   THEN                      ! save the vertical diffusive trends for further diagnostics
-         DO jk = 1, jpkm1
-            ztrdt(:,:,jk) = ( ( tsa(:,:,jk,jp_tem) - tsb(:,:,jk,jp_tem) ) / r2dtra(jk) ) - ztrdt(:,:,jk)
-            ztrds(:,:,jk) = ( ( tsa(:,:,jk,jp_sal) - tsb(:,:,jk,jp_sal) ) / r2dtra(jk) ) - ztrds(:,:,jk)
-         END DO
+         ! G Nurser 23 Mar 2017. Recalculate trend as Delta(e3t*T)/e3tn.
+         IF( lk_vvl ) THEN
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = ( ( tsa(:,:,jk,jp_tem)*fse3t_a(:,:,jk) - tsb(:,:,jk,jp_tem)*fse3t_b(:,:,jk) ) &
+                    & / (fse3t_n(:,:,jk)*r2dtra(jk)) ) - ztrdt(:,:,jk)
+               ztrds(:,:,jk) = ( ( tsa(:,:,jk,jp_sal)*fse3t_a(:,:,jk) - tsb(:,:,jk,jp_sal)*fse3t_b(:,:,jk) ) &
+                    & / (fse3t_n(:,:,jk)*r2dtra(jk)) ) - ztrds(:,:,jk)
+            END DO
+         ELSE
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = ( ( tsa(:,:,jk,jp_tem) - tsb(:,:,jk,jp_tem) ) / r2dtra(jk) ) - ztrdt(:,:,jk)
+               ztrds(:,:,jk) = ( ( tsa(:,:,jk,jp_sal) - tsb(:,:,jk,jp_sal) ) / r2dtra(jk) ) - ztrds(:,:,jk)
+            END DO
+         END IF
          CALL lbc_lnk( ztrdt, 'T', 1. )
          CALL lbc_lnk( ztrds, 'T', 1. )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trd_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trd_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trd_oce.F90	(revision 9987)
@@ -33,5 +33,5 @@
 # endif
    !                                                  !!!* Active tracers trends indexes
-   INTEGER, PUBLIC, PARAMETER ::   jptot_tra  = 14     !: Total trend nb: change it when adding/removing one indice below
+   INTEGER, PUBLIC, PARAMETER ::   jptot_tra  = 20     !: Total trend nb: change it when adding/removing one indice below
    !                               ===============     !  
    INTEGER, PUBLIC, PARAMETER ::   jptra_xad  =  1     !: x- horizontal advection
@@ -39,22 +39,28 @@
    INTEGER, PUBLIC, PARAMETER ::   jptra_zad  =  3     !: z- vertical   advection
    INTEGER, PUBLIC, PARAMETER ::   jptra_sad  =  4     !: z- vertical   advection
-   INTEGER, PUBLIC, PARAMETER ::   jptra_ldf  =  5     !: lateral       diffusion
-   INTEGER, PUBLIC, PARAMETER ::   jptra_zdf  =  6     !: vertical      diffusion
-   INTEGER, PUBLIC, PARAMETER ::   jptra_zdfp =  7     !: "PURE" vert.  diffusion (ln_traldf_iso=T)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_bbc  =  8     !: Bottom Boundary Condition (geoth. heating) 
-   INTEGER, PUBLIC, PARAMETER ::   jptra_bbl  =  9     !: Bottom Boundary Layer (diffusive and/or advective)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_npc  = 10     !: non-penetrative convection treatment
-   INTEGER, PUBLIC, PARAMETER ::   jptra_dmp  = 11     !: internal restoring (damping)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_qsr  = 12     !: penetrative solar radiation
-   INTEGER, PUBLIC, PARAMETER ::   jptra_nsr  = 13     !: non solar radiation / C/D on salinity  (+runoff if ln_rnf=T)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_atf  = 14     !: Asselin time filter
+   INTEGER, PUBLIC, PARAMETER ::   jptra_totad  =  5   !: total         advection
+   INTEGER, PUBLIC, PARAMETER ::   jptra_ldf  =  6     !: lateral       diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_iso_x  =  7   !: x-component of isopycnal diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_iso_y  =  8   !: y-component of isopycnal diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_iso_z1 =  9   !: z-component of isopycnal diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zdf  = 10     !: vertical      diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zdfp = 11     !: "PURE" vert.  diffusion (ln_traldf_iso=T)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_evd  = 12     !: EVD term (convection)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_bbc  = 13     !: Bottom Boundary Condition (geoth. heating) 
+   INTEGER, PUBLIC, PARAMETER ::   jptra_bbl  = 14     !: Bottom Boundary Layer (diffusive and/or advective)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_npc  = 15     !: non-penetrative convection treatment
+   INTEGER, PUBLIC, PARAMETER ::   jptra_dmp  = 16     !: internal restoring (damping)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_qsr  = 17     !: penetrative solar radiation
+   INTEGER, PUBLIC, PARAMETER ::   jptra_nsr  = 18     !: non solar radiation / C/D on salinity  (+runoff if ln_rnf=T)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_atf  = 19     !: Asselin time filter
+   INTEGER, PUBLIC, PARAMETER ::   jptra_tot  = 20     !: Model total trend
    !
    !                                                  !!!* Passive tracers trends indices (use if "key_top" defined)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_sms  = 15     !: sources m. sinks
-   INTEGER, PUBLIC, PARAMETER ::   jptra_radn = 16     !: corr. trn<0 in trcrad
-   INTEGER, PUBLIC, PARAMETER ::   jptra_radb = 17     !: corr. trb<0 in trcrad (like atf)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_sms  = 19     !: sources m. sinks
+   INTEGER, PUBLIC, PARAMETER ::   jptra_radn = 20     !: corr. trn<0 in trcrad
+   INTEGER, PUBLIC, PARAMETER ::   jptra_radb = 21     !: corr. trb<0 in trcrad (like atf)
    !
    !                                                  !!!* Momentum trends indices
-   INTEGER, PUBLIC, PARAMETER ::   jptot_dyn  = 15     !: Total trend nb: change it when adding/removing one indice below
+   INTEGER, PUBLIC, PARAMETER ::   jptot_dyn  = 16     !: Total trend nb: change it when adding/removing one indice below
    !                               ===============     !  
    INTEGER, PUBLIC, PARAMETER ::   jpdyn_hpg  =  1     !: hydrostatic pressure gradient 
@@ -73,4 +79,5 @@
    INTEGER, PUBLIC, PARAMETER ::   jpdyn_spgflt  = 14  !: filter contribution to surface pressure gradient (spg_flt)
    INTEGER, PUBLIC, PARAMETER ::   jpdyn_spgexp  = 15  !: explicit contribution to surface pressure gradient (spg_flt)
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_eivke   = 16  !: K.E trend from Gent McWilliams scheme
    !
    !!----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdini.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdini.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdini.F90	(revision 9987)
@@ -91,5 +91,4 @@
 !!gm end
       !
-      IF( lk_vvl .AND. ( l_trdtra .OR. l_trddyn ) )  CALL ctl_stop( 'trend diagnostics with variable volume not validated' )
       
 !!gm  : Potential BUG : 3D output only for vector invariant form!  add a ctl_stop or code the flux form case
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdken.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdken.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdken.F90	(revision 9987)
@@ -27,4 +27,5 @@
    USE lib_mpp        ! MPP library
    USE wrk_nemo       ! Memory allocation
+   USE ldfslp         ! Isopycnal slopes
 
    IMPLICIT NONE
@@ -42,4 +43,6 @@
 #  include "domzgr_substitute.h90"
 #  include "vectopt_loop_substitute.h90"
+#  include "ldfeiv_substitute.h90"
+
    !!----------------------------------------------------------------------
    !! NEMO/OPA 3.3 , NEMO Consortium (2010)
@@ -117,28 +120,28 @@
       !
       SELECT CASE( ktrd )
-      	CASE( jpdyn_hpg )   ;   CALL iom_put( "ketrd_hpg", zke )    ! hydrostatic pressure gradient
-      	CASE( jpdyn_spg )   ;   CALL iom_put( "ketrd_spg", zke )    ! surface pressure gradient
-      	CASE( jpdyn_spgexp );   CALL iom_put( "ketrd_spgexp", zke ) ! surface pressure gradient (explicit)
-      	CASE( jpdyn_spgflt );   CALL iom_put( "ketrd_spgflt", zke ) ! surface pressure gradient (filter)
-      	CASE( jpdyn_pvo )   ;   CALL iom_put( "ketrd_pvo", zke )    ! planetary vorticity
-      	CASE( jpdyn_rvo )   ;   CALL iom_put( "ketrd_rvo", zke )    ! relative  vorticity     (or metric term)
-      	CASE( jpdyn_keg )   ;   CALL iom_put( "ketrd_keg", zke )    ! Kinetic Energy gradient (or had)
-      	CASE( jpdyn_zad )   ;   CALL iom_put( "ketrd_zad", zke )    ! vertical   advection
-      	CASE( jpdyn_ldf )   ;   CALL iom_put( "ketrd_ldf", zke )    ! lateral diffusion
-      	CASE( jpdyn_zdf )   ;   CALL iom_put( "ketrd_zdf", zke )    ! vertical diffusion 
+        CASE( jpdyn_hpg )   ;   CALL iom_put( "ketrd_hpg", zke )    ! hydrostatic pressure gradient
+        CASE( jpdyn_spg )   ;   CALL iom_put( "ketrd_spg", zke )    ! surface pressure gradient
+        CASE( jpdyn_spgexp );   CALL iom_put( "ketrd_spgexp", zke ) ! surface pressure gradient (explicit)
+        CASE( jpdyn_spgflt );   CALL iom_put( "ketrd_spgflt", zke ) ! surface pressure gradient (filter)
+        CASE( jpdyn_pvo )   ;   CALL iom_put( "ketrd_pvo", zke )    ! planetary vorticity
+        CASE( jpdyn_rvo )   ;   CALL iom_put( "ketrd_rvo", zke )    ! relative  vorticity     (or metric term)
+        CASE( jpdyn_keg )   ;   CALL iom_put( "ketrd_keg", zke )    ! Kinetic Energy gradient (or had)
+        CASE( jpdyn_zad )   ;   CALL iom_put( "ketrd_zad", zke )    ! vertical   advection
+        CASE( jpdyn_ldf )   ;   CALL iom_put( "ketrd_ldf", zke )    ! lateral diffusion
+        CASE( jpdyn_zdf )   ;   CALL iom_put( "ketrd_zdf", zke )    ! vertical diffusion 
                                  !                                   ! wind stress trends
-                              	CALL wrk_alloc( jpi, jpj, z2dx, z2dy, zke2d )
-         						z2dx(:,:) = un(:,:,1) * ( utau_b(:,:) + utau(:,:) ) * e1u(:,:) * e2u(:,:) * umask(:,:,1)
-         						z2dy(:,:) = vn(:,:,1) * ( vtau_b(:,:) + vtau(:,:) ) * e1v(:,:) * e2v(:,:) * vmask(:,:,1)
-         						zke2d(1,:) = 0._wp   ;   zke2d(:,1) = 0._wp
-         						DO jj = 2, jpj
-            					   DO ji = 2, jpi
-               						zke2d(ji,jj) = 0.5_wp * (   z2dx(ji,jj) + z2dx(ji-1,jj)   &
-                  					&                         + z2dy(ji,jj) + z2dy(ji,jj-1)   ) * r1_bt(ji,jj,1)
-            					   END DO
-         						END DO
-                              	CALL iom_put( "ketrd_tau", zke2d )
-                              	CALL wrk_dealloc( jpi, jpj     , z2dx, z2dy, zke2d )
-      	CASE( jpdyn_bfr )   ;   CALL iom_put( "ketrd_bfr", zke )    ! bottom friction (explicit case) 
+                                CALL wrk_alloc( jpi, jpj, z2dx, z2dy, zke2d )
+                     z2dx(:,:) = un(:,:,1) * ( utau_b(:,:) + utau(:,:) ) * e1u(:,:) * e2u(:,:) * umask(:,:,1)
+                     z2dy(:,:) = vn(:,:,1) * ( vtau_b(:,:) + vtau(:,:) ) * e1v(:,:) * e2v(:,:) * vmask(:,:,1)
+                     zke2d(1,:) = 0._wp   ;   zke2d(:,1) = 0._wp
+                     DO jj = 2, jpj
+                         DO ji = 2, jpi
+                           zke2d(ji,jj) = 0.5_wp * (   z2dx(ji,jj) + z2dx(ji-1,jj)   &
+                            &                         + z2dy(ji,jj) + z2dy(ji,jj-1)   ) * r1_bt(ji,jj,1)
+                         END DO
+                     END DO
+                                CALL iom_put( "ketrd_tau", zke2d )
+                                CALL wrk_dealloc( jpi, jpj     , z2dx, z2dy, zke2d )
+        CASE( jpdyn_bfr )   ;   CALL iom_put( "ketrd_bfr", zke )    ! bottom friction (explicit case) 
 !!gm TO BE DONE properly
 !!gm only valid if ln_bfrimp=F otherwise the bottom stress as to be recomputed at the end of the computation....
@@ -162,5 +165,5 @@
 !         ENDIF
 !!gm end
-      	CASE( jpdyn_atf )   ;   CALL iom_put( "ketrd_atf", zke )    ! asselin filter trends 
+        CASE( jpdyn_atf )   ;   CALL iom_put( "ketrd_atf", zke )    ! asselin filter trends 
 !! a faire !!!!  idee changer dynnxt pour avoir un appel a jpdyn_bfr avant le swap !!!
 !! reflechir a une possible sauvegarde du "vrai" un,vn pour le calcul de atf....
@@ -184,12 +187,33 @@
 !                              CALL iom_put( "ketrd_bfri", zke2d )
 !         ENDIF
-      	CASE( jpdyn_ken )   ;   ! kinetic energy
-      							! called in dynnxt.F90 before asselin time filter
-      							! with putrd=ua and pvtrd=va
-      							zke(:,:,:) = 0.5_wp * zke(:,:,:)
-      							CALL iom_put( "KE", zke )
-      							!
-      							CALL ken_p2k( kt , zke )
-            					CALL iom_put( "ketrd_convP2K", zke )     ! conversion -rau*g*w
+        CASE( jpdyn_ken )   ;   ! kinetic energy
+                    ! called in dynnxt.F90 before asselin time filter
+                    ! with putrd=ua and pvtrd=va
+                    zke(:,:,:) = 0.5_wp * zke(:,:,:)
+                    CALL iom_put( "KE", zke )
+                    !
+                    CALL ken_p2k( kt , zke )
+                      CALL iom_put( "ketrd_convP2K", zke )     ! conversion -rau*g*w
+        CASE( jpdyn_eivke )
+            ! CMIP6 diagnostic tknebto = tendency of KE from
+            ! parameterized mesoscale eddy advection
+            ! = vertical_integral( k (N S)^2 ) rho dz
+            ! rho = reference density
+            ! S = isoneutral slope.
+            ! Most terms are on W grid so work on this grid
+            CALL wrk_alloc( jpi, jpj, zke2d )
+            zke2d(:,:) = 0._wp
+            DO jk = 1,jpk
+               DO ji = 1,jpi
+                  DO jj = 1,jpj
+                     zke2d(ji,jj) = zke2d(ji,jj) +  rau0 * fsaeiw(ji, jj, jk)               &
+                          &                      * ( wslpi(ji, jj, jk) * wslpi(ji,jj,jk)    &
+                          &                      +   wslpj(ji, jj, jk) * wslpj(ji,jj,jk) )  &
+                          &                      *   rn2(ji,jj,jk) * fse3w(ji, jj, jk)
+                  ENDDO
+               ENDDO
+            ENDDO
+            CALL iom_put("ketrd_eiv", zke2d)
+            CALL wrk_dealloc( jpi, jpj, zke2d )
          !
       END SELECT
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl.F90	(revision 9987)
@@ -165,11 +165,11 @@
 
 
-		SELECT CASE( ktrd )
-		CASE( jptra_npc  )               ! non-penetrative convection: regrouped with zdf
+      SELECT CASE( ktrd )
+      CASE( jptra_npc  )               ! non-penetrative convection: regrouped with zdf
 !!gm : to be completed ! 
-!		   IF( ....
+!         IF( ....
 !!gm end
-		CASE( jptra_zdfp )               ! iso-neutral diffusion: "pure" vertical diffusion
-		   !                                   ! regroup iso-neutral diffusion in one term
+      CASE( jptra_zdfp )               ! iso-neutral diffusion: "pure" vertical diffusion
+         !                                   ! regroup iso-neutral diffusion in one term
          tmltrd(:,:,jpmxl_ldf) = tmltrd(:,:,jpmxl_ldf) + ( tmltrd(:,:,jpmxl_zdf) - tmltrd(:,:,jpmxl_zdfp) )
          smltrd(:,:,jpmxl_ldf) = smltrd(:,:,jpmxl_ldf) + ( smltrd(:,:,jpmxl_zdf) - smltrd(:,:,jpmxl_zdfp) )
@@ -811,5 +811,5 @@
 
 
-   	nkstp     = nit000 - 1              ! current time step indicator initialization
+      nkstp     = nit000 - 1              ! current time step indicator initialization
 
 
@@ -851,5 +851,5 @@
       IF( nn_ctls == 1 ) THEN
          CALL ctl_opn( inum, 'ctlsurf_idx', 'OLD', 'UNFORMATTED', 'SEQUENTIAL', -1, numout, lwp )
-         READ ( inum ) nbol
+         READ ( inum, * ) nbol
          CLOSE( inum )
       END IF
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_oce.F90	(revision 9987)
@@ -15,5 +15,5 @@
 
    !                                                !* mixed layer trend indices
-   INTEGER, PUBLIC, PARAMETER ::   jpltrd = 11      !: number of mixed-layer trends arrays
+   INTEGER, PUBLIC, PARAMETER ::   jpltrd = 12      !: number of mixed-layer trends arrays
    INTEGER, PUBLIC            ::   jpktrd           !: max level for mixed-layer trends diag.
    !
@@ -28,6 +28,6 @@
    INTEGER, PUBLIC, PARAMETER ::   jpmxl_for =  9   !: forcing 
    INTEGER, PUBLIC, PARAMETER ::   jpmxl_dmp = 10   !: internal restoring trend
-   INTEGER, PUBLIC, PARAMETER ::   jpmxl_zdfp = 11   !: asselin trend (**MUST BE THE LAST ONE**)
-   INTEGER, PUBLIC, PARAMETER ::   jpmxl_atf  = 12   !: asselin trend (**MUST BE THE LAST ONE**)
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_zdfp = 11  !: iso-neutral diffusion:"pure" vertical diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_atf  = 12  !: asselin trend (**MUST BE THE LAST ONE**)
    !                                                            !!* Namelist namtrd_mxl:  trend diagnostics in the mixed layer *
    INTEGER           , PUBLIC ::   nn_ctls  = 0                  !: control surface type for trends vertical integration
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdpen.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdpen.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdpen.F90	(revision 9987)
@@ -99,7 +99,7 @@
                                    CALL wrk_alloc( jpi, jpj, z2d )
                                    z2d(:,:) = wn(:,:,1) * ( &
-                                   	  &   - ( rab_n(:,:,1,jp_tem) + rab_pe(:,:,1,jp_tem) ) * tsn(:,:,1,jp_tem)    &
-                                   	  &   + ( rab_n(:,:,1,jp_sal) + rab_pe(:,:,1,jp_sal) ) * tsn(:,:,1,jp_sal)    &
-                                      &   					) / fse3t(:,:,1)
+                                       &   - ( rab_n(:,:,1,jp_tem) + rab_pe(:,:,1,jp_tem) ) * tsn(:,:,1,jp_tem)    &
+                                       &   + ( rab_n(:,:,1,jp_sal) + rab_pe(:,:,1,jp_sal) ) * tsn(:,:,1,jp_sal)    &
+                                       &             ) / fse3t(:,:,1)
                                    CALL iom_put( "petrd_sad" , z2d )
                                    CALL wrk_dealloc( jpi, jpj, z2d )
@@ -150,5 +150,5 @@
       rab_pe(:,:,:,:) = 0._wp
       !
-      IF ( lk_vvl               )   CALL ctl_stop('trd_pen_init : PE trends not coded for variable volume')
+!      IF ( lk_vvl               )   CALL ctl_stop('trd_pen_init : PE trends not coded for variable volume')
       !
       nkstp     = nit000 - 1
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdtra.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdtra.F90	(revision 9987)
@@ -38,5 +38,6 @@
    REAL(wp) ::   r2dt   ! time-step, = 2 rdttra except at nit000 (=rdttra) if neuler=0
 
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   trdtx, trdty, trdt   ! use to store the temperature trends
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   trdtx, trdty, trdt  ! use to store the temperature trends
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   avt_evd  ! store avt_evd to calculate EVD trend
 
    !! * Substitutions
@@ -55,5 +56,5 @@
       !!                  ***  FUNCTION trd_tra_alloc  ***
       !!---------------------------------------------------------------------
-      ALLOCATE( trdtx(jpi,jpj,jpk) , trdty(jpi,jpj,jpk) , trdt(jpi,jpj,jpk) , STAT= trd_tra_alloc )
+      ALLOCATE( trdtx(jpi,jpj,jpk) , trdty(jpi,jpj,jpk) , trdt(jpi,jpj,jpk) , avt_evd(jpi,jpj,jpk), STAT= trd_tra_alloc )
       !
       IF( lk_mpp             )   CALL mpp_sum ( trd_tra_alloc )
@@ -104,4 +105,5 @@
                                  ztrds(:,:,:) = 0._wp
                                  CALL trd_tra_mng( trdt, ztrds, ktrd, kt )
+         CASE( jptra_evd )   ;   avt_evd(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)
          CASE DEFAULT                 ! other trends: masked trends
             trdt(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)              ! mask & store
@@ -128,5 +130,5 @@
             zwt(:,:,jpk) = 0._wp   ;   zws(:,:,jpk) = 0._wp
             DO jk = 2, jpk
-               zwt(:,:,jk) =   avt(:,:,jk) * ( tsa(:,:,jk-1,jp_tem) - tsa(:,:,jk,jp_tem) ) / fse3w(:,:,jk) * tmask(:,:,jk)
+               zwt(:,:,jk) = avt(:,:,jk) * ( tsa(:,:,jk-1,jp_tem) - tsa(:,:,jk,jp_tem) ) / fse3w(:,:,jk) * tmask(:,:,jk)
                zws(:,:,jk) = fsavs(:,:,jk) * ( tsa(:,:,jk-1,jp_sal) - tsa(:,:,jk,jp_sal) ) / fse3w(:,:,jk) * tmask(:,:,jk)
             END DO
@@ -138,4 +140,18 @@
             END DO
             CALL trd_tra_mng( ztrdt, ztrds, jptra_zdfp, kt )  
+            !
+            !                         ! Also calculate EVD trend at this point. 
+            zwt(:,:,:) = 0._wp   ;   zws(:,:,:) = 0._wp            ! vertical diffusive fluxes
+            DO jk = 2, jpk
+               zwt(:,:,jk) = avt_evd(:,:,jk) * ( tsa(:,:,jk-1,jp_tem) - tsa(:,:,jk,jp_tem) ) / fse3w(:,:,jk) * tmask(:,:,jk)
+               zws(:,:,jk) = avt_evd(:,:,jk) * ( tsa(:,:,jk-1,jp_sal) - tsa(:,:,jk,jp_sal) ) / fse3w(:,:,jk) * tmask(:,:,jk)
+            END DO
+            !
+            ztrdt(:,:,jpk) = 0._wp   ;   ztrds(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = ( zwt(:,:,jk) - zwt(:,:,jk+1) ) / fse3t(:,:,jk)
+               ztrds(:,:,jk) = ( zws(:,:,jk) - zws(:,:,jk+1) ) / fse3t(:,:,jk) 
+            END DO
+            CALL trd_tra_mng( ztrdt, ztrds, jptra_evd, kt )  
             !
             CALL wrk_dealloc( jpi, jpj, jpk, zwt, zws, ztrdt )
@@ -285,51 +301,70 @@
       !! ** Purpose :   output 3D tracer trends using IOM
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
-      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
-      INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
-      INTEGER                   , INTENT(in   ) ::   kt      ! time step
-      !!
-      INTEGER ::   ji, jj, jk   ! dummy loop indices
-      INTEGER ::   ikbu, ikbv   ! local integers
-      REAL(wp), POINTER, DIMENSION(:,:)   ::   z2dx, z2dy   ! 2D workspace 
-      !!----------------------------------------------------------------------
-      !
-!!gm Rq: mask the trends already masked in trd_tra, but lbc_lnk should probably be added
-      !
-      SELECT CASE( ktrd )
-      CASE( jptra_xad  )   ;   CALL iom_put( "ttrd_xad" , ptrdx )        ! x- horizontal advection
-                               CALL iom_put( "strd_xad" , ptrdy )
-      CASE( jptra_yad  )   ;   CALL iom_put( "ttrd_yad" , ptrdx )        ! y- horizontal advection
-                               CALL iom_put( "strd_yad" , ptrdy )
-      CASE( jptra_zad  )   ;   CALL iom_put( "ttrd_zad" , ptrdx )        ! z- vertical   advection
-                               CALL iom_put( "strd_zad" , ptrdy )
-                               IF( .NOT. lk_vvl ) THEN                   ! cst volume : adv flux through z=0 surface
-                               	 CALL wrk_alloc( jpi, jpj, z2dx, z2dy )
-                                  z2dx(:,:) = wn(:,:,1) * tsn(:,:,1,jp_tem) / fse3t(:,:,1)
-                                  z2dy(:,:) = wn(:,:,1) * tsn(:,:,1,jp_sal) / fse3t(:,:,1)
-                                  CALL iom_put( "ttrd_sad", z2dx )
-                                  CALL iom_put( "strd_sad", z2dy )
-                                  CALL wrk_dealloc( jpi, jpj, z2dx, z2dy )
-                               ENDIF
-      CASE( jptra_ldf  )   ;   CALL iom_put( "ttrd_ldf" , ptrdx )        ! lateral diffusion
-                               CALL iom_put( "strd_ldf" , ptrdy )
-      CASE( jptra_zdf  )   ;   CALL iom_put( "ttrd_zdf" , ptrdx )        ! vertical diffusion (including Kz contribution)
-                               CALL iom_put( "strd_zdf" , ptrdy )
-      CASE( jptra_zdfp )   ;   CALL iom_put( "ttrd_zdfp", ptrdx )        ! PURE vertical diffusion (no isoneutral contribution)
-                               CALL iom_put( "strd_zdfp", ptrdy )
-      CASE( jptra_dmp  )   ;   CALL iom_put( "ttrd_dmp" , ptrdx )        ! internal restoring (damping)
-                               CALL iom_put( "strd_dmp" , ptrdy )
-      CASE( jptra_bbl  )   ;   CALL iom_put( "ttrd_bbl" , ptrdx )        ! bottom boundary layer
-                               CALL iom_put( "strd_bbl" , ptrdy )
-      CASE( jptra_npc  )   ;   CALL iom_put( "ttrd_npc" , ptrdx )        ! static instability mixing
-                               CALL iom_put( "strd_npc" , ptrdy )
-      CASE( jptra_nsr  )   ;   CALL iom_put( "ttrd_qns" , ptrdx )        ! surface forcing + runoff (ln_rnf=T)
-                               CALL iom_put( "strd_cdt" , ptrdy )
-      CASE( jptra_qsr  )   ;   CALL iom_put( "ttrd_qsr" , ptrdx )        ! penetrative solar radiat. (only on temperature)
-      CASE( jptra_bbc  )   ;   CALL iom_put( "ttrd_bbc" , ptrdx )        ! geothermal heating   (only on temperature)
-      CASE( jptra_atf  )   ;   CALL iom_put( "ttrd_atf" , ptrdx )        ! asselin time Filter
-                               CALL iom_put( "strd_atf" , ptrdy )
-      END SELECT
-      !
+     REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
+     REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
+     INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
+     INTEGER                   , INTENT(in   ) ::   kt      ! time step
+     !!
+     INTEGER ::   ji, jj, jk   ! dummy loop indices
+     INTEGER ::   ikbu, ikbv   ! local integers
+     REAL(wp), POINTER, DIMENSION(:,:)   ::   z2dx, z2dy   ! 2D workspace 
+     !!----------------------------------------------------------------------
+     !
+     !!gm Rq: mask the trends already masked in trd_tra, but lbc_lnk should probably be added
+     !
+     ! Trends evaluated every time step that could go to the standard T file and can be output every ts into a 1ts file if 1ts output is selected
+     SELECT CASE( ktrd )
+     ! This total trend is done every time step
+     CASE( jptra_tot  )   ;   CALL iom_put( "ttrd_tot" , ptrdx )           ! model total trend
+        CALL iom_put( "strd_tot" , ptrdy )
+     END SELECT
+
+     ! These trends are done every second time step. When 1ts output is selected must go different (2ts) file from standard T-file
+     IF( MOD( kt, 2 ) == 0 ) THEN
+        SELECT CASE( ktrd )
+        CASE( jptra_xad  )   ;   CALL iom_put( "ttrd_xad" , ptrdx )        ! x- horizontal advection
+           CALL iom_put( "strd_xad" , ptrdy )
+        CASE( jptra_yad  )   ;   CALL iom_put( "ttrd_yad" , ptrdx )        ! y- horizontal advection
+           CALL iom_put( "strd_yad" , ptrdy )
+        CASE( jptra_zad  )   ;   CALL iom_put( "ttrd_zad" , ptrdx )        ! z- vertical   advection
+           CALL iom_put( "strd_zad" , ptrdy )
+           IF( .NOT. lk_vvl ) THEN                   ! cst volume : adv flux through z=0 surface
+              CALL wrk_alloc( jpi, jpj, z2dx, z2dy )
+              z2dx(:,:) = wn(:,:,1) * tsn(:,:,1,jp_tem) / fse3t(:,:,1)
+              z2dy(:,:) = wn(:,:,1) * tsn(:,:,1,jp_sal) / fse3t(:,:,1)
+              CALL iom_put( "ttrd_sad", z2dx )
+              CALL iom_put( "strd_sad", z2dy )
+              CALL wrk_dealloc( jpi, jpj, z2dx, z2dy )
+           ENDIF
+        CASE( jptra_totad  ) ;   CALL iom_put( "ttrd_totad" , ptrdx )      ! total   advection
+           CALL iom_put( "strd_totad" , ptrdy )
+        CASE( jptra_ldf  )   ;   CALL iom_put( "ttrd_ldf" , ptrdx )        ! lateral diffusion
+           CALL iom_put( "strd_ldf" , ptrdy )
+        CASE( jptra_zdf  )   ;   CALL iom_put( "ttrd_zdf" , ptrdx )        ! vertical diffusion (including Kz contribution)
+           CALL iom_put( "strd_zdf" , ptrdy )
+        CASE( jptra_zdfp )   ;   CALL iom_put( "ttrd_zdfp", ptrdx )        ! PURE vertical diffusion (no isoneutral contribution)
+           CALL iom_put( "strd_zdfp", ptrdy )
+        CASE( jptra_evd )    ;   CALL iom_put( "ttrd_evd", ptrdx )         ! EVD trend (convection)
+           CALL iom_put( "strd_evd", ptrdy )
+        CASE( jptra_dmp  )   ;   CALL iom_put( "ttrd_dmp" , ptrdx )        ! internal restoring (damping)
+           CALL iom_put( "strd_dmp" , ptrdy )
+        CASE( jptra_bbl  )   ;   CALL iom_put( "ttrd_bbl" , ptrdx )        ! bottom boundary layer
+           CALL iom_put( "strd_bbl" , ptrdy )
+        CASE( jptra_npc  )   ;   CALL iom_put( "ttrd_npc" , ptrdx )        ! static instability mixing
+           CALL iom_put( "strd_npc" , ptrdy )
+        CASE( jptra_bbc  )   ;   CALL iom_put( "ttrd_bbc" , ptrdx )        ! geothermal heating   (only on temperature)
+        CASE( jptra_nsr  )   ;   CALL iom_put( "ttrd_qns" , ptrdx(:,:,1) ) ! surface forcing + runoff (ln_rnf=T)
+           CALL iom_put( "strd_cdt" , ptrdy(:,:,1) )        ! output as 2D surface fields
+        CASE( jptra_qsr  )   ;   CALL iom_put( "ttrd_qsr" , ptrdx )        ! penetrative solar radiat. (only on temperature)
+        END SELECT
+        ! the Asselin filter trend  is also every other time step but needs to be lagged one time step
+        ! Even when 1ts output is selected can go to the same (2ts) file as the trends plotted every even time step.
+     ELSE IF( MOD( kt, 2 ) == 1 ) THEN
+        SELECT CASE( ktrd )
+        CASE( jptra_atf  )   ;   CALL iom_put( "ttrd_atf" , ptrdx )        ! asselin time Filter
+           CALL iom_put( "strd_atf" , ptrdy )
+        END SELECT
+     END IF
+     !
    END SUBROUTINE trd_tra_iom
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdtrc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdtrc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/TRD/trdtrc.F90	(revision 9987)
@@ -1,2 +1,3 @@
+#if ! defined key_top
 MODULE trdtrc
    !!======================================================================
@@ -22,2 +23,3 @@
    !!======================================================================
 END MODULE trdtrc
+#endif
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfddm.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfddm.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfddm.F90	(revision 9987)
@@ -177,5 +177,10 @@
                   &                             +  0.15 * zrau(ji,jj)          * zmskd2(ji,jj)  )
                ! add to the eddy viscosity coef. previously computed
+# if defined key_zdftmx_new
+               ! key_zdftmx_new: New internal wave-driven param: use avs value computed by zdftmx
+               avs (ji,jj,jk) = avs(ji,jj,jk) + zavfs + zavds
+# else
                avs (ji,jj,jk) = avt(ji,jj,jk) + zavfs + zavds
+# endif
                avt (ji,jj,jk) = avt(ji,jj,jk) + zavft + zavdt
                avm (ji,jj,jk) = avm(ji,jj,jk) + MAX( zavft + zavdt, zavfs + zavds )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfevd.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfevd.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfevd.F90	(revision 9987)
@@ -19,4 +19,6 @@
    USE zdf_oce         ! ocean vertical physics variables
    USE zdfkpp          ! KPP vertical mixing
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
    USE in_out_manager  ! I/O manager
    USE iom             ! for iom_put
@@ -122,4 +124,5 @@
       zavt_evd(:,:,:) = avt(:,:,:) - zavt_evd(:,:,:)   ! change in avt due to evd
       CALL iom_put( "avt_evd", zavt_evd )              ! output this change
+      IF( l_trdtra ) CALL trd_tra( kt, 'TRA', jp_tem, jptra_evd, zavt_evd )
       !
       IF( nn_timing == 1 )  CALL timing_stop('zdf_evd')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfmxl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfmxl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfmxl.F90	(revision 9987)
@@ -18,4 +18,5 @@
    USE phycst          ! physical constants
    USE iom             ! I/O library
+   USE eosbn2          ! for zdf_mxl_zint
    USE lib_mpp         ! MPP library
    USE wrk_nemo        ! work arrays
@@ -27,4 +28,5 @@
 
    PUBLIC   zdf_mxl       ! called by step.F90
+   PUBLIC   zdf_mxl_alloc ! Used in zdf_tke_init
 
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   nmln    !: number of level in the mixed layer (used by TOP)
@@ -32,7 +34,18 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmlp    !: mixed layer depth  (rho=rho0+zdcrit) [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmlpt   !: mixed layer depth at t-points        [m]
+   REAL(wp), PUBLIC, ALLOCATABLE,       DIMENSION(:,:) ::   hmld_zint  !: vertically-interpolated mixed layer depth   [m] 
+   REAL(wp), PUBLIC, ALLOCATABLE,       DIMENSION(:,:) ::   htc_mld    ! Heat content of hmld_zint
+   LOGICAL, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)    :: ll_found   ! Is T_b to be found by interpolation ? 
+   LOGICAL, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  :: ll_belowml ! Flag points below mixed layer when ll_found=F
 
    REAL(wp), PUBLIC ::   rho_c = 0.01_wp    !: density criterion for mixed layer depth
    REAL(wp)         ::   avt_c = 5.e-4_wp   ! Kz criterion for the turbocline depth
+
+   TYPE, PUBLIC :: MXL_ZINT   !: Structure for MLD defs
+      INTEGER   :: mld_type   ! mixed layer type     
+      REAL(wp)  :: zref       ! depth of initial T_ref
+      REAL(wp)  :: dT_crit    ! Critical temp diff
+      REAL(wp)  :: iso_frac   ! Fraction of rn_dT_crit used
+   END TYPE MXL_ZINT
 
    !! * Substitutions
@@ -51,5 +64,7 @@
       zdf_mxl_alloc = 0      ! set to zero if no array to be allocated
       IF( .NOT. ALLOCATED( nmln ) ) THEN
-         ALLOCATE( nmln(jpi,jpj), hmld(jpi,jpj), hmlp(jpi,jpj), hmlpt(jpi,jpj), STAT= zdf_mxl_alloc )
+         ALLOCATE( nmln(jpi,jpj), hmld(jpi,jpj), hmlp(jpi,jpj), hmlpt(jpi,jpj), hmld_zint(jpi,jpj),       &
+        &          htc_mld(jpi,jpj),                                                                    &
+        &          ll_found(jpi,jpj), ll_belowml(jpi,jpj,jpk), STAT= zdf_mxl_alloc )
          !
          IF( lk_mpp             )   CALL mpp_sum ( zdf_mxl_alloc )
@@ -79,7 +94,7 @@
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       !
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      INTEGER  ::   iikn, iiki, ikt, imkt   ! local integer
-      REAL(wp) ::   zN2_c        ! local scalar
+      INTEGER  ::   ji, jj, jk      ! dummy loop indices
+      INTEGER  ::   iikn, iiki, ikt ! local integer
+      REAL(wp) ::   zN2_c           ! local scalar
       INTEGER, POINTER, DIMENSION(:,:) ::   imld   ! 2D workspace
       !!----------------------------------------------------------------------
@@ -89,5 +104,5 @@
       CALL wrk_alloc( jpi,jpj, imld )
 
-      IF( kt == nit000 ) THEN
+      IF( kt <= nit000 ) THEN
          IF(lwp) WRITE(numout,*)
          IF(lwp) WRITE(numout,*) 'zdf_mxl : mixed layer depth'
@@ -116,6 +131,5 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               imkt = mikt(ji,jj)
-               IF( avt (ji,jj,jk) < avt_c )   imld(ji,jj) = MAX( imkt, jk )      ! Turbocline 
+               IF( avt (ji,jj,jk) < avt_c * wmask(ji,jj,jk) )   imld(ji,jj) = jk      ! Turbocline 
             END DO
          END DO
@@ -126,15 +140,30 @@
             iiki = imld(ji,jj)
             iikn = nmln(ji,jj)
-            imkt = mikt(ji,jj)
-            hmld (ji,jj) = ( fsdepw(ji,jj,iiki  ) - fsdepw(ji,jj,imkt )            )   * ssmask(ji,jj)    ! Turbocline depth 
-            hmlp (ji,jj) = ( fsdepw(ji,jj,iikn  ) - fsdepw(ji,jj,MAX( imkt,nla10 ) ) ) * ssmask(ji,jj)    ! Mixed layer depth
-            hmlpt(ji,jj) = ( fsdept(ji,jj,iikn-1) - fsdepw(ji,jj,imkt )            )   * ssmask(ji,jj)    ! depth of the last T-point inside the mixed layer
+            hmld (ji,jj) = fsdepw(ji,jj,iiki  ) * ssmask(ji,jj)    ! Turbocline depth 
+            hmlp (ji,jj) = fsdepw(ji,jj,iikn  ) * ssmask(ji,jj)    ! Mixed layer depth
+            hmlpt(ji,jj) = fsdept(ji,jj,iikn-1) * ssmask(ji,jj)    ! depth of the last T-point inside the mixed layer
          END DO
       END DO
-      IF( .NOT.lk_offline ) THEN            ! no need to output in offline mode
-         CALL iom_put( "mldr10_1", hmlp )   ! mixed layer depth
-         CALL iom_put( "mldkz5"  , hmld )   ! turbocline depth
+      ! no need to output in offline mode
+      IF( .NOT.lk_offline ) THEN   
+         IF ( iom_use("mldr10_1") ) THEN
+            IF( ln_isfcav ) THEN
+               CALL iom_put( "mldr10_1", hmlp - risfdep)   ! mixed layer thickness
+            ELSE
+               CALL iom_put( "mldr10_1", hmlp )            ! mixed layer depth
+            END IF
+         END IF
+         IF ( iom_use("mldkz5") ) THEN
+            IF( ln_isfcav ) THEN
+               CALL iom_put( "mldkz5"  , hmld - risfdep )   ! turbocline thickness
+            ELSE
+               CALL iom_put( "mldkz5"  , hmld )             ! turbocline depth
+            END IF
+         END IF
       ENDIF
       
+      ! Vertically-interpolated mixed-layer depth diagnostic
+      CALL zdf_mxl_zint( kt )
+
       IF(ln_ctl)   CALL prt_ctl( tab2d_1=REAL(nmln,wp), clinfo1=' nmln : ', tab2d_2=hmlp, clinfo2=' hmlp : ', ovlap=1 )
       !
@@ -144,4 +173,344 @@
       !
    END SUBROUTINE zdf_mxl
+
+   SUBROUTINE zdf_mxl_zint_mld( sf ) 
+      !!---------------------------------------------------------------------------------- 
+      !!                    ***  ROUTINE zdf_mxl_zint_mld  *** 
+      !                                                                        
+      !   Calculate vertically-interpolated mixed layer depth diagnostic. 
+      !            
+      !   This routine can calculate the mixed layer depth diagnostic suggested by
+      !   Kara et al, 2000, JGR, 105, 16803, but is more general and can calculate
+      !   vertically-interpolated mixed-layer depth diagnostics with other parameter
+      !   settings set in the namzdf_mldzint namelist.  
+      ! 
+      !   If mld_type=1 the mixed layer depth is calculated as the depth at which the  
+      !   density has increased by an amount equivalent to a temperature difference of  
+      !   0.8C at the surface. 
+      ! 
+      !   For other values of mld_type the mixed layer is calculated as the depth at  
+      !   which the temperature differs by 0.8C from the surface temperature.  
+      !                                                                        
+      !   David Acreman, Daley Calvert                                      
+      ! 
+      !!----------------------------------------------------------------------------------- 
+
+      TYPE(MXL_ZINT), INTENT(in)  :: sf
+
+      ! Diagnostic criteria
+      INTEGER   :: nn_mld_type   ! mixed layer type     
+      REAL(wp)  :: rn_zref       ! depth of initial T_ref
+      REAL(wp)  :: rn_dT_crit    ! Critical temp diff
+      REAL(wp)  :: rn_iso_frac   ! Fraction of rn_dT_crit used
+
+      ! Local variables
+      REAL(wp), PARAMETER :: zepsilon = 1.e-30          ! local small value
+      INTEGER, POINTER, DIMENSION(:,:) :: ikmt          ! number of active tracer levels 
+      INTEGER, POINTER, DIMENSION(:,:) :: ik_ref        ! index of reference level 
+      INTEGER, POINTER, DIMENSION(:,:) :: ik_iso        ! index of last uniform temp level 
+      REAL, POINTER, DIMENSION(:,:,:)  :: zT            ! Temperature or density 
+      REAL, POINTER, DIMENSION(:,:)    :: ppzdep        ! depth for use in calculating d(rho) 
+      REAL, POINTER, DIMENSION(:,:)    :: zT_ref        ! reference temperature 
+      REAL    :: zT_b                                   ! base temperature 
+      REAL, POINTER, DIMENSION(:,:,:)  :: zdTdz         ! gradient of zT 
+      REAL, POINTER, DIMENSION(:,:,:)  :: zmoddT        ! Absolute temperature difference 
+      REAL    :: zdz                                    ! depth difference 
+      REAL    :: zdT                                    ! temperature difference 
+      REAL, POINTER, DIMENSION(:,:)    :: zdelta_T      ! difference critereon 
+      REAL, POINTER, DIMENSION(:,:)    :: zRHO1, zRHO2  ! Densities 
+      INTEGER :: ji, jj, jk                             ! loop counter 
+
+      !!------------------------------------------------------------------------------------- 
+      !  
+      CALL wrk_alloc( jpi, jpj, ikmt, ik_ref, ik_iso) 
+      CALL wrk_alloc( jpi, jpj, ppzdep, zT_ref, zdelta_T, zRHO1, zRHO2 ) 
+      CALL wrk_alloc( jpi, jpj, jpk, zT, zdTdz, zmoddT ) 
+
+      ! Unpack structure
+      nn_mld_type = sf%mld_type
+      rn_zref     = sf%zref
+      rn_dT_crit  = sf%dT_crit
+      rn_iso_frac = sf%iso_frac
+
+      ! Set the mixed layer depth criterion at each grid point 
+      IF( nn_mld_type == 0 ) THEN
+         zdelta_T(:,:) = rn_dT_crit
+         zT(:,:,:) = rhop(:,:,:)
+      ELSE IF( nn_mld_type == 1 ) THEN
+         ppzdep(:,:)=0.0 
+         call eos ( tsn(:,:,1,:), ppzdep(:,:), zRHO1(:,:) ) 
+! Use zT temporarily as a copy of tsn with rn_dT_crit added to SST 
+! [assumes number of tracers less than number of vertical levels] 
+         zT(:,:,1:jpts)=tsn(:,:,1,1:jpts) 
+         zT(:,:,jp_tem)=zT(:,:,1)+rn_dT_crit 
+         CALL eos( zT(:,:,1:jpts), ppzdep(:,:), zRHO2(:,:) ) 
+         zdelta_T(:,:) = abs( zRHO1(:,:) - zRHO2(:,:) ) * rau0 
+         ! RHO from eos (2d version) doesn't calculate north or east halo: 
+         CALL lbc_lnk( zdelta_T, 'T', 1. ) 
+         zT(:,:,:) = rhop(:,:,:) 
+      ELSE 
+         zdelta_T(:,:) = rn_dT_crit                      
+         zT(:,:,:) = tsn(:,:,:,jp_tem)                           
+      END IF 
+
+      ! Calculate the gradient of zT and absolute difference for use later 
+      DO jk = 1 ,jpk-2 
+         zdTdz(:,:,jk)  =    ( zT(:,:,jk+1) - zT(:,:,jk) ) / fse3w(:,:,jk+1) 
+         zmoddT(:,:,jk) = abs( zT(:,:,jk+1) - zT(:,:,jk) ) 
+      END DO 
+
+      ! Find density/temperature at the reference level (Kara et al use 10m).          
+      ! ik_ref is the index of the box centre immediately above or at the reference level 
+      ! Find rn_zref in the array of model level depths and find the ref    
+      ! density/temperature by linear interpolation.                                   
+      DO jk = jpkm1, 2, -1 
+         WHERE ( fsdept(:,:,jk) > rn_zref ) 
+           ik_ref(:,:) = jk - 1 
+           zT_ref(:,:) = zT(:,:,jk-1) + zdTdz(:,:,jk-1) * ( rn_zref - fsdept(:,:,jk-1) ) 
+         END WHERE 
+      END DO 
+
+      ! If the first grid box centre is below the reference level then use the 
+      ! top model level to get zT_ref 
+      WHERE ( fsdept(:,:,1) > rn_zref )  
+         zT_ref = zT(:,:,1) 
+         ik_ref = 1 
+      END WHERE 
+
+      ! The number of active tracer levels is 1 less than the number of active w levels 
+      ikmt(:,:) = mbathy(:,:) - 1 
+
+      ! Initialize / reset
+      ll_found(:,:) = .false.
+
+      IF ( rn_iso_frac - zepsilon > 0. ) THEN
+         ! Search for a uniform density/temperature region where adjacent levels          
+         ! differ by less than rn_iso_frac * deltaT.                                      
+         ! ik_iso is the index of the last level in the uniform layer  
+         ! ll_found indicates whether the mixed layer depth can be found by interpolation 
+         ik_iso(:,:)   = ik_ref(:,:) 
+         DO jj = 1, nlcj 
+            DO ji = 1, nlci 
+!CDIR NOVECTOR 
+               DO jk = ik_ref(ji,jj), ikmt(ji,jj)-1 
+                  IF ( zmoddT(ji,jj,jk) > ( rn_iso_frac * zdelta_T(ji,jj) ) ) THEN 
+                     ik_iso(ji,jj)   = jk 
+                     ll_found(ji,jj) = ( zmoddT(ji,jj,jk) > zdelta_T(ji,jj) ) 
+                     EXIT 
+                  END IF 
+               END DO 
+            END DO 
+         END DO 
+
+         ! Use linear interpolation to find depth of mixed layer base where possible 
+         hmld_zint(:,:) = rn_zref 
+         DO jj = 1, jpj 
+            DO ji = 1, jpi 
+               IF (ll_found(ji,jj) .and. tmask(ji,jj,1) == 1.0) THEN 
+                  zdz =  abs( zdelta_T(ji,jj) / zdTdz(ji,jj,ik_iso(ji,jj)) ) 
+                  hmld_zint(ji,jj) = fsdept(ji,jj,ik_iso(ji,jj)) + zdz 
+               END IF 
+            END DO 
+         END DO 
+      END IF
+
+      ! If ll_found = .false. then calculate MLD using difference of zdelta_T    
+      ! from the reference density/temperature 
+ 
+! Prevent this section from working on land points 
+      WHERE ( tmask(:,:,1) /= 1.0 ) 
+         ll_found = .true. 
+      END WHERE 
+ 
+      DO jk=1, jpk 
+         ll_belowml(:,:,jk) = abs( zT(:,:,jk) - zT_ref(:,:) ) >= zdelta_T(:,:)  
+      END DO 
+ 
+! Set default value where interpolation cannot be used (ll_found=false)  
+      DO jj = 1, jpj 
+         DO ji = 1, jpi 
+            IF ( .not. ll_found(ji,jj) )  hmld_zint(ji,jj) = fsdept(ji,jj,ikmt(ji,jj)) 
+         END DO 
+      END DO 
+
+      DO jj = 1, jpj 
+         DO ji = 1, jpi 
+!CDIR NOVECTOR 
+            DO jk = ik_ref(ji,jj)+1, ikmt(ji,jj) 
+               IF ( ll_found(ji,jj) ) EXIT 
+               IF ( ll_belowml(ji,jj,jk) ) THEN                
+                  zT_b = zT_ref(ji,jj) + zdelta_T(ji,jj) * SIGN(1.0, zdTdz(ji,jj,jk-1) ) 
+                  zdT  = zT_b - zT(ji,jj,jk-1)                                      
+                  zdz  = zdT / zdTdz(ji,jj,jk-1)                                       
+                  hmld_zint(ji,jj) = fsdept(ji,jj,jk-1) + zdz 
+                  EXIT                                                   
+               END IF 
+            END DO 
+         END DO 
+      END DO 
+
+      hmld_zint(:,:) = hmld_zint(:,:)*tmask(:,:,1) 
+      !  
+      CALL wrk_dealloc( jpi, jpj, ikmt, ik_ref, ik_iso) 
+      CALL wrk_dealloc( jpi, jpj, ppzdep, zT_ref, zdelta_T, zRHO1, zRHO2 ) 
+      CALL wrk_dealloc( jpi,jpj, jpk, zT, zdTdz, zmoddT ) 
+      ! 
+   END SUBROUTINE zdf_mxl_zint_mld
+
+   SUBROUTINE zdf_mxl_zint_htc( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_mxl_zint_htc  ***
+      !! 
+      !! ** Purpose :   
+      !!
+      !! ** Method  :   
+      !!----------------------------------------------------------------------
+
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+
+      INTEGER :: ji, jj, jk
+      INTEGER :: ikmax
+      REAL(wp) :: zc, zcoef
+      !
+      INTEGER,  ALLOCATABLE, DIMENSION(:,:) ::   ilevel
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zthick_0, zthick
+
+      !!----------------------------------------------------------------------
+
+      IF( .NOT. ALLOCATED(ilevel) ) THEN
+         ALLOCATE( ilevel(jpi,jpj), zthick_0(jpi,jpj), &
+         &         zthick(jpi,jpj), STAT=ji )
+         IF( lk_mpp  )   CALL mpp_sum(ji)
+         IF( ji /= 0 )   CALL ctl_stop( 'STOP', 'zdf_mxl_zint_htc : unable to allocate arrays' )
+      ENDIF
+
+      ! Find last whole model T level above the MLD
+      ilevel(:,:)   = 0
+      zthick_0(:,:) = 0._wp
+
+      DO jk = 1, jpkm1  
+         DO jj = 1, jpj
+            DO ji = 1, jpi                    
+               zthick_0(ji,jj) = zthick_0(ji,jj) + fse3t(ji,jj,jk)
+               IF( zthick_0(ji,jj) < hmld_zint(ji,jj) )   ilevel(ji,jj) = jk
+            END DO
+         END DO
+         WRITE(numout,*) 'zthick_0(jk =',jk,') =',zthick_0(2,2)
+         WRITE(numout,*) 'fsdepw(jk+1 =',jk+1,') =',fsdepw(2,2,jk+1)
+      END DO
+
+      ! Surface boundary condition
+      IF( lk_vvl ) THEN   ;   zthick(:,:) = 0._wp       ;   htc_mld(:,:) = 0._wp                                   
+      ELSE                ;   zthick(:,:) = sshn(:,:)   ;   htc_mld(:,:) = tsn(:,:,1,jp_tem) * sshn(:,:) * tmask(:,:,1)   
+      ENDIF
+
+      ! Deepest whole T level above the MLD
+      ikmax = MIN( MAXVAL( ilevel(:,:) ), jpkm1 )
+
+      ! Integration down to last whole model T level
+      DO jk = 1, ikmax
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zc = fse3t(ji,jj,jk) * REAL( MIN( MAX( 0, ilevel(ji,jj) - jk + 1 ) , 1  )  )    ! 0 below ilevel
+               zthick(ji,jj) = zthick(ji,jj) + zc
+               htc_mld(ji,jj) = htc_mld(ji,jj) + zc * tsn(ji,jj,jk,jp_tem) * tmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      ! Subsequent partial T level
+      zthick(:,:) = hmld_zint(:,:) - zthick(:,:)   !   remaining thickness to reach MLD
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            htc_mld(ji,jj) = htc_mld(ji,jj) + tsn(ji,jj,ilevel(ji,jj)+1,jp_tem)  & 
+      &                      * MIN( fse3t(ji,jj,ilevel(ji,jj)+1), zthick(ji,jj) ) * tmask(ji,jj,ilevel(ji,jj)+1)
+         END DO
+      END DO
+
+      WRITE(numout,*) 'htc_mld(after) =',htc_mld(2,2)
+
+      ! Convert to heat content
+      zcoef = rau0 * rcp
+      htc_mld(:,:) = zcoef * htc_mld(:,:)
+
+   END SUBROUTINE zdf_mxl_zint_htc
+
+   SUBROUTINE zdf_mxl_zint( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_mxl_zint  ***
+      !! 
+      !! ** Purpose :   
+      !!
+      !! ** Method  :   
+      !!----------------------------------------------------------------------
+
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+
+      INTEGER :: ios
+      INTEGER :: jn
+
+      INTEGER :: nn_mld_diag = 0    ! number of diagnostics
+
+      CHARACTER(len=1) :: cmld
+
+      TYPE(MXL_ZINT) :: sn_mld1, sn_mld2, sn_mld3, sn_mld4, sn_mld5
+      TYPE(MXL_ZINT), SAVE, DIMENSION(5) ::   mld_diags
+
+      NAMELIST/namzdf_mldzint/ nn_mld_diag, sn_mld1, sn_mld2, sn_mld3, sn_mld4, sn_mld5
+
+      !!----------------------------------------------------------------------
+      
+      IF( kt == nit000 ) THEN
+         REWIND( numnam_ref )              ! Namelist namzdf_mldzint in reference namelist 
+         READ  ( numnam_ref, namzdf_mldzint, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_mldzint in reference namelist', lwp )
+
+         REWIND( numnam_cfg )              ! Namelist namzdf_mldzint in configuration namelist 
+         READ  ( numnam_cfg, namzdf_mldzint, IOSTAT = ios, ERR = 902 )
+902      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_mldzint in configuration namelist', lwp )
+         IF(lwm) WRITE ( numond, namzdf_mldzint )
+
+         IF( nn_mld_diag > 5 )   CALL ctl_stop( 'STOP', 'zdf_mxl_ini: Specify no more than 5 MLD definitions' )
+
+         mld_diags(1) = sn_mld1
+         mld_diags(2) = sn_mld2
+         mld_diags(3) = sn_mld3
+         mld_diags(4) = sn_mld4
+         mld_diags(5) = sn_mld5
+
+         IF( lwp .AND. (nn_mld_diag > 0) ) THEN
+            WRITE(numout,*) '=============== Vertically-interpolated mixed layer ================'
+            WRITE(numout,*) '(Diagnostic number, nn_mld_type, rn_zref, rn_dT_crit, rn_iso_frac)'
+            DO jn = 1, nn_mld_diag
+               WRITE(numout,*) 'MLD criterion',jn,':'
+               WRITE(numout,*) '    nn_mld_type =', mld_diags(jn)%mld_type
+               WRITE(numout,*) '    rn_zref ='    , mld_diags(jn)%zref
+               WRITE(numout,*) '    rn_dT_crit =' , mld_diags(jn)%dT_crit
+               WRITE(numout,*) '    rn_iso_frac =', mld_diags(jn)%iso_frac
+            END DO
+            WRITE(numout,*) '===================================================================='
+         ENDIF
+      ENDIF
+
+      IF( nn_mld_diag > 0 ) THEN
+         DO jn = 1, nn_mld_diag
+            WRITE(cmld,'(I1)') jn
+            IF( iom_use( "mldzint_"//cmld ) .OR. iom_use( "mldhtc_"//cmld ) ) THEN
+               CALL zdf_mxl_zint_mld( mld_diags(jn) )
+
+               IF( iom_use( "mldzint_"//cmld ) ) THEN
+                  CALL iom_put( "mldzint_"//cmld, hmld_zint(:,:) )
+               ENDIF
+
+               IF( iom_use( "mldhtc_"//cmld ) )  THEN
+                  CALL zdf_mxl_zint_htc( kt )
+                  CALL iom_put( "mldhtc_"//cmld , htc_mld(:,:)   )
+               ENDIF
+            ENDIF
+         END DO
+      ENDIF
+
+   END SUBROUTINE zdf_mxl_zint
 
    !!======================================================================
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftke.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftke.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftke.F90	(revision 9987)
@@ -53,4 +53,10 @@
    USE timing         ! Timing
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+#if defined key_agrif
+   USE agrif_opa_interp
+   USE agrif_opa_update
+#endif
+
+
 
    IMPLICIT NONE
@@ -77,4 +83,5 @@
    INTEGER  ::   nn_htau   ! type of tke profile of penetration (=0/1)
    REAL(wp) ::   rn_efr    ! fraction of TKE surface value which penetrates in the ocean
+   REAL(wp) ::   rn_c      ! fraction of TKE added within the mixed layer by nn_etau
    LOGICAL  ::   ln_lc     ! Langmuir cells (LC) as a source term of TKE or not
    REAL(wp) ::   rn_lc     ! coef to compute vertical velocity of Langmuir cells
@@ -82,8 +89,11 @@
    REAL(wp) ::   ri_cri    ! critic Richardson number (deduced from rn_ediff and rn_ediss values)
    REAL(wp) ::   rmxl_min  ! minimum mixing length value (deduced from rn_ediff and rn_emin values)  [m]
+   REAL(wp) ::   rhtau                     ! coefficient to relate MLD to htau when nn_htau == 2
    REAL(wp) ::   rhftau_add = 1.e-3_wp     ! add offset   applied to HF part of taum  (nn_etau=3)
    REAL(wp) ::   rhftau_scl = 1.0_wp       ! scale factor applied to HF part of taum  (nn_etau=3)
 
    REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   htau           ! depth of tke penetration (nn_htau)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   e_niw          !: TKE budget- near-inertial waves term
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   efr            ! surface boundary condition for nn_etau = 4
    REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dissl          ! now mixing lenght of dissipation
 #if defined key_c1d
@@ -108,4 +118,5 @@
       !!----------------------------------------------------------------------
       ALLOCATE(                                                                    &
+         &      efr  (jpi,jpj)     , e_niw(jpi,jpj,jpk) ,                         &      
 #if defined key_c1d
          &      e_dis(jpi,jpj,jpk) , e_mix(jpi,jpj,jpk) ,                          &
@@ -184,4 +195,9 @@
       avmv_k(:,:,:) = avmv(:,:,:) 
       !
+#if defined key_agrif
+      ! Update child grid f => parent grid 
+      IF( .NOT.Agrif_Root() )   CALL Agrif_Update_Tke( kt )      ! children only
+#endif      
+     ! 
    END SUBROUTINE zdf_tke
 
@@ -312,5 +328,6 @@
                   zwlc = zind * rn_lc * zus * SIN( rpi * fsdepw(ji,jj,jk) / zhlc(ji,jj) )
                   !                                           ! TKE Langmuir circulation source term
-                  en(ji,jj,jk) = en(ji,jj,jk) + rdt * ( zwlc * zwlc * zwlc ) / zhlc(ji,jj) * wmask(ji,jj,jk) * tmask(ji,jj,1)
+                  en(ji,jj,jk) = en(ji,jj,jk) + rdt * ( 1._wp - fr_i(ji,jj) ) * ( zwlc * zwlc * zwlc ) /   &
+                     &   zhlc(ji,jj) * wmask(ji,jj,jk) * tmask(ji,jj,1)
                END DO
             END DO
@@ -345,8 +362,16 @@
             DO ji = fs_2, fs_jpim1   ! vector opt.
                zcof   = zfact1 * tmask(ji,jj,jk)
+# if defined key_zdftmx_new
+               ! key_zdftmx_new: New internal wave-driven param: set a minimum value for Kz on TKE (ensure numerical stability)
+               zzd_up = zcof * ( MAX( avm(ji,jj,jk+1) + avm(ji,jj,jk), 2.e-5_wp ) )   &  ! upper diagonal
+                  &          / ( fse3t(ji,jj,jk  ) * fse3w(ji,jj,jk  ) )
+               zzd_lw = zcof * ( MAX( avm(ji,jj,jk) + avm(ji,jj,jk-1), 2.e-5_wp ) )   &  ! lower diagonal
+                  &          / ( fse3t(ji,jj,jk-1) * fse3w(ji,jj,jk  ) )
+# else
                zzd_up = zcof * ( avm  (ji,jj,jk+1) + avm  (ji,jj,jk  ) )   &  ! upper diagonal
                   &          / ( fse3t(ji,jj,jk  ) * fse3w(ji,jj,jk  ) )
                zzd_lw = zcof * ( avm  (ji,jj,jk  ) + avm  (ji,jj,jk-1) )   &  ! lower diagonal
                   &          / ( fse3t(ji,jj,jk-1) * fse3w(ji,jj,jk  ) )
+# endif
                   !                                                           ! shear prod. at w-point weightened by mask
                zesh2  =  ( avmu(ji-1,jj,jk) + avmu(ji,jj,jk) ) / MAX( 1._wp , umask(ji-1,jj,jk) + umask(ji,jj,jk) )   &
@@ -408,7 +433,22 @@
       END DO
 
+      !                                 ! Save TKE prior to nn_etau addition  
+      e_niw(:,:,:) = en(:,:,:)  
+      !  
       !                            !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
       !                            !  TKE due to surface and internal wave breaking
       !                            !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( nn_htau == 2 ) THEN           !* mixed-layer depth dependant length scale
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               htau(ji,jj) = rhtau * hmlp(ji,jj)
+            END DO
+         END DO
+      ENDIF
+#if defined key_iomput
+      !
+      CALL iom_put( "htau", htau(:,:) )  ! Check htau (even if constant in time)
+#endif
+      !
       IF( nn_etau == 1 ) THEN           !* penetration below the mixed layer (rn_efr fraction)
          DO jk = 2, jpkm1
@@ -445,6 +485,32 @@
             END DO
          END DO
+      ELSEIF( nn_etau == 4 ) THEN       !* column integral independant of htau (rn_efr must be scaled up)
+         IF( nn_htau == 2 ) THEN        ! efr dependant on time-varying htau 
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  efr(ji,jj) = rn_efr / ( htau(ji,jj) * ( 1._wp - EXP( -bathy(ji,jj) / htau(ji,jj) ) ) )
+               END DO
+            END DO
+         ENDIF
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  en(ji,jj,jk) = en(ji,jj,jk) + efr(ji,jj) * en(ji,jj,1) * EXP( -fsdepw(ji,jj,jk) / htau(ji,jj) )   &
+                     &                                                   * ( 1._wp - fr_i(ji,jj) )  * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
       ENDIF
       CALL lbc_lnk( en, 'W', 1. )      ! Lateral boundary conditions (sign unchanged)
+      !
+      DO jk = 2, jpkm1                             ! TKE budget: near-inertial waves term  
+         DO jj = 2, jpjm1  
+            DO ji = fs_2, fs_jpim1   ! vector opt.  
+               e_niw(ji,jj,jk) = en(ji,jj,jk) - e_niw(ji,jj,jk)  
+            END DO  
+         END DO  
+      END DO  
+      !  
+      CALL lbc_lnk( e_niw, 'W', 1. )  
       !
       CALL wrk_dealloc( jpi,jpj, imlc )    ! integer
@@ -705,12 +771,12 @@
       !!----------------------------------------------------------------------
       INTEGER ::   ji, jj, jk   ! dummy loop indices
-      INTEGER ::   ios
+      INTEGER ::   ios, ierr
       !!
       NAMELIST/namzdf_tke/ rn_ediff, rn_ediss , rn_ebb , rn_emin  ,   &
          &                 rn_emin0, rn_bshear, nn_mxl , ln_mxl0  ,   &
          &                 rn_mxl0 , nn_pdl   , ln_lc  , rn_lc    ,   &
-         &                 nn_etau , nn_htau  , rn_efr   
+         &                 nn_etau , nn_htau  , rn_efr , rn_c   
       !!----------------------------------------------------------------------
-      !
+
       REWIND( numnam_ref )              ! Namelist namzdf_tke in reference namelist : Turbulent Kinetic Energy
       READ  ( numnam_ref, namzdf_tke, IOSTAT = ios, ERR = 901)
@@ -723,5 +789,16 @@
       !
       ri_cri   = 2._wp    / ( 2._wp + rn_ediss / rn_ediff )   ! resulting critical Richardson number
+# if defined key_zdftmx_new
+      ! key_zdftmx_new: New internal wave-driven param: specified value of rn_emin & rmxl_min are used
+      rn_emin  = 1.e-10_wp
+      rmxl_min = 1.e-03_wp
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_tke_init :  New tidal mixing case: force rn_emin = 1.e-10 and rmxl_min = 1.e-3 '
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+# else
       rmxl_min = 1.e-6_wp / ( rn_ediff * SQRT( rn_emin ) )    ! resulting minimum length to recover molecular viscosity
+# endif
       !
       IF(lwp) THEN                    !* Control print
@@ -745,4 +822,5 @@
          WRITE(numout,*) '      flag for computation of exp. tke profile    nn_htau   = ', nn_htau
          WRITE(numout,*) '      fraction of en which pene. the thermocline  rn_efr    = ', rn_efr
+         WRITE(numout,*) '      fraction of TKE added within the mixed layer by nn_etau rn_c    = ', rn_c
          WRITE(numout,*)
          WRITE(numout,*) '      critical Richardson nb with your parameters  ri_cri = ', ri_cri
@@ -755,5 +833,5 @@
       IF( nn_mxl  < 0   .OR.  nn_mxl  > 3 )   CALL ctl_stop( 'bad flag: nn_mxl is  0, 1 or 2 ' )
       IF( nn_pdl  < 0   .OR.  nn_pdl  > 1 )   CALL ctl_stop( 'bad flag: nn_pdl is  0 or 1    ' )
-      IF( nn_htau < 0   .OR.  nn_htau > 1 )   CALL ctl_stop( 'bad flag: nn_htau is 0, 1 or 2 ' )
+      IF( nn_htau < 0  .OR.  nn_htau > 5 )   CALL ctl_stop( 'bad flag: nn_htau is 0 to 5    ' )
       IF( nn_etau == 3 .AND. .NOT. ln_cpl )   CALL ctl_stop( 'nn_etau == 3 : HF taum only known in coupled mode' )
 
@@ -763,8 +841,17 @@
       ENDIF
       
-      IF( nn_etau == 2  )   CALL zdf_mxl( nit000 )      ! Initialization of nmln 
+      IF( nn_etau == 2  ) THEN
+          ierr = zdf_mxl_alloc()
+          nmln(:,:) = nlb10           ! Initialization of nmln
+      ENDIF
+
+      IF( nn_etau /= 0 .and. nn_htau == 2 ) THEN
+          ierr = zdf_mxl_alloc()
+          nmln(:,:) = nlb10           ! Initialization of nmln
+      ENDIF
 
       !                               !* depth of penetration of surface tke
       IF( nn_etau /= 0 ) THEN      
+         htau(:,:) = 0._wp
          SELECT CASE( nn_htau )             ! Choice of the depth of penetration
          CASE( 0 )                                 ! constant depth penetration (here 10 meters)
@@ -772,5 +859,37 @@
          CASE( 1 )                                 ! F(latitude) : 0.5m to 30m poleward of 40 degrees
             htau(:,:) = MAX(  0.5_wp, MIN( 30._wp, 45._wp* ABS( SIN( rpi/180._wp * gphit(:,:) ) ) )   )            
+         CASE( 2 )                                 ! fraction of depth-integrated TKE within mixed-layer
+            rhtau = -1._wp / LOG( 1._wp - rn_c )
+         CASE( 3 )                                 ! F(latitude) : 0.5m to 15m poleward of 20 degrees
+            htau(:,:) = MAX(  0.5_wp, MIN( 15._wp, 45._wp* ABS( SIN( rpi/180._wp * gphit(:,:) ) ) )   )
+         CASE( 4 )                                 ! F(latitude) : 0.5m to 10m/30m poleward of 13/40 degrees north/south
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( gphit(ji,jj) <= 0._wp ) THEN
+                     htau(ji,jj) = MAX(  0.5_wp, MIN( 30._wp, 45._wp* ABS( SIN( rpi/180._wp * gphit(ji,jj) ) ) )   )
+                  ELSE
+                     htau(ji,jj) = MAX(  0.5_wp, MIN( 10._wp, 45._wp* ABS( SIN( rpi/180._wp * gphit(ji,jj) ) ) )   )
+                  ENDIF
+               END DO
+            END DO
+         CASE ( 5 )                                ! F(latitude) : 0.5m to 10m poleward of 13 degrees north/south,
+            DO jj = 2, jpjm1                       !               10m to 30m between 30/45 degrees south
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( gphit(ji,jj) <= -30._wp ) THEN
+                     htau(ji,jj) = MAX(  10._wp, MIN( 30._wp, 55._wp* ABS( SIN( rpi/120._wp * ( gphit(ji,jj) + 23._wp ) ) ) )   )
+                  ELSE
+                     htau(ji,jj) = MAX(  0.5_wp, MIN( 10._wp, 45._wp* ABS( SIN( rpi/180._wp * gphit(ji,jj) ) ) )   )
+                  ENDIF
+               END DO
+            END DO
          END SELECT
+         !
+         IF( nn_etau == 4 .AND. nn_htau /= 2 ) THEN            ! efr dependant on constant htau
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  efr(ji,jj) = rn_efr / ( htau(ji,jj) * ( 1._wp - EXP( -bathy(ji,jj) / htau(ji,jj) ) ) )
+               END DO
+            END DO
+         ENDIF
       ENDIF
       !                               !* set vertical eddy coef. to the background value
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftmx.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftmx.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftmx.F90	(revision 9987)
@@ -561,4 +561,491 @@
    END SUBROUTINE zdf_tmx_init
 
+#elif defined key_zdftmx_new
+   !!----------------------------------------------------------------------
+   !!   'key_zdftmx_new'               Internal wave-driven vertical mixing
+   !!----------------------------------------------------------------------
+   !!   zdf_tmx       : global     momentum & tracer Kz with wave induced Kz
+   !!   zdf_tmx_init  : global     momentum & tracer Kz with wave induced Kz
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics variables
+   USE zdfddm         ! ocean vertical physics: double diffusive mixing
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE eosbn2         ! ocean equation of state
+   USE phycst         ! physical constants
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O Manager
+   USE lib_mpp        ! MPP library
+   USE wrk_nemo       ! work arrays
+   USE timing         ! Timing
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_tmx         ! called in step module 
+   PUBLIC   zdf_tmx_init    ! called in nemogcm module 
+   PUBLIC   zdf_tmx_alloc   ! called in nemogcm module
+
+   LOGICAL, PUBLIC, PARAMETER ::   lk_zdftmx = .TRUE.    !: wave-driven mixing flag
+
+   !                       !!* Namelist  namzdf_tmx : internal wave-driven mixing *
+   INTEGER  ::  nn_zpyc     ! pycnocline-intensified mixing energy proportional to N (=1) or N^2 (=2)
+   LOGICAL  ::  ln_mevar    ! variable (=T) or constant (=F) mixing efficiency
+   LOGICAL  ::  ln_tsdiff   ! account for differential T/S wave-driven mixing (=T) or not (=F)
+
+   REAL(wp) ::  r1_6 = 1._wp / 6._wp
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ebot_tmx     ! power available from high-mode wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   epyc_tmx     ! power available from low-mode, pycnocline-intensified wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ecri_tmx     ! power available from low-mode, critical slope wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hbot_tmx     ! WKB decay scale for high-mode energy dissipation (m)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hcri_tmx     ! decay scale for low-mode critical slope dissipation (m)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   emix_tmx     ! local energy density available for mixing (W/kg)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   bflx_tmx     ! buoyancy flux Kz * N^2 (W/kg)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   pcmap_tmx    ! vertically integrated buoyancy flux (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   zav_ratio    ! S/T diffusivity ratio (only for ln_tsdiff=T)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   zav_wave     ! Internal wave-induced diffusivity
+
+   !! * Substitutions
+#  include "zdfddm_substitute.h90"
+#  include "domzgr_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0 , NEMO Consortium (2016)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_tmx_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION zdf_tmx_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE(     ebot_tmx(jpi,jpj),  epyc_tmx(jpi,jpj),  ecri_tmx(jpi,jpj)    ,   &
+      &             hbot_tmx(jpi,jpj),  hcri_tmx(jpi,jpj),  emix_tmx(jpi,jpj,jpk),   &
+      &         bflx_tmx(jpi,jpj,jpk), pcmap_tmx(jpi,jpj), zav_ratio(jpi,jpj,jpk),   & 
+      &         zav_wave(jpi,jpj,jpk), STAT=zdf_tmx_alloc     )
+      !
+      IF( lk_mpp             )   CALL mpp_sum ( zdf_tmx_alloc )
+      IF( zdf_tmx_alloc /= 0 )   CALL ctl_warn('zdf_tmx_alloc: failed to allocate arrays')
+   END FUNCTION zdf_tmx_alloc
+
+
+   SUBROUTINE zdf_tmx( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_tmx  ***
+      !!                   
+      !! ** Purpose :   add to the vertical mixing coefficients the effect of
+      !!              breaking internal waves.
+      !!
+      !! ** Method  : - internal wave-driven vertical mixing is given by:
+      !!                  Kz_wave = min(  100 cm2/s, f(  Reb = emix_tmx /( Nu * N^2 )  )
+      !!              where emix_tmx is the 3D space distribution of the wave-breaking 
+      !!              energy and Nu the molecular kinematic viscosity.
+      !!              The function f(Reb) is linear (constant mixing efficiency)
+      !!              if the namelist parameter ln_mevar = F and nonlinear if ln_mevar = T.
+      !!
+      !!              - Compute emix_tmx, the 3D power density that allows to compute
+      !!              Reb and therefrom the wave-induced vertical diffusivity.
+      !!              This is divided into three components:
+      !!                 1. Bottom-intensified low-mode dissipation at critical slopes
+      !!                     emix_tmx(z) = ( ecri_tmx / rau0 ) * EXP( -(H-z)/hcri_tmx )
+      !!                                   / ( 1. - EXP( - H/hcri_tmx ) ) * hcri_tmx
+      !!              where hcri_tmx is the characteristic length scale of the bottom 
+      !!              intensification, ecri_tmx a map of available power, and H the ocean depth.
+      !!                 2. Pycnocline-intensified low-mode dissipation
+      !!                     emix_tmx(z) = ( epyc_tmx / rau0 ) * ( sqrt(rn2(z))^nn_zpyc )
+      !!                                   / SUM( sqrt(rn2(z))^nn_zpyc * e3w(z) )
+      !!              where epyc_tmx is a map of available power, and nn_zpyc
+      !!              is the chosen stratification-dependence of the internal wave
+      !!              energy dissipation.
+      !!                 3. WKB-height dependent high mode dissipation
+      !!                     emix_tmx(z) = ( ebot_tmx / rau0 ) * rn2(z) * EXP(-z_wkb(z)/hbot_tmx)
+      !!                                   / SUM( rn2(z) * EXP(-z_wkb(z)/hbot_tmx) * e3w(z) )
+      !!              where hbot_tmx is the characteristic length scale of the WKB bottom 
+      !!              intensification, ebot_tmx is a map of available power, and z_wkb is the
+      !!              WKB-stretched height above bottom defined as
+      !!                    z_wkb(z) = H * SUM( sqrt(rn2(z'>=z)) * e3w(z'>=z) )
+      !!                                 / SUM( sqrt(rn2(z'))    * e3w(z')    )
+      !!
+      !!              - update the model vertical eddy viscosity and diffusivity: 
+      !!                     avt  = avt  +    av_wave
+      !!                     avm  = avm  +    av_wave
+      !!                     avmu = avmu + mi(av_wave)
+      !!                     avmv = avmv + mj(av_wave)
+      !!
+      !!              - if namelist parameter ln_tsdiff = T, account for differential mixing:
+      !!                     avs  = avt  +    av_wave * diffusivity_ratio(Reb)
+      !!
+      !! ** Action  : - Define emix_tmx used to compute internal wave-induced mixing
+      !!              - avt, avs, avm, avmu, avmv increased by internal wave-driven mixing    
+      !!
+      !! References :  de Lavergne et al. 2015, JPO; 2016, in prep.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step 
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   ztpc         ! scalar workspace
+      REAL(wp), DIMENSION(:,:)  , POINTER ::  zfact     ! Used for vertical structure
+      REAL(wp), DIMENSION(:,:)  , POINTER ::  zhdep     ! Ocean depth
+      REAL(wp), DIMENSION(:,:,:), POINTER ::  zwkb      ! WKB-stretched height above bottom
+      REAL(wp), DIMENSION(:,:,:), POINTER ::  zweight   ! Weight for high mode vertical distribution
+      REAL(wp), DIMENSION(:,:,:), POINTER ::  znu_t     ! Molecular kinematic viscosity (T grid)
+      REAL(wp), DIMENSION(:,:,:), POINTER ::  znu_w     ! Molecular kinematic viscosity (W grid)
+      REAL(wp), DIMENSION(:,:,:), POINTER ::  zReb      ! Turbulence intensity parameter
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )   CALL timing_start('zdf_tmx')
+      !
+      CALL wrk_alloc( jpi,jpj,       zfact, zhdep )
+      CALL wrk_alloc( jpi,jpj,jpk,   zwkb, zweight, znu_t, znu_w, zReb )
+
+      !                          ! ----------------------------- !
+      !                          !  Internal wave-driven mixing  !  (compute zav_wave)
+      !                          ! ----------------------------- !
+      !                             
+      !                        !* Critical slope mixing: distribute energy over the time-varying ocean depth,
+      !                                                 using an exponential decay from the seafloor.
+      DO jj = 1, jpj                ! part independent of the level
+         DO ji = 1, jpi
+            zhdep(ji,jj) = fsdepw(ji,jj,mbkt(ji,jj)+1)       ! depth of the ocean
+            zfact(ji,jj) = rau0 * (  1._wp - EXP( -zhdep(ji,jj) / hcri_tmx(ji,jj) )  )
+            IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = ecri_tmx(ji,jj) / zfact(ji,jj)
+         END DO
+      END DO
+
+      DO jk = 2, jpkm1              ! complete with the level-dependent part
+         emix_tmx(:,:,jk) = zfact(:,:) * (  EXP( ( fsde3w(:,:,jk  ) - zhdep(:,:) ) / hcri_tmx(:,:) )                      &
+            &                             - EXP( ( fsde3w(:,:,jk-1) - zhdep(:,:) ) / hcri_tmx(:,:) )  ) * wmask(:,:,jk)   &
+            &                          / ( fsde3w(:,:,jk) - fsde3w(:,:,jk-1) )
+      END DO
+
+      !                        !* Pycnocline-intensified mixing: distribute energy over the time-varying 
+      !                        !* ocean depth as proportional to sqrt(rn2)^nn_zpyc
+
+      SELECT CASE ( nn_zpyc )
+
+      CASE ( 1 )               ! Dissipation scales as N (recommended)
+
+         zfact(:,:) = 0._wp
+         DO jk = 2, jpkm1              ! part independent of the level
+            zfact(:,:) = zfact(:,:) + fse3w(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         END DO
+
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = epyc_tmx(ji,jj) / ( rau0 * zfact(ji,jj) )
+            END DO
+         END DO
+
+         DO jk = 2, jpkm1              ! complete with the level-dependent part
+            emix_tmx(:,:,jk) = emix_tmx(:,:,jk) + zfact(:,:) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         END DO
+
+      CASE ( 2 )               ! Dissipation scales as N^2
+
+         zfact(:,:) = 0._wp
+         DO jk = 2, jpkm1              ! part independent of the level
+            zfact(:,:) = zfact(:,:) + fse3w(:,:,jk) * MAX( 0._wp, rn2(:,:,jk) ) * wmask(:,:,jk)
+         END DO
+
+         DO jj= 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = epyc_tmx(ji,jj) / ( rau0 * zfact(ji,jj) )
+            END DO
+         END DO
+
+         DO jk = 2, jpkm1              ! complete with the level-dependent part
+            emix_tmx(:,:,jk) = emix_tmx(:,:,jk) + zfact(:,:) * MAX( 0._wp, rn2(:,:,jk) ) * wmask(:,:,jk)
+         END DO
+
+      END SELECT
+
+      !                        !* WKB-height dependent mixing: distribute energy over the time-varying 
+      !                        !* ocean depth as proportional to rn2 * exp(-z_wkb/rn_hbot)
+      
+      zwkb(:,:,:) = 0._wp
+      zfact(:,:) = 0._wp
+      DO jk = 2, jpkm1
+         zfact(:,:) = zfact(:,:) + fse3w(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         zwkb(:,:,jk) = zfact(:,:)
+      END DO
+
+      DO jk = 2, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zwkb(ji,jj,jk) = zhdep(ji,jj) * ( zfact(ji,jj) - zwkb(ji,jj,jk) )   &
+                                            &           * tmask(ji,jj,jk) / zfact(ji,jj)
+            END DO
+         END DO
+      END DO
+      zwkb(:,:,1) = zhdep(:,:) * tmask(:,:,1)
+
+      zweight(:,:,:) = 0._wp
+      DO jk = 2, jpkm1
+         zweight(:,:,jk) = MAX( 0._wp, rn2(:,:,jk) ) * hbot_tmx(:,:) * wmask(:,:,jk)                    &
+            &   * (  EXP( -zwkb(:,:,jk) / hbot_tmx(:,:) ) - EXP( -zwkb(:,:,jk-1) / hbot_tmx(:,:) )  )
+      END DO
+
+      zfact(:,:) = 0._wp
+      DO jk = 2, jpkm1              ! part independent of the level
+         zfact(:,:) = zfact(:,:) + zweight(:,:,jk)
+      END DO
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = ebot_tmx(ji,jj) / ( rau0 * zfact(ji,jj) )
+         END DO
+      END DO
+
+      DO jk = 2, jpkm1              ! complete with the level-dependent part
+         emix_tmx(:,:,jk) = emix_tmx(:,:,jk) + zweight(:,:,jk) * zfact(:,:) * wmask(:,:,jk)   &
+            &                                / ( fsde3w(:,:,jk) - fsde3w(:,:,jk-1) )
+      END DO
+
+
+      ! Calculate molecular kinematic viscosity
+      znu_t(:,:,:) = 1.e-4_wp * (  17.91_wp - 0.53810_wp * tsn(:,:,:,jp_tem) + 0.00694_wp * tsn(:,:,:,jp_tem) * tsn(:,:,:,jp_tem)  &
+         &                                  + 0.02305_wp * tsn(:,:,:,jp_sal)  ) * tmask(:,:,:) * r1_rau0
+      DO jk = 2, jpkm1
+         znu_w(:,:,jk) = 0.5_wp * ( znu_t(:,:,jk-1) + znu_t(:,:,jk) ) * wmask(:,:,jk)
+      END DO
+
+      ! Calculate turbulence intensity parameter Reb
+      DO jk = 2, jpkm1
+         zReb(:,:,jk) = emix_tmx(:,:,jk) / MAX( 1.e-20_wp, znu_w(:,:,jk) * rn2(:,:,jk) )
+      END DO
+
+      ! Define internal wave-induced diffusivity
+      DO jk = 2, jpkm1
+         zav_wave(:,:,jk) = znu_w(:,:,jk) * zReb(:,:,jk) * r1_6   ! This corresponds to a constant mixing efficiency of 1/6
+      END DO
+
+      IF( ln_mevar ) THEN              ! Variable mixing efficiency case : modify zav_wave in the
+         DO jk = 2, jpkm1              ! energetic (Reb > 480) and buoyancy-controlled (Reb <10.224 ) regimes
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( zReb(ji,jj,jk) > 480.00_wp ) THEN
+                     zav_wave(ji,jj,jk) = 3.6515_wp * znu_w(ji,jj,jk) * SQRT( zReb(ji,jj,jk) )
+                  ELSEIF( zReb(ji,jj,jk) < 10.224_wp ) THEN
+                     zav_wave(ji,jj,jk) = 0.052125_wp * znu_w(ji,jj,jk) * zReb(ji,jj,jk) * SQRT( zReb(ji,jj,jk) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      DO jk = 2, jpkm1                 ! Bound diffusivity by molecular value and 100 cm2/s
+         zav_wave(:,:,jk) = MIN(  MAX( 1.4e-7_wp, zav_wave(:,:,jk) ), 1.e-2_wp  ) * wmask(:,:,jk)
+      END DO
+
+      IF( kt == nit000 ) THEN        !* Control print at first time-step: diagnose the energy consumed by zav_wave
+         ztpc = 0._wp
+         DO jk = 2, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ztpc = ztpc + fse3w(ji,jj,jk) * e1e2t(ji,jj)   &
+                     &         * MAX( 0._wp, rn2(ji,jj,jk) ) * zav_wave(ji,jj,jk) * wmask(ji,jj,jk) * tmask_i(ji,jj)
+               END DO
+            END DO
+         END DO
+         IF( lk_mpp )   CALL mpp_sum( ztpc )
+         ztpc = rau0 * ztpc ! Global integral of rauo * Kz * N^2 = power contributing to mixing 
+ 
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'zdf_tmx : Internal wave-driven mixing (tmx)'
+            WRITE(numout,*) '~~~~~~~ '
+            WRITE(numout,*)
+            WRITE(numout,*) '      Total power consumption by av_wave: ztpc =  ', ztpc * 1.e-12_wp, 'TW'
+         ENDIF
+      ENDIF
+
+      !                          ! ----------------------- !
+      !                          !   Update  mixing coefs  !                          
+      !                          ! ----------------------- !
+      !      
+      IF( ln_tsdiff ) THEN          !* Option for differential mixing of salinity and temperature
+         DO jk = 2, jpkm1              ! Calculate S/T diffusivity ratio as a function of Reb
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zav_ratio(ji,jj,jk) = ( 0.505_wp + 0.495_wp *                                                                  &
+                      &   TANH(    0.92_wp * (   LOG10(  MAX( 1.e-20_wp, zReb(ji,jj,jk) * 5._wp * r1_6 )  ) - 0.60_wp   )    )   &
+                      &                 ) * wmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "av_ratio", zav_ratio )
+         DO jk = 2, jpkm1           !* update momentum & tracer diffusivity with wave-driven mixing
+            fsavs(:,:,jk) = avt(:,:,jk) + zav_wave(:,:,jk) * zav_ratio(:,:,jk)
+            avt  (:,:,jk) = avt(:,:,jk) + zav_wave(:,:,jk)
+            avm  (:,:,jk) = avm(:,:,jk) + zav_wave(:,:,jk)
+         END DO
+         !
+      ELSE                          !* update momentum & tracer diffusivity with wave-driven mixing
+         DO jk = 2, jpkm1
+            fsavs(:,:,jk) = avt(:,:,jk) + zav_wave(:,:,jk)
+            avt  (:,:,jk) = avt(:,:,jk) + zav_wave(:,:,jk)
+            avm  (:,:,jk) = avm(:,:,jk) + zav_wave(:,:,jk)
+         END DO
+      ENDIF
+
+      DO jk = 2, jpkm1              !* update momentum diffusivity at wu and wv points
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1  ! vector opt.
+               avmu(ji,jj,jk) = avmu(ji,jj,jk) + 0.5_wp * ( zav_wave(ji,jj,jk) + zav_wave(ji+1,jj  ,jk) ) * wumask(ji,jj,jk)
+               avmv(ji,jj,jk) = avmv(ji,jj,jk) + 0.5_wp * ( zav_wave(ji,jj,jk) + zav_wave(ji  ,jj+1,jk) ) * wvmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( avmu, 'U', 1. )   ;   CALL lbc_lnk( avmv, 'V', 1. )      ! lateral boundary condition
+
+      !                             !* output internal wave-driven mixing coefficient
+      CALL iom_put( "av_wave", zav_wave )
+                                    !* output useful diagnostics: N^2, Kz * N^2 (bflx_tmx), 
+                                    !  vertical integral of rau0 * Kz * N^2 (pcmap_tmx), energy density (emix_tmx)
+      IF( iom_use("bflx_tmx") .OR. iom_use("pcmap_tmx") ) THEN
+         bflx_tmx(:,:,:) = MAX( 0._wp, rn2(:,:,:) ) * zav_wave(:,:,:)
+         pcmap_tmx(:,:) = 0._wp
+         DO jk = 2, jpkm1
+            pcmap_tmx(:,:) = pcmap_tmx(:,:) + fse3w(:,:,jk) * bflx_tmx(:,:,jk) * wmask(:,:,jk)
+         END DO
+         pcmap_tmx(:,:) = rau0 * pcmap_tmx(:,:)
+         CALL iom_put( "bflx_tmx", bflx_tmx )
+         CALL iom_put( "pcmap_tmx", pcmap_tmx )
+      ENDIF
+      CALL iom_put( "emix_tmx", emix_tmx )
+      
+      CALL wrk_dealloc( jpi,jpj,       zfact, zhdep )
+      CALL wrk_dealloc( jpi,jpj,jpk,   zwkb, zweight, znu_t, znu_w, zReb )
+
+      IF(ln_ctl)   CALL prt_ctl(tab3d_1=zav_wave , clinfo1=' tmx - av_wave: ', tab3d_2=avt, clinfo2=' avt: ', ovlap=1, kdim=jpk)
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('zdf_tmx')
+      !
+   END SUBROUTINE zdf_tmx
+
+
+   SUBROUTINE zdf_tmx_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_tmx_init  ***
+      !!                     
+      !! ** Purpose :   Initialization of the wave-driven vertical mixing, reading
+      !!              of input power maps and decay length scales in netcdf files.
+      !!
+      !! ** Method  : - Read the namzdf_tmx namelist and check the parameters
+      !!
+      !!              - Read the input data in NetCDF files :
+      !!              power available from high-mode wave breaking (mixing_power_bot.nc)
+      !!              power available from pycnocline-intensified wave-breaking (mixing_power_pyc.nc)
+      !!              power available from critical slope wave-breaking (mixing_power_cri.nc)
+      !!              WKB decay scale for high-mode wave-breaking (decay_scale_bot.nc)
+      !!              decay scale for critical slope wave-breaking (decay_scale_cri.nc)
+      !!
+      !! ** input   : - Namlist namzdf_tmx
+      !!              - NetCDF files : mixing_power_bot.nc, mixing_power_pyc.nc, mixing_power_cri.nc,
+      !!              decay_scale_bot.nc decay_scale_cri.nc
+      !!
+      !! ** Action  : - Increase by 1 the nstop flag is setting problem encounter
+      !!              - Define ebot_tmx, epyc_tmx, ecri_tmx, hbot_tmx, hcri_tmx
+      !!
+      !! References : de Lavergne et al. 2015, JPO; 2016, in prep.
+      !!			  
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   inum         ! local integer
+      INTEGER  ::   ios
+      REAL(wp) ::   zbot, zpyc, zcri   ! local scalars
+      !!
+      NAMELIST/namzdf_tmx_new/ nn_zpyc, ln_mevar, ln_tsdiff
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('zdf_tmx_init')
+      !
+      REWIND( numnam_ref )              ! Namelist namzdf_tmx in reference namelist : Wave-driven mixing
+      READ  ( numnam_ref, namzdf_tmx_new, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_tmx in reference namelist', lwp )
+      !
+      REWIND( numnam_cfg )              ! Namelist namzdf_tmx in configuration namelist : Wave-driven mixing
+      READ  ( numnam_cfg, namzdf_tmx_new, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_tmx in configuration namelist', lwp )
+      IF(lwm) WRITE ( numond, namzdf_tmx_new )
+      !
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_tmx_init : internal wave-driven mixing'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_tmx_new : set wave-driven mixing parameters'
+         WRITE(numout,*) '      Pycnocline-intensified diss. scales as N (=1) or N^2 (=2) = ', nn_zpyc
+         WRITE(numout,*) '      Variable (T) or constant (F) mixing efficiency            = ', ln_mevar
+         WRITE(numout,*) '      Differential internal wave-driven mixing (T) or not (F)   = ', ln_tsdiff
+      ENDIF
+      
+      ! The new wave-driven mixing parameterization elevates avt and avm in the interior, and
+      ! ensures that avt remains larger than its molecular value (=1.4e-7). Therefore, avtb should 
+      ! be set here to a very small value, and avmb to its (uniform) molecular value (=1.4e-6).
+      avmb(:) = 1.4e-6_wp        ! viscous molecular value
+      avtb(:) = 1.e-10_wp        ! very small diffusive minimum (background avt is specified in zdf_tmx)    
+      avtb_2d(:,:) = 1.e0_wp     ! uniform 
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Force the background value applied to avm & avt in TKE to be everywhere ',   &
+            &               'the viscous molecular value & a very small diffusive value, resp.'
+      ENDIF
+      
+      IF( .NOT.lk_zdfddm )   CALL ctl_stop( 'STOP', 'zdf_tmx_init_new : key_zdftmx_new requires key_zdfddm' )
+      
+      !                             ! allocate tmx arrays
+      IF( zdf_tmx_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_tmx_init : unable to allocate tmx arrays' )
+      !
+      !                             ! read necessary fields
+      CALL iom_open('mixing_power_bot',inum)       ! energy flux for high-mode wave breaking [W/m2]
+      CALL iom_get  (inum, jpdom_data, 'field', ebot_tmx, 1 ) 
+      CALL iom_close(inum)
+      !
+      CALL iom_open('mixing_power_pyc',inum)       ! energy flux for pynocline-intensified wave breaking [W/m2]
+      CALL iom_get  (inum, jpdom_data, 'field', epyc_tmx, 1 )
+      CALL iom_close(inum)
+      !
+      CALL iom_open('mixing_power_cri',inum)       ! energy flux for critical slope wave breaking [W/m2]
+      CALL iom_get  (inum, jpdom_data, 'field', ecri_tmx, 1 )
+      CALL iom_close(inum)
+      !
+      CALL iom_open('decay_scale_bot',inum)        ! spatially variable decay scale for high-mode wave breaking [m]
+      CALL iom_get  (inum, jpdom_data, 'field', hbot_tmx, 1 )
+      CALL iom_close(inum)
+      !
+      CALL iom_open('decay_scale_cri',inum)        ! spatially variable decay scale for critical slope wave breaking [m]
+      CALL iom_get  (inum, jpdom_data, 'field', hcri_tmx, 1 )
+      CALL iom_close(inum)
+
+      ebot_tmx(:,:) = ebot_tmx(:,:) * ssmask(:,:)
+      epyc_tmx(:,:) = epyc_tmx(:,:) * ssmask(:,:)
+      ecri_tmx(:,:) = ecri_tmx(:,:) * ssmask(:,:)
+
+      ! Set once for all to zero the first and last vertical levels of appropriate variables
+      emix_tmx (:,:, 1 ) = 0._wp
+      emix_tmx (:,:,jpk) = 0._wp
+      zav_ratio(:,:, 1 ) = 0._wp
+      zav_ratio(:,:,jpk) = 0._wp
+      zav_wave (:,:, 1 ) = 0._wp
+      zav_wave (:,:,jpk) = 0._wp
+
+      zbot = glob_sum( e1e2t(:,:) * ebot_tmx(:,:) )
+      zpyc = glob_sum( e1e2t(:,:) * epyc_tmx(:,:) )
+      zcri = glob_sum( e1e2t(:,:) * ecri_tmx(:,:) )
+      IF(lwp) THEN
+         WRITE(numout,*) '      High-mode wave-breaking energy:             ', zbot * 1.e-12_wp, 'TW'
+         WRITE(numout,*) '      Pycnocline-intensifed wave-breaking energy: ', zpyc * 1.e-12_wp, 'TW'
+         WRITE(numout,*) '      Critical slope wave-breaking energy:        ', zcri * 1.e-12_wp, 'TW'
+      ENDIF
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('zdf_tmx_init')
+      !
+   END SUBROUTINE zdf_tmx_init
+
 #else
    !!----------------------------------------------------------------------
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/nemogcm.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/nemogcm.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/nemogcm.F90	(revision 9987)
@@ -68,4 +68,5 @@
    USE icbini          ! handle bergs, initialisation
    USE icbstp          ! handle bergs, calving, themodynamics and transport
+   USE sbccpl 
    USE cpl_oasis3      ! OASIS3 coupling
    USE c1d             ! 1D configuration
@@ -74,4 +75,5 @@
 #if defined key_top
    USE trcini          ! passive tracer initialisation
+   USE trc, ONLY: numstr  ! tracer stats unit number
 #endif
    USE lib_mpp         ! distributed memory computing
@@ -161,9 +163,25 @@
           ENDIF
 
+#if defined key_agrif
+          CALL Agrif_Regrid()
+#endif
+
          DO WHILE ( istp <= nitend .AND. nstop == 0 )
 #if defined key_agrif
-            CALL Agrif_Step( stp )           ! AGRIF: time stepping
+            CALL stp                         ! AGRIF: time stepping
 #else
-            CALL stp( istp )                 ! standard time stepping
+            IF (lk_oasis) CALL sbc_cpl_snd( istp )  ! Coupling to atmos
+ 	    CALL stp( istp )
+            ! We don't couple on the final timestep because
+            ! our restart file has already been written
+            ! and contains all the necessary data for a
+            ! restart. sbc_cpl_snd could be called here
+            ! but it would require
+            ! a) A test to ensure it was not performed
+            !    on the very last time-step
+            ! b) the presence of another call to
+            !    sbc_cpl_snd call prior to the main DO loop
+            ! This solution produces identical results
+            ! with fewer lines of code. 
 #endif
             istp = istp + 1
@@ -187,8 +205,10 @@
       !
 #if defined key_agrif
-      CALL Agrif_ParentGrid_To_ChildGrid()
-      IF( lk_diaobs ) CALL dia_obs_wri
-      IF( nn_timing == 1 )   CALL timing_finalize
-      CALL Agrif_ChildGrid_To_ParentGrid()
+      IF( .NOT. Agrif_Root() ) THEN
+         CALL Agrif_ParentGrid_To_ChildGrid()
+         IF( lk_diaobs ) CALL dia_obs_wri
+         IF( nn_timing == 1 )   CALL timing_finalize
+         CALL Agrif_ChildGrid_To_ParentGrid()
+      ENDIF
 #endif
       IF( nn_timing == 1 )   CALL timing_finalize
@@ -206,4 +226,7 @@
       ENDIF
 #endif
+      !
+      ! Met Office addition: if failed, return non-zero exit code
+      IF( nstop /= 0 )  CALL exit( 9 ) 
       !
    END SUBROUTINE nemo_gcm
@@ -277,5 +300,5 @@
       IF( Agrif_Root() ) THEN
          IF( lk_oasis ) THEN
-            CALL cpl_init( "oceanx", ilocal_comm )                     ! nemo local communicator given by oasis
+            CALL cpl_init( "toyoce", ilocal_comm )                     ! nemo local communicator given by oasis
             CALL xios_initialize( "not used",local_comm=ilocal_comm )    ! send nemo communicator to xios
          ELSE
@@ -288,5 +311,5 @@
       IF( lk_oasis ) THEN
          IF( Agrif_Root() ) THEN
-            CALL cpl_init( "oceanx", ilocal_comm )                      ! nemo local communicator given by oasis
+            CALL cpl_init( "toyoce", ilocal_comm )                      ! nemo local communicator given by oasis
          ENDIF
          ! Nodes selection (control print return in cltxt)
@@ -334,6 +357,14 @@
          jpj = ( jpjglo-2*jprecj + (jpnj-1) ) / jpnj + 2*jprecj   ! second dim.
 #endif
-      ENDIF
+      ENDIF         
          jpk = jpkdta                                             ! third dim
+#if defined key_agrif
+         ! simple trick to use same vertical grid as parent
+         ! but different number of levels: 
+         ! Save maximum number of levels in jpkdta, then define all vertical grids
+         ! with this number.
+         ! Suppress once vertical online interpolation is ok
+         IF(.NOT.Agrif_Root()) jpkdta = Agrif_Parent(jpkdta)
+#endif
          jpim1 = jpi-1                                            ! inner domain indices
          jpjm1 = jpj-1                                            !   "           "
@@ -448,9 +479,9 @@
       !                                     ! Diagnostics
       IF( lk_floats     )   CALL     flo_init   ! drifting Floats
-      IF( lk_diaar5     )   CALL dia_ar5_init   ! ar5 diag
                             CALL dia_ptr_init   ! Poleward TRansports initialization
       IF( lk_diadct     )   CALL dia_dct_init   ! Sections tranports
                             CALL dia_hsb_init   ! heat content, salt content and volume budgets
                             CALL     trd_init   ! Mixed-layer/Vorticity/Integral constraints trends
+                            CALL     bias_init  ! Pressure correction bias
       IF( lk_diaobs     ) THEN                  ! Observation & model comparison
                             CALL dia_obs_init            ! Initialize observational data
@@ -461,4 +492,9 @@
       IF( lk_asminc     )   CALL asm_inc_init   ! Initialize assimilation increments
       IF(lwp) WRITE(numout,*) 'Euler time step switch is ', neuler
+      
+      IF (nstop > 0) THEN
+        CALL CTL_STOP('STOP','Critical errors in NEMO initialisation')
+      END IF
+
       !
    END SUBROUTINE nemo_init
@@ -596,5 +632,7 @@
       IF( numdct_heat     /= -1 )   CLOSE( numdct_heat     )   ! heat transports
       IF( numdct_salt     /= -1 )   CLOSE( numdct_salt     )   ! salt transports
-
+#if defined key_top
+      IF( numstr          /= -1 )   CLOSE( numstr          )   ! tracer statistics 
+#endif
       !
       numout = 6                                     ! redefine numout in case it is used after this point...
@@ -612,4 +650,5 @@
       !!----------------------------------------------------------------------
       USE diawri    , ONLY: dia_wri_alloc
+      USE insitu_tem, ONLY: insitu_tem_alloc
       USE dom_oce   , ONLY: dom_oce_alloc
       USE ldfdyn_oce, ONLY: ldfdyn_oce_alloc
@@ -628,4 +667,5 @@
       ierr =        oce_alloc       ()          ! ocean
       ierr = ierr + dia_wri_alloc   ()
+      ierr = ierr + insitu_tem_alloc()
       ierr = ierr + dom_oce_alloc   ()          ! ocean domain
       ierr = ierr + ldfdyn_oce_alloc()          ! ocean lateral  physics : dynamics
@@ -710,10 +750,11 @@
       INTEGER :: ifac, jl, inu
       INTEGER, PARAMETER :: ntest = 14
-      INTEGER :: ilfax(ntest)
-      !
-      ! lfax contains the set of allowed factors.
-      data (ilfax(jl),jl=1,ntest) / 16384, 8192, 4096, 2048, 1024, 512, 256,  &
-         &                            128,   64,   32,   16,    8,   4,   2  /
-      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(ntest) :: ilfax
+      !
+      ! ilfax contains the set of allowed factors.
+      ilfax(:) = (/(2**jl,jl=ntest,1,-1)/)
+      !!----------------------------------------------------------------------
+      ! ilfax contains the set of allowed factors.
+      ilfax(:) = (/(2**jl,jl=ntest,1,-1)/)
 
       ! Clear the error flag and initialise output vars
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/oce.F90	(revision 9987)
@@ -71,5 +71,21 @@
    !! Energy budget of the leads (open water embedded in sea ice)
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fraqsr_1lev        !: fraction of solar net radiation absorbed in the first ocean level [-]
+ 
+   !! Arrays used in coupling when MEDUSA is present. These arrays need to be declared
+   !! even if MEDUSA is not active, to allow compilation, in which case they will not be allocated. 
+   !! ---------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE :: CO2Flux_out_cpl(:,:)  ! Output coupling CO2 flux  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE :: DMS_out_cpl(:,:)      ! Output coupling DMS  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE :: chloro_out_cpl(:,:)   ! Output coupling chlorophyll 
+                                                                ! (expected in Kg/M3)  
 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE :: PCO2a_in_cpl(:,:)     ! Input coupling CO2 partial pressure 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE :: Dust_in_cpl(:,:)      ! Input coupling dust 
+
+#if defined key_medusa
+   LOGICAL, PUBLIC, PARAMETER :: ln_medusa=.TRUE. ! Medusa switched on or off. 
+#else
+   LOGICAL, PUBLIC, PARAMETER :: ln_medusa=.FALSE. ! Medusa switched on or off. 
+#endif
    !!----------------------------------------------------------------------
    !! NEMO/OPA 4.0 , NEMO Consortium (2011)
@@ -83,5 +99,5 @@
       !!                   ***  FUNCTION oce_alloc  ***
       !!----------------------------------------------------------------------
-      INTEGER :: ierr(4)
+      INTEGER :: ierr(5)
       !!----------------------------------------------------------------------
       !
@@ -119,4 +135,15 @@
       ALLOCATE( fraqsr_1lev(jpi,jpj) , STAT=ierr(4) )
          !
+#if defined key_oasis3
+      IF (ln_medusa) THEN
+         ! We only actually need these arrays to be allocated if coupling and MEDUSA 
+         ! are enabled
+         ALLOCATE( CO2Flux_out_cpl(jpi,jpj), DMS_out_cpl(jpi,jpj),               &
+                   chloro_out_cpl(jpi,jpj),                                      &
+                   PCO2a_in_cpl(jpi,jpj), Dust_in_cpl(jpi,jpj),     STAT=ierr(5) )
+
+      ENDIF
+#endif
+
       oce_alloc = MAXVAL( ierr )
       IF( oce_alloc /= 0 )   CALL ctl_warn('oce_alloc: failed to allocate arrays')
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/step.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/step.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/step.F90	(revision 9987)
@@ -33,4 +33,5 @@
    USE step_oce         ! time stepping definition modules
    USE iom
+   USE lbclnk
 
    IMPLICIT NONE
@@ -50,5 +51,5 @@
 
 #if defined key_agrif
-   SUBROUTINE stp( )
+   RECURSIVE SUBROUTINE stp( )
       INTEGER             ::   kstp   ! ocean time-step index
 #else
@@ -73,4 +74,5 @@
       !!----------------------------------------------------------------------
       INTEGER ::   jk       ! dummy loop indice
+      INTEGER ::   tind     ! tracer loop index
       INTEGER ::   indic    ! error indicator if < 0
       INTEGER ::   kcall    ! optional integer argument (dom_vvl_sf_nxt)
@@ -79,7 +81,11 @@
 #if defined key_agrif
       kstp = nit000 + Agrif_Nb_Step()
-!      IF ( Agrif_Root() .and. lwp) Write(*,*) '---'
-!      IF (lwp) Write(*,*) 'Grid Number',Agrif_Fixed(),' time step ',kstp
+      IF ( lk_agrif_debug ) THEN
+         IF ( Agrif_Root() .and. lwp) Write(*,*) '---'
+         IF (lwp) Write(*,*) 'Grid Number',Agrif_Fixed(),' time step ',kstp, 'int tstep',Agrif_NbStepint()
+      ENDIF
+
       IF ( kstp == (nit000 + 1) ) lk_agrif_fstep = .FALSE.
+
 # if defined key_iomput
       IF( Agrif_Nbstepint() == 0 )   CALL iom_swap( cxios_context )
@@ -97,4 +103,6 @@
       IF( ln_crs     )       CALL iom_setkt( kstp - nit000 + 1, TRIM(cxios_context)//"_crs" )   ! tell iom we are at time step kstp
 
+      IF( ln_bias )          CALL bias_opn( kstp )
+
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Update data, open boundaries, surface boundary condition (including sea-ice)
@@ -105,4 +113,10 @@
                          CALL bdy_dta ( kstp, time_offset=+1 )   ! update dynamic & tracer data at open boundaries
       ENDIF
+
+      ! We must ensure that tsb halos are up to date on EVERY timestep.
+      DO tind = 1, jpts
+         CALL lbc_lnk( tsb(:,:,:,tind), 'T', 1. )
+      END DO
+
                          CALL sbc    ( kstp )         ! Sea Boundary Condition (including sea-ice)
                                                       ! clem: moved here for bdy ice purpose
@@ -110,5 +124,6 @@
       ! Update stochastic parameters and random T/S fluctuations
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-                        CALL sto_par( kstp )          ! Stochastic parameters
+       IF( ln_sto_eos ) CALL sto_par( kstp )          ! Stochastic parameters
+       IF( ln_sto_eos ) CALL sto_pts( tsn  )          ! Random T/S fluctuations
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -152,6 +167,5 @@
       !
       IF( lk_ldfslp ) THEN                            ! slope of lateral mixing
-         IF(ln_sto_eos ) CALL sto_pts( tsn )          ! Random T/S fluctuations
-                         CALL eos( tsb, rhd, gdept_0(:,:,:) )               ! before in situ density
+         CALL eos( tsb, rhd, gdept_0(:,:,:) )               ! before in situ density
          IF( ln_zps .AND. .NOT. ln_isfcav)                               &
             &            CALL zps_hde    ( kstp, jpts, tsb, gtsu, gtsv,  &  ! Partial steps: before horizontal gradient
@@ -188,6 +202,5 @@
           ! Note that the computation of vertical velocity above, hence "after" sea level
           ! is necessary to compute momentum advection for the rhs of barotropic loop:
-            IF(ln_sto_eos ) CALL sto_pts( tsn )                             ! Random T/S fluctuations
-                            CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) ) ! now in situ density for hpg computation
+            CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) ) ! now in situ density for hpg computation
             IF( ln_zps .AND. .NOT. ln_isfcav)                               &
                &            CALL zps_hde    ( kstp, jpts, tsn, gtsu, gtsv,  &    ! Partial steps: before horizontal gradient
@@ -200,5 +213,5 @@
                                   ua(:,:,:) = 0.e0             ! set dynamics trends to zero
                                   va(:,:,:) = 0.e0
-          IF(  ln_asmiau .AND. &
+          IF(  lk_asminc .AND. ln_asmiau .AND. &
              & ln_dyninc       )  CALL dyn_asm_inc  ( kstp )   ! apply dynamics assimilation increment
           IF( ln_neptsimp )       CALL dyn_nept_cor ( kstp )   ! subtract Neptune velocities (simplified)
@@ -231,4 +244,5 @@
       IF( lk_diaar5  )      CALL dia_ar5( kstp )         ! ar5 diag
       IF( lk_diaharm )      CALL dia_harm( kstp )        ! Tidal harmonic analysis
+                            CALL dia_prod( kstp )        ! ocean model: product diagnostics
                             CALL dia_wri( kstp )         ! ocean model: outputs
       !
@@ -248,5 +262,5 @@
                              tsa(:,:,:,:) = 0.e0            ! set tracer trends to zero
 
-      IF(  ln_asmiau .AND. &
+      IF(  lk_asminc .AND. ln_asmiau .AND. &
          & ln_trainc     )   CALL tra_asm_inc( kstp )       ! apply tracer assimilation increment
                              CALL tra_sbc    ( kstp )       ! surface boundary condition
@@ -255,4 +269,5 @@
       IF( lk_trabbl      )   CALL tra_bbl    ( kstp )       ! advective (and/or diffusive) bottom boundary layer scheme
       IF( ln_tradmp      )   CALL tra_dmp    ( kstp )       ! internal damping trends
+      IF( ln_bias        )   CALL tra_bias   ( kstp )
       IF( lk_bdy         )   CALL bdy_tra_dmp( kstp )       ! bdy damping trends
                              CALL tra_adv    ( kstp )       ! horizontal & vertical advection
@@ -270,5 +285,4 @@
          IF( ln_zdfnpc   )   CALL tra_npc( kstp )                ! update after fields by non-penetrative convection
                              CALL tra_nxt( kstp )                ! tracer fields at next time step
-            IF( ln_sto_eos ) CALL sto_pts( tsn )                 ! Random T/S fluctuations
                              CALL eos    ( tsa, rhd, rhop, fsdept_n(:,:,:) )  ! Time-filtered in situ density for hpg computation
             IF( ln_zps .AND. .NOT. ln_isfcav)                                &
@@ -279,7 +293,7 @@
                &                                           rhd, gru , grv , aru , arv , gzu , gzv , ge3ru , ge3rv ,   &
                &                                    gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi    ) ! of t, s, rd at the last ocean level
+            IF( ln_bias )    CALL dyn_bias( kstp )
       ELSE                                                  ! centered hpg  (eos then time stepping)
          IF ( .NOT. lk_dynspg_ts ) THEN                     ! eos already called in time-split case
-            IF( ln_sto_eos ) CALL sto_pts( tsn )    ! Random T/S fluctuations
                              CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) )  ! now in situ density for hpg computation
          IF( ln_zps .AND. .NOT. ln_isfcav)                                   &
@@ -293,4 +307,5 @@
          IF( ln_zdfnpc   )   CALL tra_npc( kstp )                ! update after fields by non-penetrative convection
                              CALL tra_nxt( kstp )                ! tracer fields at next time step
+         IF( ln_bias )       CALL dyn_bias( kstp )
       ENDIF
 
@@ -314,5 +329,5 @@
                                va(:,:,:) = 0.e0
 
-        IF(  ln_asmiau .AND. &
+        IF(  lk_asminc .AND. ln_asmiau .AND. &
            & ln_dyninc      )  CALL dyn_asm_inc( kstp )     ! apply dynamics assimilation increment
         IF( ln_bkgwri )        CALL asm_bkg_wri( kstp )     ! output background fields
@@ -335,10 +350,24 @@
                                CALL ssh_swp( kstp )         ! swap of sea surface height
       IF( lk_vvl           )   CALL dom_vvl_sf_swp( kstp )  ! swap of vertical scale factors
-
+      !
+      IF( lrst_oce         )   CALL rst_write( kstp )       ! write output ocean restart file
+      IF( ln_sto_eos       )   CALL sto_rst_write( kstp )   ! write restart file for stochastic parameters
+
+#if defined key_agrif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! AGRIF
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+                               CALL Agrif_Integrate_ChildGrids( stp )  
+
+      IF ( Agrif_NbStepint().EQ.0 ) THEN
+                               CALL Agrif_Update_Tra()      ! Update active tracers
+                               CALL Agrif_Update_Dyn()      ! Update momentum
+      ENDIF
+#endif
       IF( ln_diahsb        )   CALL dia_hsb( kstp )         ! - ML - global conservation diagnostics
       IF( lk_diaobs  )         CALL dia_obs( kstp )         ! obs-minus-model (assimilation) diagnostics (call after dynamics update)
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! Control and restarts
+      ! Control
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                                CALL stp_ctl( kstp, indic )
@@ -352,10 +381,12 @@
          IF( lwm.AND.numoni /= -1 ) CALL FLUSH    ( numoni )     ! flush output namelist ice
       ENDIF
-      IF( lrst_oce         )   CALL rst_write    ( kstp )   ! write output ocean restart file
+
+
+      IF( lrst_bias )          CALL bias_wrt     ( kstp )
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Coupled mode
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-      IF( lk_oasis         )   CALL sbc_cpl_snd( kstp )     ! coupled mode : field exchanges
+      !IF( lk_oasis         )   CALL sbc_cpl_snd( kstp )     ! coupled mode : field exchanges
       !
 #if defined key_iomput
@@ -367,4 +398,5 @@
       !
       IF( nn_timing == 1 .AND.  kstp == nit000  )   CALL timing_reset
+      !     
       !
    END SUBROUTINE stp
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/step_oce.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/step_oce.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/step_oce.F90	(revision 9987)
@@ -88,4 +88,5 @@
 
    USE diawri           ! Standard run outputs             (dia_wri routine)
+   USE diaprod          ! Product diagnostics              (dia_prod routine)
    USE diaptr           ! poleward transports              (dia_ptr routine)
    USE diadct           ! sections transports              (dia_dct routine)
@@ -99,5 +100,7 @@
 
    USE crsfld           ! Standard output on coarse grid   (crs_fld routine)
-
+   USE biaspar          ! bias param
+   USE bias             ! bias routines                    (tra_bias routine
+                        !                                   dyn_bias routine)
    USE asminc           ! assimilation increments      (tra_asm_inc routine)
    !                                                   (dyn_asm_inc routine)
@@ -112,4 +115,5 @@
 #if defined key_agrif
    USE agrif_opa_sponge ! Momemtum and tracers sponges
+   USE agrif_opa_update ! Update (2-way nesting)
 #endif
 #if defined key_top
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/stpctl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/stpctl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/stpctl.F90	(revision 9987)
@@ -17,4 +17,5 @@
    USE dom_oce         ! ocean space and time domain variables 
    USE sol_oce         ! ocean space and time domain variables 
+   USE sbc_oce         ! surface boundary conditions variables
    USE in_out_manager  ! I/O manager
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
@@ -22,4 +23,5 @@
    USE dynspg_oce      ! pressure gradient schemes 
    USE c1d             ! 1D vertical configuration
+
 
    IMPLICIT NONE
@@ -52,4 +54,5 @@
       INTEGER, INTENT( inout ) ::   kindic  ! indicator of solver convergence
       !!
+      CHARACTER(len = 32) ::        clfname ! time stepping output file name
       INTEGER  ::   ji, jj, jk              ! dummy loop indices
       INTEGER  ::   ii, ij, ik              ! temporary integers
@@ -63,6 +66,11 @@
          WRITE(numout,*) 'stp_ctl : time-stepping control'
          WRITE(numout,*) '~~~~~~~'
-         ! open time.step file
-         CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+         ! open time.step file with special treatment for SAS
+         IF ( nn_components == jp_iam_sas ) THEN
+            clfname = 'time.step.sas'
+         ELSE
+            clfname = 'time.step'
+         ENDIF
+         CALL ctl_opn( numstp, TRIM(clfname), 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
       ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/wrk_nemo.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/wrk_nemo.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/OPA_SRC/wrk_nemo.F90	(revision 9987)
@@ -453,4 +453,5 @@
    SUBROUTINE wrk_allocbase( kidim , kjdim , kkdim , kldim , kisrt , kjsrt , kksrt , klsrt ,   &
       &                      kwrk1d, kwrk2d, kwrk3d, kwrk4d, pwrk1d, pwrk2d, pwrk3d, pwrk4d    )
+   USE in_out_manager, ONLY: numout
       INTEGER                              , INTENT(in   )           :: kidim, kjdim, kkdim, kldim
       INTEGER                              , INTENT(in   )           :: kisrt, kjsrt, kksrt, klsrt
@@ -483,5 +484,10 @@
          &      .AND. SUM( tree(ii)%ishape ) /= 0 )
          ii = ii + 1
-         IF (ii > jparray) STOP   ! increase the value of jparray (should not be needed as already very big!)
+         IF (ii > jparray) THEN
+            WRITE(numout,*) "E R R O R: NEMO aborted wrk_allocbase"
+            FLUSH(numout)
+            STOP 'Increase the value of jparray'
+                           ! increase the value of jparray (should not be needed as already very big!)
+         END IF
       END DO
       
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/SAS_SRC/daymod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/SAS_SRC/daymod.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/SAS_SRC/daymod.F90	(revision 9987)
@@ -71,4 +71,9 @@
       !!----------------------------------------------------------------------
       !
+      ! max number of seconds between each restart
+      IF( REAL( nitend - nit000 + 1 ) * rdt > REAL( HUGE( nsec1jan000 ) ) ) THEN
+         CALL ctl_stop( 'The number of seconds between each restart exceeds the integer 4 max value: 2^31-1. ',   &
+            &           'You must do a restart at higher frequency (or remove this stop and recompile the code in I8)' )
+      ENDIF
       ! all calendar staff is based on the fact that MOD( rday, rdttra(1) ) == 0
       IF( MOD( rday     , rdttra(1) ) /= 0. )   CALL ctl_stop( 'the time step must devide the number of second of in a day' )
@@ -239,9 +244,4 @@
                nday_year = 1
                nsec_year = ndt05
-               IF( nsec1jan000 >= 2 * (2**30 - nsecd * nyear_len(1) / 2 ) ) THEN   ! test integer 4 max value
-                  CALL ctl_stop( 'The number of seconds between Jan. 1st 00h of nit000 year and Jan. 1st 00h ',   &
-                     &           'of the current year is exceeding the INTEGER 4 max VALUE: 2^31-1 -> 68.09 years in seconds', &
-                     & 'You must do a restart at higher frequency (or remove this STOP and recompile everything in I8)' )
-               ENDIF
                nsec1jan000 = nsec1jan000 + nsecd * nyear_len(1)
                IF( nleapy == 1 )   CALL day_mth
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/SAS_SRC/nemogcm.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/SAS_SRC/nemogcm.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/SAS_SRC/nemogcm.F90	(revision 9987)
@@ -521,5 +521,5 @@
 #endif
       !
-      INTEGER :: ierr,ierr1,ierr2,ierr3,ierr4,ierr5,ierr6
+      INTEGER :: ierr,ierr1,ierr2,ierr3,ierr4,ierr5,ierr6,ierr7,ierr8
       INTEGER :: jpm
       !!----------------------------------------------------------------------
@@ -545,5 +545,7 @@
       ALLOCATE( tsb(jpi,jpj,1,jpm)  , STAT=ierr5 )
       ALLOCATE( sshn(jpi,jpj)       , STAT=ierr6 )
-      ierr = ierr + ierr1 + ierr2 + ierr3 + ierr4 + ierr5 + ierr6 
+      ALLOCATE( un(jpi,jpj,1)       , STAT=ierr7 )
+      ALLOCATE( vn(jpi,jpj,1)       , STAT=ierr8 )
+      ierr = ierr + ierr1 + ierr2 + ierr3 + ierr4 + ierr5 + ierr6  + ierr7 + ierr8
 #endif
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/par_age.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/par_age.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/par_age.F90	(revision 9987)
@@ -0,0 +1,83 @@
+MODULE par_age
+   !!======================================================================
+   !!                        ***  par_age  ***
+   !! TOP :   set the AGE parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+   USE par_pisces , ONLY : jp_pisces       !: number of tracers in PISCES
+   USE par_pisces , ONLY : jp_pisces_2d    !: number of 2D diag in PISCES
+   USE par_pisces , ONLY : jp_pisces_3d    !: number of 3D diag in PISCES
+   USE par_pisces , ONLY : jp_pisces_trd   !: number of biological diag in PISCES
+
+   USE par_medusa , ONLY : jp_medusa       !: number of tracers in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_2d    !: number of 2D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_3d    !: number of 3D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_trd   !: number of biological diag in MEDUSA
+
+   USE par_idtra  , ONLY : jp_idtra        !: number of tracers in MEDUSA
+   USE par_idtra  , ONLY : jp_idtra_2d     !: number of tracers in MEDUSA
+   USE par_idtra  , ONLY : jp_idtra_3d     !: number of tracers in MEDUSA
+   USE par_idtra  , ONLY : jp_idtra_trd    !: number of tracers in MEDUSA
+
+   USE par_cfc    , ONLY : jp_cfc          !: number of tracers in CFC
+   USE par_cfc    , ONLY : jp_cfc_2d       !: number of tracers in CFC
+   USE par_cfc    , ONLY : jp_cfc_3d       !: number of tracers in CFC
+   USE par_cfc    , ONLY : jp_cfc_trd      !: number of tracers in CFC
+
+   USE par_c14b   , ONLY : jp_c14b         !: number of tracers in C14
+   USE par_c14b   , ONLY : jp_c14b_2d      !: number of tracers in C14
+   USE par_c14b   , ONLY : jp_c14b_3d      !: number of tracers in C14
+   USE par_c14b   , ONLY : jp_c14b_trd     !: number of tracers in C14
+
+   IMPLICIT NONE
+
+   INTEGER, PARAMETER ::   jp_lm      =  jp_pisces     + jp_medusa     +            &
+                      jp_idtra      + jp_cfc     + jp_c14b     !:  cum. number of pass. tracers
+   INTEGER, PARAMETER ::   jp_lm_2d   =  jp_pisces_2d  + jp_medusa_2d  +            &
+                      jp_idtra_2d   + jp_cfc_2d  + jp_c14b_2d  !:
+   INTEGER, PARAMETER ::   jp_lm_3d   =  jp_pisces_3d  + jp_medusa_3d  +            &
+                      jp_idtra_3d   + jp_cfc_3d  + jp_c14b_3d  !:
+   INTEGER, PARAMETER ::   jp_lm_trd  =  jp_pisces_trd + jp_medusa_trd +            &
+                      jp_idtra_trd  + jp_cfc_trd + jp_c14b_trd !:
+
+#if defined key_age
+   !!---------------------------------------------------------------------
+   !!   'key_age'                     user defined tracers (AGE)
+   !!---------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_age     = .TRUE.   !: PTS flag 
+   INTEGER, PUBLIC, PARAMETER ::   jp_age     =  1       !: number of PTS tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age_2d  =  0       !: additional 2d output arrays ('key_trc_diaadd')
+   INTEGER, PUBLIC, PARAMETER ::   jp_age_3d  =  0       !: additional 3d output arrays ('key_trc_diaadd')
+   INTEGER, PUBLIC, PARAMETER ::   jp_age_trd =  0       !: number of sms trends for AGE
+
+   ! assign an index in trc arrays for each PTS prognostic variables
+   INTEGER, PUBLIC, PARAMETER ::   jpage1 = jp_lm + 1     !: 1st AGE tracer
+
+#else
+   !!---------------------------------------------------------------------
+   !!   Default                           No user defined tracers (AGE)
+   !!---------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_age     = .FALSE.  !: AGE flag 
+   INTEGER, PUBLIC, PARAMETER ::   jp_age     =  0       !: No AGE tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age_2d  =  0       !: No AGE additional 2d output arrays 
+   INTEGER, PUBLIC, PARAMETER ::   jp_age_3d  =  0       !: No AGE additional 3d output arrays 
+   INTEGER, PUBLIC, PARAMETER ::   jp_age_trd =  0       !: number of sms trends for AGE
+#endif
+
+   ! Starting/ending PISCES do-loop indices (N.B. no PISCES : jpl_pcs < jpf_pcs the do-loop are never done)
+   INTEGER, PUBLIC, PARAMETER ::   jp_age0     = jp_lm     + 1              !: First index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age1     = jp_lm     + jp_age      !: Last  index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age0_2d  = jp_lm_2d  + 1              !: First index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age1_2d  = jp_lm_2d  + jp_age_2d   !: Last  index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age0_3d  = jp_lm_3d  + 1              !: First index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age1_3d  = jp_lm_3d  + jp_age_3d   !: Last  index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age0_trd = jp_lm_trd + 1              !: First index of AGE passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_age1_trd = jp_lm_trd + jp_age_trd  !: Last  index of AGE passive tracers
+
+   !!======================================================================
+END MODULE par_age
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcini_age.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcini_age.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcini_age.F90	(revision 9987)
@@ -0,0 +1,71 @@
+MODULE trcini_age
+   !!======================================================================
+   !!                         ***  MODULE trcini_age  ***
+   !! TOP :   initialisation of the AGE tracer
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (G. Nurser, G. Madec, C. Ethe ) Original code
+   !!----------------------------------------------------------------------
+#if defined key_age
+   !!----------------------------------------------------------------------
+   !!   'key_age'                                               AGE tracer
+   !!----------------------------------------------------------------------
+   !! trc_ini_age   : MY_TRC model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc
+   USE trc
+   USE trcsms_age
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_age   ! called by trcini.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_age
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_age  ***  
+      !!
+      !! ** Purpose :   initialization for AGE model
+      !!
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_age: passive tracer age'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+
+      rryear  = 1._wp / ( nyear_len(1) * rday )    ! recip number of seconds in one year
+
+      !! BUG in s-coordinate this does not work!
+      nlb_age = MINLOC( gdepw_1d, mask = gdepw_1d > rn_age_depth, dim = 1 ) ! shallowest W level Below age_depth
+                                                                            !  = shallowest T level wholly below age_depth
+
+      nl_age  = nlb_age - 1                                                 ! deepest    W level Above age_depth
+                                                                            !  = T level surrounding age_depth
+
+      nla_age = nl_age - 1                                                   ! deepest    T level wholly above age_depth
+
+      frac_kill_age = ( rn_age_depth - gdepw_1d(nl_age) ) / e3t_1d(nl_age)      ! fraction of level nl_age above age_depth
+      frac_add_age  = 1._wp -  frac_kill_age                                    ! fraction of level nl_age below age_depth
+
+      
+      IF( .NOT. ln_rsttr ) trn(:,:,:,jp_age0:jp_age1) = 0.
+      !
+   END SUBROUTINE trc_ini_age
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                        No AGE model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ini_age             ! Empty routine
+   END SUBROUTINE trc_ini_age
+#endif
+
+   !!======================================================================
+END MODULE trcini_age
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcnam_age.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcnam_age.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcnam_age.F90	(revision 9987)
@@ -0,0 +1,82 @@
+MODULE trcnam_age
+   !!======================================================================
+   !!                         ***  MODULE trcnam_age  ***
+   !! TOP :   initialisation of some run parameters for Age tracer
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) 
+   !!----------------------------------------------------------------------
+#if defined key_age
+   !!----------------------------------------------------------------------
+   !!   'key_age'                                               AGE tracers
+   !!----------------------------------------------------------------------
+   !! trc_nam_age      : AGE  tracer initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE trcsms_age      ! AGE specific variable
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nam_age   ! called by trcnam.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_nam_age
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_nam_age  ***
+      !!                 
+      !! ** Purpose :   Definition some run parameter for AGE model
+      !!
+      !! ** input   :   Namelist namage
+      !!----------------------------------------------------------------------
+      INTEGER ::  numnatg_ref = -1   ! Logical unit for reference AGE namelist
+      INTEGER ::  numnatg_cfg = -1   ! Logical unit for configuration AGE namelist
+      INTEGER ::  numong      = -1   ! Logical unit for output namelist
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      INTEGER :: jl, jn
+      !!
+      NAMELIST/namage/ rn_age_depth, rn_age_kill_rate 
+      !!----------------------------------------------------------------------
+      !                             ! Open namelist files
+      CALL ctl_opn( numnatg_ref, 'namelist_age_ref'   ,     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      CALL ctl_opn( numnatg_cfg, 'namelist_age_cfg'   ,     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      IF(lwm) CALL ctl_opn( numong, 'output.namelist.age', 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+
+      REWIND( numnatg_ref )              ! Namelist namagedate in reference namelist : AGE parameters
+      READ  ( numnatg_ref, namage, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namage in reference namelist', lwp )
+
+      REWIND( numnatg_cfg )              ! Namelist namagedate in configuration namelist : AGE parameters
+      READ  ( numnatg_cfg, namage, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namage in configuration namelist', lwp )
+      IF(lwm) WRITE ( numong, namage )
+
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) ' trc_nam_age: Read namage, namelist for Age passive tracer'
+         WRITE(numout,*) ' ~~~~~~~'
+         WRITE(numout,*) '  depth over which age tracer reset to zero                              rn_age_depth      = ', rn_age_depth 
+         WRITE(numout,*) '  recip of relax. timescale (s) for age tracer shallower than age_depth  rn_age_kill_rate  = ', rn_age_kill_rate 
+      ENDIF
+
+      IF(lwm) CALL FLUSH ( numong )     ! flush output namelist
+
+   END SUBROUTINE trc_nam_age
+   
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                                No AGE
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_nam_age                      ! Empty routine
+   END  SUBROUTINE  trc_nam_age
+#endif  
+
+   !!======================================================================
+END MODULE trcnam_age
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcsms_age.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcsms_age.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcsms_age.F90	(revision 9987)
@@ -0,0 +1,102 @@
+MODULE trcsms_age
+   !!======================================================================
+   !!                         ***  MODULE trcsms_age  ***
+   !! TOP :   Main module of the AGE tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!----------------------------------------------------------------------
+#if defined key_age
+   !!----------------------------------------------------------------------
+   !!   'key_age'                                               AGE tracer
+   !!----------------------------------------------------------------------
+   !! trc_sms_age       : AGE model main routine
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+   USE trd_oce
+   USE trdtrc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_age       ! called by trcsms.F90 module
+
+   INTEGER , PUBLIC :: nl_age             ! T level surrounding age_depth
+   INTEGER , PUBLIC :: nla_age            ! T level wholly above age_depth
+   INTEGER , PUBLIC :: nlb_age            ! T level wholly below age_depth
+
+   REAL(wp), PUBLIC :: rn_age_depth       ! = 10       depth over which age tracer reset to zero
+   REAL(wp), PUBLIC :: rn_age_kill_rate   ! = -1./7200  recip of relaxation timescale (s) for  age tracer shallower than age_depth
+   
+   REAL(wp), PUBLIC :: rryear          !: recip number of seconds in one year
+   REAL(wp), PUBLIC :: frac_kill_age   !: fraction of level nl_age above age_depth where it is relaxed towards zero
+   REAL(wp), PUBLIC :: frac_add_age    !: fraction of level nl_age below age_depth where it is incremented
+
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms_age( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_sms_age  ***
+      !!
+      !! ** Purpose :   main routine of AGE model
+      !!
+      !! ** Method  : -
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      INTEGER ::   jn, jk   ! dummy loop index
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztrage
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('trc_sms_age')
+      !
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_sms_age:  AGE model'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      ENDIF
+
+      IF( l_trdtrc )  CALL wrk_alloc( jpi, jpj, jpk, ztrage )
+
+      DO jk = 1, nla_age
+         tra(:,:,jk,jpage1) = rn_age_kill_rate * trb(:,:,jk,jpage1)
+      ENDDO
+      !
+      tra(:,:,nl_age,jpage1) = frac_kill_age * rn_age_kill_rate * trb(:,:,nl_age,jpage1)  &
+          &                  + frac_add_age  * rryear * tmask(:,:,nl_age)
+      !
+      DO jk = nlb_age, jpk
+         tra(:,:,jk,jpage1) = tmask(:,:,jk) * rryear
+      ENDDO
+      !
+      IF( l_trdtrc ) THEN      ! Save the trends in the mixed layer
+          DO jn = jp_age0, jp_age1
+            ztrage(:,:,:) = tra(:,:,:,jn)
+            CALL trd_trc( ztrage, jn, jptra_sms, kt )   ! save trends
+          END DO
+          CALL wrk_dealloc( jpi, jpj, jpk, ztrage )
+      END IF
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('trc_sms_age')
+      !
+   END SUBROUTINE trc_sms_age
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                        No AGE model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_sms_age( kt )             ! Empty routine
+      INTEGER, INTENT( in ) ::   kt
+      WRITE(*,*) 'trc_sms_age: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sms_age
+#endif
+
+   !!======================================================================
+END MODULE trcsms_age
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcwri_age.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcwri_age.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/AGE/trcwri_age.F90	(revision 9987)
@@ -0,0 +1,62 @@
+MODULE trcwri_age
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    age :   Output of age tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_age && defined key_iomput
+   !!----------------------------------------------------------------------
+   !!   'key_age'                                           age model
+   !!----------------------------------------------------------------------
+   !! trc_wri_age   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   USE par_age     
+   USE trc         
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_age 
+
+#  include "top_substitute.h90"
+CONTAINS
+
+   SUBROUTINE trc_wri_age
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra
+      INTEGER              :: jn
+      !!---------------------------------------------------------------------
+
+ 
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      DO jn = jp_age0, jp_age1
+         cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
+         CALL iom_put( TRIM(cltra), trn(:,:,:,jn) )
+      END DO
+      !
+      !
+   END SUBROUTINE trc_wri_age
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_age
+CONTAINS
+   SUBROUTINE trc_wri_age                     ! Empty routine  
+   END SUBROUTINE trc_wri_age
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!======================================================================
+END MODULE trcwri_age
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/C14b/par_c14b.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/C14b/par_c14b.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/C14b/par_c14b.F90	(revision 9987)
@@ -11,4 +11,14 @@
    USE par_pisces , ONLY : jp_pisces_trd   !: number of biological diag in PISCES
 
+   USE par_medusa , ONLY : jp_medusa       !: number of tracers in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_2d    !: number of 2D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_3d    !: number of 3D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_trd   !: number of biological diag in MEDUSA
+
+   USE par_idtra  , ONLY : jp_idtra        !: number of tracers in MEDUSA
+   USE par_idtra  , ONLY : jp_idtra_2d     !: number of tracers in MEDUSA
+   USE par_idtra  , ONLY : jp_idtra_3d     !: number of tracers in MEDUSA
+   USE par_idtra  , ONLY : jp_idtra_trd    !: number of tracers in MEDUSA
+
    USE par_cfc    , ONLY : jp_cfc          !: number of tracers in CFC
    USE par_cfc    , ONLY : jp_cfc_2d       !: number of 2D diag in CFC
@@ -19,8 +29,12 @@
    IMPLICIT NONE
 
-   INTEGER, PARAMETER ::   jp_lb      =  jp_pisces     + jp_cfc     !: cum. number of pass. tracers
-   INTEGER, PARAMETER ::   jp_lb_2d   =  jp_pisces_2d  + jp_cfc_2d  !:
-   INTEGER, PARAMETER ::   jp_lb_3d   =  jp_pisces_3d  + jp_cfc_3d  !:
-   INTEGER, PARAMETER ::   jp_lb_trd  =  jp_pisces_trd + jp_cfc_trd !:
+   INTEGER, PARAMETER ::   jp_lb      =  jp_pisces     + jp_medusa     +   &
+                      jp_idtra      + jp_cfc                               !: cum. number of pass. tracers
+   INTEGER, PARAMETER ::   jp_lb_2d   =  jp_pisces_2d  + jp_medusa_2d  +   &
+                      jp_idtra_2d   + jp_cfc_2d  !:
+   INTEGER, PARAMETER ::   jp_lb_3d   =  jp_pisces_3d  + jp_medusa_3d  +   &
+                      jp_idtra_3d   + jp_cfc_3d  !:
+   INTEGER, PARAMETER ::   jp_lb_trd  =  jp_pisces_trd + jp_medusa_trd +   &
+                      jp_idtra_trd  + jp_cfc_trd !:
    
 #if defined key_c14b
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/C14b/trcnam_c14b.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/C14b/trcnam_c14b.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/C14b/trcnam_c14b.F90	(revision 9987)
@@ -49,9 +49,6 @@
       ! definition of additional diagnostic as a structure
       INTEGER :: jl, jn
-      TYPE(DIAG), DIMENSION(jp_c14b_2d) :: c14dia2d
-      TYPE(DIAG), DIMENSION(jp_c14b_3d) :: c14dia3d
       !!
       NAMELIST/namc14date/ ndate_beg_b, nyear_res_b
-      NAMELIST/namc14dia/  c14dia2d, c14dia3d     ! additional diagnostics
       !!-------------------------------------------------------------------
       !                             ! Open namelist file
@@ -77,50 +74,4 @@
       IF(lwp) WRITE(numout,*) '    initial year (aa)                  nyear_beg_b = ', nyear_beg_b
       !
-      IF( .NOT.lk_iomput .AND. ln_diatrc ) THEN
-         !
-         ! Namelist namc14dia
-         ! -------------------
-         REWIND( numnatb_ref )              ! Namelist namc14dia in reference namelist : c14b diagnostics
-         READ  ( numnatb_ref, namc14dia, IOSTAT = ios, ERR = 903)
-903      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namc14dia in reference namelist', lwp )
-
-         REWIND( numnatb_cfg )              ! Namelist namc14dia in configuration namelist : c14b diagnostics
-         READ  ( numnatb_cfg, namc14dia, IOSTAT = ios, ERR = 904 )
-904      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namc14dia in configuration namelist', lwp )
-         IF(lwm) WRITE ( numonb, namc14dia )
-
-         DO jl = 1, jp_c14b_2d
-            jn = jp_c14b0_2d + jl - 1
-            ctrc2d(jn) = c14dia2d(jl)%sname
-            ctrc2l(jn) = c14dia2d(jl)%lname
-            ctrc2u(jn) = c14dia2d(jl)%units
-         END DO
-
-         DO jl = 1, jp_c14b_3d
-            jn = jp_c14b0_3d + jl - 1
-            ctrc3d(jn) = c14dia3d(jl)%sname
-            ctrc3l(jn) = c14dia3d(jl)%lname
-            ctrc3u(jn) = c14dia3d(jl)%units
-         END DO
-
-         IF(lwp) THEN                   ! control print
-            WRITE(numout,*)
-            WRITE(numout,*) ' Namelist : natadd'
-            DO jl = 1, jp_c14b_3d
-               jn = jp_c14b0_3d + jl - 1
-               WRITE(numout,*) '  3d diag nb : ', jn, '    short name : ', ctrc3d(jn), &
-                 &             '  long name  : ', ctrc3l(jn), '   unit : ', ctrc3u(jn)
-            END DO
-            WRITE(numout,*) ' '
-
-            DO jl = 1, jp_c14b_2d
-               jn = jp_c14b0_2d + jl - 1
-               WRITE(numout,*) '  2d diag nb : ', jn, '    short name : ', ctrc2d(jn), &
-                 &             '  long name  : ', ctrc2l(jn), '   unit : ', ctrc2u(jn)
-            END DO
-            WRITE(numout,*) ' '
-         ENDIF
-         !
-      ENDIF
 
    IF(lwm) CALL FLUSH ( numonb )     ! flush output namelist C14b
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/par_cfc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/par_cfc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/par_cfc.F90	(revision 9987)
@@ -5,4 +5,5 @@
    !!======================================================================
    !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!                  !  2017-04  (A. Yool)  add SF6
    !!----------------------------------------------------------------------
    !! NEMO/TOP 3.3 , NEMO Consortium (2010)
@@ -15,10 +16,24 @@
    USE par_pisces , ONLY : jp_pisces_trd   !: number of biological diag in PISCES
 
+   USE par_medusa , ONLY : jp_medusa       !: number of tracers in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_2d    !: number of 2D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_3d    !: number of 3D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_trd   !: number of biological diag in MEDUSA
+
+   USE par_idtra  , ONLY : jp_idtra        !: number of tracers in ideal tracer
+   USE par_idtra  , ONLY : jp_idtra_2d     !: number of tracers in ideal tracer
+   USE par_idtra  , ONLY : jp_idtra_3d     !: number of tracers in ideal tracer
+   USE par_idtra  , ONLY : jp_idtra_trd    !: number of tracers in ideal tracer
+
    IMPLICIT NONE
 
-   INTEGER, PARAMETER ::   jp_lc      =  jp_pisces     !: cumulative number of passive tracers
-   INTEGER, PARAMETER ::   jp_lc_2d   =  jp_pisces_2d  !:
-   INTEGER, PARAMETER ::   jp_lc_3d   =  jp_pisces_3d  !:
-   INTEGER, PARAMETER ::   jp_lc_trd  =  jp_pisces_trd !:
+   INTEGER, PARAMETER ::   jp_lc      =  jp_pisces     + jp_medusa     + &
+                      jp_idtra     !: cumulative number of passive tracers
+   INTEGER, PARAMETER ::   jp_lc_2d   =  jp_pisces_2d  + jp_medusa_2d  + &
+                      jp_idtra_2d !:
+   INTEGER, PARAMETER ::   jp_lc_3d   =  jp_pisces_3d  + jp_medusa_3d  + &
+                      jp_idtra_3d !:
+   INTEGER, PARAMETER ::   jp_lc_trd  =  jp_pisces_trd + jp_medusa_trd + &
+                      jp_idtra_trd !:
    
 #if defined key_cfc
@@ -27,6 +42,6 @@
    !!---------------------------------------------------------------------
    LOGICAL, PUBLIC, PARAMETER ::   lk_cfc     = .TRUE.      !: CFC flag 
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc     =  1          !: number of passive tracers
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc_2d  =  2          !: additional 2d output arrays ('key_trc_diaadd')
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc     =  3          !: number of passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc_2d  =  6          !: additional 2d output arrays ('key_trc_diaadd')
    INTEGER, PUBLIC, PARAMETER ::   jp_cfc_3d  =  0          !: additional 3d output arrays ('key_trc_diaadd')
    INTEGER, PUBLIC, PARAMETER ::   jp_cfc_trd =  0          !: number of sms trends for CFC
@@ -34,5 +49,6 @@
    ! assign an index in trc arrays for each CFC prognostic variables
    INTEGER, PUBLIC, PARAMETER ::   jpc11       = jp_lc + 1   !: CFC-11 
-   INTEGER, PUBLIC, PARAMETER ::   jpc12       = jp_lc + 2   !: CFC-12   
+   INTEGER, PUBLIC, PARAMETER ::   jpc12       = jp_lc + 2   !: CFC-12 (priority tracer for CMIP6)
+   INTEGER, PUBLIC, PARAMETER ::   jpsf6       = jp_lc + 3   !: SF6
 #else
    !!---------------------------------------------------------------------
@@ -47,12 +63,12 @@
 
    ! Starting/ending CFC do-loop indices (N.B. no CFC : jp_cfc0 > jp_cfc1 the do-loop are never done)
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0     = jp_lc + 1       !: First index of CFC tracers
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc1     = jp_lc + jp_cfc  !: Last  index of CFC tracers
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0_2d  = jp_lc_2d  + 1       !: First index of CFC tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0     = jp_lc + 1              !: First index of CFC tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc1     = jp_lc + jp_cfc         !: Last  index of CFC tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0_2d  = jp_lc_2d  + 1          !: First index of CFC tracers
    INTEGER, PUBLIC, PARAMETER ::   jp_cfc1_2d  = jp_lc_2d  + jp_cfc_2d  !: Last  index of CFC tracers
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0_3d  = jp_lc_3d  + 1       !: First index of CFC tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0_3d  = jp_lc_3d  + 1          !: First index of CFC tracers
    INTEGER, PUBLIC, PARAMETER ::   jp_cfc1_3d  = jp_lc_3d  + jp_cfc_3d  !: Last  index of CFC tracers
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0_trd = jp_lc_trd + 1       !: First index of CFC tracers
-   INTEGER, PUBLIC, PARAMETER ::   jp_cfc1_trd = jp_lc_trd + jp_cfc_trd  !: Last  index of CFC tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc0_trd = jp_lc_trd + 1          !: First index of CFC tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_cfc1_trd = jp_lc_trd + jp_cfc_trd !: Last  index of CFC tracers
 
    !!======================================================================
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcini_cfc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcini_cfc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcini_cfc.F90	(revision 9987)
@@ -5,4 +5,5 @@
    !!======================================================================
    !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) 
+   !!                  !  2017-04  (A. Yool)  Add SF6
    !!----------------------------------------------------------------------
 #if defined key_cfc
@@ -22,5 +23,5 @@
    PUBLIC   trc_ini_cfc   ! called by trcini.F90 module
 
-   CHARACTER (len=34) ::   clname = 'cfc1112.atm'   ! ???
+   CHARACTER (len=34) ::   clname = 'cfc1112sf6.atm'   ! ???
 
    INTEGER  ::   inum                   ! unit number
@@ -44,5 +45,5 @@
       !!----------------------------------------------------------------------
       INTEGER  ::  ji, jj, jn, jl, jm, js, io, ierr
-      INTEGER  ::  iskip = 6   ! number of 1st descriptor lines
+      INTEGER  ::  iskip = 7   ! number of 1st descriptor lines
       REAL(wp) ::  zyy, zyd
       !!----------------------------------------------------------------------
@@ -53,5 +54,5 @@
 
 
-      IF(lwp) WRITE(numout,*) 'read of formatted file cfc1112atm'
+      IF(lwp) WRITE(numout,*) 'read of formatted file cfc1112sf6.atm'
       
       CALL ctl_opn( inum, clname, 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
@@ -69,5 +70,5 @@
       !                                ! Allocate CFC arrays
 
-      ALLOCATE( p_cfc(jpyear,jphem,2), STAT=ierr )
+      ALLOCATE( p_cfc(jpyear,jphem,3), STAT=ierr )
       IF( ierr > 0 ) THEN
          CALL ctl_stop( 'trc_ini_cfc: unable to allocate p_cfc array' )   ;   RETURN
@@ -90,8 +91,5 @@
          ENDIF
          qint_cfc(:,:,:) = 0._wp
-         DO jl = 1, jp_cfc
-            jn = jp_cfc0 + jl - 1
-            trn(:,:,:,jn) = 0._wp
-         END DO
+         trn(:,:,:,jp_cfc0:jp_cfc1) = 0._wp
       ENDIF
 
@@ -105,26 +103,30 @@
       jn = 31
       DO 
-        READ(inum,*, IOSTAT=io) zyy, p_cfc(jn,1,1), p_cfc(jn,1,2), p_cfc(jn,2,1), p_cfc(jn,2,2)
+        READ(inum,*, IOSTAT=io) zyy, p_cfc(jn,1,1), p_cfc(jn,1,2), &
+             & p_cfc(jn,1,3), p_cfc(jn,2,1),  &
+             & p_cfc(jn,2,2), p_cfc(jn,2,3)
         IF( io < 0 ) exit
         jn = jn + 1
       END DO
 
-      p_cfc(32,1:2,1) = 5.e-4      ! modify the values of the first years
-      p_cfc(33,1:2,1) = 8.e-4
-      p_cfc(34,1:2,1) = 1.e-6
-      p_cfc(35,1:2,1) = 2.e-3
-      p_cfc(36,1:2,1) = 4.e-3
-      p_cfc(37,1:2,1) = 6.e-3
-      p_cfc(38,1:2,1) = 8.e-3
-      p_cfc(39,1:2,1) = 1.e-2
+      ! AXY (25/04/17): do not adjust
+      ! p_cfc(32,1:2,1) = 5.e-4      ! modify the values of the first years
+      ! p_cfc(33,1:2,1) = 8.e-4
+      ! p_cfc(34,1:2,1) = 1.e-6
+      ! p_cfc(35,1:2,1) = 2.e-3
+      ! p_cfc(36,1:2,1) = 4.e-3
+      ! p_cfc(37,1:2,1) = 6.e-3
+      ! p_cfc(38,1:2,1) = 8.e-3
+      ! p_cfc(39,1:2,1) = 1.e-2
       
       IF(lwp) THEN        ! Control print
          WRITE(numout,*)
-         WRITE(numout,*) ' Year   p11HN    p11HS    p12HN    p12HS '
+         WRITE(numout,*) ' Year   p11HN    p11HS    p12HN    p12HS    pSF6N    pSF6S '
          DO jn = 30, jpyear
-            WRITE(numout, '( 1I4, 4F9.2)') jn, p_cfc(jn,1,1), p_cfc(jn,2,1), p_cfc(jn,1,2), p_cfc(jn,2,2)
+            WRITE(numout, '( 1I4, 6F9.2)') jn, p_cfc(jn,1,1), p_cfc(jn,2,1), &
+                 & p_cfc(jn,1,2), p_cfc(jn,2,2), &
+                 & p_cfc(jn,1,3), p_cfc(jn,2,3)
          END DO
       ENDIF
-
 
       ! Interpolation factor of atmospheric partial pressure
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcnam_cfc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcnam_cfc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcnam_cfc.F90	(revision 9987)
@@ -47,8 +47,6 @@
       INTEGER :: ios                 ! Local integer output status for namelist read
       INTEGER :: jl, jn
-      TYPE(DIAG), DIMENSION(jp_cfc_2d) :: cfcdia2d
       !!
-      NAMELIST/namcfcdate/ ndate_beg, nyear_res
-      NAMELIST/namcfcdia/  cfcdia2d     ! additional diagnostics
+      NAMELIST/namcfcdate/ ndate_beg, nyear_res, simu_type 
       !!----------------------------------------------------------------------
       !                             ! Open namelist files
@@ -72,41 +70,13 @@
          WRITE(numout,*) '    initial calendar date (aammjj) for CFC  ndate_beg = ', ndate_beg
          WRITE(numout,*) '    restoring time constant (year)          nyear_res = ', nyear_res
+         IF (simu_type==1) THEN
+            WRITE(numout,*) ' CFC running on SPIN-UP mode             simu_type = ', simu_type
+         ELSEIF (simu_type==2) THEN
+            WRITE(numout,*) ' CFC running on HINDCAST/PROJECTION mode simu_type = ', simu_type
+         ENDIF
       ENDIF
       nyear_beg = ndate_beg / 10000
       IF(lwp) WRITE(numout,*) '    initial year (aa)                       nyear_beg = ', nyear_beg
       !
-
-      IF( .NOT.lk_iomput .AND. ln_diatrc ) THEN
-         !
-         ! Namelist namcfcdia
-         ! -------------------
-         REWIND( numnatc_ref )              ! Namelist namcfcdia in reference namelist : CFC diagnostics
-         READ  ( numnatc_ref, namcfcdia, IOSTAT = ios, ERR = 903)
-903      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namcfcdia in reference namelist', lwp )
-
-         REWIND( numnatc_cfg )              ! Namelist namcfcdia in configuration namelist : CFC diagnostics
-         READ  ( numnatc_cfg, namcfcdia, IOSTAT = ios, ERR = 904 )
-904      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namcfcdia in configuration namelist', lwp )
-         IF(lwm) WRITE ( numonc, namcfcdia )
-
-         DO jl = 1, jp_cfc_2d
-            jn = jp_cfc0_2d + jl - 1
-            ctrc2d(jn) = TRIM( cfcdia2d(jl)%sname )
-            ctrc2l(jn) = TRIM( cfcdia2d(jl)%lname )
-            ctrc2u(jn) = TRIM( cfcdia2d(jl)%units )
-         END DO
-
-         IF(lwp) THEN                   ! control print
-            WRITE(numout,*)
-            WRITE(numout,*) ' Namelist : natadd'
-            DO jl = 1, jp_cfc_2d
-               jn = jp_cfc0_2d + jl - 1
-               WRITE(numout,*) '  2d diag nb : ', jn, '    short name : ', ctrc2d(jn), &
-                 &             '  long name  : ', ctrc2l(jn), '   unit : ', ctrc2u(jn)
-            END DO
-            WRITE(numout,*) ' '
-         ENDIF
-         !
-      ENDIF
 
    IF(lwm) CALL FLUSH ( numonc )     ! flush output namelist CFC
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcsms_cfc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcsms_cfc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/CFC/trcsms_cfc.F90	(revision 9987)
@@ -7,4 +7,6 @@
    !!  NEMO      1.0  !  2004-03  (C. Ethe) free form + modularity
    !!            2.0  !  2007-12  (C. Ethe, G. Madec)  reorganisation
+   !!                 !  2016-06  (J. Palmieri)  update for UKESM1
+   !!                 !  2017-04  (A. Yool)  update to add SF6, fix coefficients
    !!----------------------------------------------------------------------
 #if defined key_cfc
@@ -15,4 +17,5 @@
    !!   cfc_init     :  sets constants for CFC surface forcing computation
    !!----------------------------------------------------------------------
+   USE dom_oce       ! ocean space and time domain
    USE oce_trc       ! Ocean variables
    USE par_trc       ! TOP parameters
@@ -31,4 +34,6 @@
    INTEGER , PUBLIC            ::   jpyear         ! Number of years read in CFC1112 file
    INTEGER , PUBLIC            ::   ndate_beg      ! initial calendar date (aammjj) for CFC
+   INTEGER , PUBLIC            ::   simu_type      ! Kind of simulation: 1- Spin-up 
+                                                   !                     2- Hindcast/projection
    INTEGER , PUBLIC            ::   nyear_res      ! restoring time constant (year)
    INTEGER , PUBLIC            ::   nyear_beg      ! initial year (aa) 
@@ -40,7 +45,7 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   patm     ! atmospheric function
 
-   REAL(wp), DIMENSION(4,2) ::   soa   ! coefficient for solubility of CFC [mol/l/atm]
-   REAL(wp), DIMENSION(3,2) ::   sob   !    "               "
-   REAL(wp), DIMENSION(4,2) ::   sca   ! coefficients for schmidt number in degre Celcius
+   REAL(wp), DIMENSION(4,3) ::   soa   ! coefficient for solubility of CFC [mol/l/atm]
+   REAL(wp), DIMENSION(3,3) ::   sob   !    "               "
+   REAL(wp), DIMENSION(5,3) ::   sca   ! coefficients for schmidt number in degre Celcius
       
    !                          ! coefficients for conversion
@@ -79,8 +84,8 @@
       !
       INTEGER  ::   ji, jj, jn, jl, jm, js
-      INTEGER  ::   iyear_beg, iyear_end
+      INTEGER  ::   iyear_beg, iyear_end, iyear_tmp
       INTEGER  ::   im1, im2, ierr
       REAL(wp) ::   ztap, zdtap        
-      REAL(wp) ::   zt1, zt2, zt3, zv2
+      REAL(wp) ::   zt1, zt2, zt3, zt4, zv2
       REAL(wp) ::   zsol      ! solubility
       REAL(wp) ::   zsch      ! schmidt number 
@@ -103,5 +108,38 @@
       ! Temporal interpolation
       ! ----------------------
-      iyear_beg = nyear - 1900
+      !! JPALM -- 15-06-2016 -- define 2 kinds of CFC run:
+      !!                     1- the SPIN-UP and 2- Hindcast/Projections
+      !!                     -- main difference is the way to define the year of
+      !!                     simulation, that determine the atm pCFC.
+      !!                     1-- Spin-up: our atm forcing is of 30y we cycle on.
+      !!                     So we do 90y CFC cycles to be in good
+      !!                     correspondence with the atmosphere
+      !!                     2-- Hindcast/proj, instead of nyear-1900 we keep
+      !!                     the 2 last digit, and enable 3 cycle from 1800 to 2100.  
+      !!----------------------------------------------------------------------
+      IF (simu_type==1) THEN
+         !! 1 -- SPIN-UP
+         iyear_tmp = nyear - nyear_res  !! JPALM -- in our spin-up, nyear_res is 1000
+         iyear_beg = MOD( iyear_tmp , 90 )
+         !! JPALM -- the pCFC file only got 78 years.
+         !!       So if iyear_beg > 78 then we set pCFC to 0
+         !!             iyear_beg = 0 as well -- must try to avoid obvious problems
+         !!             as Pcfc is set to 0.00 up to year 32, let set iyear_beg to year 10
+         !!          else, must add 30 to iyear_beg to match with P_cfc indices
+         !!---------------------------------------
+         IF ((iyear_beg > 77) .OR. (iyear_beg==0)) THEN
+            iyear_beg = 10
+         ELSE 
+            iyear_beg = iyear_beg + 30
+         ENDIF
+      ELSEIF (simu_type==2) THEN
+         !! 2 -- Hindcast/proj
+         iyear_beg = MOD(nyear, 100)
+         IF (iyear_beg < 20)  iyear_beg = iyear_beg + 100
+         !! JPALM -- Same than previously, if iyear_beg is out of P_cfc range,
+         !!       we want to set p_CFC to 0.00 --> set iyear_beg = 10
+         IF ((iyear_beg < 30) .OR. (iyear_beg > 115)) iyear_beg = 10             
+      ENDIF
+      !!
       IF ( nmonth <= 6 ) THEN
          iyear_beg = iyear_beg - 1
@@ -152,10 +190,13 @@
                zt2  = zt1 * zt1 
                zt3  = zt1 * zt2
-               zsch = sca(1,jl) + sca(2,jl) * zt1 + sca(3,jl) * zt2 + sca(4,jl) * zt3
+               zt4  = zt1 * zt3
+               zsch = sca(1,jl) + sca(2,jl) * zt1 + sca(3,jl) * zt2 + sca(4,jl) * zt3 + sca(5,jl) * zt4
 
                !    speed transfert : formulae of wanninkhof 1992
                zv2     = wndm(ji,jj) * wndm(ji,jj)
                zsch    = zsch / 660.
-               zak_cfc = ( 0.39 * xconv2 * zv2 / SQRT(zsch) ) * tmask(ji,jj,1)
+               ! AXY (25/04/17): OMIP protocol specifies lower Wanninkhof (2014) value
+               ! zak_cfc = ( 0.39 * xconv2 * zv2 / SQRT(zsch) ) * tmask(ji,jj,1)
+               zak_cfc = ( 0.251 * xconv2 * zv2 / SQRT(zsch) ) * tmask(ji,jj,1)
 
                ! Input function  : speed *( conc. at equil - concen at surface )
@@ -176,24 +217,50 @@
          !                                                  !----------------!
       END DO                                                !  end CFC loop  !
-      !
-      IF( lrst_trc ) THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'trc_sms_cfc : cumulated input function fields written in ocean restart file ',   &
-            &                    'at it= ', kt,' date= ', ndastp
-         IF(lwp) WRITE(numout,*) '~~~~'
-         DO jn = jp_cfc0, jp_cfc1
-            CALL iom_rstput( kt, nitrst, numrtw, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jn) )
-         END DO
-      ENDIF                                            
-      !
-      IF( lk_iomput ) THEN
-         CALL iom_put( "qtrCFC11"  , qtr_cfc (:,:,1) )
-         CALL iom_put( "qintCFC11" , qint_cfc(:,:,1) )
-      ELSE
-         IF( ln_diatrc ) THEN
-            trc2d(:,:,jp_cfc0_2d    ) = qtr_cfc (:,:,1)
-            trc2d(:,:,jp_cfc0_2d + 1) = qint_cfc(:,:,1)
-         END IF
-      END IF
+         !
+      IF( kt == nittrc000 ) THEN
+         DO jl = 1, jp_cfc   
+             WRITE(NUMOUT,*) ' '
+             WRITE(NUMOUT,*) 'CFC interpolation verification '  !! Jpalm  
+             WRITE(NUMOUT,*) '################################## '
+             WRITE(NUMOUT,*) ' '
+               if (jl.EQ.1) then
+                   WRITE(NUMOUT,*) 'Traceur = CFC11: '
+               elseif (jl.EQ.2) then
+                   WRITE(NUMOUT,*) 'Traceur = CFC12: '
+               elseif (jl.EQ.3) then
+                   WRITE(NUMOUT,*) 'Traceur = SF6: '
+               endif
+             WRITE(NUMOUT,*) 'nyear    = ', nyear
+             WRITE(NUMOUT,*) 'nmonth   = ', nmonth
+             WRITE(NUMOUT,*) 'iyear_beg= ', iyear_beg
+             WRITE(NUMOUT,*) 'iyear_end= ', iyear_end
+             WRITE(NUMOUT,*) 'p_cfc(iyear_beg)= ',p_cfc(iyear_beg, 1, jl)
+             WRITE(NUMOUT,*) 'p_cfc(iyear_end)= ',p_cfc(iyear_end, 1, jl)
+             WRITE(NUMOUT,*) 'Im1= ',im1
+             WRITE(NUMOUT,*) 'Im2= ',im2
+             WRITE(NUMOUT,*) 'zpp_cfc = ',zpp_cfc
+             WRITE(NUMOUT,*) ' '
+         END DO  
+# if defined key_debug_medusa
+         CALL flush(numout)
+# endif
+      ENDIF
+        !
+      !IF( lrst_trc ) THEN
+      !   IF(lwp) WRITE(numout,*)
+      !   IF(lwp) WRITE(numout,*) 'trc_sms_cfc : cumulated input function fields written in ocean restart file ',   &
+      !      &                    'at it= ', kt,' date= ', ndastp
+      !   IF(lwp) WRITE(numout,*) '~~~~'
+      !   DO jn = jp_cfc0, jp_cfc1
+      !      CALL iom_rstput( kt, nitrst, numrtw, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jn) )
+      !   END DO
+      !ENDIF                                            
+      !
+      IF  (iom_use("qtrCFC11"))  CALL iom_put( "qtrCFC11"  , qtr_cfc (:,:,1) )
+      IF  (iom_use("qintCFC11")) CALL iom_put( "qintCFC11" , qint_cfc(:,:,1) )
+      IF  (iom_use("qtrCFC12"))  CALL iom_put( "qtrCFC12"  , qtr_cfc (:,:,2) )
+      IF  (iom_use("qintCFC12")) CALL iom_put( "qintCFC12" , qint_cfc(:,:,2) )
+      IF  (iom_use("qtrSF6"))    CALL iom_put( "qtrSF6"    , qtr_cfc (:,:,3) )
+      IF  (iom_use("qintSF6"))   CALL iom_put( "qintSF6"   , qint_cfc(:,:,3) )
       !
       IF( l_trdtrc ) THEN
@@ -203,4 +270,8 @@
       END IF
       !
+# if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) '   CFC - Check: nn_timing = ', nn_timing
+      CALL flush(numout)
+# endif
       IF( nn_timing == 1 )  CALL timing_stop('trc_sms_cfc')
       !
@@ -214,5 +285,5 @@
       !! ** Purpose : sets constants for CFC model
       !!---------------------------------------------------------------------
-      INTEGER :: jn
+      INTEGER :: jl, jn, iyear_beg, iyear_tmp
 
       ! coefficient for CFC11 
@@ -223,15 +294,16 @@
       soa(2,1) =  319.6552
       soa(3,1) =  119.4471
-      soa(4,1) =  -1.39165
-
-      sob(1,1) =  -0.142382
-      sob(2,1) =   0.091459
-      sob(3,1) =  -0.0157274
-
-      ! Schmidt number 
-      sca(1,1) = 3501.8
-      sca(2,1) = -210.31
-      sca(3,1) =  6.1851
-      sca(4,1) = -0.07513
+      soa(4,1) =   -1.39165
+
+      sob(1,1) = -0.142382
+      sob(2,1) =  0.091459
+      sob(3,1) = -0.0157274
+
+      ! Schmidt number          AXY (25/04/17)
+      sca(1,1) = 3579.2       ! = 3501.8
+      sca(2,1) = -222.63      ! = -210.31
+      sca(3,1) =    7.5749    ! =    6.1851
+      sca(4,1) =   -0.14595   ! =   -0.07513
+      sca(5,1) =    0.0011874 ! = absent
 
       ! coefficient for CFC12 
@@ -242,25 +314,79 @@
       soa(2,2) =  298.9702
       soa(3,2) =  113.8049
-      soa(4,2) =  -1.39165
-
-      sob(1,2) =  -0.143566
-      sob(2,2) =   0.091015
-      sob(3,2) =  -0.0153924
-
-      ! schmidt number 
-      sca(1,2) =  3845.4 
-      sca(2,2) =  -228.95
-      sca(3,2) =  6.1908 
-      sca(4,2) =  -0.067430
-
-      IF( ln_rsttr ) THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) ' Read specific variables from CFC model '
-         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
-         !
-         DO jn = jp_cfc0, jp_cfc1
-            CALL iom_get( numrtr, jpdom_autoglo, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jn) ) 
-         END DO
+      soa(4,2) =   -1.39165
+
+      sob(1,2) = -0.143566
+      sob(2,2) =  0.091015
+      sob(3,2) = -0.0153924
+
+      ! schmidt number         AXY (25/04/17)
+      sca(1,2) = 3828.1      ! = 3845.4 
+      sca(2,2) = -249.86     ! = -228.95
+      sca(3,2) =    8.7603   ! =    6.1908 
+      sca(4,2) =   -0.1716   ! =   -0.067430
+      sca(5,2) =    0.001408 ! = absent
+
+      ! coefficients for SF6   AXY (25/04/17)
+      !---------------------
+      
+      ! Solubility
+      soa(1,3) =  -80.0343
+      soa(2,3) =  117.232
+      soa(3,3) =   29.5817
+      soa(4,3) =    0.0
+
+      sob(1,3) =  0.0335183
+      sob(2,3) = -0.0373942
+      sob(3,3) =  0.00774862
+
+      ! Schmidt number
+      sca(1,3) = 3177.5
+      sca(2,3) = -200.57
+      sca(3,3) =    6.8865
+      sca(4,3) =   -0.13335
+      sca(5,3) =    0.0010877
+
+      !!---------------------------------------------
+      !! JPALM -- re-initialize CFC fields and diags if restart a CFC cycle,
+      !!       Or if out of P_cfc range
+      IF (simu_type==1) THEN
+         iyear_tmp = nyear - nyear_res  !! JPALM -- in our spin-up, nyear_res is 1000
+         iyear_beg = MOD( iyear_tmp , 90 )
+         !!---------------------------------------
+         IF ((iyear_beg > 77) .OR. (iyear_beg==0)) THEN
+            qtr_cfc(:,:,:) = 0._wp
+            IF(lwp) THEN
+               WRITE(numout,*) 
+               WRITE(numout,*) 'restart a CFC cycle or out of P_cfc year bounds zero --'
+               WRITE(numout,*) '                          --    set qtr_CFC = 0.00   --'
+               WRITE(numout,*) '                          --   set qint_CFC = 0.00   --'
+               WRITE(numout,*) '                          --   set trn(CFC) = 0.00   --'
+            ENDIF
+            qtr_cfc(:,:,:) = 0._wp
+            qint_cfc(:,:,:) = 0._wp
+            trn(:,:,:,jp_cfc0:jp_cfc1) = 0._wp
+            trb(:,:,:,jp_cfc0:jp_cfc1) = 0._wp
+         ENDIF
+      !!
+      !! 2 -- Hindcast/proj
+      ELSEIF (simu_type==2) THEN
+         iyear_beg = MOD(nyear, 100)
+         IF (iyear_beg < 20)  iyear_beg = iyear_beg + 100
+         IF ((iyear_beg < 30) .OR. (iyear_beg > 115)) THEN
+            qtr_cfc(:,:,:) = 0._wp
+            IF(lwp) THEN
+               WRITE(numout,*)
+               WRITE(numout,*) 'restart a CFC cycle or out of P_cfc year bounds zero --'
+               WRITE(numout,*) '                          --    set qtr_CFC = 0.00   --'
+               WRITE(numout,*) '                          --   set qint_CFC = 0.00   --'
+               WRITE(numout,*) '                          --   set trn(CFC) = 0.00   --'
+            ENDIF
+            qtr_cfc(:,:,:) = 0._wp
+            qint_cfc(:,:,:) = 0._wp
+            trn(:,:,:,jp_cfc0:jp_cfc1) = 0._wp
+            trb(:,:,:,jp_cfc0:jp_cfc1) = 0._wp
+         ENDIF
       ENDIF
+
       IF(lwp) WRITE(numout,*)
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/par_idtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/par_idtra.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/par_idtra.F90	(revision 9987)
@@ -0,0 +1,67 @@
+MODULE par_idtra
+   !!======================================================================
+   !!                        ***  par_idtra  ***
+   !! TOP :   set the IDEAL-TRACER parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007)
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+   USE par_pisces , ONLY : jp_pisces       !: number of tracers in PISCES
+   USE par_pisces , ONLY : jp_pisces_2d    !: number of 2D diag in PISCES
+   USE par_pisces , ONLY : jp_pisces_3d    !: number of 3D diag in PISCES
+   USE par_pisces , ONLY : jp_pisces_trd   !: number of biological diag in PISCES
+
+   USE par_medusa , ONLY : jp_medusa       !: number of tracers in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_2d    !: number of 2D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_3d    !: number of 3D diag in MEDUSA
+   USE par_medusa , ONLY : jp_medusa_trd   !: number of biological diag in MEDUSA
+
+   IMPLICIT NONE
+
+   INTEGER, PARAMETER ::   jp_lp      =  jp_pisces     +  jp_medusa     !: cumulative number of passive tracers
+   INTEGER, PARAMETER ::   jp_lp_2d   =  jp_pisces_2d  +  jp_medusa_2d  !:
+   INTEGER, PARAMETER ::   jp_lp_3d   =  jp_pisces_3d  +  jp_medusa_3d  !:
+   INTEGER, PARAMETER ::   jp_lp_trd  =  jp_pisces_trd +  jp_medusa_trd !:
+
+#if defined key_idtra
+   !!---------------------------------------------------------------------
+   !!   'key_idtra'   :                                          Ideal tracers
+   !!---------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_idtra     = .TRUE.      !: IDEAL-TRACER flag
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra     =  1          !: number of passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra_2d  =  3          !: additional 2d output arrays ('key_trc_diaadd')
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra_3d  =  0          !: additional 3d output arrays ('key_trc_diaadd')
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra_trd =  0          !: number of sms trends for IDEAL-TRACER
+
+   ! assign an index in trc arrays for each IDEAL-TRACER prognostic variables
+   INTEGER, PUBLIC, PARAMETER ::   jpidtra       = jp_lp + 1   !: IDEAL-TRACER
+#else
+   !!---------------------------------------------------------------------
+   !!   Default     :                                       No IDEAL-TRACER tracers
+   !!---------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_idtra     = .FALSE.     !: IDEAL-TRACER flag
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra     =  0          !: No IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra_2d  =  0          !: No IDEAL-TRACER additional 2d output arrays
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra_3d  =  0          !: No IDEAL-TRACER additional 3d output arrays
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra_trd =  0          !: number of sms trends for IDEAL-TRACER
+#endif
+
+   ! Starting/ending IDEAL-TRACER do-loop indices (N.B. no IDEAL-TRACER : jp_idtra0 > jp_idtra1 the do-loop are never done)
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra0     = jp_lp + 1                !: First index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra1     = jp_lp + jp_idtra         !: Last  index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra0_2d  = jp_lp_2d  + 1            !: First index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra1_2d  = jp_lp_2d  + jp_idtra_2d  !: Last  index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra0_3d  = jp_lp_3d  + 1            !: First index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra1_3d  = jp_lp_3d  + jp_idtra_3d  !: Last  index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra0_trd = jp_lp_trd + 0            !: First index of IDEAL-TRACER tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_idtra1_trd = jp_lp_trd + jp_idtra_trd !: Last  index of IDEAL-TRACER tracers
+
+   !!======================================================================
+END MODULE par_idtra
+
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcice_idtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcice_idtra.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcice_idtra.F90	(revision 9987)
@@ -0,0 +1,53 @@
+MODULE trcice_idtra
+   !!======================================================================
+   !!                         ***  MODULE trcice_idtra  ***
+   !! TOP :   Main module of the MY_TRC tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!----------------------------------------------------------------------
+#if defined key_idtra
+   !!----------------------------------------------------------------------
+   !!   'key_idtra'                                    IDEAL TRACER tracers
+   !!----------------------------------------------------------------------
+   !! trc_ice_idtra       : MY_TRC model main routine
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ice_ini_idtra       ! called by trcice.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ice_ini_idtra
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ice_idtra  ***
+      !!
+      !! ** Purpose :   main routine of MY_TRC model
+      !!
+      !! ** Method  : -
+      !!----------------------------------------------------------------------
+      !
+      !
+   END SUBROUTINE trc_ice_ini_idtra
+
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                        No MY_TRC model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ice_ini_idtra             ! Empty routine
+   END SUBROUTINE trc_ice_ini_idtra
+#endif
+
+   !!======================================================================
+END MODULE trcice_idtra
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcini_idtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcini_idtra.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcini_idtra.F90	(revision 9987)
@@ -0,0 +1,105 @@
+MODULE trcini_idtra
+   !!======================================================================
+   !!                         ***  MODULE trcini_idtra  ***
+   !! TOP :   initialisation of the IDEAL-TRACER tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) from trcini.idtra.h90
+   !!----------------------------------------------------------------------
+#if defined key_idtra
+   !!----------------------------------------------------------------------
+   !!   'key_idtra'                                               IDEAL-TRACER tracers
+   !!----------------------------------------------------------------------
+   !! trc_ini_idtra      : IDEAL-TRACER model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE par_trc         ! TOP parameters
+   USE trc             ! TOP variables
+   USE trcsms_idtra    ! IDEAL-TRACER sms trends
+   ! USE par_idtra       ! IDEAL-TRACER parameters
+   ! USE in_out_manager  ! I/O manager
+   ! USE lib_mpp
+   ! USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_idtra   ! called by trcini.F90 module
+
+   INTEGER  ::   inum                   ! unit number
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007)
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_idtra
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_idtra  ***
+      !!
+      !! ** Purpose :   initialization for idtra model
+      !!
+      !! ** Method  : - Read the namidtra namelist and check the parameter values
+      !!----------------------------------------------------------------------
+      INTEGER  ::    jn, jl 
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_idtra: initialisation of Ideal Tracers model'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~'
+
+      IF( trc_sms_idtra_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_ini_idtra:unable to allocate CFC arrays' )
+
+
+      ! Initialization of trn in case of  no restart
+      !----------------------------------------------
+      qtr_idtra(:,:,:) = 0._wp
+      inv_idtra(:,:,:) = 0._wp
+      IF( .NOT. ln_rsttr ) THEN
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'Initialization of id-tracers ; No restart : '
+            WRITE(numout,*) '                             ; Init field equal 1 at surface - zero elsewhere'
+            WRITE(numout,*) '                             ; qint idtra equal 0 '
+         ENDIF
+         qint_idtra(:,:,:) = 0._wp
+         DO jn = jp_idtra0, jp_idtra1
+             trn(:,:,:,jn) = 0.e0
+             trn(:,:,1,jn) = 1.0
+           IF(lwp) WRITE(numout,*) 'Idealise Tracer initialisation -- jn = ',jn
+         END DO
+      ENDIF
+
+
+      !   Ideal traceur do not need any atmospheric concentration.
+      ! We consider that sucface concentration is equal to 1,
+      ! that it is advectied within the water circulation,
+      ! and that it is regularly degraded as if it was a radiactive tracer (tricium for example)
+      ! But we can play with tha caracteristic time of
+      !--------------------------------------------------------------------
+
+
+
+      IF(lwp) WRITE(numout,*) 'Initialization of IDEAL-TRACER tracers done'
+      IF(lwp) WRITE(numout,*) ' '
+
+   END SUBROUTINE trc_ini_idtra
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                         No IDEAL-TRACER tracers
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ini_idtra             ! Empty routine
+
+
+   END SUBROUTINE trc_ini_idtra
+#endif
+
+   !!======================================================================
+END MODULE trcini_idtra
+                                                
+
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcnam_idtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcnam_idtra.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcnam_idtra.F90	(revision 9987)
@@ -0,0 +1,123 @@
+MODULE trcnam_idtra
+   !!======================================================================
+   !!                         ***  MODULE trcnam_idtra  ***
+   !! TOP :   initialisation of some run parameters for IDEAL-TRACER chemical model
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) from trcnam.idtra.h90
+   !!----------------------------------------------------------------------
+#if defined key_idtra
+   !!----------------------------------------------------------------------
+   !!   'key_idtra'                                               IDEAL-TRACER tracers
+   !!----------------------------------------------------------------------
+   !! trc_nam_idtra      : IDEAL-TRACER model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE par_trc         ! TOP parameters
+   USE trc             ! TOP variables
+   USE trcsms_idtra    ! IDEAL-TRACER specific variable
+   USE iom             ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nam_idtra   ! called by trcnam.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007)
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_nam_idtra
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_nam_idtra  ***
+      !!
+      !! ** Purpose :   Definition some run parameter for IDEAL-TRACER model
+      !!
+      !! ** Method  :   Read the namidtra namelist and check the parameter
+      !!       values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namidtra
+      !!----------------------------------------------------------------------
+      INTEGER  :: numnatm_ref = -1   ! Logical unit for reference ID-TRA namelist
+      INTEGER  :: numnatm_cfg = -1   ! Logical unit for configuration ID-TRA namelist
+      INTEGER  :: numonc      = -1   ! Logical unit for output namelist
+      INTEGER  :: ios                 ! Local integer output status for namelist read
+      REAL(wp) :: tmp_decay          !! Years ; half time decay of our idealize tracer
+      REAL(wp) :: TDECyr, TDEC   
+      !! ----------------------------------------------------------------
+      NAMELIST/namidtra/tmp_decay
+      !!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+      !! Jpalm -- 4-11-2014
+      !! namelist for idealize tracer
+      !! only thing in namelist is the chosen half time decay
+      !! no atmospheric conditions, cause we do impose a surface concentration of 1,
+      !! and no additionnal diagnostics, 
+      !! because the only thing we are interested in is the water mass concentration on this tracer.
+      !!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_nam_idtra: read IDEAL-TRACER namelist'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      !!
+      !! Open the namelist file :
+      !!~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+      CALL ctl_opn( numnatm_ref, 'namelist_idtra_ref', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      CALL ctl_opn( numnatm_cfg, 'namelist_idtra_cfg', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      IF(lwm) CALL ctl_opn( numonc, 'output.namelist.idtra', 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      !! Read the namelists :
+      !!~~~~~~~~~~~~~~~~~~~~~~~
+      !! First namelist of our idealize tracer :
+      !! read the decay 1/2 time of our tracer, to define in the namelist.
+      !! tmp_decay = 1y ; 10y ; 100y or 1000y depending of which water mass you want to track
+      !!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+      REWIND( numnatm_ref )              ! Namelist namidtra in reference namelist : IDTRA parameters
+      READ  ( numnatm_ref, namidtra, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namidtra in reference namelist', lwp )
+
+      REWIND( numnatm_cfg )              ! Namelist namidtra in configuration namelist : IDTRA parameters
+      READ  ( numnatm_cfg, namidtra, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namidtra in configuration namelist', lwp )
+      IF(lwm) WRITE ( numonc, namidtra )
+
+      IF(lwp) WRITE(numout,*) '   -  half time decay of our idealize tracer : ', tmp_decay
+
+      ! decroissance radioactive du traceur ideal
+      ! ---------------------------------------
+      ! TDECyr = 12.43/LOG(2.)             !! Tricium as example
+       TDECyr = tmp_decay/LOG(2.)          !! Idealise tracer -- with tmp_decay given in the idtracer namelist
+       TDEC = TDECyr*365.*24.*60.*60.      !! translate in second
+       FDEC = EXP( -rdt/TDEC )
+
+
+!! #if defined key_trc_diaadd  && ! defined key_iomput
+      !!
+      !!  -Here you can add tracers names to be read
+      !! in a namelist.
+      !!  -But this is not necessary with the iomput module
+      !! cause names are written in the Iodef file.
+      !!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+!! #endif
+
+   END SUBROUTINE trc_nam_idtra
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                                No IDEAL-TRACER
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_nam_idtra                      ! Empty routine
+   END  SUBROUTINE  trc_nam_idtra
+#endif
+
+   !!======================================================================
+END MODULE trcnam_idtra
+
+
+
+
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcsms_idtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcsms_idtra.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcsms_idtra.F90	(revision 9987)
@@ -0,0 +1,251 @@
+MODULE trcsms_idtra
+   !!======================================================================
+   !!                      ***  MODULE trcsms_idtra  ***
+   !! TOP : TRI main model
+   !!======================================================================
+   !! History :    -   !  1999-10  (JC. Dutay)  original code
+   !!             1.0  !  2004-03 (C. Ethe) free form + modularity
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  reorganisation
+   !!----------------------------------------------------------------------
+#if defined key_idtra
+   !!----------------------------------------------------------------------
+   !!   'key_idtra'                                               TRI tracers
+   !!----------------------------------------------------------------------
+   !!   trc_sms_idtra     :  compute and add TRI suface forcing to TRI trends
+   !!   trc_idtra_cst :  sets constants for TRI surface forcing computation
+   !!----------------------------------------------------------------------
+   USE oce_trc      ! Ocean variables
+   USE par_trc      ! TOP parameters
+   USE trc          ! TOP variables
+   USE trd_oce
+   USE trdtrc
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_idtra        ! called in ???
+   PUBLIC   trc_sms_idtra_alloc  ! called in ???
+   !
+   INTEGER , PUBLIC    ::   nyear_res      ! restoring time constant (year)
+   INTEGER , PUBLIC    ::   numnatm
+   REAL(wp), PUBLIC    ::   FDEC
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qtr_idtra  ! flux at surface
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qint_idtra ! cumulative flux 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   inv_idtra  ! vertic. inventory
+
+   !                          ! coefficients for conversion
+   REAL(wp) ::  WTEMP
+
+
+   !! * Substitutions
+#  include "top_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007)
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_sms_idtra( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sms_idtra  ***
+      !!
+      !! ** Purpose :   Compute the surface boundary contition on TRI 11
+      !!             passive tracer associated with air-mer fluxes and add it
+      !!             to the general trend of tracers equations.
+      !!
+      !! ** Method  : - get the atmospheric partial pressure - given in pico -
+      !!              - computation of solubility ( in 1.e-12 mol/l then in 1.e-9 mol/m3)
+      !!              - computation of transfert speed ( given in cm/hour ----> cm/s )
+      !!              - the input function is given by :
+      !!                speed * ( concentration at equilibrium - concentration at surface )
+      !!              - the input function is in pico-mol/m3/s and the
+      !!                TRI concentration in pico-mol/m3
+      !!               
+      !! *** For Idealized Tracers              
+      !!              - no need for any temporal references, 
+      !!              nor any atmospheric concentration, nor air -sea fluxes
+      !!              - Here we fixe surface concentration to 1.0 Tracer-Unit/m3
+      !!              - Then we add a decay (radioactive-like) to this tracer concentration 
+      !!              - the Half life deccay is chosen by the user, depending of the experiment. 
+      !!              
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in )  ::   kt    ! ocean time-step index
+      !!
+      INTEGER                ::   ji, jj, jn, jl, jk
+      REAL(wp)               ::   rlx                 !! relaxation time (1 day)
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('trc_sms_idtra')
+      !
+      rlx = 10./(60. * 60. * 24.)                              !! relaxation time (1/10 day)
+      IF (kt == nittrc000) THEN
+         IF(lwp) WRITE(numout,*) '   trcsms_idtra :'
+         IF(lwp) WRITE(numout,*) '   ~~~~~~~~~~~~~~~~~'
+         IF(lwp) WRITE(numout,*) '   - idtra decay factor : ', FDEC
+         IF(lwp) WRITE(numout,*) '   - relaxation time    : ', rlx
+# if defined key_debug_medusa
+         CALL flush(numout)
+# endif
+      !   CALL idtra_init
+      ENDIF
+
+         !
+      inv_idtra(:,:,:) = 0.0                                   !! init the inventory
+      qtr_idtra(:,:,:) = 0.0                                   !! init the air-sea flux
+      DO jl = 1, jp_idtra
+         jn = jp_idtra0 + jl - 1
+
+      !!   DO jj = 1, jpj
+      !!      DO ji = 1, jpi
+           DO jj = 2,jpjm1
+              DO ji = 2,jpim1
+
+         !! First, a crude version. will be much inproved later.
+             qtr_idtra(ji,jj,jl)  = rlx * (1. - trb(ji,jj,1,jn)) * tmask(ji,jj,1) *   & 
+                                  fse3t(ji,jj,1)                  !! Air-sea Flux
+
+           !! DEBUG-TEST : Set flux equal to 0, see if it induces the pb we see in the MED  
+           !!  qtr_idtra(ji,jj,jl)  = 0.0
+           ENDDO
+         ENDDO
+         tra(:,:,1,jn)      = tra(:,:,1,jn) + ( qtr_idtra(:,:,jl) *  &
+                            tmask(:,:,1) / fse3t(:,:,1) )
+         qint_idtra(:,:,jl) = qint_idtra(:,:,jl) +                   &           
+                              qtr_idtra(:,:,jl) * rdt              !! Cumulative Air-sea Flux
+
+
+         DO jk =1,jpk
+            inv_idtra(:,:,jl) = inv_idtra(:,:,jl) +                  &
+                     (trn(:,:,jk,jn) * fse3t(:,:,jk) * tmask(:,:,jk))  !! vertical inventory
+         ENDDO
+!
+!DECAY of OUR IDEALIZED TRACER
+! ---------------------------------------
+
+         DO  jk =1,jpk
+      !!      DO jj=1,jpj
+      !!        DO  ji =1,jpi
+            DO jj = 2,jpjm1
+               DO ji = 2,jpim1
+            
+                 !! IF (trn(ji,jj,jk,jn) > 0.0) THEN
+                    WTEMP = trn(ji,jj,jk,jn) * (1. - FDEC )
+                    tra(ji,jj,jk,jn) = (tra(ji,jj,jk,jn) - WTEMP/rdt ) * &
+                                     tmask(ji,jj,jk)
+                 !! ENDIF 
+              ENDDO 
+            ENDDO
+         ENDDO
+
+      ENDDO
+    !! jn loop
+!
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) '   IDTRA - calculation part - DONE trc_sms_idtra -- '
+      CALL flush(numout)
+# endif
+        !
+        !! restart and diagnostics management -- 
+      !IF( lrst_trc ) THEN
+      !   IF(lwp) WRITE(numout,*)
+      !   IF(lwp) WRITE(numout,*) 'trc_sms_idtra : cumulated input function fields written in ocean restart file ',   &
+      !      &                    'at it= ', kt,' date= ', ndastp
+      !   IF(lwp) WRITE(numout,*) '~~~~'
+      !   !!DO jn = jp_idtra0, jp_idtra1
+      !      CALL iom_rstput( kt, nitrst, numrtw, 'qint_IDTRA', qint_idtra(:,:,1) )
+      !   !!END DO
+ ! if defined key_debug_medusa
+      !   IF(lwp) WRITE(numout,*) '   IDTRA - writing diag-restart - DONE trc_sms_idtra -- '
+      !   CALL flush(numout)
+ ! endif
+      !ENDIF
+      !
+         CALL iom_put( "qtrIDTRA"  , qtr_idtra (:,:,1) )
+         CALL iom_put( "qintIDTRA" , qint_idtra(:,:,1) )
+         CALL iom_put( "invIDTRA" , inv_idtra(:,:,1) )
+      !
+# if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) '   IDTRA - writing diag - DONE trc_sms_idtra -- '
+      CALL flush(numout)
+# endif
+      !
+      IF( l_trdtrc ) THEN
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) '   IDTRA - writing trends - trc_sms_idtra -- '
+         CALL flush(numout)
+# endif
+          DO jn = jp_idtra0, jp_idtra1
+            CALL trd_trc( tra(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
+          END DO
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) '   IDTRA - writing trends - DONE trc_sms_idtra -- '
+         CALL flush(numout)
+# endif
+      END IF
+      !
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) '   IDTRA - Check: nn_timing = ', nn_timing 
+         CALL flush(numout)
+# endif
+      IF( nn_timing == 1 )  CALL timing_stop('trc_sms_idtra')
+      !
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) '   IDTRA DONE trc_sms_idtra -- '
+      CALL flush(numout)
+# endif
+      !
+   END SUBROUTINE trc_sms_idtra
+
+   SUBROUTINE idtra_init
+      !!---------------------------------------------------------------------
+      !!                     ***  idtra_init  ***
+      !!
+      !! ** Purpose : read restart values for IDTRA model
+      !!---------------------------------------------------------------------
+      INTEGER :: jn
+
+      IF( ln_rsttr ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' Read specific variables from Ideal Tracers model '
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+         !
+         DO jn = jp_idtra0, jp_idtra1
+            CALL iom_get( numrtr, jpdom_autoglo, 'qint_IDTRA', qint_idtra(:,:,jn) )
+         END DO
+      ENDIF
+      IF(lwp) WRITE(numout,*) 'idtra restart variables read -- OK'
+      !
+   END SUBROUTINE idtra_init
+
+   INTEGER FUNCTION trc_sms_idtra_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sms_idtra_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( qtr_idtra (jpi,jpj,jp_idtra) ,     &
+         &      inv_idtra(jpi,jpj,jp_idtra)  ,     &
+         &      qint_idtra(jpi,jpj,jp_idtra) , STAT=trc_sms_idtra_alloc )
+         !
+      IF( trc_sms_idtra_alloc /= 0 ) CALL ctl_warn('trc_sms_idtra_alloc : failed to allocate arrays.')
+      !
+   END FUNCTION trc_sms_idtra_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                         No TRI tracers
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_sms_idtra( kt )       ! Empty routine
+      WRITE(*,*) 'trc_sms_idtra: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sms_idtra
+#endif
+
+   !!======================================================================
+END MODULE trcsms_idtra
+
+
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcwri_idtra.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcwri_idtra.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/IDTRA/trcwri_idtra.F90	(revision 9987)
@@ -0,0 +1,63 @@
+MODULE trcwri_idtra
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    IDEALIZED Tracer :   Output of IDEALIZED Tracer tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!             1.1  !  2013-05 (A. Yool)  converted for MEDUSA
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_iomput && defined key_idtra
+   !!----------------------------------------------------------------------
+   !!   'key_idtra'                                           IDEALIZED Tracer model
+   !!----------------------------------------------------------------------
+   !! trc_wri_idtra   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   ! USE oce_trc         ! Ocean variables
+   ! USE par_trc         ! TOP parameters
+   USE trc             ! passive tracers common variables
+   ! USE trcsms_idtra    ! IDEALIZE TRACER sms trends
+   USE iom             ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_idtra
+
+CONTAINS
+
+   SUBROUTINE trc_wri_idtra
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra
+      INTEGER              :: jn
+      !!---------------------------------------------------------------------
+
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      DO jn = jp_idtra0, jp_idtra1
+         cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
+         CALL iom_put( cltra, trn(:,:,:,jn) )
+      END DO
+      !
+   END SUBROUTINE trc_wri_idtra
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_idtra
+CONTAINS
+   SUBROUTINE trc_wri_idtra                     ! Empty routine  
+   END SUBROUTINE trc_wri_idtra
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!======================================================================
+END MODULE trcwri_idtra
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/air_sea.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/air_sea.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/air_sea.F90	(revision 9987)
@@ -0,0 +1,579 @@
+MODULE air_sea_mod
+   !!======================================================================
+   !!                         ***  MODULE air_sea_mod  ***
+   !! Calculate the carbon chemistry for the whole ocean
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   air_sea        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE air_sea( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE air_sea  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - calculate air-sea gas exchange
+      !!  - river inputs
+      !!----------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: f_riv_alk, f_riv_c, f_riv_n,           &
+                                   f_riv_si, f_runoff,                    & 
+                                   fgco2, zphn, zphd,                     &
+# if defined key_roam
+                                   dms_andr, dms_andr2d, dms_aran,        &
+                                   dms_aran2d, dms_hall, dms_hall2d,      &
+                                   dms_simo, dms_simo2d, dms_surf,        &
+                                   dms_surf2d, dms_andm, dms_andm2d,      &
+                                   dms_nlim, dms_wtkn,                    &
+                                   f_co2flux, f_co2flux2d,                &
+                                   f_co2starair_2d, f_co3,                &
+                                   f_dcf, f_fco2a_2d, f_fco2w_2d,         &
+                                   f_h2co3, f_hco3, f_henry,              &
+                                   f_kw660, f_kw6602d,                    &
+                                   f_o2flux, f_o2flux2d, f_o2sat,         &
+                                   f_o2sat2d, f_ocndpco2_2d,              &
+                                   f_ocnk0_2d, f_ocnkwco2_2d,             &
+                                   f_ocnrhosw_2d, f_ocnschco2_2d,         &
+                                   f_omarg, f_omcal,                      &
+                                   f_pco2a2d, f_pco2atm, f_pco2w,         &
+                                   f_pco2w2d, f_ph, f_pp0, f_pp02d,       &
+                                   f_TALK, f_TALK2d, f_TDIC, f_TDIC2d,    &
+                                   f_xco2a, f_xco2a_2d,                   &
+                                   zalk, zdic, zoxy, zsal, ztmp,          &
+# endif
+# if defined key_mocsy
+                                   zpho,                                  &
+# endif
+                                   zchd, zchn, zdin, zsil
+      USE dom_oce,           ONLY: e3t_0, e3t_n, gphit, tmask
+# if defined key_iomput
+      USE iom,               ONLY: lk_iomput
+# endif
+      USE in_out_manager,    ONLY: lwp, numout
+      USE oce,               ONLY: PCO2a_in_cpl
+      USE par_kind,          ONLY: wp
+      USE par_oce,           ONLY: jpi, jpim1, jpj, jpjm1
+      USE sbc_oce,           ONLY: fr_i, lk_oasis, qsr, wndm
+      USE sms_medusa,        ONLY: jdms, jdms_input, jdms_model,          &
+                                   jriver_alk, jriver_c,                  &
+                                   jriver_n, jriver_si,                   &
+                                   riv_alk, riv_c, riv_n, riv_si,         &
+                                   zn_dms_chd, zn_dms_chn, zn_dms_din,    &
+                                   zn_dms_mld, zn_dms_qsr,                &
+                                   xnln, xnld 
+      USE trc,               ONLY: med_diag
+      USE zdfmxl,            ONLY: hmld
+
+# if defined key_roam
+      USE gastransfer,       ONLY: gas_transfer
+#  if defined key_mocsy
+      USE mocsy_wrapper,     ONLY: mocsy_interface
+#  else
+      USE trcco2_medusa,     ONLY: trc_co2_medusa
+#  endif
+      USE trcdms_medusa,     ONLY: trc_dms_medusa
+      USE trcoxy_medusa,     ONLY: trc_oxy_medusa
+# endif
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! time (integer timestep)
+      INTEGER, INTENT( in ) :: kt
+
+      !! Loop variables
+      INTEGER :: ji, jj
+
+# if defined key_roam
+      !! jpalm 14-07-2016: convert CO2flux diag from mmol/m2/d to kg/m2/s
+      REAL, PARAMETER :: weight_CO2_mol = 44.0095  !! g / mol
+      REAL, PARAMETER :: secs_in_day    = 86400.0  !! s / d
+      REAL, PARAMETER :: CO2flux_conv   = (1.e-6 * weight_CO2_mol) / secs_in_day
+
+      INTEGER :: iters
+
+      !! AXY (23/06/15): additional diagnostics for MOCSY and oxygen
+      REAL(wp), DIMENSION(jpi,jpj) :: f_fco2w, f_rhosw
+      REAL(wp), DIMENSION(jpi,jpj) :: f_fco2atm
+      REAL(wp), DIMENSION(jpi,jpj) :: f_schmidtco2, f_kwco2, f_K0
+      REAL(wp), DIMENSION(jpi,jpj) :: f_co2starair, f_dpco2
+      !! Output arguments from mocsy_interface, which aren't used
+      REAL(wp) :: f_BetaD_dum, f_opres_dum
+      REAL(wp) :: f_insitut_dum
+      REAL(wp) :: f_kwo2_dum
+# endif
+
+
+# if defined key_roam
+      !!-----------------------------------------------------------
+      !! Air-sea gas exchange
+      !!-----------------------------------------------------------
+
+#   if defined key_debug_medusa
+               IF (lwp) write (numout,*)                     & 
+               'air-sea: gas_transfer kt = ', kt
+               CALL flush(numout)
+#   endif
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,1) == 1) then
+               IF (lk_oasis) THEN
+                  !! use 2D atm xCO2 from atm coupling
+                  f_xco2a(ji,jj) = PCO2a_in_cpl(ji,jj)
+               ENDIF
+               !!
+               !! AXY (23/06/15): as part of an effort to update the 
+               !!                 carbonate chemistry in MEDUSA, the gas 
+               !!                 transfer velocity used in the carbon
+               !!                 and oxygen cycles has been harmonised 
+               !!                 and is calculated by the same function 
+               !!                 here; this harmonisation includes
+               !!                 changes to the PML carbonate chemistry 
+               !!                 scheme so that it too makes use of the 
+               !!                 same gas transfer velocity; the
+               !!                 preferred parameterisation of this is 
+               !!                 Wanninkhof (2014), option 7
+               !!
+               CALL gas_transfer( wndm(ji,jj), 1, 7,         &  ! inputs
+                                  f_kw660(ji,jj) )              ! outputs
+            ENDIF
+         ENDDO
+      ENDDO
+
+#   if defined key_debug_medusa
+               IF (lwp) write (numout,*)                     &
+               'air-sea: carb-chem kt = ', kt
+               CALL flush(numout)
+#   endif
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,1) == 1) then
+               !! air pressure (atm); ultimately this will use air 
+               !! pressure at the base of the UKESM1 atmosphere 
+               !!                                     
+               f_pp0(ji,jj)   = 1.0
+               !!
+               !! IF(lwp) WRITE(numout,*) ' MEDUSA ztmp    =', ztmp(ji,jj)
+               !! IF(lwp) WRITE(numout,*) ' MEDUSA wndm    =', wndm(ji,jj)
+               !! IF(lwp) WRITE(numout,*) ' MEDUSA fr_i    =', fr_i(ji,jj)
+               !!
+#  if defined key_axy_carbchem
+#   if defined key_mocsy
+               !!
+               !! AXY (22/06/15): use Orr & Epitalon (2015) MOCSY-2 carbonate
+               !!                 chemistry package; note that depth is set to
+               !!                 zero in this call
+               CALL mocsy_interface(ztmp(ji,jj),zsal(ji,jj),zalk(ji,jj),     &
+                                    zdic(ji,jj),zsil(ji,jj),zpho(ji,jj),     &
+                                    f_pp0(ji,jj),0.0,                        &
+                                    gphit(ji,jj),f_kw660(ji,jj),             &
+                                    f_xco2a(ji,jj),1,f_ph(ji,jj),            &
+                                    f_pco2w(ji,jj),f_fco2w(ji,jj),           &
+                                    f_h2co3(ji,jj),f_hco3(ji,jj),            &
+                                    f_co3(ji,jj),f_omarg(ji,jj),             &
+                                    f_omcal(ji,jj),f_BetaD_dum,              &
+                                    f_rhosw(ji,jj),f_opres_dum,              &
+                                    f_insitut_dum,f_pco2atm(ji,jj),          &
+                                    f_fco2atm(ji,jj),f_schmidtco2(ji,jj),    &
+                                    f_kwco2(ji,jj),f_K0(ji,jj),              &
+                                    f_co2starair(ji,jj),f_co2flux(ji,jj),    &
+                                    f_dpco2(ji,jj))
+               !! mmol / m3 -> umol / kg
+               f_TDIC(ji,jj) = (zdic(ji,jj) / f_rhosw(ji,jj)) * 1000.
+               !! meq / m3 ->  ueq / kg
+               f_TALK(ji,jj) = (zalk(ji,jj) / f_rhosw(ji,jj)) * 1000.
+               f_dcf(ji,jj)  = f_rhosw(ji,jj)
+            ENDIF
+         ENDDO
+      ENDDO
+
+#   else   
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,1) == 1) then     
+               iters = 0
+               !!
+               !! carbon dioxide (CO2); Jerry Blackford code (ostensibly 
+               !! OCMIP-2, but not)
+               CALL trc_co2_medusa(ztmp(ji,jj),zsal(ji,jj),zdic(ji,jj),      &
+                                   zalk(ji,jj),0.0,                          &
+                                   f_kw660(ji,jj),f_xco2a(ji,jj),            &
+                                   f_ph(ji,jj),                              &
+                                   f_pco2w(ji,jj),f_h2co3(ji,jj),            &
+                                   f_hco3(ji,jj),f_co3(ji,jj),               &
+                                   f_omcal(ji,jj),f_omarg(ji,jj),            &
+                                   f_co2flux(ji,jj),f_TDIC(ji,jj),           &
+                                   f_TALK(ji,jj),f_dcf(ji,jj),               &
+                                   f_henry(ji,jj),iters)
+               !!
+               !! AXY (09/01/14): removed iteration and NaN checks; these have
+               !!                 been moved to trc_co2_medusa together with a
+               !!                 fudge that amends erroneous values (this is
+               !!                 intended to be a temporary fudge!); the
+               !!                 output warnings are retained here so that
+               !!                 failure position can be determined
+               if (iters .eq. 25) then
+                  IF(lwp) WRITE(numout,*) 'air-sea: ITERS WARNING, ',       &
+                     iters, ' AT (', ji, ', ', jj, ', 1) AT ', kt
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+#   endif
+#  else
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,1) == 1) then
+               !! AXY (18/04/13): switch off carbonate chemistry 
+               !!                 calculations; provide quasi-sensible 
+               !!                 alternatives
+               f_ph(ji,jj)           = 8.1
+               f_pco2w(ji,jj)        = f_xco2a(ji,jj)
+               f_h2co3(ji,jj)        = 0.005 * zdic(ji,jj)
+               f_hco3(ji,jj)         = 0.865 * zdic(ji,jj)
+               f_co3(ji,jj)          = 0.130 * zdic(ji,jj)
+               f_omcal(ji,jj) = 4.
+               f_omarg(ji,jj) = 2.
+               f_co2flux(ji,jj)      = 0.
+               f_TDIC(ji,jj)         = zdic(ji,jj)
+               f_TALK(ji,jj)         = zalk(ji,jj)
+               f_dcf(ji,jj)          = 1.026
+               f_henry(ji,jj)        = 1.
+               !! AXY (23/06/15): add in some extra MOCSY diagnostics
+               f_fco2w(ji,jj)        = f_xco2a(ji,jj)
+! This doesn't seem to be used - marc 16/5/17
+!               f_BetaD(ji,jj)        = 1.
+               f_rhosw(ji,jj)        = 1.026
+! This doesn't seem to be used - marc 16/5/17
+!               f_opres(ji,jj)        = 0.
+!               f_insitut(ji,jj)      = ztmp(ji,jj)
+               f_pco2atm(ji,jj)      = f_xco2a(ji,jj)
+               f_fco2atm(ji,jj)      = f_xco2a(ji,jj)
+               f_schmidtco2(ji,jj)   = 660.
+               f_kwco2(ji,jj)        = 0.
+               f_K0(ji,jj)           = 0.
+               f_co2starair(ji,jj)   = f_xco2a(ji,jj)
+               f_dpco2(ji,jj)        = 0.
+            ENDIF
+         ENDDO
+      ENDDO
+#  endif
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,1) == 1) then
+               !! mmol/m2/s -> mmol/m3/d; correct for sea-ice; divide 
+               !! through by layer thickness
+               f_co2flux(ji,jj) = (1. - fr_i(ji,jj)) * f_co2flux(ji,jj) *    &
+                                  86400. / fse3t(ji,jj,1)
+               !!
+               !! oxygen (O2); OCMIP-2 code
+               !! AXY (23/06/15): amend input list for oxygen to account 
+               !!                 for common gas transfer velocity
+               CALL trc_oxy_medusa(ztmp(ji,jj),zsal(ji,jj),f_kw660(ji,jj),   &
+                                   f_pp0(ji,jj),zoxy(ji,jj),                 &
+                                   f_kwo2_dum,f_o2flux(ji,jj),               &
+                                   f_o2sat(ji,jj))
+               !!
+               !! mmol/m2/s -> mol/m3/d; correct for sea-ice; divide 
+               !! through by layer thickness
+               f_o2flux(ji,jj)  = (1. - fr_i(ji,jj)) * f_o2flux(ji,jj) *     &
+                                  86400. / fse3t(ji,jj,1)
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !! Jpalm (08-2014)
+      !! DMS surface concentration calculation
+      !! initialy added for UKESM1 model.
+      !! using MET-OFFICE subroutine.
+      !! DMS module only needs Chl concentration and MLD
+      !! to get an aproximate value of DMS concentration.
+      !! air-sea fluxes are calculated by atmospheric chemitry model
+      !! from atm and oc-surface concentrations.
+      !!
+      !! AXY (13/03/15): this is amended to calculate all of the DMS
+      !!                 estimates examined during UKESM1 (see
+      !!                 comments in trcdms_medusa.F90)
+      !!
+      !! AXY (25/05/17): amended to additionally pass DIN limitation as well as [DIN]; 
+      !!                 accounts for differences in nutrient half-saturations; changes 
+      !!                 also made in trc_dms_medusa; this permits an additional DMS 
+      !!                 calculation while retaining the existing Anderson one 
+      !! 
+      IF (jdms == 1) THEN
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,1) == 1) then
+                  !! calculate weighted half-saturation for DIN uptake
+                  dms_wtkn(ji,jj) = ((zphn(ji,jj) * xnln) +            &
+                                     (zphd(ji,jj) * xnld)) /           &
+                                     (zphn(ji,jj) + zphd(ji,jj))        
+                  !!
+                  !! feed in correct inputs
+                  if (jdms_input .eq. 0) then
+                     !! use instantaneous inputs
+                     dms_nlim(ji,jj) = zdin(ji,jj) / (zdin(ji,jj) + dms_wtkn(ji,jj))
+                     !!
+                     CALL trc_dms_medusa(zchn(ji,jj),zchd(ji,jj),             &
+                                         hmld(ji,jj),qsr(ji,jj),              &
+                                         zdin(ji,jj), dms_nlim(ji,jj),        &
+                                         dms_andr,dms_simo,dms_aran,dms_hall, & 
+                                         dms_andm)
+                  else
+                     !! use diel-average inputs
+                     dms_nlim(ji,jj) = zn_dms_din(ji,jj) /                    &
+                                      (zn_dms_din(ji,jj) + dms_wtkn(ji,jj))
+                     !!
+                     CALL trc_dms_medusa(zn_dms_chn(ji,jj),zn_dms_chd(ji,jj), &
+                                         zn_dms_mld(ji,jj),zn_dms_qsr(ji,jj), &
+                                         zn_dms_din(ji,jj),dms_nlim(ji,jj),   &
+                                         dms_andr,dms_simo,dms_aran,dms_hall, & 
+                                         dms_andm)
+                  endif
+                  !!
+                  !! assign correct output to variable passed to atmosphere
+                  if (jdms_model .eq. 1) then
+                     dms_surf = dms_andr
+                  elseif (jdms_model .eq. 2) then
+                     dms_surf = dms_simo
+                  elseif (jdms_model .eq. 3) then
+                     dms_surf = dms_aran
+                  elseif (jdms_model .eq. 4) then
+                     dms_surf = dms_hall
+                  elseif (jdms_model .eq. 5) then
+                     dms_surf = dms_andm
+                  endif
+                  !!
+                  !! 2D diag through iom_use
+                  IF( med_diag%DMS_SURF%dgsave ) THEN
+                     dms_surf2d(ji,jj) = dms_surf
+                  ENDIF
+                  IF( med_diag%DMS_ANDR%dgsave ) THEN
+                     dms_andr2d(ji,jj) = dms_andr
+                  ENDIF
+                  IF( med_diag%DMS_SIMO%dgsave ) THEN
+                     dms_simo2d(ji,jj) = dms_simo
+                  ENDIF
+                  IF( med_diag%DMS_ARAN%dgsave ) THEN
+                     dms_aran2d(ji,jj) = dms_aran
+                  ENDIF
+                  IF( med_diag%DMS_HALL%dgsave ) THEN
+                     dms_hall2d(ji,jj) = dms_hall
+                  ENDIF 
+                  IF( med_diag%DMS_ANDM%dgsave ) THEN 
+                     dms_andm2d(ji,jj) = dms_andm
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+#   if defined key_debug_medusa
+         IF (lwp) write (numout,*)                                &
+            'air-sea: finish calculating dms kt = ',kt
+            CALL flush(numout)
+#   endif 
+      ENDIF                  !! End IF (jdms == 1)
+
+      !!
+      !! store 2D outputs
+      !!
+      !! JPALM -- 17-11-16 -- put fgco2 out of diag request
+      !!       is needed for coupling; pass through restart
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,1) == 1) then
+               !! IF( med_diag%FGCO2%dgsave ) THEN
+               !! convert from  mol/m2/day to kg/m2/s
+               !! mmol-C/m3/d -> kg-CO2/m2/s
+               fgco2(ji,jj) = f_co2flux(ji,jj) * fse3t(ji,jj,1) *             &
+                              CO2flux_conv
+               !! ENDIF
+               IF ( lk_iomput ) THEN
+                  IF( med_diag%ATM_PCO2%dgsave ) THEN
+                     f_pco2a2d(ji,jj) = f_pco2atm(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_PCO2%dgsave ) THEN
+                     f_pco2w2d(ji,jj) = f_pco2w(ji,jj)
+                  ENDIF
+                  IF( med_diag%CO2FLUX%dgsave ) THEN
+                     !! mmol/m3/d -> mmol/m2/d
+                     f_co2flux2d(ji,jj) = f_co2flux(ji,jj) * fse3t(ji,jj,1)
+                  ENDIF
+                  IF( med_diag%TCO2%dgsave ) THEN
+                     f_TDIC2d(ji,jj) = f_TDIC(ji,jj)
+                  ENDIF
+                  IF( med_diag%TALK%dgsave ) THEN
+                     f_TALK2d(ji,jj) = f_TALK(ji,jj)
+                  ENDIF
+                  IF( med_diag%KW660%dgsave ) THEN
+                      f_kw6602d(ji,jj) = f_kw660(ji,jj)
+                  ENDIF
+                  IF( med_diag%ATM_PP0%dgsave ) THEN
+                      f_pp02d(ji,jj) = f_pp0(ji,jj)
+                  ENDIF
+                  IF( med_diag%O2FLUX%dgsave ) THEN
+                     f_o2flux2d(ji,jj) = f_o2flux(ji,jj)
+                  ENDIF
+                  IF( med_diag%O2SAT%dgsave ) THEN
+                     f_o2sat2d(ji,jj) = f_o2sat(ji,jj)
+                  ENDIF
+                  !! AXY (24/11/16): add in extra MOCSY diagnostics
+                  IF( med_diag%ATM_XCO2%dgsave ) THEN
+                     f_xco2a_2d(ji,jj) = f_xco2a(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_FCO2%dgsave ) THEN
+                     f_fco2w_2d(ji,jj) = f_fco2w(ji,jj)
+                  ENDIF
+                  IF( med_diag%ATM_FCO2%dgsave ) THEN
+                     f_fco2a_2d(ji,jj) = f_fco2atm(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_RHOSW%dgsave ) THEN
+                     f_ocnrhosw_2d(ji,jj) = f_rhosw(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_SCHCO2%dgsave ) THEN
+                     f_ocnschco2_2d(ji,jj) = f_schmidtco2(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_KWCO2%dgsave ) THEN
+                     f_ocnkwco2_2d(ji,jj) = f_kwco2(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_K0%dgsave ) THEN
+                     f_ocnk0_2d(ji,jj) = f_K0(ji,jj)
+                  ENDIF
+                  IF( med_diag%CO2STARAIR%dgsave ) THEN
+                     f_co2starair_2d(ji,jj) = f_co2starair(ji,jj)
+                  ENDIF
+                  IF( med_diag%OCN_DPCO2%dgsave ) THEN
+                     f_ocndpco2_2d(ji,jj) = f_dpco2(ji,jj)
+                  ENDIF
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+# endif
+
+      !!-----------------------------------------------------------------
+      !! River inputs
+      !!-----------------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,1) == 1) then
+               !!
+               !! runoff comes in as        kg / m2 / s
+               !! used and written out as   m3 / m2 / d (= m / d)
+               !! where                     1000 kg / m2 / d = 
+               !!                             1 m3 / m2 / d = 1 m / d
+               !!
+               !! AXY (17/07/14): the compiler doesn't like this line for 
+               !!                 some reason; as MEDUSA doesn't even use 
+               !!                 runoff for riverine inputs, a temporary 
+               !!                 solution is to switch off runoff entirely
+               !!                 here; again, this change is one of several 
+               !!                 that will need revisiting once MEDUSA has 
+               !!                 bedded down in UKESM1; particularly so if 
+               !!                 the land scheme provides information
+               !!                 concerning nutrient fluxes
+               !!
+               !! f_runoff(ji,jj) = sf_rnf(1)%fnow(ji,jj,1) / 1000. * 60. *   &
+               !!                   60. * 24.
+               f_runoff(ji,jj) = 0.0
+               !!
+               !! nutrients are added via rivers to the model in one of 
+               !! two ways:
+               !!   1. via river concentration; i.e. the average nutrient 
+               !!      concentration of a river water is described by a 
+               !!      spatial file, and this is multiplied by runoff to 
+               !!      give a nutrient flux
+               !!   2. via direct river flux; i.e. the average nutrient 
+               !!      flux due to rivers is described by a spatial file, 
+               !!      and this is simply applied as a direct nutrient 
+               !!      flux (i.e. it does not relate or respond to model 
+               !!      runoff) nutrient fields are derived from the 
+               !!      GlobalNEWS 2 database; carbon and alkalinity are 
+               !!      derived from continent-scale DIC estimates (Huang et 
+               !!      al., 2012) and some Arctic river alkalinity 
+               !!      estimates (Katya?)
+               !! 
+               !! as of 19/07/12, riverine nutrients can now be spread 
+               !! vertically across several grid cells rather than just 
+               !! poured into the surface box; this block of code is still 
+               !! executed, however, to set up the total amounts of 
+               !! nutrient entering via rivers
+               !!
+               !! nitrogen
+               if (jriver_n .eq. 1) then
+                  !! river concentration specified; use runoff to 
+                  !! calculate input
+                  f_riv_n(ji,jj) = f_runoff(ji,jj) * riv_n(ji,jj)
+               elseif (jriver_n .eq. 2) then
+                  !! river flux specified; independent of runoff
+                  f_riv_n(ji,jj) = riv_n(ji,jj)
+               endif
+               !!
+               !! silicon
+               if (jriver_si .eq. 1) then
+                  !! river concentration specified; use runoff to 
+                  !! calculate input
+                  f_riv_si(ji,jj) = f_runoff(ji,jj) * riv_si(ji,jj)
+               elseif (jriver_si .eq. 2) then
+                  !! river flux specified; independent of runoff
+                  f_riv_si(ji,jj) = riv_si(ji,jj)
+               endif
+               !!
+               !! carbon
+               if (jriver_c .eq. 1) then
+                  !! river concentration specified; use runoff to 
+                  !! calculate input
+                  f_riv_c(ji,jj) = f_runoff(ji,jj) * riv_c(ji,jj)
+               elseif (jriver_c .eq. 2) then
+                  !! river flux specified; independent of runoff
+                  f_riv_c(ji,jj) = riv_c(ji,jj)
+               endif
+               !!
+               !! alkalinity
+               if (jriver_alk .eq. 1) then
+                  !! river concentration specified; use runoff to 
+                  !! calculate input
+                  f_riv_alk(ji,jj) = f_runoff(ji,jj) * riv_alk(ji,jj)
+               elseif (jriver_alk .eq. 2) then
+                  !! river flux specified; independent of runoff
+                  f_riv_alk(ji,jj) = riv_alk(ji,jj)
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE air_sea
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE air_sea( )                    ! Empty routine
+      WRITE(*,*) 'air_sea: You should not have seen this print! error?'
+   END SUBROUTINE air_sea
+#endif 
+
+   !!======================================================================
+END MODULE air_sea_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_med_diag_iomput.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_med_diag_iomput.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_med_diag_iomput.F90	(revision 9987)
@@ -0,0 +1,725 @@
+MODULE bio_med_diag_iomput_mod
+   !!======================================================================
+   !!                         ***  MODULE bio_med_diag_iomput_mod  ***
+   !! Calculates diagnostics
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   bio_med_diag_iomput        ! Called in bio_medusa_diag.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE bio_med_diag_iomput( jk )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE bio_med_diag_iomput  ***
+      !! Calculates the diagnostics used with iom_put
+      !!-------------------------------------------------------------------
+      USE bio_medusa_mod
+      USE dom_oce,           ONLY: e3t_0, e3t_n, mbathy, tmask
+      USE in_out_manager,    ONLY: lwp, numout
+      USE par_oce,           ONLY: jpim1, jpjm1
+      USE phycst,            ONLY: rsmall
+      USE sms_medusa,        ONLY: f3_omarg, f3_omcal,                   &
+                                   i0100, i0500, i1000,                  &
+                                   xbetac, xbetan, xphi,                 &
+                                   xthetapd, xthetapn, xthetazmi
+      USE trc,               ONLY: med_diag
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! level
+      INTEGER, INTENT( in ) :: jk
+
+      !! Loop avariables
+      INTEGER :: ji, jj, jn
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!-------------------------------------------------------
+               !! Add in XML diagnostics stuff
+               !!-------------------------------------------------------
+               !!
+               !! ** 2D diagnostics
+#   if defined key_debug_medusa
+               IF (lwp) write (numout,*)                                     &
+                  'bio_med_diag_iomput: in ij-jj loop jk = ', jk
+               CALL flush(numout)
+#   endif
+               IF ( med_diag%PRN%dgsave ) THEN
+                   fprn2d(ji,jj) = fprn2d(ji,jj) +                           &
+                                   (fprn(ji,jj)  * zphn(ji,jj) *             &
+                                    fse3t(ji,jj,jk)) 
+               ENDIF
+               IF ( med_diag%MPN%dgsave ) THEN
+                   fdpn2d(ji,jj) = fdpn2d(ji,jj) + (fdpn(ji,jj) *            &
+                                                    fse3t(ji,jj,jk))
+               ENDIF
+               IF ( med_diag%PRD%dgsave ) THEN
+                   fprd2d(ji,jj) = fprd2d(ji,jj) +                           &
+                                   (fprd(ji,jj)  * zphd(ji,jj) *             &
+                                    fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%MPD%dgsave ) THEN
+                   fdpd2d(ji,jj) = fdpd2d(ji,jj) + (fdpd(ji,jj) *            &
+                                                    fse3t(ji,jj,jk)) 
+               ENDIF
+               !  IF( med_diag%DSED%dgsave ) THEN
+               !      CALL iom_put( "DSED"  , ftot_n )
+               !  ENDIF
+               IF( med_diag%OPAL%dgsave ) THEN
+                   fprds2d(ji,jj) = fprds2d(ji,jj) +                         &
+                                    (fprds(ji,jj) * zpds(ji,jj) *            &
+                                     fse3t(ji,jj,jk)) 
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%OPALDISS%dgsave ) THEN
+                   fsdiss2d(ji,jj) = fsdiss2d(ji,jj) + (fsdiss(ji,jj) *      &
+                                                        fse3t(ji,jj,jk))  
+               ENDIF
+               IF( med_diag%GMIPn%dgsave ) THEN
+                   fgmipn2d(ji,jj) = fgmipn2d(ji,jj) +                       &
+                                     (fgmipn(ji,jj)  * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%GMID%dgsave ) THEN
+                   fgmid2d(ji,jj) = fgmid2d(ji,jj) + (fgmid(ji,jj) *         &
+                                                      fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%MZMI%dgsave ) THEN
+                   fdzmi2d(ji,jj) = fdzmi2d(ji,jj) + (fdzmi(ji,jj) *         &
+                                                      fse3t(ji,jj,jk)) 
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%GMEPN%dgsave ) THEN
+                   fgmepn2d(ji,jj) = fgmepn2d(ji,jj) + (fgmepn(ji,jj) *      &
+                                                        fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%GMEPD%dgsave ) THEN
+                   fgmepd2d(ji,jj) = fgmepd2d(ji,jj) + (fgmepd(ji,jj) *      &
+                                                        fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%GMEZMI%dgsave ) THEN
+                   fgmezmi2d(ji,jj) = fgmezmi2d(ji,jj) +                     &
+                                      (fgmezmi(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%GMED%dgsave ) THEN
+                   fgmed2d(ji,jj) = fgmed2d(ji,jj) +                         &
+                                       (fgmed(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%MZME%dgsave ) THEN
+                  fdzme2d(ji,jj) = fdzme2d(ji,jj) +                          &
+                                    (fdzme(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               !  IF( med_diag%DEXP%dgsave ) THEN
+               !      CALL iom_put( "DEXP"  , ftot_n )
+               !  ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%DETN%dgsave ) THEN
+                  fslown2d(ji,jj) = fslown2d(ji,jj) +                        &
+                                    (fslown(ji,jj) * fse3t(ji,jj,jk))  
+               ENDIF
+               IF( med_diag%MDET%dgsave ) THEN
+                  fdd2d(ji,jj) = fdd2d(ji,jj) +                              &
+                                 (fdd(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%AEOLIAN%dgsave ) THEN
+                  ffetop2d(ji,jj) = ffetop2d(ji,jj) +                        &
+                                    (ffetop(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%BENTHIC%dgsave ) THEN
+                  ffebot2d(ji,jj) = ffebot2d(ji,jj) +                        &
+                                    (ffebot(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%SCAVENGE%dgsave ) THEN
+                  ffescav2d(ji,jj) = ffescav2d(ji,jj) +                      &
+                                     (ffescav(ji,jj) * fse3t(ji,jj,jk))  
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%PN_JLIM%dgsave ) THEN
+                  ! fjln2d(ji,jj) = fjln2d(ji,jj) +                          &
+                  !                 (fjln(ji,jj)  * zphn(ji,jj) *            &
+                  !                  fse3t(ji,jj,jk)) 
+                  fjln2d(ji,jj) = fjln2d(ji,jj) +                            &
+                                  (fjlim_pn(ji,jj) * zphn(ji,jj) *           &
+                                   fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%PN_NLIM%dgsave ) THEN
+                  fnln2d(ji,jj) = fnln2d(ji,jj) +                            &
+                                  (fnln(ji,jj) * zphn(ji,jj) *               &
+                                   fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%PN_FELIM%dgsave ) THEN
+                  ffln2d(ji,jj) = ffln2d(ji,jj) +                            &
+                                  (ffln2(ji,jj) * zphn(ji,jj) *              &
+                                   fse3t(ji,jj,jk)) 
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%PD_JLIM%dgsave ) THEN
+                   ! fjld2d(ji,jj) = fjld2d(ji,jj) +                          &
+                   !                 (fjld(ji,jj)  * zphd(ji,jj) *            &
+                   !                  fse3t(ji,jj,jk)) 
+                   fjld2d(ji,jj) = fjld2d(ji,jj) +                           &
+                                   (fjlim_pd(ji,jj) * zphd(ji,jj) *          &
+                                    fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%PD_NLIM%dgsave ) THEN
+                   fnld2d(ji,jj) = fnld2d(ji,jj) +                           &
+                                   (fnld(ji,jj) * zphd(ji,jj) *              &
+                                    fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%PD_FELIM%dgsave ) THEN
+                   ffld2d(ji,jj) = ffld2d(ji,jj) +                           &
+                                   (ffld(ji,jj) * zphd(ji,jj) *              &
+                                    fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%PD_SILIM%dgsave ) THEN
+                   fsld2d2(ji,jj) = fsld2d2(ji,jj) +                         &
+                                    (fsld2(ji,jj) * zphd(ji,jj) *            &
+                                     fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%PDSILIM2%dgsave ) THEN
+                   fsld2d(ji,jj) = fsld2d(ji,jj) +                           &
+                                   (fsld(ji,jj) * zphd(ji,jj) *              &
+                                    fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !! 
+               IF( med_diag%TOTREG_N%dgsave ) THEN
+                  fregen2d(ji,jj) = fregen2d(ji,jj) + fregen(ji,jj)
+               ENDIF
+               IF( med_diag%TOTRG_SI%dgsave ) THEN
+                  fregensi2d(ji,jj) = fregensi2d(ji,jj) + fregensi(ji,jj)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !! 
+               IF( med_diag%FASTN%dgsave ) THEN
+                   ftempn2d(ji,jj) = ftempn2d(ji,jj) +                       &
+                                     (ftempn(ji,jj)  * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FASTSI%dgsave ) THEN
+                   ftempsi2d(ji,jj) = ftempsi2d(ji,jj) +                     &
+                                      (ftempsi(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FASTFE%dgsave ) THEN
+                   ftempfe2d(ji,jj) = ftempfe2d(ji,jj) +                     &
+                                      (ftempfe(ji,jj) * fse3t(ji,jj,jk))  
+               ENDIF
+               IF( med_diag%FASTC%dgsave ) THEN
+                   ftempc2d(ji,jj) = ftempc2d(ji,jj) +                       &
+                                     (ftempc(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FASTCA%dgsave ) THEN
+                   ftempca2d(ji,jj) = ftempca2d(ji,jj) +                     &
+                                      (ftempca(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !! 
+               IF( med_diag%REMINN%dgsave ) THEN
+                   freminn2d(ji,jj) = freminn2d(ji,jj) +                     &
+                                      (freminn(ji,jj)  * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%REMINSI%dgsave ) THEN
+                   freminsi2d(ji,jj) = freminsi2d(ji,jj) +                   &
+                                       (freminsi(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%REMINFE%dgsave ) THEN
+                   freminfe2d(ji,jj) = freminfe2d(ji,jj) +                   &
+                                       (freminfe(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%REMINC%dgsave ) THEN
+                   freminc2d(ji,jj) = freminc2d(ji,jj) +                     &
+                                      (freminc(ji,jj)  * fse3t(ji,jj,jk)) 
+               ENDIF
+               IF( med_diag%REMINCA%dgsave ) THEN
+                   freminca2d(ji,jj) = freminca2d(ji,jj) +                   &
+                                       (freminca(ji,jj) * fse3t(ji,jj,jk)) 
+               ENDIF
+               !!
+            ENDIF
+         ENDDO
+      ENDDO
+
+# if defined key_roam
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!
+               !! AXY (09/11/16): CMIP6 diagnostics
+               IF( med_diag%FD_NIT3%dgsave ) THEN
+                  fd_nit3(ji,jj,jk) = ffastn(ji,jj)
+               ENDIF
+               IF( med_diag%FD_SIL3%dgsave ) THEN
+                  fd_sil3(ji,jj,jk) = ffastsi(ji,jj)
+               ENDIF
+               IF( med_diag%FD_CAR3%dgsave ) THEN
+                  fd_car3(ji,jj,jk) = ffastc(ji,jj)
+               ENDIF
+               IF( med_diag%FD_CAL3%dgsave ) THEN
+                  fd_cal3(ji,jj,jk) = ffastca(ji,jj)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      IF (jk.eq.i0100) THEN
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  IF( med_diag%RR_0100%dgsave ) THEN
+                     ffastca2d(ji,jj) =                                      &
+                                ffastca(ji,jj)/MAX(ffastc(ji,jj), rsmall)
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+      ELSE IF (jk.eq.i0500) THEN
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  IF( med_diag%RR_0500%dgsave ) THEN
+                     ffastca2d(ji,jj) =                                      &
+                                ffastca(ji,jj)/MAX(ffastc(ji,jj), rsmall)
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+      ELSE IF (jk.eq.i1000) THEN
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  IF( med_diag%RR_1000%dgsave ) THEN
+                     ffastca2d(ji,jj) =                                      &
+                                ffastca(ji,jj)/MAX(ffastc(ji,jj), rsmall)
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+      ELSE
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (jk.eq.mbathy(ji,jj)) THEN
+                  IF (tmask(ji,jj,jk) == 1) THEN
+                     IF( med_diag%IBEN_N%dgsave ) THEN
+                        iben_n2d(ji,jj) = f_sbenin_n(ji,jj) +                &
+                                          f_fbenin_n(ji,jj)
+                     ENDIF
+                     IF( med_diag%IBEN_FE%dgsave ) THEN
+                        iben_fe2d(ji,jj) = f_sbenin_fe(ji,jj) +              &
+                                           f_fbenin_fe(ji,jj)
+                     ENDIF
+                     IF( med_diag%IBEN_C%dgsave ) THEN
+                        iben_c2d(ji,jj) = f_sbenin_c(ji,jj) +                &
+                                          f_fbenin_c(ji,jj)
+                     ENDIF
+                     IF( med_diag%IBEN_SI%dgsave ) THEN
+                        iben_si2d(ji,jj) = f_fbenin_si(ji,jj)
+                     ENDIF
+                     IF( med_diag%IBEN_CA%dgsave ) THEN
+                        iben_ca2d(ji,jj) = f_fbenin_ca(ji,jj)
+                     ENDIF
+                     IF( med_diag%OBEN_N%dgsave ) THEN
+                        oben_n2d(ji,jj) = f_benout_n(ji,jj)
+                     ENDIF
+                     IF( med_diag%OBEN_FE%dgsave ) THEN
+                        oben_fe2d(ji,jj) = f_benout_fe(ji,jj)
+                     ENDIF
+                     IF( med_diag%OBEN_C%dgsave ) THEN
+                        oben_c2d(ji,jj) = f_benout_c(ji,jj)
+                     ENDIF
+                     IF( med_diag%OBEN_SI%dgsave ) THEN
+                        oben_si2d(ji,jj) = f_benout_si(ji,jj)
+                     ENDIF
+                     IF( med_diag%OBEN_CA%dgsave ) THEN
+                        oben_ca2d(ji,jj) = f_benout_ca(ji,jj)
+                     ENDIF
+                     IF( med_diag%SFR_OCAL%dgsave ) THEN
+                        sfr_ocal2d(ji,jj) = f3_omcal(ji,jj,jk)
+                     ENDIF
+                     IF( med_diag%SFR_OARG%dgsave ) THEN
+                        sfr_oarg2d(ji,jj) =  f3_omarg(ji,jj,jk)
+                     ENDIF
+                     IF( med_diag%LYSO_CA%dgsave ) THEN
+                        lyso_ca2d(ji,jj) = f_benout_lyso_ca(ji,jj)
+                     ENDIF
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+      ENDIF
+      !! end bathy-1 diags
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!
+               IF( med_diag%RIV_N%dgsave ) THEN
+                  rivn2d(ji,jj) = rivn2d(ji,jj) +                            &
+                                  (f_riv_loc_n(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%RIV_SI%dgsave ) THEN
+                  rivsi2d(ji,jj) = rivsi2d(ji,jj) +                          &
+                                   (f_riv_loc_si(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%RIV_C%dgsave ) THEN
+                  rivc2d(ji,jj) = rivc2d(ji,jj) +                            &
+                                  (f_riv_loc_c(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%RIV_ALK%dgsave ) THEN
+                  rivalk2d(ji,jj) = rivalk2d(ji,jj) +                        &
+                                    (f_riv_loc_alk(ji,jj) *                  &
+                                     fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%DETC%dgsave ) THEN
+                  fslowc2d(ji,jj) = fslowc2d(ji,jj) +                        &
+                                    (fslowc(ji,jj)  * fse3t(ji,jj,jk))   
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!
+               IF( med_diag%PN_LLOSS%dgsave ) THEN
+                  fdpn22d(ji,jj) = fdpn22d(ji,jj) +                          &
+                                   (fdpn2(ji,jj)  * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%PD_LLOSS%dgsave ) THEN
+                  fdpd22d(ji,jj) = fdpd22d(ji,jj) +                          &
+                                   (fdpd2(ji,jj)  * fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%ZI_LLOSS%dgsave ) THEN
+                  fdzmi22d(ji,jj) = fdzmi22d(ji,jj) +                        &
+                                    (fdzmi2(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_LLOSS%dgsave ) THEN
+                  fdzme22d(ji,jj) = fdzme22d(ji,jj) +                        &
+                                    (fdzme2(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%ZI_MES_N%dgsave ) THEN
+                  zimesn2d(ji,jj) = zimesn2d(ji,jj) +                        &
+                                    (xphi * (fgmipn(ji,jj) +                 &
+                                             fgmid(ji,jj)) *                 &
+                                     fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZI_MES_D%dgsave ) THEN
+                  zimesd2d(ji,jj) = zimesd2d(ji,jj) +                        & 
+                                    ((1. - xbetan) * finmi(ji,jj) *          &
+                                     fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZI_MES_C%dgsave ) THEN
+                  zimesc2d(ji,jj) = zimesc2d(ji,jj) +                        &
+                                    (xphi * ((xthetapn * fgmipn(ji,jj)) +    &
+                                             fgmidc(ji,jj)) *                &
+                                             fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZI_MESDC%dgsave ) THEN
+                  zimesdc2d(ji,jj) = zimesdc2d(ji,jj) +                      &
+                                     ((1. - xbetac) * ficmi(ji,jj) *         &
+                                      fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZI_EXCR%dgsave ) THEN
+                  ziexcr2d(ji,jj) = ziexcr2d(ji,jj) +                        &
+                                    (fmiexcr(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZI_RESP%dgsave ) THEN
+                  ziresp2d(ji,jj) = ziresp2d(ji,jj) +                        &
+                                    (fmiresp(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZI_GROW%dgsave ) THEN
+                  zigrow2d(ji,jj) = zigrow2d(ji,jj) +                        &
+                                    (fmigrow(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               IF( med_diag%ZE_MES_N%dgsave ) THEN
+                  zemesn2d(ji,jj) = zemesn2d(ji,jj) +                        &
+                                    (xphi *                                  &
+                                     (fgmepn(ji,jj) + fgmepd(ji,jj) +        &
+                                      fgmezmi(ji,jj) + fgmed(ji,jj)) *       &
+                                     fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_MES_D%dgsave ) THEN
+                  zemesd2d(ji,jj) = zemesd2d(ji,jj) +                        &
+                                    ((1. - xbetan) * finme(ji,jj) *          &
+                                     fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_MES_C%dgsave ) THEN
+                  zemesc2d(ji,jj) = zemesc2d(ji,jj) +                        & 
+                                    (xphi *                                  &
+                                     ((xthetapn * fgmepn(ji,jj)) +           &
+                                      (xthetapd * fgmepd(ji,jj)) +           &
+                                      (xthetazmi * fgmezmi(ji,jj)) +         &
+                                      fgmedc(ji,jj)) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_MESDC%dgsave ) THEN
+                  zemesdc2d(ji,jj) = zemesdc2d(ji,jj) +                      &
+                                     ((1. - xbetac) * ficme(ji,jj) *         &
+                                      fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_EXCR%dgsave ) THEN
+                  zeexcr2d(ji,jj) = zeexcr2d(ji,jj) +                        &
+                                    (fmeexcr(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_RESP%dgsave ) THEN
+                  zeresp2d(ji,jj) = zeresp2d(ji,jj) +                        &
+                                    (fmeresp(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%ZE_GROW%dgsave ) THEN
+                  zegrow2d(ji,jj) = zegrow2d(ji,jj) +                        &
+                                    (fmegrow(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+              IF( med_diag%MDETC%dgsave ) THEN
+                  mdetc2d(ji,jj) = mdetc2d(ji,jj) +                          &
+                                   (fddc(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%GMIDC%dgsave ) THEN
+                  gmidc2d(ji,jj) = gmidc2d(ji,jj) +                          &
+                                   (fgmidc(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%GMEDC%dgsave ) THEN
+                  gmedc2d(ji,jj) = gmedc2d(ji,jj) +                          &
+                                   (fgmedc(ji,jj) * fse3t(ji,jj,jk))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+# endif                   
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!
+               !! ** 3D diagnostics
+               IF( med_diag%TPP3%dgsave ) THEN
+                  tpp3d(ji,jj,jk) = (fprn(ji,jj) * zphn(ji,jj)) +            &
+                                    (fprd(ji,jj) * zphd(ji,jj))
+                  !CALL iom_put( "TPP3"  , tpp3d )
+               ENDIF
+               IF( med_diag%TPPD3%dgsave ) THEN
+                  tppd3(ji,jj,jk) = (fprd(ji,jj) * zphd(ji,jj))
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+                  
+               IF( med_diag%REMIN3N%dgsave ) THEN
+                  !! remineralisation
+                  remin3dn(ji,jj,jk) = fregen(ji,jj) +                       &
+                                       (freminn(ji,jj) * fse3t(ji,jj,jk))
+                  !CALL iom_put( "REMIN3N"  , remin3dn )
+               ENDIF
+               !! IF( med_diag%PH3%dgsave ) THEN
+               !!     CALL iom_put( "PH3"  , f3_pH )
+               !! ENDIF
+               !! IF( med_diag%OM_CAL3%dgsave ) THEN
+               !!     CALL iom_put( "OM_CAL3"  , f3_omcal )
+               !! ENDIF
+	       !! 
+	       !! AXY (09/11/16): CMIP6 diagnostics
+	       IF ( med_diag%DCALC3%dgsave   ) THEN
+                  dcalc3(ji,jj,jk) = freminca(ji,jj)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+	       IF ( med_diag%FEDISS3%dgsave  ) THEN
+                  fediss3(ji,jj,jk) = ffetop(ji,jj)
+               ENDIF
+	       IF ( med_diag%FESCAV3%dgsave  ) THEN
+                  fescav3(ji,jj,jk) = ffescav(ji,jj)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+	       IF ( med_diag%MIGRAZP3%dgsave ) THEN
+                  migrazp3(ji,jj,jk) = fgmipn(ji,jj) * xthetapn
+               ENDIF
+	       IF ( med_diag%MIGRAZD3%dgsave ) THEN
+                  migrazd3(ji,jj,jk) = fgmidc(ji,jj)
+               ENDIF
+	       IF ( med_diag%MEGRAZP3%dgsave ) THEN
+                  megrazp3(ji,jj,jk) = (fgmepn(ji,jj) * xthetapn) +          &
+                                       (fgmepd(ji,jj) * xthetapd)
+               ENDIF
+	       IF ( med_diag%MEGRAZD3%dgsave ) THEN
+                  megrazd3(ji,jj,jk) = fgmedc(ji,jj)
+               ENDIF
+	       IF ( med_diag%MEGRAZZ3%dgsave ) THEN
+                   megrazz3(ji,jj,jk) = (fgmezmi(ji,jj) * xthetazmi)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+	       IF ( med_diag%PBSI3%dgsave    ) THEN
+                  pbsi3(ji,jj,jk)    = (fprds(ji,jj) * zpds(ji,jj))
+               ENDIF
+	       IF ( med_diag%PCAL3%dgsave    ) THEN
+                  pcal3(ji,jj,jk)    = ftempca(ji,jj)
+               ENDIF
+	       IF ( med_diag%REMOC3%dgsave   ) THEN
+                  remoc3(ji,jj,jk)   = freminc(ji,jj)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+	       IF ( med_diag%PNLIMJ3%dgsave  ) THEN
+                  ! pnlimj3(ji,jj,jk)  = fjln(ji,jj)
+                  pnlimj3(ji,jj,jk)  = fjlim_pn(ji,jj)
+               ENDIF
+	       IF ( med_diag%PNLIMN3%dgsave  ) THEN
+                  pnlimn3(ji,jj,jk)  = fnln(ji,jj)
+               ENDIF
+	       IF ( med_diag%PNLIMFE3%dgsave ) THEN
+                  pnlimfe3(ji,jj,jk) = ffln2(ji,jj)
+               ENDIF
+	       IF ( med_diag%PDLIMJ3%dgsave  ) THEN
+                  ! pdlimj3(ji,jj,jk)  = fjld(ji,jj)
+                  pdlimj3(ji,jj,jk)  = fjlim_pd(ji,jj)
+               ENDIF
+	       IF ( med_diag%PDLIMN3%dgsave  ) THEN
+                  pdlimn3(ji,jj,jk)  = fnld(ji,jj)
+               ENDIF
+	       IF ( med_diag%PDLIMFE3%dgsave ) THEN
+                  pdlimfe3(ji,jj,jk) = ffld(ji,jj)
+               ENDIF
+	       IF ( med_diag%PDLIMSI3%dgsave ) THEN
+                  pdlimsi3(ji,jj,jk) = fsld2(ji,jj)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE bio_med_diag_iomput
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE bio_med_diag_iomput( )                    ! Empty routine
+      WRITE(*,*) 'bio_med_diag_iomput: You should not have seen this print! error?'
+   END SUBROUTINE bio_med_diag_iomput
+#endif 
+
+   !!======================================================================
+END MODULE bio_med_diag_iomput_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_diag.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_diag.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_diag.F90	(revision 9987)
@@ -0,0 +1,212 @@
+MODULE bio_medusa_diag_mod
+   !!======================================================================
+   !!                         ***  MODULE bio_medusa_diag_mod  ***
+   !! Calculates diagnostics
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   bio_medusa_diag        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE bio_medusa_diag( jk )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE bio_medusa_diag  ***
+      !! This called from TRC_BIO_MEDUSA and calculates diagnostics
+      !!-------------------------------------------------------------------
+      USE bio_med_diag_iomput_mod,  ONLY: bio_med_diag_iomput
+      USE bio_medusa_mod
+      USE dom_oce,                  ONLY: e3t_0, e3t_n,                  &
+                                          gdepw_0, gdepw_n, tmask
+      USE in_out_manager,           ONLY: lwp, numout
+# if defined key_iomput
+      USE iom,                      ONLY: lk_iomput
+# endif
+      USE par_oce,                  ONLY: jpim1, jpjm1
+      USE sms_medusa,               ONLY: xrfn, xthetapd, xthetapn,      &
+                                          xthetazme, xthetazmi
+      USE trc,                      ONLY: med_diag 
+# if defined key_roam
+      USE trcoxy_medusa,            ONLY: oxy_sato
+# endif
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! level
+      INTEGER, INTENT( in ) :: jk
+
+      !! Loop avariables
+      INTEGER :: ji, jj, jn
+
+# if defined key_trc_diabio
+      !!==========================================================
+      !! LOCAL GRID CELL DIAGNOSTICS
+      !!==========================================================
+      !!
+      !!----------------------------------------------------------
+      !! Full diagnostics key_trc_diabio:
+      !! LOBSTER and PISCES support full diagnistics option 
+      !! key_trc_diabio which gives an option of FULL output of 
+      !! biological sourses and sinks. I cannot see any reason 
+      !! for doing this. If needed, it can be done as shown
+      !! below.
+      !!----------------------------------------------------------
+      !!
+      IF(lwp) WRITE(numout,*) ' MEDUSA does not support key_trc_diabio'
+# endif
+
+      !! The section below, down to calculation of zo2min, was moved 
+      !! from before the call to AIR_SEA in trcbio_medusa.F90 - marc 9/5/17 
+      IF( lk_iomput ) THEN
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  !! sum tracers for inventory checks
+                  IF ( med_diag%INVTN%dgsave )   THEN
+                     ftot_n(ji,jj)  = ftot_n(ji,jj) +                        &
+                        (fse3t(ji,jj,jk) * (zphn(ji,jj) + zphd(ji,jj) +      &
+                                            zzmi(ji,jj) + zzme(ji,jj) +      &
+                                            zdet(ji,jj) + zdin(ji,jj)))
+                  ENDIF
+                  IF ( med_diag%INVTSI%dgsave )  THEN
+                     ftot_si(ji,jj) = ftot_si(ji,jj) +                       & 
+                       (fse3t(ji,jj,jk) * (zpds(ji,jj) + zsil(ji,jj)))
+                  ENDIF
+                  IF ( med_diag%INVTFE%dgsave )  THEN
+                     ftot_fe(ji,jj) = ftot_fe(ji,jj) +                       & 
+                        (fse3t(ji,jj,jk) * (xrfn *                           &
+                                            (zphn(ji,jj) + zphd(ji,jj) +     &
+                                             zzmi(ji,jj) + zzme(ji,jj) +     &
+                                             zdet(ji,jj)) +                  &
+                                            zfer(ji,jj)))
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+
+# if defined key_roam
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  IF ( med_diag%INVTC%dgsave )  THEN
+                     ftot_c(ji,jj)  = ftot_c(ji,jj) +                        & 
+                        (fse3t(ji,jj,jk) * ((xthetapn * zphn(ji,jj)) +       &
+                                            (xthetapd * zphd(ji,jj)) +       &
+                                            (xthetazmi * zzmi(ji,jj)) +      &
+                                            (xthetazme * zzme(ji,jj)) +      &
+                                            zdtc(ji,jj) + zdic(ji,jj)))
+                  ENDIF
+                  IF ( med_diag%INVTALK%dgsave ) THEN
+                     ftot_a(ji,jj)  = ftot_a(ji,jj) + (fse3t(ji,jj,jk) *     &
+                                                       zalk(ji,jj))
+                  ENDIF
+                  IF ( med_diag%INVTO2%dgsave )  THEN
+                     ftot_o2(ji,jj) = ftot_o2(ji,jj) + (fse3t(ji,jj,jk) *    &
+                                                        zoxy(ji,jj))
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  IF ( med_diag%INVTC%dgsave )  THEN
+                     !!
+                     !! AXY (10/11/16): CMIP6 diagnostics
+                     IF ( med_diag%INTDISSIC%dgsave ) THEN
+                        intdissic(ji,jj) = intdissic(ji,jj) +                &
+                                           (fse3t(ji,jj,jk) * zdic(ji,jj))
+                     ENDIF
+                     IF ( med_diag%INTDISSIN%dgsave ) THEN
+                        intdissin(ji,jj) = intdissin(ji,jj) +                &
+                                           (fse3t(ji,jj,jk) * zdin(ji,jj))
+                     ENDIF
+                     IF ( med_diag%INTDISSISI%dgsave ) THEN
+                        intdissisi(ji,jj) = intdissisi(ji,jj) +              &
+                                            (fse3t(ji,jj,jk) * zsil(ji,jj))
+                     ENDIF
+                     IF ( med_diag%INTTALK%dgsave ) THEN
+                        inttalk(ji,jj) = inttalk(ji,jj) +                    &
+                                         (fse3t(ji,jj,jk) * zalk(ji,jj))
+                     ENDIF
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  IF ( med_diag%O2min%dgsave ) THEN
+                     if ( zoxy(ji,jj) < o2min(ji,jj) ) then
+                        o2min(ji,jj)  = zoxy(ji,jj)
+                        IF ( med_diag%ZO2min%dgsave ) THEN
+                           !! layer midpoint
+                           zo2min(ji,jj) = (fsdepw(ji,jj,jk) +               &
+                                            fdep1(ji,jj)) / 2.0
+                        ENDIF
+                     endif
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDDO
+# endif
+      ENDIF
+
+# if defined key_roam
+      !! This section is moved from just below CALL to AIR_SEA in
+      !! trcbio_medusa.F90 - marc 9/5/17
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+
+               !! AXY (11/11/16): CMIP6 oxygen saturation 3D diagnostic
+               IF ( med_diag%O2SAT3%dgsave ) THEN
+! Remove f_o2sat3 - marc 9/5/17
+!                  call oxy_sato( ztmp(ji,jj), zsal(ji,jj), f_o2sat3 )
+!                  o2sat3(ji, jj, jk) = f_o2sat3
+                  call oxy_sato( ztmp(ji,jj), zsal(ji,jj),                   &
+                                 o2sat3(ji,jj,jk) )
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+# endif
+
+      !!---------------------------------------------------------------
+      !! Calculates the diagnostics used with iom_put
+      !!---------------------------------------------------------------
+      CALL bio_med_diag_iomput( jk )
+
+   END SUBROUTINE bio_medusa_diag
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE bio_medusa_diag( )                    ! Empty routine
+      WRITE(*,*) 'bio_medusa_diag: You should not have seen this print! error?'
+   END SUBROUTINE bio_medusa_diag
+#endif 
+
+   !!======================================================================
+END MODULE bio_medusa_diag_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_diag_slice.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_diag_slice.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_diag_slice.F90	(revision 9987)
@@ -0,0 +1,420 @@
+MODULE bio_medusa_diag_slice_mod
+   !!======================================================================
+   !!                         ***  MODULE bio_medusa_diag_slice_mod  ***
+   !! Diagnostic calculations at different levels
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   bio_medusa_diag_slice     ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE bio_medusa_diag_slice( jk )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE bio_medusa_diag_slice  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - ...
+      !!----------------------------------------------------------------------
+      USE bio_medusa_mod
+      USE par_medusa,        ONLY: jpchd, jpchn      
+      USE dom_oce,           ONLY: tmask
+      USE in_out_manager,    ONLY: lwp, numout
+# if defined key_iomput
+      USE iom,               ONLY: iom_put
+# endif
+      USE lbclnk,            ONLY: lbc_lnk
+      USE trc,               ONLY: trn
+      USE oce,               ONLY: CO2Flux_out_cpl, DMS_out_cpl, chloro_out_cpl
+      USE par_oce,           ONLY: jpi, jpj
+      USE sbc_oce,           ONLY: lk_oasis, qsr, wndm
+      USE sms_medusa,        ONLY: i0100, i0150, i0200, i0500, i1000,      &
+                                   f2_ccd_arg, f2_ccd_cal,                 &
+                                   f3_co3, f3_h2co3, f3_hco3, f3_pH,       &
+                                   jdms, ocal_ccd, xpar, xze,              &
+                                   zb_co2_flx, zb_dms_srf,                 &
+                                   zn_co2_flx, zn_dms_srf, zn_chl_srf
+      USE trc,               ONLY: med_diag
+
+      !! The vertical level
+      INTEGER, INTENT( in ) ::    jk
+      !!----------------------------------------------------------------------
+
+      !!-----------------------------------------
+      !!
+      !! 2d specific k level diags
+      !!
+      !!-----------------------------------------
+#   if defined key_debug_medusa
+         IF (lwp) write (numout,*) 'bio_medusa_diag_slice: start jk = ', jk
+         CALL flush(numout)
+#   endif
+      !!
+      IF (jk.eq.1) THEN
+         !! JPALM -- 02-06-2017 --
+         !! add Chl surf coupling
+         !! no need to output, just pass to cpl var
+         IF (lk_oasis) THEN
+            zn_chl_srf(:,:) = (trn(:,:,1,jpchd) + trn(:,:,1,jpchn)) * 1.0E-6  !! surf Chl in Kg-chl/m3 as needed for cpl
+            chloro_out_cpl(:,:) = zn_chl_srf(:,:)        !! Coupling Chl
+         END IF
+         IF( med_diag%MED_QSR%dgsave ) THEN
+            CALL iom_put( "MED_QSR"  , qsr ) !
+         ENDIF
+         IF( med_diag%MED_XPAR%dgsave ) THEN
+            CALL iom_put( "MED_XPAR"  , xpar(:,:,jk) ) !
+         ENDIF       
+         IF( med_diag%OCAL_CCD%dgsave ) THEN
+            CALL iom_put( "OCAL_CCD"  , ocal_ccd ) !
+         ENDIF
+         IF( med_diag%FE_0000%dgsave ) THEN
+            CALL iom_put( "FE_0000"  , xFree ) !
+         ENDIF                     
+         IF( med_diag%MED_XZE%dgsave ) THEN
+            CALL iom_put( "MED_XZE"  , xze ) !
+         ENDIF 
+# if defined key_roam                     
+         IF( med_diag%WIND%dgsave ) THEN
+            CALL iom_put( "WIND"  , wndm )
+         ENDIF
+         IF( med_diag%ATM_PCO2%dgsave ) THEN
+            CALL iom_put( "ATM_PCO2"  , f_pco2a2d )
+            DEALLOCATE( f_pco2a2d )
+         ENDIF
+         IF( med_diag%OCN_PH%dgsave ) THEN
+            zw2d(:,:) = f3_pH(:,:,jk)
+            CALL iom_put( "OCN_PH"  , zw2d )
+         ENDIF
+         IF( med_diag%OCN_PCO2%dgsave ) THEN
+            CALL iom_put( "OCN_PCO2"  , f_pco2w2d )
+            DEALLOCATE( f_pco2w2d )
+         ENDIF
+         IF( med_diag%OCNH2CO3%dgsave ) THEN
+            zw2d(:,:) = f3_h2co3(:,:,jk)
+            CALL iom_put( "OCNH2CO3"  , zw2d )
+         ENDIF
+         IF( med_diag%OCN_HCO3%dgsave ) THEN
+            zw2d(:,:) = f3_hco3(:,:,jk)
+            CALL iom_put( "OCN_HCO3"  , zw2d )
+         ENDIF
+         IF( med_diag%OCN_CO3%dgsave ) THEN
+            zw2d(:,:) = f3_co3(:,:,jk)
+            CALL iom_put( "OCN_CO3"  , zw2d )
+         ENDIF
+         IF( med_diag%CO2FLUX%dgsave ) THEN
+            CALL iom_put( "CO2FLUX"  , f_co2flux2d )
+            DEALLOCATE( f_co2flux2d )
+         ENDIF
+         !! 
+         !! AXY (10/11/16): repeat CO2 flux diagnostic in UKMO/CMIP6 units;
+         !!                 this both outputs the CO2 flux in specified units
+         !!                 and sends the resulting field to the coupler
+         !! JPALM (17/11/16): put CO2 flux (fgco2) alloc/unalloc/pass to zn 
+         !!                   out of diag list request 
+         CALL lbc_lnk( fgco2(:,:),'T',1. )
+         IF( med_diag%FGCO2%dgsave ) THEN
+            CALL iom_put( "FGCO2"  , fgco2 )
+         ENDIF
+         !! JPALM (17/11/16): should mv this fgco2 part 
+         !!                   out of lk_iomput loop
+         zb_co2_flx = zn_co2_flx
+         zn_co2_flx = fgco2
+         IF (lk_oasis) THEN
+            CO2Flux_out_cpl = zn_co2_flx
+         ENDIF
+         DEALLOCATE( fgco2 )
+         !! ---
+         IF( med_diag%OM_CAL%dgsave ) THEN
+            CALL iom_put( "OM_CAL"  , f_omcal )
+         ENDIF
+         IF( med_diag%OM_ARG%dgsave ) THEN
+            CALL iom_put( "OM_ARG"  , f_omarg )
+         ENDIF
+         IF( med_diag%TCO2%dgsave ) THEN
+            CALL iom_put( "TCO2"  , f_TDIC2d )
+            DEALLOCATE( f_TDIC2d )
+         ENDIF
+         IF( med_diag%TALK%dgsave ) THEN
+            CALL iom_put( "TALK"  , f_TALK2d )
+            DEALLOCATE( f_TALK2d )
+         ENDIF
+         IF( med_diag%KW660%dgsave ) THEN
+            CALL iom_put( "KW660"  , f_kw6602d )
+            DEALLOCATE( f_kw6602d )
+         ENDIF
+         IF( med_diag%ATM_PP0%dgsave ) THEN
+            CALL iom_put( "ATM_PP0"  , f_pp02d )
+            DEALLOCATE( f_pp02d )
+         ENDIF
+         IF( med_diag%O2FLUX%dgsave ) THEN
+            CALL iom_put( "O2FLUX"  , f_o2flux2d )
+            DEALLOCATE( f_o2flux2d )
+         ENDIF
+         IF( med_diag%O2SAT%dgsave ) THEN
+            CALL iom_put( "O2SAT"  , f_o2sat2d )
+            DEALLOCATE( f_o2sat2d )
+         ENDIF
+         IF( med_diag%CAL_CCD%dgsave ) THEN
+            CALL iom_put( "CAL_CCD"  , f2_ccd_cal )
+         ENDIF
+         IF( med_diag%ARG_CCD%dgsave ) THEN
+            CALL iom_put( "ARG_CCD"  , f2_ccd_arg )
+         ENDIF
+         IF (jdms .eq. 1) THEN
+            IF( med_diag%DMS_SURF%dgsave ) THEN
+               CALL lbc_lnk(dms_surf2d(:,:),'T',1. )
+               CALL iom_put( "DMS_SURF"  , dms_surf2d )
+               zb_dms_srf = zn_dms_srf
+               zn_dms_srf = dms_surf2d
+               IF (lk_oasis) THEN
+                  DMS_out_cpl = zn_dms_srf
+               ENDIF
+               DEALLOCATE( dms_surf2d ) 
+            ENDIF
+            IF( med_diag%DMS_ANDR%dgsave ) THEN
+               CALL iom_put( "DMS_ANDR"  , dms_andr2d )
+               DEALLOCATE( dms_andr2d )
+            ENDIF
+            IF( med_diag%DMS_SIMO%dgsave ) THEN
+               CALL iom_put( "DMS_SIMO"  , dms_simo2d )
+               DEALLOCATE( dms_simo2d )
+            ENDIF
+            IF( med_diag%DMS_ARAN%dgsave ) THEN
+               CALL iom_put( "DMS_ARAN"  , dms_aran2d )
+               DEALLOCATE( dms_aran2d )
+            ENDIF
+            IF( med_diag%DMS_HALL%dgsave ) THEN
+               CALL iom_put( "DMS_HALL"  , dms_hall2d )
+               DEALLOCATE( dms_hall2d )
+            ENDIF
+            IF( med_diag%DMS_ANDM%dgsave ) THEN
+               CALL iom_put( "DMS_ANDM"  , dms_andm2d )
+               DEALLOCATE( dms_andm2d )
+            ENDIF
+         ENDIF
+         !! AXY (24/11/16): extra MOCSY diagnostics
+         IF( med_diag%ATM_XCO2%dgsave ) THEN
+            CALL iom_put( "ATM_XCO2"  ,   f_xco2a_2d      )
+            DEALLOCATE( f_xco2a_2d )
+         ENDIF
+         IF( med_diag%OCN_FCO2%dgsave ) THEN
+            CALL iom_put( "OCN_FCO2"  ,   f_fco2w_2d      )
+            DEALLOCATE( f_fco2w_2d )
+         ENDIF
+         IF( med_diag%ATM_FCO2%dgsave ) THEN
+            CALL iom_put( "ATM_FCO2"  ,   f_fco2a_2d      )
+            DEALLOCATE( f_fco2a_2d )
+         ENDIF
+         IF( med_diag%OCN_RHOSW%dgsave ) THEN
+            CALL iom_put( "OCN_RHOSW"  ,  f_ocnrhosw_2d   )
+            DEALLOCATE( f_ocnrhosw_2d )
+         ENDIF
+         IF( med_diag%OCN_SCHCO2%dgsave ) THEN
+            CALL iom_put( "OCN_SCHCO2"  , f_ocnschco2_2d  )
+            DEALLOCATE( f_ocnschco2_2d )
+         ENDIF
+         IF( med_diag%OCN_KWCO2%dgsave ) THEN
+            CALL iom_put( "OCN_KWCO2"  ,  f_ocnkwco2_2d   )
+            DEALLOCATE( f_ocnkwco2_2d )
+         ENDIF
+         IF( med_diag%OCN_K0%dgsave ) THEN
+            CALL iom_put( "OCN_K0"  ,     f_ocnk0_2d      )
+            DEALLOCATE( f_ocnk0_2d )
+         ENDIF
+         IF( med_diag%CO2STARAIR%dgsave ) THEN
+            CALL iom_put( "CO2STARAIR"  , f_co2starair_2d )
+            DEALLOCATE( f_co2starair_2d )
+         ENDIF
+         IF( med_diag%OCN_DPCO2%dgsave ) THEN
+            CALL iom_put( "OCN_DPCO2"  ,  f_ocndpco2_2d   )
+            DEALLOCATE( f_ocndpco2_2d )
+         ENDIF
+# endif                     
+      ELSE IF (jk.eq.i0100) THEN 
+         IF( med_diag%SDT__100%dgsave ) THEN
+            zw2d(:,:) = fslownflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDT__100"  , zw2d )
+         ENDIF
+         IF( med_diag%REG__100%dgsave ) THEN
+            CALL iom_put( "REG__100"  , fregen2d )
+         ENDIF
+         IF( med_diag%FDT__100%dgsave ) THEN
+            CALL iom_put( "FDT__100"  , ffastn )
+         ENDIF           
+         IF( med_diag%RG__100F%dgsave ) THEN
+            CALL iom_put( "RG__100F"  , fregenfast )
+         ENDIF
+         IF( med_diag%FDS__100%dgsave ) THEN
+            CALL iom_put( "FDS__100"  , ffastsi )
+         ENDIF         
+         IF( med_diag%RGS_100F%dgsave ) THEN
+            CALL iom_put( "RGS_100F"  , fregenfastsi )
+         ENDIF
+         IF( med_diag%FE_0100%dgsave ) THEN
+            CALL iom_put( "FE_0100"  , xFree )
+         ENDIF
+# if defined key_roam                     
+         IF( med_diag%RR_0100%dgsave ) THEN
+            CALL iom_put( "RR_0100"  , ffastca2d )
+         ENDIF                     
+         IF( med_diag%SDC__100%dgsave ) THEN
+            zw2d(:,:) = fslowcflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDC__100"  , zw2d )
+         ENDIF                  
+         IF( med_diag%epC100%dgsave    ) THEN
+            zw2d(:,:) = (fslowcflux + ffastc) * tmask(:,:,jk)
+            CALL iom_put( "epC100"    , zw2d )
+         ENDIF		     
+         IF( med_diag%epCALC100%dgsave ) THEN
+            CALL iom_put( "epCALC100" , ffastca )
+         ENDIF		     
+         IF( med_diag%epN100%dgsave    ) THEN
+            zw2d(:,:) = (fslownflux + ffastn) * tmask(:,:,jk)
+            CALL iom_put( "epN100"    , zw2d )
+         ENDIF		     
+         IF( med_diag%epSI100%dgsave   ) THEN
+            CALL iom_put( "epSI100"   , ffastsi )
+         ENDIF		     
+# endif                     
+      ELSE IF (jk.eq.i0200) THEN
+         IF( med_diag%SDT__200%dgsave ) THEN
+            zw2d(:,:) = fslownflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDT__200"  , zw2d )
+         ENDIF
+         IF( med_diag%REG__200%dgsave ) THEN
+            CALL iom_put( "REG__200"  , fregen2d )
+         ENDIF
+         IF( med_diag%FDT__200%dgsave ) THEN
+            CALL iom_put( "FDT__200"  , ffastn )
+         ENDIF
+         IF( med_diag%RG__200F%dgsave ) THEN
+            CALL iom_put( "RG__200F"  , fregenfast )
+         ENDIF
+         IF( med_diag%FDS__200%dgsave ) THEN
+            CALL iom_put( "FDS__200"  , ffastsi )
+         ENDIF
+         IF( med_diag%RGS_200F%dgsave ) THEN
+            CALL iom_put( "RGS_200F"  , fregenfastsi )
+         ENDIF
+         IF( med_diag%FE_0200%dgsave ) THEN
+            CALL iom_put( "FE_0200"   , xFree )
+         ENDIF
+# if defined key_roam                     
+         IF( med_diag%SDC__200%dgsave ) THEN
+            zw2d(:,:) = fslowcflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDC__200"  , zw2d )
+         ENDIF
+# endif                     
+      ELSE IF (jk.eq.i0500) THEN
+         IF( med_diag%SDT__500%dgsave ) THEN
+            zw2d(:,:) = fslownflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDT__500"  , zw2d )
+         ENDIF
+         IF( med_diag%REG__500%dgsave ) THEN
+            CALL iom_put( "REG__500"  , fregen2d )
+         ENDIF      
+         IF( med_diag%FDT__500%dgsave ) THEN
+            CALL iom_put( "FDT__500"  , ffastn )
+         ENDIF
+         IF( med_diag%RG__500F%dgsave ) THEN
+            CALL iom_put( "RG__500F"  , fregenfast )
+         ENDIF
+         IF( med_diag%FDS__500%dgsave ) THEN
+            CALL iom_put( "FDS__500"  , ffastsi )
+         ENDIF
+         IF( med_diag%RGS_500F%dgsave ) THEN
+            CALL iom_put( "RGS_500F"  , fregenfastsi )
+         ENDIF
+         IF( med_diag%FE_0500%dgsave ) THEN
+            CALL iom_put( "FE_0500"  , xFree )
+         ENDIF
+# if defined key_roam                     
+         IF( med_diag%RR_0500%dgsave ) THEN
+            CALL iom_put( "RR_0500"  , ffastca2d )
+         ENDIF
+         IF( med_diag%SDC__500%dgsave ) THEN
+            zw2d(:,:) = fslowcflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDC__500"  , zw2d )
+         ENDIF  
+# endif                      
+      ELSE IF (jk.eq.i1000) THEN
+         IF( med_diag%SDT_1000%dgsave ) THEN
+            zw2d(:,:) = fslownflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDT_1000"  , zw2d )
+         ENDIF
+         IF( med_diag%REG_1000%dgsave ) THEN
+            CALL iom_put( "REG_1000"  , fregen2d )
+         ENDIF  
+         IF( med_diag%FDT_1000%dgsave ) THEN
+            CALL iom_put( "FDT_1000"  , ffastn )
+         ENDIF
+         IF( med_diag%RG_1000F%dgsave ) THEN
+            CALL iom_put( "RG_1000F"  , fregenfast )
+         ENDIF
+         IF( med_diag%FDS_1000%dgsave ) THEN
+            CALL iom_put( "FDS_1000"  , ffastsi )
+         ENDIF
+         IF( med_diag%RGS1000F%dgsave ) THEN
+            CALL iom_put( "RGS1000F"  , fregenfastsi )
+         ENDIF
+         IF( med_diag%FE_1000%dgsave ) THEN
+            CALL iom_put( "FE_1000"  , xFree )
+         ENDIF
+# if defined key_roam                     
+         IF( med_diag%RR_1000%dgsave ) THEN
+            CALL iom_put( "RR_1000"  , ffastca2d )
+            DEALLOCATE( ffastca2d )
+         ENDIF
+         IF( med_diag%SDC_1000%dgsave ) THEN
+            zw2d(:,:) = fslowcflux(:,:) * tmask(:,:,jk)
+            CALL iom_put( "SDC_1000"  , zw2d )
+         ENDIF 
+# endif                      
+      ENDIF
+      !! to do on every k loop :
+      IF( med_diag%DETFLUX3%dgsave ) THEN
+         !! detrital flux
+         detflux3d(:,:,jk) = (fslownflux(:,:) + ffastn(:,:)) * tmask(:,:,jk)
+         !CALL iom_put( "DETFLUX3"  , ftot_n )
+      ENDIF
+# if defined key_roam                     
+      IF( med_diag%EXPC3%dgsave ) THEN
+         expc3(:,:,jk) = (fslowcflux(:,:) + ffastc(:,:)) * tmask(:,:,jk)
+      ENDIF		     
+      IF( med_diag%EXPN3%dgsave ) THEN
+         expn3(:,:,jk) = (fslownflux(:,:) + ffastn(:,:)) * tmask(:,:,jk)
+      ENDIF		     
+# endif		     
+#   if defined key_debug_medusa
+         IF (lwp) write (numout,*) 'bio_medusa_diag_slice: end jk = ', jk
+         CALL flush(numout)
+#   endif
+
+   END SUBROUTINE bio_medusa_diag_slice
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE bio_medusa_diag_slice( )                  ! Empty routine
+      WRITE(*,*) 'bio_medusa_diag_slice: You should not have seen this print! error?'
+   END SUBROUTINE bio_medusa_diag_slice
+#endif 
+
+   !!======================================================================
+END MODULE bio_medusa_diag_slice_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_fin.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_fin.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_fin.F90	(revision 9987)
@@ -0,0 +1,1006 @@
+MODULE bio_medusa_fin_mod
+   !!======================================================================
+   !!                         ***  MODULE bio_medusa_fin_mod  ***
+   !! Finalisation for TRC_BIO_MEDUSA
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   bio_medusa_fin     ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE bio_medusa_fin( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE bio_medusa_fin  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - ...
+      !!----------------------------------------------------------------------
+      USE bio_medusa_mod
+      USE dom_oce,           ONLY: atfp, atfp1, neuler, rdt, e3t_n, tmask
+      USE in_out_manager,    ONLY: lwp, numout
+# if defined key_iomput
+      USE iom,               ONLY: iom_put, lk_iomput
+# endif
+      USE lbclnk,            ONLY: lbc_lnk
+      USE par_medusa,        ONLY: jp_medusa_2d, jp_medusa_3d,          &
+                                   jp_medusa_trd
+      USE par_oce,           ONLY: jpi, jpim1, jpj, jpjm1, jpk
+      USE phycst,            ONLY: rsmall
+      USE sms_medusa,        ONLY: jinorgben, jorgben,                  &
+                                   f3_co3, f3_h2co3, f3_hco3,           &
+                                   f3_omarg, f3_omcal, f3_pH,           &
+                                   za_sed_c, za_sed_ca, za_sed_fe,      &
+                                   za_sed_n, za_sed_si,                 &
+                                   zb_sed_c, zb_sed_ca, zb_sed_fe,      &
+                                   zb_sed_n, zb_sed_si,                 &
+                                   zn_sed_c, zn_sed_ca, zn_sed_fe,      &
+                                   zn_sed_n, zn_sed_si
+      USE trc,               ONLY: med_diag, nittrc000 
+      USE trcnam_trp,        ONLY: ln_trcadv_cen2, ln_trcadv_tvd
+ 
+      !! time (integer timestep)
+      INTEGER, INTENT( in ) ::    kt
+
+      INTEGER :: ji, jj
+      INTEGER :: jn
+
+      REAL(wp) :: fq0,fq1,fq2,fq3
+
+      !!----------------------------------------------------------------------
+      !! Process benthic in/out fluxes
+      !! These can be handled outside of the 3D calculations since the
+      !! benthic pools (and fluxes) are 2D in nature; this code is
+      !! (shamelessly) borrowed from corresponding code in the LOBSTER
+      !! model
+      !!----------------------------------------------------------------------
+      !!
+      !! IF(lwp) WRITE(numout,*) 'AXY: rdt = ', rdt
+      if (jorgben.eq.1) then
+         za_sed_n(:,:)  = zn_sed_n(:,:)  +                                 & 
+                          ( f_sbenin_n(:,:)  + f_fbenin_n(:,:)  -          &
+                            f_benout_n(:,:)  ) * (rdt / 86400.)
+         zn_sed_n(:,:)  = za_sed_n(:,:)
+         !!
+         za_sed_fe(:,:) = zn_sed_fe(:,:) +                                 &
+                          ( f_sbenin_fe(:,:) + f_fbenin_fe(:,:) -          &
+                            f_benout_fe(:,:) ) * (rdt / 86400.)
+         zn_sed_fe(:,:) = za_sed_fe(:,:)
+         !!
+         za_sed_c(:,:)  = zn_sed_c(:,:)  +                                 &
+                          ( f_sbenin_c(:,:)  + f_fbenin_c(:,:)  -          &
+                            f_benout_c(:,:)  ) * (rdt / 86400.)
+         zn_sed_c(:,:)  = za_sed_c(:,:)
+      endif
+      if (jinorgben.eq.1) then
+         za_sed_si(:,:) = zn_sed_si(:,:) +                                 & 
+                          ( f_fbenin_si(:,:) - f_benout_si(:,:) ) *        &
+                          (rdt / 86400.)
+         zn_sed_si(:,:) = za_sed_si(:,:)
+         !!
+         za_sed_ca(:,:) = zn_sed_ca(:,:) +                                 &
+                          ( f_fbenin_ca(:,:) - f_benout_ca(:,:) ) *        &
+                          (rdt / 86400.)
+         zn_sed_ca(:,:) = za_sed_ca(:,:)
+      endif
+      !!
+      if (ibenthic.eq.2) then
+         !! The code below (in this if ... then ... endif loop) is
+         !! effectively commented out because it does not work as 
+         !! anticipated; it can be deleted at a later date
+         if (jorgben.eq.1) then
+            za_sed_n(:,:)  = ( f_sbenin_n(:,:)  + f_fbenin_n(:,:)  -       &
+                               f_benout_n(:,:)  ) * rdt
+            za_sed_fe(:,:) = ( f_sbenin_fe(:,:) + f_fbenin_fe(:,:) -       &
+                               f_benout_fe(:,:) ) * rdt
+            za_sed_c(:,:)  = ( f_sbenin_c(:,:)  + f_fbenin_c(:,:)  -       &
+                               f_benout_c(:,:)  ) * rdt
+         endif
+         if (jinorgben.eq.1) then
+            za_sed_si(:,:) = ( f_fbenin_si(:,:) - f_benout_si(:,:) ) * rdt
+            za_sed_ca(:,:) = ( f_fbenin_ca(:,:) - f_benout_ca(:,:) ) * rdt
+         endif
+         !!
+         !! Leap-frog scheme - only in explicit case, otherwise the 
+         !! time stepping is already being done in trczdf
+         !! IF( l_trczdf_exp .AND. (ln_trcadv_cen2 .OR. ln_trcadv_tvd) ) THEN
+         !!    zfact = 2. * rdttra(jk) * FLOAT( ndttrc )
+         !!    IF( neuler == 0 .AND. kt == nittrc000 )  zfact = rdttra(jk) * 
+         !!                                             FLOAT(ndttrc)
+         !!    if (jorgben.eq.1) then
+         !!       za_sed_n(:,:)  = zb_sed_n(:,:)  + ( zfact * za_sed_n(:,:)  )
+         !!      za_sed_fe(:,:) = zb_sed_fe(:,:) + ( zfact * za_sed_fe(:,:) )
+         !!       za_sed_c(:,:)  = zb_sed_c(:,:)  + ( zfact * za_sed_c(:,:)  )
+         !!    endif
+         !!    if (jinorgben.eq.1) then
+         !!       za_sed_si(:,:) = zb_sed_si(:,:) + ( zfact * za_sed_si(:,:) )
+         !!       za_sed_ca(:,:) = zb_sed_ca(:,:) + ( zfact * za_sed_ca(:,:) )
+         !!    endif
+         !! ENDIF
+         !! 
+         !! Time filter and swap of arrays
+         IF( ln_trcadv_cen2 .OR. ln_trcadv_tvd  ) THEN ! centred or tvd scheme
+            IF( neuler == 0 .AND. kt == nittrc000 ) THEN
+               if (jorgben.eq.1) then
+                  zb_sed_n(:,:)  = zn_sed_n(:,:)
+                  zn_sed_n(:,:)  = za_sed_n(:,:)
+                  za_sed_n(:,:)  = 0.0
+                  !!
+                  zb_sed_fe(:,:) = zn_sed_fe(:,:)
+                  zn_sed_fe(:,:) = za_sed_fe(:,:)
+                  za_sed_fe(:,:) = 0.0
+                  !!
+                  zb_sed_c(:,:)  = zn_sed_c(:,:)
+                  zn_sed_c(:,:)  = za_sed_c(:,:)
+                  za_sed_c(:,:)  = 0.0
+               endif
+               if (jinorgben.eq.1) then
+                  zb_sed_si(:,:) = zn_sed_si(:,:)
+                  zn_sed_si(:,:) = za_sed_si(:,:)
+                  za_sed_si(:,:) = 0.0
+                  !!
+                  zb_sed_ca(:,:) = zn_sed_ca(:,:)
+                  zn_sed_ca(:,:) = za_sed_ca(:,:)
+                  za_sed_ca(:,:) = 0.0
+               endif
+            ELSE
+               if (jorgben.eq.1) then
+                  zb_sed_n(:,:)  = (atfp  *                                 &
+                                    ( zb_sed_n(:,:)  + za_sed_n(:,:)  )) +  &
+                                      (atfp1 * zn_sed_n(:,:) )
+                  zn_sed_n(:,:)  = za_sed_n(:,:)
+                  za_sed_n(:,:)  = 0.0
+                  !!
+                  zb_sed_fe(:,:) = (atfp  *                                 &
+                                    ( zb_sed_fe(:,:) + za_sed_fe(:,:) )) +  &
+                                      (atfp1 * zn_sed_fe(:,:))
+                  zn_sed_fe(:,:) = za_sed_fe(:,:)
+                  za_sed_fe(:,:) = 0.0
+                  !!
+                  zb_sed_c(:,:)  = (atfp  *                                 &
+                                    ( zb_sed_c(:,:)  + za_sed_c(:,:)  )) +  &
+                                      (atfp1 * zn_sed_c(:,:) )
+                  zn_sed_c(:,:)  = za_sed_c(:,:)
+                  za_sed_c(:,:)  = 0.0
+               endif
+               if (jinorgben.eq.1) then
+                  zb_sed_si(:,:) = (atfp  *                                 &
+                                    ( zb_sed_si(:,:) + za_sed_si(:,:) )) +  &
+                                      (atfp1 * zn_sed_si(:,:))
+                  zn_sed_si(:,:) = za_sed_si(:,:)
+                  za_sed_si(:,:) = 0.0
+                  !!
+                  zb_sed_ca(:,:) = (atfp  *                                 &
+                                    ( zb_sed_ca(:,:) + za_sed_ca(:,:) )) +  &
+                                      (atfp1 * zn_sed_ca(:,:))
+                  zn_sed_ca(:,:) = za_sed_ca(:,:)
+                  za_sed_ca(:,:) = 0.0
+               endif
+            ENDIF
+         ELSE                   !  case of smolar scheme or muscl
+            if (jorgben.eq.1) then
+               zb_sed_n(:,:)  = za_sed_n(:,:)
+               zn_sed_n(:,:)  = za_sed_n(:,:)
+               za_sed_n(:,:)  = 0.0
+               !!
+               zb_sed_fe(:,:) = za_sed_fe(:,:)
+               zn_sed_fe(:,:) = za_sed_fe(:,:)
+               za_sed_fe(:,:) = 0.0
+               !!
+               zb_sed_c(:,:)  = za_sed_c(:,:)
+               zn_sed_c(:,:)  = za_sed_c(:,:)
+               za_sed_c(:,:)  = 0.0
+            endif
+            if (jinorgben.eq.1) then
+               zb_sed_si(:,:) = za_sed_si(:,:)
+               zn_sed_si(:,:) = za_sed_si(:,:)
+               za_sed_si(:,:) = 0.0
+               !!
+               zb_sed_ca(:,:) = za_sed_ca(:,:)
+               zn_sed_ca(:,:) = za_sed_ca(:,:)
+               za_sed_ca(:,:) = 0.0
+            endif
+         ENDIF
+      endif
+
+#  if defined key_debug_medusa
+         !! AXY (12/07/17)
+         !!-----------------------------------------------------------------
+         !! Check conservation of MEDUSA's sinks-minus-sources using fflx_X 
+         !! diagnostics (i.e. biogeochemical processes only)
+         !!   - fflx_X diagnostics *should* include all transfers between
+         !!     modelled components
+         !!   - they should also include gains / losses due to air-sea 
+         !!     fluxes of C and O2, aeolian and seafloor inputs of Fe, and 
+         !!     inputs from seafloor "benthic buckets" (N, Si, Fe, C and 
+         !!     alkalinity)
+         !!   - however, they do not include the transfer of material to 
+         !!     "benthic buckets" by sedimenting slow- and fast-sinking
+         !!     detritus since these are separate 2D reservoirs
+         !!   - consequently, for a given water column, the integrated
+         !!     fluxes should sum to the "loss" of material to the "benthic
+         !!     buckets"
+         !!   - if they do not, this suggests that MEDUSA contains errors
+         !!     in its accounting (e.g. processes omitted from calculated
+         !!     fluxes)
+         !!   - here, the local integrated fluxes and benthic inputs (plus
+         !!     air-sea fluxes in the case of C) are reported together with
+         !!     the resulting error
+         !!   - only N, Si, C and alkalinity inventories considered; Fe and
+         !!     O2 overlooked because of wholesale loss (and addition, in 
+         !!     the case of O2) of these tracers within the water column
+         !!-----------------------------------------------------------------
+         !!
+         !! nitrogen
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,1) == 1) then
+                  fq0 = fflx_n(ji,jj)
+                  fq1 = f_sbenin_n(ji,jj) + f_fbenin_n(ji,jj)
+                  fq2 = fq0 + fq1
+                  IF (lwp) write (numout,'(a,2i3,a,3f15.10)')               &
+                     'AXY N   cons: (i,j)=',ji,jj,', (flx,ben,err)=',      &
+                     fq0,fq1,fq2
+               ENDIF
+            ENDDO
+         ENDDO   
+         !! silicon
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,1) == 1) then
+                  fq0 = fflx_si(ji,jj)
+                  fq1 = f_fbenin_si(ji,jj)
+                  fq2 = fq0 + fq1
+                  IF (lwp) write (numout,'(a,2i3,a,3f15.10)')               &
+                     'AXY Si  cons: (i,j)=',ji,jj,', (flx,ben,err)=',     &
+                     fq0,fq1,fq2
+               ENDIF
+            ENDDO
+         ENDDO   
+         !! carbon
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,1) == 1) then
+                  fq0 = fflx_c(ji,jj)
+                  fq1 = f_sbenin_c(ji,jj) + f_fbenin_c(ji,jj) + f_fbenin_ca(ji,jj)
+                  fq2 = f_co2flux(ji,jj) * e3t_n(ji,jj,1)
+                  fq3 = fq0 + fq1
+                  IF (lwp) write (numout,'(a,2i3,a,4f15.10)')               &
+                    'AXY C   cons: (i,j)=',ji,jj,', (flx,ben,asf,err)=',  &
+                    fq0,fq1,fq2,fq3
+               ENDIF
+            ENDDO
+         ENDDO   
+         !! alkalinity
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,1) == 1) then
+                  fq0 = fflx_a(ji,jj)
+                  fq1 = 2.0 * f_fbenin_ca(ji,jj)
+                  fq2 = fq0 + fq1
+                  IF (lwp) write (numout,'(a,2i3,a,3f15.10)')               &
+                     'AXY alk cons: (i,j)=',ji,jj,', (flx,ben,err)=',     &
+                     fq0,fq1,fq2
+               ENDIF
+            ENDDO
+         ENDDO   
+#  endif
+
+         !!!---------------------------------------------------------------
+         !! Add very last diag calculations 
+         !!!---------------------------------------------------------------
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               !!         
+               IF( med_diag%PN_JLIM%dgsave ) THEN
+                  fjln2d(ji,jj) = fjln2d(ji,jj)   / MAX(ftot_pn(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PN_NLIM%dgsave ) THEN
+                  fnln2d(ji,jj) = fnln2d(ji,jj)   / MAX(ftot_pn(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PN_FELIM%dgsave ) THEN
+                  ffln2d(ji,jj) = ffln2d(ji,jj)   / MAX(ftot_pn(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PD_JLIM%dgsave ) THEN
+                  fjld2d(ji,jj) = fjld2d(ji,jj)   / MAX(ftot_pd(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PD_NLIM%dgsave ) THEN
+                  fnld2d(ji,jj) = fnld2d(ji,jj)   / MAX(ftot_pd(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PD_FELIM%dgsave ) THEN
+                  ffld2d(ji,jj) = ffld2d(ji,jj)   / MAX(ftot_pd(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PD_SILIM%dgsave ) THEN
+                  fsld2d2(ji,jj) = fsld2d2(ji,jj) / MAX(ftot_pd(ji,jj), rsmall)
+               ENDIF
+               IF( med_diag%PDSILIM2%dgsave ) THEN
+                  fsld2d(ji,jj) = fsld2d(ji,jj)   / MAX(ftot_pd(ji,jj), rsmall)
+               ENDIF
+            ENDDO
+         ENDDO
+         !!----------------------------------------------------------------
+         !! Add in XML diagnostics stuff
+         !!----------------------------------------------------------------
+         !!
+         !! ** 2D diagnostics
+#   if defined key_debug_medusa
+         IF (lwp) write (numout,*) 'bio_medusa_fin: export all diag kt = ', kt
+         CALL flush(numout)
+#   endif
+         IF ( med_diag%INVTN%dgsave ) THEN
+            CALL iom_put( "INVTN"  , ftot_n )
+         ENDIF
+         IF ( med_diag%INVTSI%dgsave ) THEN
+            CALL iom_put( "INVTSI"  , ftot_si )
+         ENDIF
+         IF ( med_diag%INVTFE%dgsave ) THEN
+            CALL iom_put( "INVTFE"  , ftot_fe )
+         ENDIF                           
+         IF ( med_diag%ML_PRN%dgsave ) THEN
+            CALL iom_put( "ML_PRN"  , fprn_ml )
+         ENDIF
+         IF ( med_diag%ML_PRD%dgsave ) THEN
+            CALL iom_put( "ML_PRD"  , fprd_ml )
+         ENDIF
+         IF ( med_diag%OCAL_LVL%dgsave ) THEN
+            CALL iom_put( "OCAL_LVL"  , fccd )
+         ENDIF
+         IF ( med_diag%PN_JLIM%dgsave ) THEN
+            CALL iom_put( "PN_JLIM"  , fjln2d )
+            DEALLOCATE( fjln2d )
+         ENDIF
+         IF ( med_diag%PN_NLIM%dgsave ) THEN
+            CALL iom_put( "PN_NLIM"  , fnln2d )
+            DEALLOCATE( fnln2d )
+         ENDIF
+         IF ( med_diag%PN_FELIM%dgsave ) THEN
+            CALL iom_put( "PN_FELIM"  , ffln2d )
+            DEALLOCATE( ffln2d )
+         ENDIF
+         IF ( med_diag%PD_JLIM%dgsave ) THEN
+            CALL iom_put( "PD_JLIM"  , fjld2d )
+            DEALLOCATE( fjld2d )
+         ENDIF
+         IF ( med_diag%PD_NLIM%dgsave ) THEN
+            CALL iom_put( "PD_NLIM"  , fnld2d )
+            DEALLOCATE( fnld2d )
+         ENDIF
+         IF ( med_diag%PD_FELIM%dgsave ) THEN
+            CALL iom_put( "PD_FELIM"  , ffld2d )
+            DEALLOCATE( ffld2d )
+         ENDIF
+         IF ( med_diag%PD_SILIM%dgsave ) THEN
+            CALL iom_put( "PD_SILIM"  , fsld2d2 )
+            DEALLOCATE( fsld2d2 )
+         ENDIF
+         IF ( med_diag%PDSILIM2%dgsave ) THEN
+            CALL iom_put( "PDSILIM2"  , fsld2d )
+            DEALLOCATE( fsld2d )
+         ENDIF
+         IF ( med_diag%INTFLX_N%dgsave ) THEN
+            CALL iom_put( "INTFLX_N"  , fflx_n )
+         ENDIF
+         IF ( med_diag%INTFLX_SI%dgsave ) THEN
+            CALL iom_put( "INTFLX_SI"  , fflx_si )
+         ENDIF
+         IF ( med_diag%INTFLX_FE%dgsave ) THEN
+            CALL iom_put( "INTFLX_FE"  , fflx_fe )
+         ENDIF        
+         IF ( med_diag%INT_PN%dgsave ) THEN
+            CALL iom_put( "INT_PN"  , ftot_pn )
+         ENDIF
+         IF ( med_diag%INT_PD%dgsave ) THEN
+            CALL iom_put( "INT_PD"  , ftot_pd )
+         ENDIF         
+         IF ( med_diag%INT_ZMI%dgsave ) THEN
+            CALL iom_put( "INT_ZMI"  , ftot_zmi )
+         ENDIF
+         IF ( med_diag%INT_ZME%dgsave ) THEN
+            CALL iom_put( "INT_ZME"  , ftot_zme )
+         ENDIF
+         IF ( med_diag%INT_DET%dgsave ) THEN
+            CALL iom_put( "INT_DET"  , ftot_det )
+         ENDIF
+         IF ( med_diag%INT_DTC%dgsave ) THEN
+            CALL iom_put( "INT_DTC"  , ftot_dtc )
+         ENDIF
+         IF ( med_diag%BEN_N%dgsave ) THEN
+            CALL iom_put( "BEN_N"  , za_sed_n )
+         ENDIF
+         IF ( med_diag%BEN_FE%dgsave ) THEN
+            CALL iom_put( "BEN_FE"  , za_sed_fe )
+         ENDIF
+         IF ( med_diag%BEN_C%dgsave ) THEN
+            CALL iom_put( "BEN_C"  , za_sed_c )
+         ENDIF
+         IF ( med_diag%BEN_SI%dgsave ) THEN
+            CALL iom_put( "BEN_SI"  , za_sed_si )
+         ENDIF
+         IF ( med_diag%BEN_CA%dgsave ) THEN
+            CALL iom_put( "BEN_CA"  , za_sed_ca )
+         ENDIF
+         IF ( med_diag%RUNOFF%dgsave ) THEN
+            CALL iom_put( "RUNOFF"  , f_runoff )
+         ENDIF 
+# if defined key_roam        
+         IF ( med_diag%N_PROD%dgsave ) THEN
+            CALL iom_put( "N_PROD"  , fnit_prod )
+         ENDIF
+         IF ( med_diag%N_CONS%dgsave ) THEN
+            CALL iom_put( "N_CONS"  , fnit_cons )
+         ENDIF
+         IF ( med_diag%C_PROD%dgsave ) THEN
+            CALL iom_put( "C_PROD"  , fcar_prod )
+         ENDIF
+         IF ( med_diag%C_CONS%dgsave ) THEN
+            CALL iom_put( "C_CONS"  , fcar_cons )
+         ENDIF
+         IF ( med_diag%O2_PROD%dgsave ) THEN
+            CALL iom_put( "O2_PROD"  , foxy_prod )
+         ENDIF
+         IF ( med_diag%O2_CONS%dgsave ) THEN
+            CALL iom_put( "O2_CONS"  , foxy_cons )
+         ENDIF
+         IF ( med_diag%O2_ANOX%dgsave ) THEN
+            CALL iom_put( "O2_ANOX"  , foxy_anox )
+         ENDIF
+         IF ( med_diag%INVTC%dgsave ) THEN
+            CALL iom_put( "INVTC"  , ftot_c )
+         ENDIF
+         IF ( med_diag%INVTALK%dgsave ) THEN
+            CALL iom_put( "INVTALK"  , ftot_a )
+         ENDIF
+         IF ( med_diag%INVTO2%dgsave ) THEN
+            CALL iom_put( "INVTO2"  , ftot_o2 )
+         ENDIF
+         IF ( med_diag%COM_RESP%dgsave ) THEN
+            CALL iom_put( "COM_RESP"  , fcomm_resp )
+         ENDIF         
+# endif      
+         !!
+         !! diagnostic filled in the i-j-k main loop
+         !!--------------------------------------------
+         IF ( med_diag%PRN%dgsave ) THEN
+            CALL iom_put( "PRN"  , fprn2d )
+            DEALLOCATE( fprn2d )
+         ENDIF
+         IF ( med_diag%MPN%dgsave ) THEN
+            CALL iom_put( "MPN"  ,fdpn2d )
+            DEALLOCATE( fdpn2d )
+         ENDIF
+         IF ( med_diag%PRD%dgsave ) THEN
+            CALL iom_put( "PRD"  ,fprd2d )
+            DEALLOCATE( fprd2d )
+         ENDIF
+         IF( med_diag%MPD%dgsave ) THEN
+            CALL iom_put( "MPD"  , fdpd2d )
+            DEALLOCATE( fdpd2d )
+         ENDIF
+         !  IF( med_diag%DSED%dgsave ) THEN
+         !      CALL iom_put( "DSED"  , ftot_n )
+         !  ENDIF
+         IF( med_diag%OPAL%dgsave ) THEN
+            CALL iom_put( "OPAL"  , fprds2d )
+            DEALLOCATE( fprds2d )
+         ENDIF
+         IF( med_diag%OPALDISS%dgsave ) THEN
+            CALL iom_put( "OPALDISS"  , fsdiss2d )
+            DEALLOCATE( fsdiss2d )
+         ENDIF
+         IF( med_diag%GMIPn%dgsave ) THEN
+            CALL iom_put( "GMIPn"  , fgmipn2d )
+            DEALLOCATE( fgmipn2d )
+         ENDIF
+         IF( med_diag%GMID%dgsave ) THEN
+            CALL iom_put( "GMID"  , fgmid2d )
+            DEALLOCATE( fgmid2d )
+         ENDIF
+         IF( med_diag%MZMI%dgsave ) THEN
+            CALL iom_put( "MZMI"  , fdzmi2d )
+            DEALLOCATE( fdzmi2d )
+         ENDIF
+         IF( med_diag%GMEPN%dgsave ) THEN
+            CALL iom_put( "GMEPN"  , fgmepn2d )
+            DEALLOCATE( fgmepn2d )
+         ENDIF
+         IF( med_diag%GMEPD%dgsave ) THEN
+            CALL iom_put( "GMEPD"  , fgmepd2d )
+            DEALLOCATE( fgmepd2d )
+         ENDIF
+         IF( med_diag%GMEZMI%dgsave ) THEN
+            CALL iom_put( "GMEZMI"  , fgmezmi2d )
+            DEALLOCATE( fgmezmi2d )
+         ENDIF
+         IF( med_diag%GMED%dgsave ) THEN
+            CALL iom_put( "GMED"  , fgmed2d )
+            DEALLOCATE( fgmed2d )
+         ENDIF
+         IF( med_diag%MZME%dgsave ) THEN
+            CALL iom_put( "MZME"  , fdzme2d )
+            DEALLOCATE( fdzme2d )
+         ENDIF
+         !  IF( med_diag%DEXP%dgsave ) THEN
+         !      CALL iom_put( "DEXP"  , ftot_n )
+         !  ENDIF
+         IF( med_diag%DETN%dgsave ) THEN
+            CALL iom_put( "DETN"  , fslown2d )
+            DEALLOCATE( fslown2d )
+         ENDIF
+         IF( med_diag%MDET%dgsave ) THEN
+            CALL iom_put( "MDET"  , fdd2d )
+            DEALLOCATE( fdd2d )
+         ENDIF
+         IF( med_diag%AEOLIAN%dgsave ) THEN
+            CALL iom_put( "AEOLIAN"  , ffetop2d )
+            DEALLOCATE( ffetop2d )
+         ENDIF
+         IF( med_diag%BENTHIC%dgsave ) THEN
+            CALL iom_put( "BENTHIC"  , ffebot2d )
+            DEALLOCATE( ffebot2d )
+         ENDIF
+         IF( med_diag%SCAVENGE%dgsave ) THEN
+            CALL iom_put( "SCAVENGE"  , ffescav2d )
+            DEALLOCATE( ffescav2d )
+         ENDIF
+         !! 
+         IF( med_diag%TOTREG_N%dgsave ) THEN
+            CALL iom_put( "TOTREG_N"  , fregen2d )
+            DEALLOCATE( fregen2d )
+         ENDIF
+         IF( med_diag%TOTRG_SI%dgsave ) THEN
+            CALL iom_put( "TOTRG_SI"  , fregensi2d )
+            DEALLOCATE( fregensi2d )
+         ENDIF
+         !! 
+         IF( med_diag%FASTN%dgsave ) THEN
+            CALL iom_put( "FASTN"  , ftempn2d )
+            DEALLOCATE( ftempn2d )
+         ENDIF
+         IF( med_diag%FASTSI%dgsave ) THEN
+            CALL iom_put( "FASTSI"  , ftempsi2d )
+            DEALLOCATE( ftempsi2d )
+         ENDIF
+         IF( med_diag%FASTFE%dgsave ) THEN
+            CALL iom_put( "FASTFE"  , ftempfe2d )
+            DEALLOCATE( ftempfe2d )
+         ENDIF
+         IF( med_diag%FASTC%dgsave ) THEN
+            CALL iom_put( "FASTC"  , ftempc2d )
+            DEALLOCATE( ftempc2d )
+         ENDIF
+         IF( med_diag%FASTCA%dgsave ) THEN
+            CALL iom_put( "FASTCA"  , ftempca2d )
+            DEALLOCATE( ftempca2d )
+         ENDIF
+         !! 
+         IF( med_diag%REMINN%dgsave ) THEN
+            CALL iom_put( "REMINN"  , freminn2d )
+            DEALLOCATE( freminn2d )
+         ENDIF
+         IF( med_diag%REMINSI%dgsave ) THEN
+            CALL iom_put( "REMINSI"  , freminsi2d )
+            DEALLOCATE( freminsi2d )
+         ENDIF
+         IF( med_diag%REMINFE%dgsave ) THEN
+            CALL iom_put( "REMINFE"  , freminfe2d )
+            DEALLOCATE( freminfe2d )
+         ENDIF
+         IF( med_diag%REMINC%dgsave ) THEN
+            CALL iom_put( "REMINC"  , freminc2d )
+            DEALLOCATE( freminc2d )
+         ENDIF
+         IF( med_diag%REMINCA%dgsave ) THEN
+            CALL iom_put( "REMINCA"  , freminca2d )
+            DEALLOCATE( freminca2d )
+         ENDIF
+         IF( med_diag%SEAFLRN%dgsave ) THEN
+            CALL iom_put( "SEAFLRN"  , fsedn )
+         ENDIF
+         IF( med_diag%SEAFLRSI%dgsave ) THEN
+            CALL iom_put( "SEAFLRSI"  , fsedsi )
+         ENDIF
+         IF( med_diag%SEAFLRFE%dgsave ) THEN
+            CALL iom_put( "SEAFLRFE"  , fsedfe )
+         ENDIF
+         IF( med_diag%SEAFLRC%dgsave ) THEN
+            CALL iom_put( "SEAFLRC"  , fsedc )
+         ENDIF
+         IF( med_diag%SEAFLRCA%dgsave ) THEN
+            CALL iom_put( "SEAFLRCA"  , fsedca )
+         ENDIF
+         !!
+# if defined key_roam            
+         !!
+         IF( med_diag%RIV_N%dgsave ) THEN
+            CALL iom_put( "RIV_N"  , rivn2d )
+            DEALLOCATE( rivn2d )
+         ENDIF
+         IF( med_diag%RIV_SI%dgsave ) THEN
+            CALL iom_put( "RIV_SI"  , rivsi2d )
+            DEALLOCATE( rivsi2d )
+         ENDIF
+         IF( med_diag%RIV_C%dgsave ) THEN
+            CALL iom_put( "RIV_C"  , rivc2d )
+            DEALLOCATE( rivc2d )
+         ENDIF
+         IF( med_diag%RIV_ALK%dgsave ) THEN
+            CALL iom_put( "RIV_ALK"  , rivalk2d )
+            DEALLOCATE( rivalk2d )
+         ENDIF
+         IF( med_diag%DETC%dgsave ) THEN
+            CALL iom_put( "DETC"  , fslowc2d )
+            DEALLOCATE( fslowc2d )
+         ENDIF
+         !!
+         IF( med_diag%PN_LLOSS%dgsave ) THEN
+            CALL iom_put( "PN_LLOSS"  , fdpn22d )
+            DEALLOCATE( fdpn22d )
+         ENDIF
+         IF( med_diag%PD_LLOSS%dgsave ) THEN
+            CALL iom_put( "PD_LLOSS"  , fdpd22d )
+            DEALLOCATE( fdpd22d )
+         ENDIF
+         IF( med_diag%ZI_LLOSS%dgsave ) THEN
+            CALL iom_put( "ZI_LLOSS"  , fdzmi22d )
+             DEALLOCATE( fdzmi22d )
+          ENDIF
+          IF( med_diag%ZE_LLOSS%dgsave ) THEN
+             CALL iom_put( "ZE_LLOSS"  , fdzme22d )
+             DEALLOCATE( fdzme22d )
+          ENDIF
+          IF( med_diag%ZI_MES_N%dgsave ) THEN
+             CALL iom_put( "ZI_MES_N"  , zimesn2d )
+             DEALLOCATE( zimesn2d )
+          ENDIF
+          IF( med_diag%ZI_MES_D%dgsave ) THEN
+             CALL iom_put( "ZI_MES_D"  , zimesd2d )
+             DEALLOCATE( zimesd2d )
+          ENDIF
+          IF( med_diag%ZI_MES_C%dgsave ) THEN
+             CALL iom_put( "ZI_MES_C"  , zimesc2d )
+             DEALLOCATE( zimesc2d )
+          ENDIF
+          IF( med_diag%ZI_MESDC%dgsave ) THEN
+             CALL iom_put( "ZI_MESDC"  ,zimesdc2d )
+             DEALLOCATE( zimesdc2d )
+          ENDIF
+          IF( med_diag%ZI_EXCR%dgsave ) THEN
+             CALL iom_put( "ZI_EXCR"  , ziexcr2d )
+             DEALLOCATE( ziexcr2d )
+          ENDIF
+          IF( med_diag%ZI_RESP%dgsave ) THEN
+             CALL iom_put( "ZI_RESP"  , ziresp2d )
+             DEALLOCATE( ziresp2d )
+          ENDIF
+          IF( med_diag%ZI_GROW%dgsave ) THEN
+             CALL iom_put( "ZI_GROW"  , zigrow2d )
+             DEALLOCATE( zigrow2d )
+          ENDIF
+          IF( med_diag%ZE_MES_N%dgsave ) THEN
+             CALL iom_put( "ZE_MES_N"  , zemesn2d )
+             DEALLOCATE( zemesn2d )
+          ENDIF
+          IF( med_diag%ZE_MES_D%dgsave ) THEN
+             CALL iom_put( "ZE_MES_D"  , zemesd2d )
+             DEALLOCATE( zemesd2d )
+          ENDIF
+          IF( med_diag%ZE_MES_C%dgsave ) THEN
+             CALL iom_put( "ZE_MES_C"  , zemesc2d )
+             DEALLOCATE( zemesc2d )
+          ENDIF
+          IF( med_diag%ZE_MESDC%dgsave ) THEN
+             CALL iom_put( "ZE_MESDC"  , zemesdc2d )
+             DEALLOCATE( zemesdc2d )
+          ENDIF
+          IF( med_diag%ZE_EXCR%dgsave ) THEN
+             CALL iom_put( "ZE_EXCR"  , zeexcr2d )
+             DEALLOCATE( zeexcr2d )
+          ENDIF
+          IF( med_diag%ZE_RESP%dgsave ) THEN
+             CALL iom_put( "ZE_RESP"  , zeresp2d )
+             DEALLOCATE( zeresp2d )
+          ENDIF
+          IF( med_diag%ZE_GROW%dgsave ) THEN
+             CALL iom_put( "ZE_GROW"  , zegrow2d )
+             DEALLOCATE( zegrow2d )
+          ENDIF
+          IF( med_diag%MDETC%dgsave ) THEN
+             CALL iom_put( "MDETC"  , mdetc2d )
+             DEALLOCATE( mdetc2d )
+          ENDIF
+          IF( med_diag%GMIDC%dgsave ) THEN
+             CALL iom_put( "GMIDC"  , gmidc2d )
+             DEALLOCATE( gmidc2d )
+          ENDIF
+          IF( med_diag%GMEDC%dgsave ) THEN
+             CALL iom_put( "GMEDC"  , gmedc2d )
+             DEALLOCATE( gmedc2d )
+          ENDIF
+          IF( med_diag%IBEN_N%dgsave ) THEN
+             CALL iom_put( "IBEN_N"  , iben_n2d )
+             DEALLOCATE( iben_n2d )
+          ENDIF
+          IF( med_diag%IBEN_FE%dgsave ) THEN
+             CALL iom_put( "IBEN_FE"  , iben_fe2d )
+             DEALLOCATE( iben_fe2d )
+          ENDIF
+          IF( med_diag%IBEN_C%dgsave ) THEN
+             CALL iom_put( "IBEN_C"  , iben_c2d )
+             DEALLOCATE( iben_c2d )
+          ENDIF
+          IF( med_diag%IBEN_SI%dgsave ) THEN
+             CALL iom_put( "IBEN_SI"  , iben_si2d )
+             DEALLOCATE( iben_si2d )
+          ENDIF
+          IF( med_diag%IBEN_CA%dgsave ) THEN
+             CALL iom_put( "IBEN_CA"  , iben_ca2d )
+             DEALLOCATE( iben_ca2d )
+          ENDIF
+          IF( med_diag%OBEN_N%dgsave ) THEN
+             CALL iom_put( "OBEN_N"  , oben_n2d )
+             DEALLOCATE( oben_n2d )
+          ENDIF
+          IF( med_diag%OBEN_FE%dgsave ) THEN
+             CALL iom_put( "OBEN_FE"  , oben_fe2d )
+             DEALLOCATE( oben_fe2d )
+          ENDIF
+          IF( med_diag%OBEN_C%dgsave ) THEN
+             CALL iom_put( "OBEN_C"  , oben_c2d )
+             DEALLOCATE( oben_c2d )
+          ENDIF
+          IF( med_diag%OBEN_SI%dgsave ) THEN
+             CALL iom_put( "OBEN_SI"  , oben_si2d )
+             DEALLOCATE( oben_si2d )
+          ENDIF
+          IF( med_diag%OBEN_CA%dgsave ) THEN
+             CALL iom_put( "OBEN_CA"  , oben_ca2d )
+             DEALLOCATE( oben_ca2d )
+          ENDIF
+          IF( med_diag%SFR_OCAL%dgsave ) THEN
+             CALL iom_put( "SFR_OCAL"  , sfr_ocal2d )
+             DEALLOCATE( sfr_ocal2d )
+          ENDIF
+          IF( med_diag%SFR_OARG%dgsave ) THEN
+             CALL iom_put( "SFR_OARG"  , sfr_oarg2d )
+             DEALLOCATE( sfr_oarg2d )
+          ENDIF
+          IF( med_diag%LYSO_CA%dgsave ) THEN
+             CALL iom_put( "LYSO_CA"  , lyso_ca2d )
+             DEALLOCATE( lyso_ca2d )
+          ENDIF
+# endif                   
+          !!
+          !! ** 3D diagnostics
+          IF( med_diag%TPP3%dgsave ) THEN
+             CALL iom_put( "TPP3"  , tpp3d )
+             DEALLOCATE( tpp3d )
+          ENDIF
+          IF( med_diag%DETFLUX3%dgsave ) THEN
+             CALL iom_put( "DETFLUX3"  , detflux3d )
+             DEALLOCATE( detflux3d )
+          ENDIF
+          IF( med_diag%REMIN3N%dgsave ) THEN
+             CALL iom_put( "REMIN3N"  , remin3dn )
+             DEALLOCATE( remin3dn )
+          ENDIF
+# if defined key_roam          
+          IF( med_diag%PH3%dgsave ) THEN
+             CALL iom_put( "PH3"  , f3_pH )
+          ENDIF
+          IF( med_diag%OM_CAL3%dgsave ) THEN
+             CALL iom_put( "OM_CAL3"  , f3_omcal )
+          ENDIF
+          !!
+          !! AXY (09/11/16): 2D CMIP6 diagnostics
+          IF( med_diag%INTDISSIC%dgsave ) THEN
+             CALL iom_put( "INTDISSIC"  , intdissic )
+             DEALLOCATE( intdissic )
+          ENDIF          
+          IF( med_diag%INTDISSIN%dgsave ) THEN
+             CALL iom_put( "INTDISSIN"  , intdissin )
+             DEALLOCATE( intdissin )
+          ENDIF          
+          IF( med_diag%INTDISSISI%dgsave ) THEN
+             CALL iom_put( "INTDISSISI"  , intdissisi )
+             DEALLOCATE( intdissisi )
+          ENDIF          
+          IF( med_diag%INTTALK%dgsave ) THEN
+             CALL iom_put( "INTTALK"  , inttalk )
+             DEALLOCATE( inttalk )
+          ENDIF          
+          IF( med_diag%O2min%dgsave ) THEN
+             CALL iom_put( "O2min"  , o2min )
+             DEALLOCATE( o2min )
+          ENDIF          
+          IF( med_diag%ZO2min%dgsave ) THEN
+             CALL iom_put( "ZO2min"  , zo2min )
+             DEALLOCATE( zo2min )
+          ENDIF          
+          IF( med_diag%FBDDTALK%dgsave ) THEN
+             CALL iom_put( "FBDDTALK"  , fbddtalk )
+             DEALLOCATE( fbddtalk )
+          ENDIF          
+          IF( med_diag%FBDDTDIC%dgsave ) THEN
+             CALL iom_put( "FBDDTDIC"  , fbddtdic )
+             DEALLOCATE( fbddtdic )
+          ENDIF          
+          IF( med_diag%FBDDTDIFE%dgsave ) THEN
+             CALL iom_put( "FBDDTDIFE" , fbddtdife )
+             DEALLOCATE( fbddtdife )
+          ENDIF          
+          IF( med_diag%FBDDTDIN%dgsave ) THEN
+             CALL iom_put( "FBDDTDIN"  , fbddtdin )
+             DEALLOCATE( fbddtdin )
+          ENDIF          
+          IF( med_diag%FBDDTDISI%dgsave ) THEN
+             CALL iom_put( "FBDDTDISI" , fbddtdisi )
+             DEALLOCATE( fbddtdisi )
+          ENDIF    
+          !!
+          !! AXY (09/11/16): 3D CMIP6 diagnostics
+          IF( med_diag%TPPD3%dgsave ) THEN
+             CALL iom_put( "TPPD3"     , tppd3 )
+             DEALLOCATE( tppd3 )
+          ENDIF          
+          IF( med_diag%BDDTALK3%dgsave ) THEN
+             CALL iom_put( "BDDTALK3"  , bddtalk3 )
+             DEALLOCATE( bddtalk3 )
+          ENDIF          
+          IF( med_diag%BDDTDIC3%dgsave ) THEN
+             CALL iom_put( "BDDTDIC3"  , bddtdic3 )
+             DEALLOCATE( bddtdic3 )
+          ENDIF          
+          IF( med_diag%BDDTDIFE3%dgsave ) THEN
+             CALL iom_put( "BDDTDIFE3" , bddtdife3 )
+             DEALLOCATE( bddtdife3 )
+          ENDIF          
+          IF( med_diag%BDDTDIN3%dgsave ) THEN
+             CALL iom_put( "BDDTDIN3"  , bddtdin3 )
+             DEALLOCATE( bddtdin3 )
+          ENDIF          
+          IF( med_diag%BDDTDISI3%dgsave ) THEN
+             CALL iom_put( "BDDTDISI3" , bddtdisi3 )
+             DEALLOCATE( bddtdisi3 )
+          ENDIF    
+          IF( med_diag%FD_NIT3%dgsave ) THEN
+             CALL iom_put( "FD_NIT3"  , fd_nit3 )
+             DEALLOCATE( fd_nit3 )
+          ENDIF
+          IF( med_diag%FD_SIL3%dgsave ) THEN
+             CALL iom_put( "FD_SIL3"  , fd_sil3 )
+             DEALLOCATE( fd_sil3 )
+          ENDIF
+          IF( med_diag%FD_CAL3%dgsave ) THEN
+             CALL iom_put( "FD_CAL3"  , fd_cal3 )
+             DEALLOCATE( fd_cal3 )
+          ENDIF
+          IF( med_diag%FD_CAR3%dgsave ) THEN
+             CALL iom_put( "FD_CAR3"  , fd_car3 )
+             DEALLOCATE( fd_car3 )
+          ENDIF
+          IF( med_diag%CO33%dgsave ) THEN
+             CALL iom_put( "CO33"  , f3_co3 )
+          ENDIF          	        
+          IF( med_diag%CO3SATARAG3%dgsave ) THEN
+             CALL iom_put( "CO3SATARAG3"  , f3_omarg )
+          ENDIF          	        
+          IF( med_diag%CO3SATCALC3%dgsave ) THEN
+             CALL iom_put( "CO3SATCALC3"  , f3_omcal )
+          ENDIF          	        
+          IF( med_diag%EXPC3%dgsave ) THEN
+             CALL iom_put( "EXPC3"  , expc3 )
+             DEALLOCATE( expc3 )
+          ENDIF          	        
+          IF( med_diag%EXPN3%dgsave ) THEN
+             CALL iom_put( "EXPN3"  , expn3 )
+             DEALLOCATE( expn3 )
+          ENDIF          	        
+          IF( med_diag%DCALC3%dgsave ) THEN
+             CALL iom_put( "DCALC3"  , dcalc3 )
+             DEALLOCATE( dcalc3 )
+          ENDIF          	        
+          IF( med_diag%FEDISS3%dgsave ) THEN
+             CALL iom_put( "FEDISS3"  , fediss3 )
+             DEALLOCATE( fediss3 )
+          ENDIF          	        
+          IF( med_diag%FESCAV3%dgsave ) THEN
+             CALL iom_put( "FESCAV3"  , fescav3 )
+             DEALLOCATE( fescav3 )
+          ENDIF          	        
+          IF( med_diag%MIGRAZP3%dgsave ) THEN
+             CALL iom_put( "MIGRAZP3"  , migrazp3 )
+             DEALLOCATE( migrazp3 )
+          ENDIF          	        
+          IF( med_diag%MIGRAZD3%dgsave ) THEN
+             CALL iom_put( "MIGRAZD3"  , migrazd3 )
+             DEALLOCATE( migrazd3 )
+          ENDIF          	        
+          IF( med_diag%MEGRAZP3%dgsave ) THEN
+             CALL iom_put( "MEGRAZP3"  , megrazp3 )
+             DEALLOCATE( megrazp3 )
+          ENDIF          	        
+          IF( med_diag%MEGRAZD3%dgsave ) THEN
+             CALL iom_put( "MEGRAZD3"  , megrazd3 )
+             DEALLOCATE( megrazd3 )
+          ENDIF          	        
+          IF( med_diag%MEGRAZZ3%dgsave ) THEN
+             CALL iom_put( "MEGRAZZ3"  , megrazz3 )
+             DEALLOCATE( megrazz3 )
+          ENDIF          	        
+          IF( med_diag%O2SAT3%dgsave ) THEN
+             CALL iom_put( "O2SAT3"  , o2sat3 )
+             DEALLOCATE( o2sat3 )
+          ENDIF          	        
+          IF( med_diag%PBSI3%dgsave ) THEN
+             CALL iom_put( "PBSI3"  , pbsi3 )
+             DEALLOCATE( pbsi3 )
+          ENDIF          	        
+          IF( med_diag%PCAL3%dgsave ) THEN
+             CALL iom_put( "PCAL3"  , pcal3 )
+             DEALLOCATE( pcal3 )
+          ENDIF          	        
+          IF( med_diag%REMOC3%dgsave ) THEN
+             CALL iom_put( "REMOC3"  , remoc3 )
+             DEALLOCATE( remoc3 )
+          ENDIF          	        
+          IF( med_diag%PNLIMJ3%dgsave ) THEN
+             CALL iom_put( "PNLIMJ3" , pnlimj3 )
+             DEALLOCATE( pnlimj3 )
+          ENDIF          	        
+          IF( med_diag%PNLIMN3%dgsave ) THEN
+             CALL iom_put( "PNLIMN3" , pnlimn3 )
+             DEALLOCATE( pnlimn3 )
+          ENDIF          	        
+          IF( med_diag%PNLIMFE3%dgsave ) THEN
+             CALL iom_put( "PNLIMFE3" , pnlimfe3 )
+             DEALLOCATE( pnlimfe3 )
+          ENDIF          	        
+          IF( med_diag%PDLIMJ3%dgsave ) THEN
+             CALL iom_put( "PDLIMJ3" , pdlimj3 )
+             DEALLOCATE( pdlimj3 )
+          ENDIF          	        
+          IF( med_diag%PDLIMN3%dgsave ) THEN
+             CALL iom_put( "PDLIMN3" , pdlimn3 )
+             DEALLOCATE( pdlimn3 )
+          ENDIF          	        
+          IF( med_diag%PDLIMFE3%dgsave ) THEN
+             CALL iom_put( "PDLIMFE3" , pdlimfe3 )
+             DEALLOCATE( pdlimfe3 )
+          ENDIF          	        
+          IF( med_diag%PDLIMSI3%dgsave ) THEN
+             CALL iom_put( "PDLIMSI3" , pdlimsi3 )
+             DEALLOCATE( pdlimsi3 )
+          ENDIF          	        
+          
+# endif         
+
+          DEALLOCATE( zw2d )
+
+   END SUBROUTINE bio_medusa_fin
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE bio_medusa_fin( )                    ! Empty routine
+      WRITE(*,*) 'bio_medusa_fin: You should not have seen this print! error?'
+   END SUBROUTINE bio_medusa_fin
+#endif 
+
+   !!======================================================================
+END MODULE bio_medusa_fin_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_init.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_init.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_init.F90	(revision 9987)
@@ -0,0 +1,843 @@
+MODULE bio_medusa_init_mod
+   !!======================================================================
+   !!                         ***  MODULE bio_medusa_init  ***
+   !! Initialisation for TRC_BIO_MEDUSA
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   bio_medusa_init    ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE bio_medusa_init( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE bio_medusa_init  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - zeroes arrays used in TRC_BIO_MEDUSA
+      !!  - sets up the arrays needed for the diagnostics
+      !!---------------------------------------------------------------------- 
+      USE bio_medusa_mod
+      USE par_oce,           ONLY: jpi, jpj, jpk
+      USE sms_medusa,        ONLY: jdms
+      USE trc,               ONLY: ln_diatrc, med_diag, nittrc000 
+      USE in_out_manager,    ONLY: lwp
+
+# if defined key_iomput
+      USE iom,               ONLY: lk_iomput, numout
+      USE trcnam_medusa,     ONLY: trc_nam_iom_medusa
+# endif
+
+      !! time (integer timestep)
+      INTEGER, INTENT( in ) ::    kt
+
+      IF( ln_diatrc ) THEN
+         IF (lwp) write (numout,*) 'Diagnostics are now ALL through XIOS (key_xios)'
+         IF (lwp) write (numout,*) 'No more key_diatrc anymore.'
+      ENDIF
+
+      !!----------------------------------------------------------------------
+      !! Zero fast-sinking detritus 2D fields
+      !!----------------------------------------------------------------------
+      !!
+      ffastn(:,:)  = 0.0        !! organic nitrogen
+      ffastsi(:,:) = 0.0        !! biogenic silicon
+      ffastfe(:,:) = 0.0        !! organic iron
+      ffastc(:,:)  = 0.0        !! organic carbon
+      ffastca(:,:) = 0.0        !! biogenic calcium carbonate
+      !!
+      fsedn(:,:)   = 0.0        !! Seafloor flux of N 
+      fsedsi(:,:)  = 0.0        !! Seafloor flux of Si
+      fsedfe(:,:)  = 0.0        !! Seafloor flux of Fe
+      fsedc(:,:)   = 0.0        !! Seafloor flux of C
+      fsedca(:,:)  = 0.0        !! Seafloor flux of CaCO3
+      !!
+      fregenfast(:,:)   = 0.0   !! integrated  N regeneration (fast detritus)
+      fregenfastsi(:,:) = 0.0   !! integrated Si regeneration (fast detritus)
+# if defined key_roam
+      fregenfastc(:,:)  = 0.0   !! integrated  C regeneration (fast detritus)
+# endif
+      !!
+      fccd(:,:)    = 0.0        !! last depth level before CCD
+
+      !!----------------------------------------------------------------------
+      !! blank nutrient/flux inventories
+      !!----------------------------------------------------------------------
+      !!
+      fflx_n(:,:)  = 0.0        !! nitrogen flux total
+      fflx_si(:,:) = 0.0        !! silicon  flux total
+      fflx_fe(:,:) = 0.0        !! iron     flux total
+      fifd_n(:,:)  = 0.0        !! nitrogen fast detritus production
+      fifd_si(:,:) = 0.0        !! silicon  fast detritus production
+      fifd_fe(:,:) = 0.0        !! iron     fast detritus production
+      fofd_n(:,:)  = 0.0        !! nitrogen fast detritus remineralisation
+      fofd_si(:,:) = 0.0        !! silicon  fast detritus remineralisation
+      fofd_fe(:,:) = 0.0        !! iron     fast detritus remineralisation
+# if defined key_roam
+      fflx_c(:,:)  = 0.0        !! carbon     flux total
+      fflx_a(:,:)  = 0.0        !! alkalinity flux total
+      fflx_o2(:,:) = 0.0        !! oxygen     flux total
+      ftot_c(:,:)  = 0.0        !! carbon     inventory
+      ftot_a(:,:)  = 0.0        !! alkalinity inventory
+      ftot_o2(:,:) = 0.0        !! oxygen     inventory
+      fifd_c(:,:)  = 0.0        !! carbon     fast detritus production
+! I don't think fifd_a or fifd_o2 are used - marc 11/5/17
+!      fifd_a(:,:)  = 0.0        !! alkalinity fast detritus production
+!      fifd_o2(:,:) = 0.0        !! oxygen     fast detritus production
+      fofd_c(:,:)  = 0.0        !! carbon     fast detritus remineralisation
+! I don't think fofd_a or fofd_o2 are used - marc 11/5/17
+!      fofd_a(:,:)  = 0.0        !! alkalinity fast detritus remineralisation
+!      fofd_o2(:,:) = 0.0        !! oxygen     fast detritus remineralisation
+      !!
+      fnit_prod(:,:) = 0.0      !! (organic)   nitrogen production
+      fnit_cons(:,:) = 0.0      !! (organic)   nitrogen consumption
+      fsil_prod(:,:) = 0.0      !! (inorganic) silicon production
+      fsil_cons(:,:) = 0.0      !! (inorganic) silicon consumption
+      fcar_prod(:,:) = 0.0      !! (organic)   carbon production
+      fcar_cons(:,:) = 0.0      !! (organic)   carbon consumption
+      !!
+      foxy_prod(:,:) = 0.0      !! oxygen production
+      foxy_cons(:,:) = 0.0      !! oxygen consumption
+      foxy_anox(:,:) = 0.0      !! unrealised oxygen consumption
+      !!
+# endif
+      ftot_n(:,:)   = 0.0       !! N inventory 
+      ftot_si(:,:)  = 0.0       !! Si inventory
+      ftot_fe(:,:)  = 0.0       !! Fe inventory
+      ftot_pn(:,:)  = 0.0       !! integrated non-diatom phytoplankton
+      ftot_pd(:,:)  = 0.0       !! integrated diatom     phytoplankton
+      ftot_zmi(:,:) = 0.0       !! integrated microzooplankton
+      ftot_zme(:,:) = 0.0       !! integrated mesozooplankton
+      ftot_det(:,:) = 0.0       !! integrated slow detritus, nitrogen
+      ftot_dtc(:,:) = 0.0       !! integrated slow detritus, carbon
+      !!
+      fzmi_i(:,:)  = 0.0        !! material grazed by microzooplankton
+      fzmi_o(:,:)  = 0.0        !! ... sum of fate of this material
+      fzme_i(:,:)  = 0.0        !! material grazed by  mesozooplankton
+      fzme_o(:,:)  = 0.0        !! ... sum of fate of this material
+      !!
+      f_sbenin_n(:,:)  = 0.0    !! slow detritus N  -> benthic pool
+      f_sbenin_fe(:,:) = 0.0    !! slow detritus Fe -> benthic pool
+      f_sbenin_c(:,:)  = 0.0    !! slow detritus C  -> benthic pool
+      f_fbenin_n(:,:)  = 0.0    !! fast detritus N  -> benthic pool
+      f_fbenin_fe(:,:) = 0.0    !! fast detritus Fe -> benthic pool
+      f_fbenin_si(:,:) = 0.0    !! fast detritus Si -> benthic pool
+      f_fbenin_c(:,:)  = 0.0    !! fast detritus C  -> benthic pool
+      f_fbenin_ca(:,:) = 0.0    !! fast detritus Ca -> benthic pool
+      !!
+      f_benout_n(:,:)  = 0.0    !! benthic N  pool  -> dissolved
+      f_benout_fe(:,:) = 0.0    !! benthic Fe pool  -> dissolved
+      f_benout_si(:,:) = 0.0    !! benthic Si pool  -> dissolved
+      f_benout_c(:,:)  = 0.0    !! benthic C  pool  -> dissolved
+      f_benout_ca(:,:) = 0.0    !! benthic Ca pool  -> dissolved
+      !!
+      f_benout_lyso_ca(:,:) = 0.0 !! benthic Ca pool  -> dissolved (when it shouldn't!)
+      !!
+      f_runoff(:,:)  = 0.0      !! riverine runoff
+      f_riv_n(:,:)   = 0.0      !! riverine N   input 
+      f_riv_si(:,:)  = 0.0      !! riverine Si  input 
+      f_riv_c(:,:)   = 0.0      !! riverine C   input 
+      f_riv_alk(:,:) = 0.0      !! riverine alk input 
+      !! 
+      !! Jpalm -- 06-03-2017 -- Forgotten var to init
+      f_omarg(:,:) = 0.0        !!
+      f_omcal(:,:) = 0.0 
+      xFree(:,:) = 0.0          !! state variables for iron-ligand system
+      fcomm_resp(:,:) = 0.0 
+      fprn_ml(:,:) = 0.0        !! mixed layer PP diagnostics
+      fprd_ml(:,:) = 0.0        !! mixed layer PP diagnostics
+      !! 
+      fslownflux(:,:) = 0.0 
+      fslowcflux(:,:) = 0.0 
+      !!
+      !! allocate and initiate 2D diag
+      !! -----------------------------
+      !! Juju :: add kt condition !!
+      IF ( lk_iomput ) THEN 
+
+         !! initialise iom_use test
+         IF ( kt == nittrc000 )   CALL trc_nam_iom_medusa 
+
+         ALLOCATE( zw2d(1:jpi, 1:jpj) )
+         zw2d(:,:)      = 0.0   !!
+         IF ( med_diag%PRN%dgsave ) THEN
+            ALLOCATE( fprn2d(1:jpi, 1:jpj) )
+            fprn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF ( med_diag%MPN%dgsave ) THEN
+            ALLOCATE( fdpn2d(1:jpi, 1:jpj) )
+            fdpn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF ( med_diag%PRD%dgsave ) THEN
+            ALLOCATE( fprd2d(1:jpi, 1:jpj) )
+            fprd2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%MPD%dgsave ) THEN
+            ALLOCATE( fdpd2d(1:jpi, 1:jpj) )
+            fdpd2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OPAL%dgsave ) THEN
+            ALLOCATE( fprds2d(1:jpi, 1:jpj) )
+            fprds2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OPALDISS%dgsave ) THEN
+            ALLOCATE( fsdiss2d(1:jpi, 1:jpj) )
+            fsdiss2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMIPn%dgsave ) THEN
+            ALLOCATE( fgmipn2d(1:jpi, 1:jpj) )
+            fgmipn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMID%dgsave ) THEN
+            ALLOCATE( fgmid2d(1:jpi, 1:jpj) )
+            fgmid2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%MZMI%dgsave ) THEN
+            ALLOCATE( fdzmi2d(1:jpi, 1:jpj) )
+            fdzmi2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMEPN%dgsave ) THEN
+            ALLOCATE( fgmepn2d(1:jpi, 1:jpj) )
+            fgmepn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMEPD%dgsave ) THEN
+            ALLOCATE( fgmepd2d(1:jpi, 1:jpj) )
+            fgmepd2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMEZMI%dgsave ) THEN
+            ALLOCATE( fgmezmi2d(1:jpi, 1:jpj) )
+            fgmezmi2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMED%dgsave ) THEN
+            ALLOCATE( fgmed2d(1:jpi, 1:jpj) )
+            fgmed2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%MZME%dgsave ) THEN
+            ALLOCATE( fdzme2d(1:jpi, 1:jpj) )
+            fdzme2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%DETN%dgsave ) THEN
+            ALLOCATE( fslown2d(1:jpi, 1:jpj) )
+            fslown2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%MDET%dgsave ) THEN
+            ALLOCATE( fdd2d(1:jpi, 1:jpj) )
+            fdd2d(:,:)      = 0.0 !!
+         ENDIF      
+         IF( med_diag%AEOLIAN%dgsave ) THEN
+            ALLOCATE( ffetop2d(1:jpi, 1:jpj) )
+            ffetop2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%BENTHIC%dgsave ) THEN
+            ALLOCATE( ffebot2d(1:jpi, 1:jpj) )
+            ffebot2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%SCAVENGE%dgsave ) THEN
+            ALLOCATE( ffescav2d(1:jpi, 1:jpj) )
+            ffescav2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PN_JLIM%dgsave ) THEN
+            ALLOCATE( fjln2d(1:jpi, 1:jpj) )
+            fjln2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PN_NLIM%dgsave ) THEN
+            ALLOCATE( fnln2d(1:jpi, 1:jpj) )
+            fnln2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PN_FELIM%dgsave ) THEN
+            ALLOCATE( ffln2d(1:jpi, 1:jpj) )
+            ffln2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PD_JLIM%dgsave ) THEN
+            ALLOCATE( fjld2d(1:jpi, 1:jpj) )
+            fjld2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PD_NLIM%dgsave ) THEN
+            ALLOCATE( fnld2d(1:jpi, 1:jpj) )
+            fnld2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PD_FELIM%dgsave ) THEN
+            ALLOCATE( ffld2d(1:jpi, 1:jpj) )
+            ffld2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PD_SILIM%dgsave ) THEN
+            ALLOCATE( fsld2d2(1:jpi, 1:jpj) )
+            fsld2d2(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PDSILIM2%dgsave ) THEN
+            ALLOCATE( fsld2d(1:jpi, 1:jpj) )
+            fsld2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip SDT_XXXX diagnostics here
+!!
+         IF( med_diag%TOTREG_N%dgsave ) THEN
+            ALLOCATE( fregen2d(1:jpi, 1:jpj) )
+            fregen2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%TOTRG_SI%dgsave ) THEN
+            ALLOCATE( fregensi2d(1:jpi, 1:jpj) )
+            fregensi2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip REG_XXXX diagnostics here
+!!
+         IF( med_diag%FASTN%dgsave ) THEN
+            ALLOCATE( ftempn2d(1:jpi, 1:jpj) )
+            ftempn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%FASTSI%dgsave ) THEN
+            ALLOCATE( ftempsi2d(1:jpi, 1:jpj) )
+            ftempsi2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%FASTFE%dgsave ) THEN
+            ALLOCATE( ftempfe2d(1:jpi, 1:jpj) )
+            ftempfe2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%FASTC%dgsave ) THEN
+            ALLOCATE( ftempc2d(1:jpi, 1:jpj) )
+            ftempc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%FASTCA%dgsave ) THEN
+            ALLOCATE( ftempca2d(1:jpi, 1:jpj) )
+            ftempca2d(:,:)      = 0.0 !!
+         ENDIF     
+!!
+!! skip FDT_XXXX, RG_XXXXF, FDS_XXXX, RGS_XXXXF diagnostics here
+!!
+         IF( med_diag%REMINN%dgsave ) THEN
+            ALLOCATE( freminn2d(1:jpi, 1:jpj) )
+            freminn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%REMINSI%dgsave ) THEN
+            ALLOCATE( freminsi2d(1:jpi, 1:jpj) )
+            freminsi2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%REMINFE%dgsave ) THEN
+            ALLOCATE( freminfe2d(1:jpi, 1:jpj) )
+            freminfe2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%REMINC%dgsave ) THEN
+            ALLOCATE( freminc2d(1:jpi, 1:jpj) )
+            freminc2d(:,:)      = 0.0 !! 
+         ENDIF
+         IF( med_diag%REMINCA%dgsave ) THEN
+            ALLOCATE( freminca2d(1:jpi, 1:jpj) )
+            freminca2d(:,:)      = 0.0 !!
+         ENDIF
+
+# if defined key_roam
+!!
+!! skip SEAFLRXX, MED_XXXX, INTFLX_XX, INT_XX, ML_XXX, OCAL_XXX, FE_XXXX, MED_XZE, WIND diagnostics here
+!!
+         IF( med_diag%RR_0100%dgsave ) THEN
+            ALLOCATE( ffastca2d(1:jpi, 1:jpj) )
+            ffastca2d(:,:)      = 0.0 !!
+         ENDIF
+
+         IF( med_diag%ATM_PCO2%dgsave ) THEN
+            ALLOCATE( f_pco2a2d(1:jpi, 1:jpj) )
+            f_pco2a2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip OCN_PH diagnostic here
+!!
+         IF( med_diag%OCN_PCO2%dgsave ) THEN
+            ALLOCATE( f_pco2w2d(1:jpi, 1:jpj) )
+            f_pco2w2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip OCNH2CO3, OCN_HCO3, OCN_CO3 diagnostics here
+!!
+         IF( med_diag%CO2FLUX%dgsave ) THEN
+            ALLOCATE( f_co2flux2d(1:jpi, 1:jpj) )
+            f_co2flux2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip OM_XXX diagnostics here
+!!
+         IF( med_diag%TCO2%dgsave ) THEN
+            ALLOCATE( f_TDIC2d(1:jpi, 1:jpj) )
+            f_TDIC2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%TALK%dgsave ) THEN
+            ALLOCATE( f_TALK2d(1:jpi, 1:jpj) )
+            f_TALK2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%KW660%dgsave ) THEN
+            ALLOCATE( f_kw6602d(1:jpi, 1:jpj) )
+            f_kw6602d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ATM_PP0%dgsave ) THEN
+            ALLOCATE( f_pp02d(1:jpi, 1:jpj) )
+            f_pp02d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%O2FLUX%dgsave ) THEN
+            ALLOCATE( f_o2flux2d(1:jpi, 1:jpj) )
+            f_o2flux2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%O2SAT%dgsave ) THEN
+            ALLOCATE( f_o2sat2d(1:jpi, 1:jpj) )
+            f_o2sat2d(:,:)      = 0.0 !!
+         ENDIF 
+!!
+!! skip XXX_CCD diagnostics here
+!! 
+         IF( med_diag%SFR_OCAL%dgsave ) THEN
+            ALLOCATE( sfr_ocal2d(1:jpi, 1:jpj) )
+            sfr_ocal2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%SFR_OARG%dgsave ) THEN
+            ALLOCATE( sfr_oarg2d(1:jpi, 1:jpj) )
+            sfr_oarg2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip XX_PROD, XX_CONS, O2_ANOX, RR_XXXX diagnostics here
+!! 
+         IF( med_diag%IBEN_N%dgsave ) THEN
+            ALLOCATE( iben_n2d(1:jpi, 1:jpj) )
+            iben_n2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%IBEN_FE%dgsave ) THEN
+            ALLOCATE( iben_fe2d(1:jpi, 1:jpj) )
+            iben_fe2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%IBEN_C%dgsave ) THEN
+            ALLOCATE( iben_c2d(1:jpi, 1:jpj) )
+            iben_c2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%IBEN_SI%dgsave ) THEN
+            ALLOCATE( iben_si2d(1:jpi, 1:jpj) )
+            iben_si2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%IBEN_CA%dgsave ) THEN
+            ALLOCATE( iben_ca2d(1:jpi, 1:jpj) )
+            iben_ca2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OBEN_N%dgsave ) THEN
+            ALLOCATE( oben_n2d(1:jpi, 1:jpj) )
+            oben_n2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OBEN_FE%dgsave ) THEN
+            ALLOCATE( oben_fe2d(1:jpi, 1:jpj) )
+            oben_fe2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OBEN_C%dgsave ) THEN
+            ALLOCATE( oben_c2d(1:jpi, 1:jpj) )
+            oben_c2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OBEN_SI%dgsave ) THEN
+            ALLOCATE( oben_si2d(1:jpi, 1:jpj) )
+            oben_si2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OBEN_CA%dgsave ) THEN
+            ALLOCATE( oben_ca2d(1:jpi, 1:jpj) )
+            oben_ca2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip BEN_XX diagnostics here
+!!
+
+         IF( med_diag%RIV_N%dgsave ) THEN
+            ALLOCATE( rivn2d(1:jpi, 1:jpj) )
+            rivn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%RIV_SI%dgsave ) THEN
+            ALLOCATE( rivsi2d(1:jpi, 1:jpj) )
+            rivsi2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%RIV_C%dgsave ) THEN
+            ALLOCATE( rivc2d(1:jpi, 1:jpj) )
+            rivc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%RIV_ALK%dgsave ) THEN
+            ALLOCATE( rivalk2d(1:jpi, 1:jpj) )
+            rivalk2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%DETC%dgsave ) THEN
+            ALLOCATE( fslowc2d(1:jpi, 1:jpj) )
+            fslowc2d(:,:)      = 0.0 !!
+         ENDIF 
+!!
+!! skip SDC_XXXX, INVTXXX diagnostics here
+!!
+         IF( med_diag%LYSO_CA%dgsave ) THEN
+            ALLOCATE( lyso_ca2d(1:jpi, 1:jpj) )
+            lyso_ca2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip COM_RESP diagnostic here
+!!
+         IF( med_diag%PN_LLOSS%dgsave ) THEN
+            ALLOCATE( fdpn22d(1:jpi, 1:jpj) )
+            fdpn22d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%PD_LLOSS%dgsave ) THEN
+            ALLOCATE( fdpd22d(1:jpi, 1:jpj) )
+            fdpd22d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_LLOSS%dgsave ) THEN
+            ALLOCATE( fdzmi22d(1:jpi, 1:jpj) )
+            fdzmi22d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_LLOSS%dgsave ) THEN
+            ALLOCATE( fdzme22d(1:jpi, 1:jpj) )
+            fdzme22d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_MES_N%dgsave ) THEN   
+            ALLOCATE( zimesn2d(1:jpi, 1:jpj) )
+            zimesn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_MES_D%dgsave ) THEN
+            ALLOCATE( zimesd2d(1:jpi, 1:jpj) )
+            zimesd2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_MES_C%dgsave ) THEN
+            ALLOCATE( zimesc2d(1:jpi, 1:jpj) )
+            zimesc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_MESDC%dgsave ) THEN
+            ALLOCATE( zimesdc2d(1:jpi, 1:jpj) )
+            zimesdc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_EXCR%dgsave ) THEN
+            ALLOCATE( ziexcr2d(1:jpi, 1:jpj) )
+            ziexcr2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_RESP%dgsave ) THEN
+            ALLOCATE( ziresp2d(1:jpi, 1:jpj) )
+            ziresp2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZI_GROW%dgsave ) THEN
+            ALLOCATE( zigrow2d(1:jpi, 1:jpj) )
+            zigrow2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_MES_N%dgsave ) THEN
+            ALLOCATE( zemesn2d(1:jpi, 1:jpj) )
+            zemesn2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_MES_D%dgsave ) THEN
+            ALLOCATE( zemesd2d(1:jpi, 1:jpj) )
+            zemesd2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_MES_C%dgsave ) THEN
+            ALLOCATE( zemesc2d(1:jpi, 1:jpj) )
+            zemesc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_MESDC%dgsave ) THEN
+            ALLOCATE( zemesdc2d(1:jpi, 1:jpj) )
+            zemesdc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_EXCR%dgsave ) THEN
+            ALLOCATE( zeexcr2d(1:jpi, 1:jpj) )
+            zeexcr2d(:,:)      = 0.0 !!
+         ENDIF                  
+         IF( med_diag%ZE_RESP%dgsave ) THEN
+            ALLOCATE( zeresp2d(1:jpi, 1:jpj) )
+            zeresp2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ZE_GROW%dgsave ) THEN
+            ALLOCATE( zegrow2d(1:jpi, 1:jpj) )
+            zegrow2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%MDETC%dgsave ) THEN
+            ALLOCATE( mdetc2d(1:jpi, 1:jpj) )
+            mdetc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMIDC%dgsave ) THEN
+            ALLOCATE( gmidc2d(1:jpi, 1:jpj) )
+            gmidc2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%GMEDC%dgsave ) THEN
+            ALLOCATE( gmedc2d(1:jpi, 1:jpj) )
+            gmedc2d(:,:)      = 0.0 !!
+         ENDIF
+!!
+!! skip INT_XXX diagnostics here
+!!
+         IF (jdms .eq. 1) THEN
+            IF( med_diag%DMS_SURF%dgsave ) THEN
+               ALLOCATE( dms_surf2d(1:jpi, 1:jpj) )
+               dms_surf2d(:,:)      = 0.0 !!
+            ENDIF
+            IF( med_diag%DMS_ANDR%dgsave ) THEN
+               ALLOCATE( dms_andr2d(1:jpi, 1:jpj) )
+               dms_andr2d(:,:)      = 0.0 !!
+            ENDIF
+            IF( med_diag%DMS_SIMO%dgsave ) THEN
+               ALLOCATE( dms_simo2d(1:jpi, 1:jpj) )
+               dms_simo2d(:,:)      = 0.0 !!
+            ENDIF
+            IF( med_diag%DMS_ARAN%dgsave ) THEN
+               ALLOCATE( dms_aran2d(1:jpi, 1:jpj) )
+               dms_aran2d(:,:)      = 0.0 !!
+            ENDIF
+            IF( med_diag%DMS_HALL%dgsave ) THEN
+               ALLOCATE( dms_hall2d(1:jpi, 1:jpj) )
+               dms_hall2d(:,:)      = 0.0 !!
+            ENDIF
+            IF( med_diag%DMS_ANDM%dgsave ) THEN
+               ALLOCATE( dms_andm2d(1:jpi, 1:jpj) )
+               dms_andm2d(:,:)      = 0.0 !!
+            ENDIF
+         ENDIF   
+         !!
+         !! AXY (24/11/16): extra MOCSY diagnostics, 2D
+         IF( med_diag%ATM_XCO2%dgsave ) THEN
+            ALLOCATE( f_xco2a_2d(1:jpi, 1:jpj) )
+            f_xco2a_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OCN_FCO2%dgsave ) THEN
+            ALLOCATE( f_fco2w_2d(1:jpi, 1:jpj) )
+            f_fco2w_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%ATM_FCO2%dgsave ) THEN
+            ALLOCATE( f_fco2a_2d(1:jpi, 1:jpj) )
+            f_fco2a_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OCN_RHOSW%dgsave ) THEN
+            ALLOCATE( f_ocnrhosw_2d(1:jpi, 1:jpj) )
+            f_ocnrhosw_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OCN_SCHCO2%dgsave ) THEN
+            ALLOCATE( f_ocnschco2_2d(1:jpi, 1:jpj) )
+            f_ocnschco2_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OCN_KWCO2%dgsave ) THEN
+            ALLOCATE( f_ocnkwco2_2d(1:jpi, 1:jpj) )
+            f_ocnkwco2_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OCN_K0%dgsave ) THEN
+            ALLOCATE( f_ocnk0_2d(1:jpi, 1:jpj) )
+            f_ocnk0_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%CO2STARAIR%dgsave ) THEN
+            ALLOCATE( f_co2starair_2d(1:jpi, 1:jpj) )
+            f_co2starair_2d(:,:)      = 0.0 !!
+         ENDIF
+         IF( med_diag%OCN_DPCO2%dgsave ) THEN
+            ALLOCATE( f_ocndpco2_2d(1:jpi, 1:jpj) )
+            f_ocndpco2_2d(:,:)      = 0.0 !!
+         ENDIF
+# endif  
+         IF( med_diag%TPP3%dgsave ) THEN
+            ALLOCATE( tpp3d(1:jpi, 1:jpj, 1:jpk) )
+            tpp3d(:,:,:)      = 0.0 !! 
+         ENDIF
+         IF( med_diag%DETFLUX3%dgsave ) THEN
+            ALLOCATE( detflux3d(1:jpi, 1:jpj, 1:jpk) )
+            detflux3d(:,:,:)      = 0.0 !! 
+         ENDIF
+         IF( med_diag%REMIN3N%dgsave ) THEN
+             ALLOCATE( remin3dn(1:jpi, 1:jpj, 1:jpk) )
+             remin3dn(:,:,:)      = 0.0 !! 
+         ENDIF
+         !! 
+         !! AXY (10/11/16): CMIP6 diagnostics, 2D
+         !! JPALM -- 17-11-16 -- put fgco2 alloc out of diag request
+         !!                   needed for coupling/passed through restart
+         !! IF( med_diag%FGCO2%dgsave ) THEN
+            ALLOCATE( fgco2(1:jpi, 1:jpj) )
+            fgco2(:,:)      = 0.0 !!
+         !! ENDIF
+         IF( med_diag%INTDISSIC%dgsave ) THEN
+            ALLOCATE( intdissic(1:jpi, 1:jpj) )
+            intdissic(:,:)  = 0.0 !!
+         ENDIF          
+         IF( med_diag%INTDISSIN%dgsave ) THEN
+            ALLOCATE( intdissin(1:jpi, 1:jpj) )
+            intdissin(:,:)  = 0.0 !!
+         ENDIF          
+         IF( med_diag%INTDISSISI%dgsave ) THEN
+            ALLOCATE( intdissisi(1:jpi, 1:jpj) )
+            intdissisi(:,:)  = 0.0 !!
+         ENDIF          
+         IF( med_diag%INTTALK%dgsave ) THEN
+            ALLOCATE( inttalk(1:jpi, 1:jpj) )
+            inttalk(:,:)  = 0.0 !!
+         ENDIF          
+         IF( med_diag%O2min%dgsave ) THEN
+            ALLOCATE( o2min(1:jpi, 1:jpj) )
+            o2min(:,:)  = 1.e3 !! set to high value as we're looking for min(o2)
+         ENDIF          
+         IF( med_diag%ZO2min%dgsave ) THEN
+            ALLOCATE( zo2min(1:jpi, 1:jpj) )
+            zo2min(:,:)  = 0.0 !!
+         ENDIF          
+         IF( med_diag%FBDDTALK%dgsave  ) THEN
+            ALLOCATE( fbddtalk(1:jpi, 1:jpj) )
+            fbddtalk(:,:)  = 0.0 !! 
+         ENDIF
+         IF( med_diag%FBDDTDIC%dgsave  ) THEN
+            ALLOCATE( fbddtdic(1:jpi, 1:jpj) )
+            fbddtdic(:,:)  = 0.0 !! 
+         ENDIF
+         IF( med_diag%FBDDTDIFE%dgsave ) THEN
+            ALLOCATE( fbddtdife(1:jpi, 1:jpj) )
+            fbddtdife(:,:) = 0.0 !! 
+         ENDIF
+         IF( med_diag%FBDDTDIN%dgsave  ) THEN
+            ALLOCATE( fbddtdin(1:jpi, 1:jpj) )
+            fbddtdin(:,:)  = 0.0 !! 
+         ENDIF
+         IF( med_diag%FBDDTDISI%dgsave ) THEN
+            ALLOCATE( fbddtdisi(1:jpi, 1:jpj) )
+            fbddtdisi(:,:) = 0.0 !! 
+         ENDIF
+         !! 
+         !! AXY (10/11/16): CMIP6 diagnostics, 3D
+         IF( med_diag%TPPD3%dgsave     ) THEN
+            ALLOCATE( tppd3(1:jpi, 1:jpj, 1:jpk) )
+            tppd3(:,:,:)     = 0.0 !! 
+         ENDIF
+         IF( med_diag%BDDTALK3%dgsave  ) THEN
+            ALLOCATE( bddtalk3(1:jpi, 1:jpj, 1:jpk) )
+            bddtalk3(:,:,:)  = 0.0 !! 
+         ENDIF
+         IF( med_diag%BDDTDIC3%dgsave  ) THEN
+            ALLOCATE( bddtdic3(1:jpi, 1:jpj, 1:jpk) )
+            bddtdic3(:,:,:)  = 0.0 !! 
+         ENDIF
+         IF( med_diag%BDDTDIFE3%dgsave ) THEN
+            ALLOCATE( bddtdife3(1:jpi, 1:jpj, 1:jpk) )
+            bddtdife3(:,:,:) = 0.0 !! 
+         ENDIF
+         IF( med_diag%BDDTDIN3%dgsave  ) THEN
+            ALLOCATE( bddtdin3(1:jpi, 1:jpj, 1:jpk) )
+            bddtdin3(:,:,:)  = 0.0 !! 
+         ENDIF
+         IF( med_diag%BDDTDISI3%dgsave ) THEN
+            ALLOCATE( bddtdisi3(1:jpi, 1:jpj, 1:jpk) )
+            bddtdisi3(:,:,:) = 0.0 !! 
+         ENDIF
+         IF( med_diag%FD_NIT3%dgsave   ) THEN
+            ALLOCATE( fd_nit3(1:jpi, 1:jpj, 1:jpk) )
+            fd_nit3(:,:,:)   = 0.0 !! 
+         ENDIF
+         IF( med_diag%FD_SIL3%dgsave   ) THEN
+            ALLOCATE( fd_sil3(1:jpi, 1:jpj, 1:jpk) )
+            fd_sil3(:,:,:)   = 0.0 !! 
+         ENDIF
+         IF( med_diag%FD_CAR3%dgsave   ) THEN
+            ALLOCATE( fd_car3(1:jpi, 1:jpj, 1:jpk) )
+            fd_car3(:,:,:)   = 0.0 !! 
+         ENDIF
+         IF( med_diag%FD_CAL3%dgsave   ) THEN
+            ALLOCATE( fd_cal3(1:jpi, 1:jpj, 1:jpk) )
+            fd_cal3(:,:,:)   = 0.0 !! 
+         ENDIF
+         IF( med_diag%DCALC3%dgsave    ) THEN
+            ALLOCATE( dcalc3(1:jpi, 1:jpj, 1:jpk) )
+            dcalc3(:,:,: )   = 0.0 !! 
+         ENDIF
+         IF( med_diag%EXPC3%dgsave     ) THEN
+            ALLOCATE( expc3(1:jpi, 1:jpj, 1:jpk) )
+            expc3(:,:,: )    = 0.0 !! 
+         ENDIF
+         IF( med_diag%EXPN3%dgsave     ) THEN
+            ALLOCATE( expn3(1:jpi, 1:jpj, 1:jpk) )
+            expn3(:,:,: )    = 0.0 !! 
+         ENDIF
+         IF( med_diag%FEDISS3%dgsave   ) THEN
+            ALLOCATE( fediss3(1:jpi, 1:jpj, 1:jpk) )
+            fediss3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%FESCAV3%dgsave   ) THEN
+            ALLOCATE( fescav3(1:jpi, 1:jpj, 1:jpk) )
+            fescav3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%MIGRAZP3%dgsave   ) THEN
+            ALLOCATE( migrazp3(1:jpi, 1:jpj, 1:jpk) )
+            migrazp3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%MIGRAZD3%dgsave   ) THEN
+            ALLOCATE( migrazd3(1:jpi, 1:jpj, 1:jpk) )
+            migrazd3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%MEGRAZP3%dgsave   ) THEN
+            ALLOCATE( megrazp3(1:jpi, 1:jpj, 1:jpk) )
+            megrazp3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%MEGRAZD3%dgsave   ) THEN
+            ALLOCATE( megrazd3(1:jpi, 1:jpj, 1:jpk) )
+            megrazd3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%MEGRAZZ3%dgsave   ) THEN
+            ALLOCATE( megrazz3(1:jpi, 1:jpj, 1:jpk) )
+            megrazz3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%O2SAT3%dgsave     ) THEN
+            ALLOCATE( o2sat3(1:jpi, 1:jpj, 1:jpk) )
+            o2sat3(:,:,: )    = 0.0 !! 
+         ENDIF
+         IF( med_diag%PBSI3%dgsave      ) THEN
+            ALLOCATE( pbsi3(1:jpi, 1:jpj, 1:jpk) )
+            pbsi3(:,:,: )     = 0.0 !! 
+         ENDIF
+         IF( med_diag%PCAL3%dgsave      ) THEN
+            ALLOCATE( pcal3(1:jpi, 1:jpj, 1:jpk) )
+            pcal3(:,:,: )     = 0.0 !! 
+         ENDIF
+         IF( med_diag%REMOC3%dgsave     ) THEN
+            ALLOCATE( remoc3(1:jpi, 1:jpj, 1:jpk) )
+            remoc3(:,:,: )    = 0.0 !! 
+         ENDIF
+         IF( med_diag%PNLIMJ3%dgsave    ) THEN
+            ALLOCATE( pnlimj3(1:jpi, 1:jpj, 1:jpk) )
+            pnlimj3(:,:,: )   = 0.0 !! 
+         ENDIF
+         IF( med_diag%PNLIMN3%dgsave    ) THEN
+            ALLOCATE( pnlimn3(1:jpi, 1:jpj, 1:jpk) )
+            pnlimn3(:,:,: )   = 0.0 !! 
+         ENDIF
+         IF( med_diag%PNLIMFE3%dgsave   ) THEN
+            ALLOCATE( pnlimfe3(1:jpi, 1:jpj, 1:jpk) )
+            pnlimfe3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%PDLIMJ3%dgsave    ) THEN
+            ALLOCATE( pdlimj3(1:jpi, 1:jpj, 1:jpk) )
+            pdlimj3(:,:,: )   = 0.0 !! 
+         ENDIF
+         IF( med_diag%PDLIMN3%dgsave    ) THEN
+            ALLOCATE( pdlimn3(1:jpi, 1:jpj, 1:jpk) )
+            pdlimn3(:,:,: )   = 0.0 !! 
+         ENDIF
+         IF( med_diag%PDLIMFE3%dgsave   ) THEN
+            ALLOCATE( pdlimfe3(1:jpi, 1:jpj, 1:jpk) )
+            pdlimfe3(:,:,: )  = 0.0 !! 
+         ENDIF
+         IF( med_diag%PDLIMSI3%dgsave   ) THEN
+            ALLOCATE( pdlimsi3(1:jpi, 1:jpj, 1:jpk) )
+            pdlimsi3(:,:,: )  = 0.0 !! 
+         ENDIF
+      ENDIF
+      !! lk_iomput
+
+   END SUBROUTINE bio_medusa_init
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE bio_medusa_init( )                   ! Empty routine
+      WRITE(*,*) 'bio_medusa_init: You should not have seen this print! error?'
+   END SUBROUTINE bio_medusa_init
+#endif 
+
+   !!======================================================================
+END MODULE bio_medusa_init_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_mod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_mod.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_mod.F90	(revision 9987)
@@ -0,0 +1,393 @@
+MODULE bio_medusa_mod
+   !!======================================================================
+   !!                      ***  MODULE  bio_medusa_mod  ***
+   !! MEDUSA variables   :  module for MEDUSA variables which are shared
+   !!                       across subroutines 
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                           MEDUSA
+   !!----------------------------------------------------------------------
+   !! Variable conventions
+   !!----------------------------------------------------------------------
+   !!
+   !! names: z*** - state variable 
+   !!        f*** - function (or temporary variable used in part of a function)
+   !!        b*** - right-hand part (sources and sinks)
+   !!        i*** - integer variable (usually used in yes/no flags)
+   !!----------------------------------------------------------------------
+   USE par_kind,          ONLY: wp
+   
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC   bio_medusa_alloc     ! called by trcini.F90
+
+   !! model state variables
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zchn,zchd,zphn,zphd,zpds,zzmi
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zzme,zdet,zdtc,zdin,zsil,zfer
+# if defined key_roam
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zdic, zalk, zoxy
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ztmp, zsal
+# endif
+# if defined key_mocsy
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zpho
+# endif
+
+   !! integrated source and sink terms
+   REAL(wp) ::    b0
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fthetan,fprn,frn
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fthetad,fprd,frd
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fjlim_pn,fjlim_pd
+   !! AXY (16/07/09): add in Eppley curve functionality
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fun_T,xvpnT,xvpdT
+
+   !! AXY (16/05/11): per Katya's prompting, add in new T-dependence
+   !!                 for phytoplankton growth only (i.e. no change
+   !!                 for remineralisation)
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fun_Q10
+   !! AXY (01/03/10): add in mixed layer PP diagnostics
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fprn_ml,fprd_ml
+   !!
+   !! nutrient limiting factors
+   !! N and Fe (renaming ffln to ffln2 to avoid conflict with
+   !! ffln in module sms_medusa - marc 25/4/17)
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fnln,ffln2
+   !! N, Fe and Si
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fnld,ffld,fsld,fsld2
+   !!
+   !! silicon cycle
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fsin,fprds,fsdiss
+
+   !! iron cycle; includes parameters for Parekh et al. (2005) iron scheme
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ffetop,ffebot,ffescav
+   !! Variable for iron-ligand system
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: xFree
+
+   !! Microzooplankton grazing
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fgmipn,fgmid,fgmidc
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: finmi,ficmi
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fmigrow,fmiexcr,fmiresp
+   !!
+   !! Mesozooplankton grazing
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fgmepn,fgmepd
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fgmepds,fgmezmi,fgmed,fgmedc
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: finme,ficme
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fmegrow,fmeexcr,fmeresp
+   !!
+   !! mortality/Remineralisation
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fdpn,fdpd,fdpds,fdzmi,fdzme,fdd
+# if defined key_roam
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fddc
+# endif
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fdpn2,fdpd2,fdpds2,fdzmi2,fdzme2
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fslown, fslowc
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fslownflux, fslowcflux
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fregen,fregensi
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fregenfast,fregenfastsi
+# if defined key_roam
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fregenfastc
+# endif
+
+   !! Particle flux
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fdep1
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftempn,ftempsi,ftempfe
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftempc,ftempca
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: freminn,freminsi,freminfe
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: freminc,freminca
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ffastn,ffastsi,ffastfe
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ffastc,ffastca
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fsedn,fsedsi,fsedfe,fsedc,fsedca
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fccd
+
+   !! AXY (08/07/11): fate of fast detritus reaching the seafloor
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ffast2slown,ffast2slowc
+
+   !! water column nutrient and flux integrals
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftot_n,ftot_si,ftot_fe
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fflx_n,fflx_si,fflx_fe
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fifd_n,fifd_si,fifd_fe
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fofd_n,fofd_si,fofd_fe
+# if defined key_roam
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftot_c,ftot_a,ftot_o2
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fflx_c,fflx_a,fflx_o2
+! I don't think fifd_a, fifd_o2, fofd_a or fofd_o2 are used - marc 11/5/17
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fifd_c,fifd_a,fifd_o2
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fofd_c,fofd_a,fofd_o2
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fifd_c
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fofd_c
+# endif
+
+   !! Zooplankton grazing integrals
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fzmi_i,fzmi_o,fzme_i,fzme_o
+
+   !! Limitation term temporary variables
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftot_pn,ftot_pd
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftot_zmi,ftot_zme,ftot_det,ftot_dtc
+
+   !! use biological fluxes (1) or not (0)
+   INTEGER  ::    ibio_switch
+   !!
+   !! diagnose fluxes (should only be used in 1D runs)
+   INTEGER                               :: idf, idfval
+
+   !! Nitrogen and silicon production and consumption
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fnit_prod,fnit_cons
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fsil_prod,fsil_cons
+
+# if defined key_roam
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_xco2a
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_ph,f_pco2w,f_h2co3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_hco3,f_co3,f_co2flux
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_TDIC,f_TALK,f_dcf,f_henry
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_pp0
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_kw660,f_o2flux,f_o2sat
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_omcal,f_omarg
+
+   !! AXY (23/06/15): additional diagnostics for MOCSY and oxygen
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_pco2atm
+
+   !! Carbon, alkalinity production and consumption
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fcomm_resp
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fcar_prod,fcar_cons
+
+   !! Oxygen production and consumption (and non-consumption)
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: foxy_prod,foxy_cons,foxy_anox
+
+   !! Add DMS in MEDUSA for UKESM1 model
+   REAL(wp)                              :: dms_surf,dms_andm
+   !! AXY (13/03/15): add in other DMS calculations
+   REAL(wp)                              :: dms_andr,dms_simo,dms_aran,dms_hall
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: dms_nlim, dms_wtkn
+# endif
+
+   !! Benthic fluxes
+   INTEGER  ::    ibenthic
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_sbenin_n,f_sbenin_fe,f_sbenin_c
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_fbenin_n,f_fbenin_fe,f_fbenin_si
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_fbenin_c,f_fbenin_ca
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_benout_n,f_benout_fe,f_benout_si 
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_benout_c,f_benout_ca
+
+   !! Benthic fluxes of CaCO3 that shouldn't happen because of lysocline
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_benout_lyso_ca
+
+   !! riverine fluxes
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_runoff,f_riv_n,f_riv_si
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_riv_c,f_riv_alk
+   !! AXY (19/07/12): variables for local riverine fluxes to handle 
+   !! inputs below surface
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_riv_loc_n,f_riv_loc_si
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_riv_loc_c, f_riv_loc_alk
+
+   !! Jpalm -- 11-10-2015 -- adapt diag to iom_use
+   !! 2D var for diagnostics.
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fprn2d, fdpn2d, fprd2d, fdpd2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fprds2d, fsdiss2d, fgmipn2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fgmid2d, fdzmi2d, fgmepn2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fgmepd2d, fgmezmi2d, fgmed2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fdzme2d, fslown2d, fdd2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ffetop2d, ffebot2d, ffescav2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fjln2d, fnln2d, ffln2d, fjld2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fnld2d, ffld2d, fsld2d2
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fsld2d, fregen2d, fregensi2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftempn2d, ftempsi2d, ftempfe2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ftempc2d, ftempca2d, freminn2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: freminsi2d, freminfe2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: freminc2d, freminca2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zw2d
+# if defined key_roam
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ffastca2d, rivn2d, rivsi2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: rivc2d, rivalk2d, fslowc2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fdpn22d, fdpd22d, fdzmi22d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fdzme22d, zimesn2d, zimesd2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zimesc2d, zimesdc2d, ziexcr2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ziresp2d, zigrow2d, zemesn2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zemesd2d, zemesc2d, zemesdc2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zeexcr2d, zeresp2d, zegrow2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: mdetc2d, gmidc2d, gmedc2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_pco2a2d, f_pco2w2d, f_co2flux2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_TDIC2d, f_TALK2d, f_kw6602d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_pp02d, f_o2flux2d, f_o2sat2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: dms_andr2d, dms_simo2d, dms_aran2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: dms_hall2d, dms_andm2d, dms_surf2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: iben_n2d, iben_fe2d, iben_c2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: iben_si2d, iben_ca2d, oben_n2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: oben_fe2d, oben_c2d, oben_si2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: oben_ca2d, sfr_ocal2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: sfr_oarg2d, lyso_ca2d 
+   !! AXY (23/11/16): extra MOCSY diagnostics
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_xco2a_2d, f_fco2w_2d, f_fco2a_2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_ocnrhosw_2d, f_ocnschco2_2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_ocnkwco2_2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_ocnk0_2d, f_co2starair_2d
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: f_ocndpco2_2d
+# endif
+   !!
+   !! 3D var for diagnostics.
+   REAL(wp), POINTER, DIMENSION(:,:,:) :: tpp3d, detflux3d, remin3dn
+   !!
+# if defined key_roam
+   !! AXY (04/11/16)
+   !! 2D var for new CMIP6 diagnostics (behind a key_roam ifdef 
+   !! for simplicity)
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fgco2,intdissic,intdissin
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: intdissisi,inttalk,o2min,zo2min
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fbddtalk,fbddtdic,fbddtdife
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: fbddtdin,fbddtdisi
+   !!
+   !! 3D var for new CMIP6 diagnostics
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: tppd3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: bddtalk3,bddtdic3,bddtdife3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: bddtdin3, bddtdisi3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: fd_nit3,fd_sil3,fd_car3,fd_cal3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: co33,co3satarag3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: co3satcalc3,dcalc3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: expc3,expn3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: fediss3,fescav3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: migrazp3,migrazd3,megrazp3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: megrazd3, megrazz3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: o2sat3,pbsi3,pcal3,remoc3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: pnlimj3,pnlimn3,pnlimfe3
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: pdlimj3,pdlimn3,pdlimfe3,pdlimsi3
+# endif
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3.1 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION bio_medusa_alloc()
+      !!-------------------------------------------------------------------
+      !!                    *** ROUTINE bio_medusa_alloc ***
+      !!-------------------------------------------------------------------
+      USE lib_mpp,           ONLY: ctl_warn
+      USE par_oce,           ONLY: jpi, jpj
+      !!-------------------------------------------------------------------
+      !
+      ALLOCATE(zchn(jpi,jpj),zchd(jpi,jpj),zphn(jpi,jpj),             &
+               zphd(jpi,jpj),zpds(jpi,jpj),zzmi(jpi,jpj),             &
+               zzme(jpi,jpj),zdet(jpi,jpj),zdtc(jpi,jpj),             &
+               zdin(jpi,jpj),zsil(jpi,jpj),zfer(jpi,jpj),             &
+# if defined key_roam
+               zdic(jpi,jpj),zalk(jpi,jpj),zoxy(jpi,jpj),             &
+               ztmp(jpi,jpj),zsal(jpi,jpj),                           &
+# endif
+# if defined key_mocsy
+               zpho(jpi,jpj),                                         &
+# endif
+               fthetan(jpi,jpj),fprn(jpi,jpj),frn(jpi,jpj),           &
+               fthetad(jpi,jpj),fprd(jpi,jpj),frd(jpi,jpj),           &
+               fjlim_pn(jpi,jpj),fjlim_pd(jpi,jpj),                   &
+               fun_T(jpi,jpj),fun_Q10(jpi,jpj),                       &
+               fprn_ml(jpi,jpj),fprd_ml(jpi,jpj),                     &
+               fnln(jpi,jpj),ffln2(jpi,jpj),                          &
+               fnld(jpi,jpj),ffld(jpi,jpj),fsld(jpi,jpj),             &
+               fsld2(jpi,jpj),                                        &
+               fsin(jpi,jpj),fprds(jpi,jpj),fsdiss(jpi,jpj),          &
+               ffetop(jpi,jpj),ffebot(jpi,jpj),ffescav(jpi,jpj),      &
+               xFree(jpi,jpj),                                        &
+               fgmipn(jpi,jpj),fgmid(jpi,jpj),fgmidc(jpi,jpj),        &
+               finmi(jpi,jpj),ficmi(jpi,jpj),                         &
+               fmigrow(jpi,jpj),fmiexcr(jpi,jpj),fmiresp(jpi,jpj),    &
+               fgmepn(jpi,jpj),fgmepd(jpi,jpj),                       &
+               fgmepds(jpi,jpj),fgmezmi(jpi,jpj),fgmed(jpi,jpj),      &
+               fgmedc(jpi,jpj),                                       &
+               finme(jpi,jpj),ficme(jpi,jpj),                         &
+               fmegrow(jpi,jpj),fmeexcr(jpi,jpj),fmeresp(jpi,jpj),    &
+               fdpn(jpi,jpj),fdpd(jpi,jpj),fdpds(jpi,jpj),            &
+               fdzmi(jpi,jpj),fdzme(jpi,jpj),fdd(jpi,jpj),            &
+# if defined key_roam
+               fddc(jpi,jpj),                                         &
+# endif
+               fdpn2(jpi,jpj),fdpd2(jpi,jpj),fdpds2(jpi,jpj),         &
+               fdzmi2(jpi,jpj),fdzme2(jpi,jpj),                       &
+               fslown(jpi,jpj),fslowc(jpi,jpj),                       &
+               fslownflux(jpi,jpj),fslowcflux(jpi,jpj),               &
+               fregen(jpi,jpj),fregensi(jpi,jpj),                     &
+               fregenfast(jpi,jpj),fregenfastsi(jpi,jpj),             &
+# if defined key_roam
+               fregenfastc(jpi,jpj),                                  &
+# endif
+               fdep1(jpi,jpj),                                        &
+               ftempn(jpi,jpj),ftempsi(jpi,jpj),ftempfe(jpi,jpj),     &
+               ftempc(jpi,jpj),ftempca(jpi,jpj),                      &
+               freminn(jpi,jpj),freminsi(jpi,jpj),freminfe(jpi,jpj),  &
+               freminc(jpi,jpj),freminca(jpi,jpj),                    &
+               ffastn(jpi,jpj),ffastsi(jpi,jpj),ffastfe(jpi,jpj),     &
+               ffastc(jpi,jpj),ffastca(jpi,jpj),                      &
+               fsedn(jpi,jpj),fsedsi(jpi,jpj),fsedfe(jpi,jpj),        &
+               fsedc(jpi,jpj),fsedca(jpi,jpj),                        &
+               fccd(jpi,jpj),                                         &
+               ffast2slown(jpi,jpj),ffast2slowc(jpi,jpj),             &
+               ftot_n(jpi,jpj),ftot_si(jpi,jpj),ftot_fe(jpi,jpj),     &
+               fflx_n(jpi,jpj),fflx_si(jpi,jpj),fflx_fe(jpi,jpj),     &
+               fifd_n(jpi,jpj),fifd_si(jpi,jpj),fifd_fe(jpi,jpj),     &
+               fofd_n(jpi,jpj),fofd_si(jpi,jpj),fofd_fe(jpi,jpj),     &
+# if defined key_roam
+               ftot_c(jpi,jpj),ftot_a(jpi,jpj),ftot_o2(jpi,jpj),      &
+               fflx_c(jpi,jpj),fflx_a(jpi,jpj),fflx_o2(jpi,jpj),      &
+! I don't think fifd_a, fifd_o2, fofd_a or fofd_o2 are used - marc 11/5/17
+!               fifd_c(jpi,jpj),fifd_a(jpi,jpj),fifd_o2(jpi,jpj),      &
+!               fofd_c(jpi,jpj),fofd_a(jpi,jpj),fofd_o2(jpi,jpj),      &
+               fifd_c(jpi,jpj), fofd_c(jpi,jpj),                      &
+# endif
+               fzmi_i(jpi,jpj),fzmi_o(jpi,jpj),fzme_i(jpi,jpj),       &
+               fzme_o(jpi,jpj),                                       &
+               ftot_pn(jpi,jpj),ftot_pd(jpi,jpj),                     &
+               ftot_zmi(jpi,jpj),ftot_zme(jpi,jpj),ftot_det(jpi,jpj), &
+               ftot_dtc(jpi,jpj),                                     &
+               fnit_prod(jpi,jpj),fnit_cons(jpi,jpj),                 &
+               fsil_prod(jpi,jpj),fsil_cons(jpi,jpj),                 &
+# if defined key_roam
+               f_xco2a(jpi,jpj),                                      &
+               f_ph(jpi,jpj),f_pco2w(jpi,jpj),f_h2co3(jpi,jpj),       &
+               f_hco3(jpi,jpj),f_co3(jpi,jpj),f_co2flux(jpi,jpj),     &
+               f_TDIC(jpi,jpj),f_TALK(jpi,jpj),f_dcf(jpi,jpj),        &
+               f_henry(jpi,jpj),                                      &
+               f_pp0(jpi,jpj),                                        &
+               f_kw660(jpi,jpj),f_o2flux(jpi,jpj),f_o2sat(jpi,jpj),   &
+               f_omcal(jpi,jpj),f_omarg(jpi,jpj),                     &
+               f_pco2atm(jpi,jpj),                 &
+               fcomm_resp(jpi,jpj),                                   &
+               fcar_prod(jpi,jpj),fcar_cons(jpi,jpj),                 &
+               foxy_prod(jpi,jpj), foxy_cons(jpi,jpj),                &
+               foxy_anox(jpi,jpj),                                    &
+               dms_nlim(jpi,jpj),dms_wtkn(jpi,jpj),                   &
+# endif
+               f_sbenin_n(jpi,jpj),f_sbenin_fe(jpi,jpj),              &
+               f_sbenin_c(jpi,jpj),                                   &
+               f_fbenin_n(jpi,jpj),f_fbenin_fe(jpi,jpj),              &
+               f_fbenin_si(jpi,jpj),                                  &
+               f_fbenin_c(jpi,jpj),f_fbenin_ca(jpi,jpj),              &
+               f_benout_n(jpi,jpj),f_benout_fe(jpi,jpj),              &
+               f_benout_si(jpi,jpj),                                  &
+               f_benout_c(jpi,jpj),f_benout_ca(jpi,jpj),              &
+               f_benout_lyso_ca(jpi,jpj),                             &
+               f_runoff(jpi,jpj),f_riv_n(jpi,jpj),f_riv_si(jpi,jpj),  &
+               f_riv_c(jpi,jpj),f_riv_alk(jpi,jpj),                   &
+               f_riv_loc_n(jpi,jpj),f_riv_loc_si(jpi,jpj),            &
+               f_riv_loc_c(jpi,jpj),f_riv_loc_alk(jpi,jpj),           &
+               STAT = bio_medusa_alloc)
+
+      !! Check that allocation was successful
+      IF ( bio_medusa_alloc /= 0 ) THEN  
+         CALL ctl_warn('bio_medusa_alloc: failed to allocate arrays')
+      END IF
+   
+   END FUNCTION bio_medusa_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Empty module :                                          No MEDUSA
+   !!----------------------------------------------------------------------
+#endif 
+
+   !!======================================================================
+END MODULE bio_medusa_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_update.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_update.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/bio_medusa_update.F90	(revision 9987)
@@ -0,0 +1,838 @@
+MODULE bio_medusa_update_mod
+   !!======================================================================
+   !!                         ***  MODULE bio_medusa_update_mod  ***
+   !! Update tracer fields
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   bio_medusa_update        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE bio_medusa_update( kt, jk )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE bio_medusa_update  ***
+      !! This called from TRC_BIO_MEDUSA and updates the tracer fields
+      !!---------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: b0, bddtalk3, bddtdic3, bddtdife3,        &
+                                   bddtdin3, bddtdisi3,                      &
+                                   ibenthic, ibio_switch, idf, idfval,       &
+                                   f_benout_c, f_benout_ca, f_benout_n,      &
+                                   f_benout_si,                              &
+                                   f_co2flux, f_o2flux,                      &
+                                   f_riv_loc_alk, f_riv_loc_c,               &
+                                   f_riv_loc_n, f_riv_loc_si,                & 
+                                   f_riv_alk, f_riv_c, f_riv_n, f_riv_si,    &
+                                   fbddtalk, fbddtdic, fbddtdife,            &
+                                   fbddtdin, fbddtdisi,                      & 
+                                   fdd, fdpd, fdpd2, fdpds, fdpds2,          &
+                                   fdpn, fdpn2,                              &
+                                   fdzme, fdzme2, fdzmi, fdzmi2,             &
+                                   ffast2slowc, ffast2slown,                 &
+                                   ffebot, ffetop, ffescav,                  &
+                                   fflx_fe, fflx_n, fflx_si,                 &
+                                   fgmed, fgmepd, fgmedc, fgmepd, fgmepds,   &
+                                   fgmepn, fgmezmi,                          &
+                                   fgmid, fgmidc, fgmipn,                    &
+                                   ficme, ficmi, finme, finmi,               &
+                                   fmeexcr, fmegrow, fmeresp,                &
+                                   fmiexcr, fmigrow, fmiresp,                &
+                                   fnit_cons, fnit_prod,                     &
+                                   fprd, fprds, fprn,                        &
+                                   frd,                                      &
+                                   freminc, freminca, freminn, freminsi,     &
+                                   frn,                                      &
+                                   fsil_cons, fsil_prod, fsdiss,             &
+                                   ftempca, fthetad, fthetan,                &
+# if defined key_roam
+                                   fcar_cons, fcar_prod, fcomm_resp,         &
+                                   fddc, fflx_a, fflx_c, fflx_o2, zoxy,      &
+                                   foxy_anox, foxy_cons, foxy_prod,          &
+# endif
+                                   zpds, zphd, zphn
+      USE dom_oce,           ONLY: e3t_0, e3t_n, gphit, mbathy, tmask
+      USE in_out_manager,    ONLY: lwp, numout
+      USE lib_mpp,           ONLY: ctl_stop
+      USE par_kind,          ONLY: wp
+      USE par_medusa,        ONLY: jp_medusa,                                &
+                                   jpalk, jpchd, jpchn, jpdet, jpdic,        &
+                                   jpdin, jpdtc, jpfer, jpoxy, jppds,        &
+                                   jpphd, jpphn, jpsil, jpzme, jpzmi,        &
+                                   jpalk_lc, jpchd_lc, jpchn_lc, jpdet_lc,   & 
+                                   jpdic_lc, jpdin_lc, jpdtc_lc, jpfer_lc,   & 
+                                   jpoxy_lc, jppds_lc, jpphd_lc, jpphn_lc,   &
+                                   jpsil_lc, jpzme_lc, jpzmi_lc
+      USE par_oce,           ONLY: jpi, jpim1, jpj, jpjm1
+      USE par_trc,           ONLY: jptra
+      USE sms_medusa,        ONLY: friver_dep,                               &
+                                   jinorgben, jorgben,                       &
+                                   jriver_alk, jriver_c,                     &
+                                   jriver_n, jriver_si,                      &
+                                   xbetac, xbetan,                           &
+                                   xfdfrac1, xfdfrac2, xfdfrac3,             &
+                                   xo2min, xphi, xrfn,                       &
+                                   xthetanit, xthetapd, xthetapn,            &
+                                   xthetarem, xthetazme, xthetazmi,          &
+                                   xxi
+      USE trc,               ONLY: med_diag, tra
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! time (integer timestep)
+      INTEGER, INTENT( in ) :: kt
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+
+      !! Loop variables
+      INTEGER :: ji, jj, jn
+
+      !! AXY (23/08/13): changed from individual variables for each flux to
+      !!                 an array that holds all fluxes
+      REAL(wp), DIMENSION(jpi,jpj,jp_medusa) :: btra
+
+      !! nitrogen and silicon production and consumption
+      REAL(wp) :: fn_prod, fn_cons, fs_prod, fs_cons
+
+      !! carbon, alkalinity production and consumption
+      REAL(wp) :: fc_prod, fc_cons, fa_prod, fa_cons
+
+      !! oxygen production and consumption (and non-consumption)
+      REAL(wp), DIMENSION(jpi,jpj) :: fo2_prod, fo2_cons
+      REAL(wp), DIMENSION(jpi,jpj) :: fo2_ncons, fo2_ccons
+
+      !! temporary variables
+      REAL(wp) :: fq0
+
+      !!==========================================================
+      !! LOCAL GRID CELL TRENDS
+      !!==========================================================
+      !!
+      !!----------------------------------------------------------
+      !! Determination of trends
+      !!----------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! chlorophyll
+               btra(ji,jj,jpchn_lc) = b0 * ( ( (frn(ji,jj) * fprn(ji,jj) *      &
+                                             zphn(ji,jj) ) -                 &
+                                           fgmipn(ji,jj) - fgmepn(ji,jj) -   &
+                                           fdpn(ji,jj) - fdpn2(ji,jj) ) *    &
+                                          (fthetan(ji,jj) / xxi) )
+               btra(ji,jj,jpchd_lc) = b0 * ( ( (frd(ji,jj) * fprd(ji,jj) *      &
+                                             zphd(ji,jj) ) -                 &
+                                           fgmepd(ji,jj) - fdpd(ji,jj) -     &
+                                           fdpd2(ji,jj) ) *                  &
+                                          (fthetad(ji,jj) / xxi) )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! phytoplankton
+               btra(ji,jj,jpphn_lc) = b0 * ( (fprn(ji,jj) * zphn(ji,jj)) -      &
+                                          fgmipn(ji,jj) - fgmepn(ji,jj) -    &
+                                          fdpn(ji,jj) - fdpn2(ji,jj) )
+               btra(ji,jj,jpphd_lc) = b0 * ( (fprd(ji,jj) * zphd(ji,jj)) -      &
+                                          fgmepd(ji,jj) - fdpd(ji,jj) -      &
+                                          fdpd2(ji,jj) )
+               btra(ji,jj,jppds_lc) = b0 * ( (fprds(ji,jj) * zpds(ji,jj)) -     &
+                                          fgmepds(ji,jj) - fdpds(ji,jj) -    &
+                                          fsdiss(ji,jj) - fdpds2(ji,jj) )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! zooplankton
+               btra(ji,jj,jpzmi_lc) = b0 * (fmigrow(ji,jj) - fgmezmi(ji,jj) -   &
+                                         fdzmi(ji,jj) - fdzmi2(ji,jj))
+               btra(ji,jj,jpzme_lc) = b0 * (fmegrow(ji,jj) - fdzme(ji,jj) -     &
+                                         fdzme2(ji,jj))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! detritus
+               btra(ji,jj,jpdet_lc) = b0 *                                      &
+                                          ! mort. losses 
+                                   (fdpn(ji,jj) + ((1.0 - xfdfrac1) *        &
+                                                   fdpd(ji,jj)) +            &
+                                    fdzmi(ji,jj) +                           &
+                                    ((1.0 - xfdfrac2) * fdzme(ji,jj)) +      &
+                                          ! assim. inefficiency
+                                    ((1.0 - xbetan) * (finmi(ji,jj) +        &
+                                                       finme(ji,jj))) -      &
+                                          ! grazing and remin.
+                                    fgmid(ji,jj) - fgmed(ji,jj) -            &
+                                    fdd(ji,jj) +                             &
+                                          ! seafloor fast->slow
+                                    ffast2slown(ji,jj))
+               !!
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! dissolved inorganic nitrogen nutrient
+               !! primary production
+               fn_cons = - (fprn(ji,jj) * zphn(ji,jj)) -                     &
+                           (fprd(ji,jj) * zphd(ji,jj))
+               !! 
+               fn_prod =                                                     &
+                                         ! messy feeding remin.
+                         (xphi * (fgmipn(ji,jj) + fgmid(ji,jj))) +           &
+                         (xphi * (fgmepn(ji,jj) + fgmepd(ji,jj) +            &
+                                  fgmezmi(ji,jj) + fgmed(ji,jj))) +          &
+                                         ! excretion and remin.
+                         fmiexcr(ji,jj) + fmeexcr(ji,jj) + fdd(ji,jj) +      &
+                         freminn(ji,jj) +                                    &
+                                         ! metab. losses
+                         fdpn2(ji,jj) + fdpd2(ji,jj) + fdzmi2(ji,jj) +       &
+                         fdzme2(ji,jj)
+               !! 
+               !! riverine flux
+               if ( jriver_n .gt. 0 ) then
+                  f_riv_loc_n(ji,jj) = f_riv_n(ji,jj) *                      &
+                     friver_dep(jk,mbathy(ji,jj)) / fse3t(ji,jj,jk)
+                  fn_prod = fn_prod + f_riv_loc_n(ji,jj)
+               endif
+               !!  
+               !! benthic remineralisation
+               if (jk.eq.mbathy(ji,jj) .and. jorgben.eq.1 .and.              &
+                   ibenthic.eq.1) then
+                  fn_prod = fn_prod + (f_benout_n(ji,jj) / fse3t(ji,jj,jk))
+               endif
+               !!
+               btra(ji,jj,jpdin_lc) = b0 * ( fn_prod + fn_cons )
+               !!
+               !! consumption of dissolved nitrogen
+               fnit_cons(ji,jj) = fnit_cons(ji,jj) + ( fse3t(ji,jj,jk) *     &
+                                                       fn_cons )
+               !! production of dissolved nitrogen
+               fnit_prod(ji,jj) = fnit_prod(ji,jj) + ( fse3t(ji,jj,jk) *     &
+                                                       fn_prod )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! dissolved silicic acid nutrient
+               !! opal production
+               fs_cons = - (fprds(ji,jj) * zpds(ji,jj))
+               !!
+               fs_prod =                                                     &
+                             ! opal dissolution
+                         fsdiss(ji,jj) +                                     &
+                             ! mort. loss
+                         ((1.0 - xfdfrac1) * fdpds(ji,jj)) +                 &
+                             &  ! egestion of grazed Si
+                         ((1.0 - xfdfrac3) * fgmepds(ji,jj)) +               &
+                             ! fast diss. and metab. losses
+                         freminsi(ji,jj) + fdpds2(ji,jj)
+               !! 
+               !! riverine flux
+               if ( jriver_si .gt. 0 ) then
+                  f_riv_loc_si(ji,jj) = f_riv_si(ji,jj) *                    &
+                                        friver_dep(jk,mbathy(ji,jj)) /       &
+                                        fse3t(ji,jj,jk)
+                  fs_prod = fs_prod + f_riv_loc_si(ji,jj)
+               endif
+               !!  
+               !! benthic remineralisation
+               if (jk.eq.mbathy(ji,jj) .and. jinorgben.eq.1 .and.            &
+                   ibenthic.eq.1) then
+                  fs_prod = fs_prod + (f_benout_si(ji,jj) / fse3t(ji,jj,jk))
+               endif
+               !!
+               btra(ji,jj,jpsil_lc) = b0 * ( &
+                 fs_prod + fs_cons )
+               !! consumption of dissolved silicon
+               fsil_cons(ji,jj) = fsil_cons(ji,jj) + ( fse3t(ji,jj,jk) *     &
+                                                       fs_cons )
+               !! production of dissolved silicon
+               fsil_prod(ji,jj) = fsil_prod(ji,jj) + ( fse3t(ji,jj,jk) *     &
+                                                       fs_prod )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then !!
+               !!----------------------------------------------------------
+               !! dissolved "iron" nutrient
+               btra(ji,jj,jpfer_lc) = b0 * ( (xrfn * btra(ji,jj,jpdin_lc)) +       &
+                                          ffetop(ji,jj) + ffebot(ji,jj) -    &
+                                          ffescav(ji,jj) )
+# if defined key_roam
+               !!
+               !!----------------------------------------------------------
+               !! AXY (26/11/08): implicit detrital carbon change
+               btra(ji,jj,jpdtc_lc) = b0 * (                                    &
+                                            ! mort. losses
+                                         (xthetapn * fdpn(ji,jj)) +          &
+                                         ((1.0 - xfdfrac1) *                 &
+                                          (xthetapd * fdpd(ji,jj))) +        &
+                                         (xthetazmi * fdzmi(ji,jj)) +        &
+                                         ((1.0 - xfdfrac2) *                 &
+                                          (xthetazme * fdzme(ji,jj))) +      &
+                                             ! assim. inefficiency
+                                         ((1.0 - xbetac) *                   &
+                                          (ficmi(ji,jj) + ficme(ji,jj))) -   &
+                                             ! grazing and remin.
+                                         fgmidc(ji,jj) - fgmedc(ji,jj) -     &
+                                         fddc(ji,jj) +                       &
+                                             ! seafloor fast->slow
+                                         ffast2slowc(ji,jj) )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! dissolved inorganic carbon
+               !! primary production
+               fc_cons = - (xthetapn * fprn(ji,jj) * zphn(ji,jj)) -          &
+                           (xthetapd * fprd(ji,jj) * zphd(ji,jj))
+               !!
+               fc_prod =                                                     &
+                            ! messy feeding remin
+                         (xthetapn * xphi * fgmipn(ji,jj)) +                 &
+                         (xphi * fgmidc(ji,jj)) +                            &
+                         (xthetapn * xphi * fgmepn(ji,jj)) +                 &
+                         (xthetapd * xphi * fgmepd(ji,jj)) +                 &
+                         (xthetazmi * xphi * fgmezmi(ji,jj)) +               &
+                         (xphi * fgmedc(ji,jj)) +                            &
+                            ! resp., remin., losses
+                         fmiresp(ji,jj) + fmeresp(ji,jj) + fddc(ji,jj) +     &
+                         freminc(ji,jj) + (xthetapn * fdpn2(ji,jj)) +        &
+                            ! losses
+                         (xthetapd * fdpd2(ji,jj)) +                         &
+                         (xthetazmi * fdzmi2(ji,jj)) +                       &
+                         (xthetazme * fdzme2(ji,jj))
+               !! 
+               !! riverine flux
+               if ( jriver_c .gt. 0 ) then
+                  f_riv_loc_c(ji,jj) = f_riv_c(ji,jj) *                      &
+                                       friver_dep(jk,mbathy(ji,jj)) /        &
+                                       fse3t(ji,jj,jk)
+                  fc_prod = fc_prod + f_riv_loc_c(ji,jj)
+               endif
+               !!  
+               !! benthic remineralisation
+               if (jk.eq.mbathy(ji,jj) .and. jorgben.eq.1 .and.              &
+                   ibenthic.eq.1) then
+                  fc_prod = fc_prod + (f_benout_c(ji,jj) / fse3t(ji,jj,jk))
+               endif
+               if (jk.eq.mbathy(ji,jj) .and. jinorgben.eq.1 .and.            &
+                   ibenthic.eq.1) then
+                  fc_prod = fc_prod + (f_benout_ca(ji,jj) / fse3t(ji,jj,jk))
+               endif
+               !!
+               !! community respiration (does not include CaCO3 terms - 
+               !! obviously!)
+               fcomm_resp(ji,jj) = fcomm_resp(ji,jj) + fc_prod
+               !!
+               !! CaCO3
+               fc_prod = fc_prod - ftempca(ji,jj) + freminca(ji,jj)
+               !! 
+               !! riverine flux
+               if ( jk .eq. 1 .and. jriver_c .gt. 0 ) then
+                  fc_prod = fc_prod + f_riv_c(ji,jj)
+               endif
+               !!
+               btra(ji,jj,jpdic_lc) = b0 * ( fc_prod + fc_cons )
+               !! consumption of dissolved carbon
+               fcar_cons(ji,jj) = fcar_cons(ji,jj) + ( fse3t(ji,jj,jk) *     &
+                                                       fc_cons )
+               !! production of dissolved carbon
+               fcar_prod(ji,jj) = fcar_prod(ji,jj) + ( fse3t(ji,jj,jk) *     &
+                                                       fc_prod )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! alkalinity
+               !! CaCO3 dissolution
+               fa_prod = 2.0 * freminca(ji,jj)
+               !! CaCO3 production
+               fa_cons = - 2.0 * ftempca(ji,jj)
+               !! 
+               !! riverine flux
+               if ( jriver_alk .gt. 0 ) then
+                  f_riv_loc_alk(ji,jj) = f_riv_alk(ji,jj) *                  &
+                                         friver_dep(jk,mbathy(ji,jj)) /      &
+                                         fse3t(ji,jj,jk)
+                  fa_prod = fa_prod + f_riv_loc_alk(ji,jj)
+               endif
+               !!  
+               !! benthic remineralisation
+               if (jk.eq.mbathy(ji,jj) .and. jinorgben.eq.1 .and.            &
+                   ibenthic.eq.1) then
+                  fa_prod = fa_prod + (2.0 * f_benout_ca(ji,jj) /            &
+                                       fse3t(ji,jj,jk))
+               endif
+               !!
+               btra(ji,jj,jpalk_lc) = b0 * ( fa_prod + fa_cons )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !!----------------------------------------------------------
+               !! oxygen (has protection at low O2 concentrations; 
+               !! OCMIP-2 style)
+               fo2_prod(ji,jj) =                                             &
+                                     ! Pn primary production, N
+                                 (xthetanit * fprn(ji,jj) * zphn(ji,jj)) +   &
+                                     ! Pd primary production, N
+                                 (xthetanit * fprd(ji,jj) * zphd(ji,jj)) +   &
+                                     ! Pn primary production, C
+                                 (xthetarem * xthetapn * fprn(ji,jj) *       &
+                                  zphn(ji,jj)) +                             &
+                                     ! Pd primary production, C
+                                  (xthetarem * xthetapd * fprd(ji,jj) *      &
+                                   zphd(ji,jj))
+               fo2_ncons(ji,jj) =                                            &
+                                     ! Pn messy feeding remin., N 
+                                   - (xthetanit * xphi * fgmipn(ji,jj))      &
+                                     ! D  messy feeding remin., N
+                                   - (xthetanit * xphi * fgmid(ji,jj))       &
+                                     ! Pn messy feeding remin., N
+                                   - (xthetanit * xphi * fgmepn(ji,jj))      &
+                                     ! Pd messy feeding remin., N
+                                   - (xthetanit * xphi * fgmepd(ji,jj))      &
+                                     ! Zi messy feeding remin., N
+                                   - (xthetanit * xphi * fgmezmi(ji,jj))     &
+                                     ! D  messy feeding remin., N
+                                   - (xthetanit * xphi * fgmed(ji,jj))       &
+                                     ! microzoo excretion, N
+                                   - (xthetanit * fmiexcr(ji,jj))            &
+                                     ! mesozoo  excretion, N
+                                   - (xthetanit * fmeexcr(ji,jj))            &
+                                     ! slow detritus remin., N
+                                   - (xthetanit * fdd(ji,jj))                &
+                                     ! fast detritus remin., N
+                                   - (xthetanit * freminn(ji,jj))            &
+                                     ! Pn  losses, N
+                                   - (xthetanit * fdpn2(ji,jj))              &
+                                     ! Pd  losses, N
+                                   - (xthetanit * fdpd2(ji,jj))              &
+                                     ! Zmi losses, N
+                                   - (xthetanit * fdzmi2(ji,jj))             &
+                                     ! Zme losses, N
+                                   - (xthetanit * fdzme2(ji,jj))
+               !!  
+               !! benthic remineralisation
+               if (jk.eq.mbathy(ji,jj) .and. jorgben.eq.1 .and.              &
+                   ibenthic.eq.1) then
+                  fo2_ncons(ji,jj) = fo2_ncons(ji,jj) -                      &
+                                     (xthetanit * f_benout_n(ji,jj) /        &
+                                      fse3t(ji,jj,jk))
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               fo2_ccons(ji,jj) =                                            &
+                                     ! Pn messy feeding remin., C
+                                  - (xthetarem * xthetapn * xphi *           &
+                                     fgmipn(ji,jj))                          &
+                                     ! D  messy feeding remin., C
+                                  - (xthetarem * xphi * fgmidc(ji,jj))       &
+                                     ! Pn messy feeding remin., C
+                                  - (xthetarem * xthetapn * xphi *           &
+                                     fgmepn(ji,jj))                          &
+                                     ! Pd messy feeding remin., C
+                                  - (xthetarem * xthetapd * xphi *           &
+                                     fgmepd(ji,jj))                          &
+                                     ! Zi messy feeding remin., C
+                                  - (xthetarem * xthetazmi * xphi *          &
+                                     fgmezmi(ji,jj))                         &
+                                     ! D  messy feeding remin., C
+                                  - (xthetarem * xphi * fgmedc(ji,jj))       &
+                                     ! microzoo respiration, C
+                                  - (xthetarem * fmiresp(ji,jj))             &
+                                     ! mesozoo  respiration, C
+                                  - (xthetarem * fmeresp(ji,jj))             &
+                                     ! slow detritus remin., C
+                                  - (xthetarem * fddc(ji,jj))                &
+                                     ! fast detritus remin., C
+                                  - (xthetarem * freminc(ji,jj))             &
+                                     ! Pn  losses, C
+                                  - (xthetarem * xthetapn * fdpn2(ji,jj))    &
+                                     ! Pd  losses, C
+                                  - (xthetarem * xthetapd * fdpd2(ji,jj))    &
+                                     ! Zmi losses, C
+                                  - (xthetarem * xthetazmi * fdzmi2(ji,jj))  &
+                                     ! Zme losses, C
+                                  - (xthetarem * xthetazme * fdzme2(ji,jj))
+               !!  
+               !! benthic remineralisation
+               if (jk.eq.mbathy(ji,jj) .and. jorgben.eq.1 .and.              &
+                   ibenthic.eq.1) then
+                  fo2_ccons(ji,jj) = fo2_ccons(ji,jj) - (xthetarem *         &
+                                                         f_benout_c(ji,jj) / &
+                                                         fse3t(ji,jj,jk))
+               endif
+               fo2_cons(ji,jj) = fo2_ncons(ji,jj) + fo2_ccons(ji,jj)
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! is this a suboxic zone?
+               !! deficient O2; production fluxes only
+               if (zoxy(ji,jj).lt.xo2min) then
+                  btra(ji,jj,jpoxy_lc) = b0 * fo2_prod(ji,jj)
+                  foxy_prod(ji,jj) = foxy_prod(ji,jj) + ( fse3t(ji,jj,jk) *  &
+                                                          fo2_prod(ji,jj) )
+                  foxy_anox(ji,jj) = foxy_anox(ji,jj) + ( fse3t(ji,jj,jk) *  &
+                                                          fo2_cons(ji,jj) )
+               else
+                  !! sufficient O2; production + consumption fluxes
+                  btra(ji,jj,jpoxy_lc) = b0 * ( fo2_prod(ji,jj) +               &
+                                             fo2_cons(ji,jj) )
+                  foxy_prod(ji,jj) = foxy_prod(ji,jj) +                      &
+                                     ( fse3t(ji,jj,jk) * fo2_prod(ji,jj) )
+                  foxy_cons(ji,jj) = foxy_cons(ji,jj) +                      &
+                                     ( fse3t(ji,jj,jk) * fo2_cons(ji,jj) )
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! air-sea fluxes (if this is the surface box)
+               if (jk.eq.1) then
+                  !!
+                  !! CO2 flux
+                  btra(ji,jj,jpdic_lc) = btra(ji,jj,jpdic_lc) + (b0 *              &
+                                                           f_co2flux(ji,jj))
+                  !!
+                  !! O2 flux (mol/m3/s -> mmol/m3/d)
+                  btra(ji,jj,jpoxy_lc) = btra(ji,jj,jpoxy_lc) + (b0 *              &
+                                                           f_o2flux(ji,jj))
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+# if defined key_debug_medusa
+! I DON'T THIS IS MUCH USE, NOW IT'S BEEN PULLED OUT OF THE MAIN DO LOOP
+! - marc 5/5/17
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !! report state variable fluxes (not including 
+               !! fast-sinking detritus)
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpchn_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpchn_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpchd_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpchd_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpphn_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpphn_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpphd_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpphd_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jppds_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jppds_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpzmi_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpzmi_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpzme_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpzme_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpdet_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpdet_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpdin_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpdin_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpsil_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpsil_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpfer_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpfer_lc)
+#  if defined key_roam
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpdtc_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpdtc_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpdic_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpdic_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpalk_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpalk_lc)
+                  IF (lwp) write (numout,*) 'btra(ji,jj,jpoxy_lc)(',jk,')  = ', &
+                                            btra(ji,jj,jpoxy_lc)
+#  endif
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+# endif
+
+      !!----------------------------------------------------------
+      !! Integrate calculated fluxes for mass balance
+      !!----------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! === nitrogen ===
+               fflx_n(ji,jj)  = fflx_n(ji,jj) + fse3t(ji,jj,jk) *            &
+                                ( btra(ji,jj,jpphn_lc) + btra(ji,jj,jpphd_lc) +    &
+                                  btra(ji,jj,jpzmi_lc) + btra(ji,jj,jpzme_lc) +    &
+                                  btra(ji,jj,jpdet_lc) + btra(ji,jj,jpdin_lc) )
+               !! === silicon ===
+               fflx_si(ji,jj) = fflx_si(ji,jj) + fse3t(ji,jj,jk) *           &
+                                ( btra(ji,jj,jppds_lc) + btra(ji,jj,jpsil_lc) )
+               !! === iron ===
+               fflx_fe(ji,jj) = fflx_fe(ji,jj) + fse3t(ji,jj,jk) *           &
+                                ( (xrfn *                                    &
+                                   (btra(ji,jj,jpphn_lc) + btra(ji,jj,jpphd_lc) +  &
+                                    btra(ji,jj,jpzmi_lc) + btra(ji,jj,jpzme_lc) +  &
+                                    btra(ji,jj,jpdet_lc))) + btra(ji,jj,jpfer_lc) )
+# if defined key_roam
+               !! === carbon ===
+               fflx_c(ji,jj)  = fflx_c(ji,jj) + fse3t(ji,jj,jk) *            &
+                                ( (xthetapn * btra(ji,jj,jpphn_lc)) +           &
+                                  (xthetapd * btra(ji,jj,jpphd_lc)) +           &
+                                  (xthetazmi * btra(ji,jj,jpzmi_lc)) +          &
+                                  (xthetazme * btra(ji,jj,jpzme_lc)) +          &
+                                  btra(ji,jj,jpdtc_lc) + btra(ji,jj,jpdic_lc) )
+               !! === alkalinity ===
+               fflx_a(ji,jj)  = fflx_a(ji,jj) + fse3t(ji,jj,jk) *            &
+                                btra(ji,jj,jpalk_lc)
+               !! === oxygen ===
+               fflx_o2(ji,jj) = fflx_o2(ji,jj) + fse3t(ji,jj,jk) *           &
+                                btra(ji,jj,jpoxy_lc)
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !!----------------------------------------------------------
+      !! Apply calculated tracer fluxes
+      !!----------------------------------------------------------
+      !!
+      !! units: [unit of tracer] per second (fluxes are calculated 
+      !! above per day)
+      !!
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               ibio_switch = 1
+# if defined key_gulf_finland
+               !! AXY (17/05/13): fudge in a Gulf of Finland correction; 
+               !!                 uses longitude-latitude range to 
+               !!                 establish if this is a Gulf of Finland 
+               !!                 grid cell; if so, then BGC fluxes are 
+               !!                 ignored (though still calculated); for 
+               !!                 reference, this is meant to be a 
+               !!                 temporary fix to see if all of my 
+               !!                 problems can be done away with if I 
+               !!                 switch off BGC fluxes in the Gulf of 
+               !!                 Finland, which currently appears the 
+               !!                 source of trouble
+               if ( glamt(ji,jj).gt.24.7 .and. glamt(ji,jj).lt.27.8 .and.    &
+                    gphit(ji,jj).gt.59.2 .and. gphit(ji,jj).lt.60.2 ) then
+                  ibio_switch = 0
+               endif
+# endif               
+               if (ibio_switch.eq.1) then
+                  tra(ji,jj,jk,jpchn) = tra(ji,jj,jk,jpchn) +                &
+                                        (btra(ji,jj,jpchn_lc) / 86400.)
+                  tra(ji,jj,jk,jpchd) = tra(ji,jj,jk,jpchd) +                &
+                                        (btra(ji,jj,jpchd_lc) / 86400.)
+                  tra(ji,jj,jk,jpphn) = tra(ji,jj,jk,jpphn) +                &
+                                        (btra(ji,jj,jpphn_lc) / 86400.)
+                  tra(ji,jj,jk,jpphd) = tra(ji,jj,jk,jpphd) +                &
+                                        (btra(ji,jj,jpphd_lc) / 86400.)
+                  tra(ji,jj,jk,jppds) = tra(ji,jj,jk,jppds) +                &
+                                        (btra(ji,jj,jppds_lc) / 86400.)
+                  tra(ji,jj,jk,jpzmi) = tra(ji,jj,jk,jpzmi) +                &
+                                        (btra(ji,jj,jpzmi_lc) / 86400.)
+                  tra(ji,jj,jk,jpzme) = tra(ji,jj,jk,jpzme) +                &
+                                        (btra(ji,jj,jpzme_lc) / 86400.)
+                  tra(ji,jj,jk,jpdet) = tra(ji,jj,jk,jpdet) +                &
+                                        (btra(ji,jj,jpdet_lc) / 86400.)
+                  tra(ji,jj,jk,jpdin) = tra(ji,jj,jk,jpdin) +                &
+                                        (btra(ji,jj,jpdin_lc) / 86400.)
+                  tra(ji,jj,jk,jpsil) = tra(ji,jj,jk,jpsil) +                &
+                                        (btra(ji,jj,jpsil_lc) / 86400.)
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) +                &
+                                        (btra(ji,jj,jpfer_lc) / 86400.)
+# if defined key_roam
+                  tra(ji,jj,jk,jpdtc) = tra(ji,jj,jk,jpdtc) +                &
+                                        (btra(ji,jj,jpdtc_lc) / 86400.)
+                  tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) +                &
+                                        (btra(ji,jj,jpdic_lc) / 86400.)
+                  tra(ji,jj,jk,jpalk) = tra(ji,jj,jk,jpalk) +                &
+                                        (btra(ji,jj,jpalk_lc) / 86400.)
+                  tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) +                &
+                                        (btra(ji,jj,jpoxy_lc) / 86400.)
+# endif
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+
+               !! AXY (18/11/16): CMIP6 diagnostics
+               IF( med_diag%FBDDTALK%dgsave )  THEN
+                  fbddtalk(ji,jj)  =  fbddtalk(ji,jj)  +                     &
+                                      (btra(ji,jj,jpalk_lc) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FBDDTDIC%dgsave )  THEN
+                  fbddtdic(ji,jj)  =  fbddtdic(ji,jj)  +                     &
+                                      (btra(ji,jj,jpdic_lc) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FBDDTDIFE%dgsave ) THEN
+                  fbddtdife(ji,jj) =  fbddtdife(ji,jj) +                     &
+                                      (btra(ji,jj,jpfer_lc) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FBDDTDIN%dgsave )  THEN
+                  fbddtdin(ji,jj)  =  fbddtdin(ji,jj)  +                     &
+                                      (btra(ji,jj,jpdin_lc) * fse3t(ji,jj,jk))
+               ENDIF
+               IF( med_diag%FBDDTDISI%dgsave ) THEN
+                  fbddtdisi(ji,jj) =  fbddtdisi(ji,jj) +                     &
+                                      (btra(ji,jj,jpsil_lc) * fse3t(ji,jj,jk))
+               ENDIF
+	       !!
+               IF( med_diag%BDDTALK3%dgsave )  THEN
+                  bddtalk3(ji,jj,jk)  =  btra(ji,jj,jpalk_lc)
+               ENDIF
+               IF( med_diag%BDDTDIC3%dgsave )  THEN
+                  bddtdic3(ji,jj,jk)  =  btra(ji,jj,jpdic_lc)
+               ENDIF
+               IF( med_diag%BDDTDIFE3%dgsave ) THEN
+                  bddtdife3(ji,jj,jk) =  btra(ji,jj,jpfer_lc)
+               ENDIF
+               IF( med_diag%BDDTDIN3%dgsave )  THEN
+                  bddtdin3(ji,jj,jk)  =  btra(ji,jj,jpdin_lc)
+               ENDIF
+               IF( med_diag%BDDTDISI3%dgsave ) THEN
+                  bddtdisi3(ji,jj,jk) =  btra(ji,jj,jpsil_lc)
+               ENDIF
+            ENDIF
+         ENDDO
+      ENDDO
+
+#   if defined key_debug_medusa
+      IF (lwp) write (numout,*) '------'
+      IF (lwp) write (numout,*) 'bio_medusa_update: end all calculations'
+      IF (lwp) write (numout,*) 'bio_medusa_update: now outputs kt = ', kt
+      CALL flush(numout)
+#   endif
+
+# if defined key_axy_nancheck
+      !!----------------------------------------------------------
+      !! Check calculated tracer fluxes
+      !!----------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               DO jn = 1,jp_medusa
+                  fq0 = btra(ji,jj,jn)
+                  !! AXY (30/01/14): "isnan" problem on HECTOR
+                  !! if (fq0 /= fq0 ) then
+                  if ( ieee_is_nan( fq0 ) ) then
+                     !! there's a NaN here
+                     if (lwp) write(numout,*) 'NAN detected in btra(ji,jj,',  &
+                        ji, ',', jj, ',', jk, ',', jn, ') at time', kt
+		     CALL ctl_stop( 'trcbio_medusa, NAN in btra field' )
+                  endif
+               ENDDO
+               DO jn = jp_msa0,jp_msa1
+                  fq0 = tra(ji,jj,jk,jn)
+                  !! AXY (30/01/14): "isnan" problem on HECTOR
+                  !! if (fq0 /= fq0 ) then
+                  if ( ieee_is_nan( fq0 ) ) then
+                     !! there's a NaN here
+                     if (lwp) write(numout,*) 'NAN detected in tra(', ji, &
+                        ',', jj, ',', jk, ',', jn, ') at time', kt
+   		     CALL ctl_stop( 'trcbio_medusa, NAN in tra field' )
+                  endif
+               ENDDO
+               CALL flush(numout)
+            ENDIF
+         ENDDO
+      ENDDO
+# endif
+
+
+   END SUBROUTINE bio_medusa_update
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE bio_medusa_update( )                    ! Empty routine
+      WRITE(*,*) 'bio_medusa_update: You should not have seen this print! error?'
+   END SUBROUTINE bio_medusa_update
+#endif 
+
+   !!======================================================================
+END MODULE bio_medusa_update_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/carb_chem.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/carb_chem.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/carb_chem.F90	(revision 9987)
@@ -0,0 +1,268 @@
+MODULE carb_chem_mod
+   !!======================================================================
+   !!                         ***  MODULE carb_chem_mod  ***
+   !! Calculate the carbon chemistry for the whole ocean
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_roam
+   !!----------------------------------------------------------------------
+   !!                                                   key_roam?
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   carb_chem        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE carb_chem( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE carb_chem  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - ...
+      !!----------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: f_co2flux, f_co3, f_dcf,               &
+                                   f_h2co3, f_hco3, f_henry,              &
+                                   f_kw660, f_omarg, f_omcal,             &
+                                   f_pco2atm, f_pco2w, f_ph, f_pp0,       &
+                                   f_TALK, f_TDIC, f_xco2a,               &
+# if defined key_mocsy
+                                   zpho,                                  &
+# endif
+                                   zalk, zdic, zsal, zsil, ztmp 
+      USE dom_oce,           ONLY: gdept_0, gdept_n, gdepw_0, gdepw_n,    &
+                                   gphit, mbathy, tmask
+      USE in_out_manager,    ONLY: lwp, numout
+      USE oce,               ONLY: PCO2a_in_cpl, tsb, tsn
+      USE par_kind,          ONLY: wp
+      USE par_medusa,        ONLY: jpalk, jpdic, jpdin, jpsil 
+      USE par_oce,           ONLY: jp_sal, jp_tem, jpi, jpim1, jpj,       &
+                                   jpjm1, jpk
+      USE sbc_oce,           ONLY: lk_oasis
+      USE sms_medusa,        ONLY: f2_ccd_arg, f2_ccd_cal, f3_co3,        &
+                                   f3_h2co3, f3_hco3, f3_omarg,           &
+                                   f3_omcal, f3_pH
+      USE trc,               ONLY: trn
+
+# if defined key_mocsy
+      USE mocsy_wrapper,     ONLY: mocsy_interface
+# else
+      USE trcco2_medusa,     ONLY: trc_co2_medusa
+# endif
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+ 
+      !! time (integer timestep)
+      INTEGER, INTENT( in ) ::    kt
+
+      !! Flags to help with calculating the position of the CCD
+      INTEGER, DIMENSION(jpi,jpj) ::     i2_omcal,i2_omarg
+
+      !! AXY (23/06/15): additional diagnostics for MOCSY and oxygen
+      REAL(wp) :: f_rhosw
+      !! Output arguments from mocsy_interface, which aren't used
+      REAL(wp) :: f_fco2w_dum, f_BetaD_dum, f_opres_dum
+      REAL(wp) :: f_insitut_dum, f_fco2atm_dum
+      REAL(wp) :: f_schmidtco2_dum, f_kwco2_dum, f_K0_dum
+      REAL(wp) :: f_co2starair_dum, f_dpco2_dum
+      !! temporary variables
+      REAL(wp) ::    fq0,fq1,fq2,fq3,fq4
+
+      INTEGER :: iters
+      !! Loop variables
+      INTEGER :: ji, jj, jk
+
+      !!----------------------------------------------------------------------
+      !! Calculate the carbonate chemistry for the whole ocean on the first
+      !! simulation timestep and every month subsequently; the resulting 3D
+      !! field of omega calcite is used to determine the depth of the CCD
+      !!----------------------------------------------------------------------
+      !!
+!      IF(lwp) WRITE(numout,*)                                               &
+!              ' MEDUSA calculating all carbonate chemistry at kt =', kt
+!         CALL flush(numout)
+      !! blank flags
+      i2_omcal(:,:) = 0
+      i2_omarg(:,:) = 0
+
+      !! Loop over levels
+      DO jk = 1,jpk
+
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               !! OPEN wet point IF..THEN loop
+               IF (tmask(ji,jj,jk).eq.1) THEN
+                  IF (lk_oasis) THEN
+                     !! use 2D atm xCO2 from atm coupling
+                     f_xco2a(ji,jj) = PCO2a_in_cpl(ji,jj)
+                  ENDIF
+                  !! Do carbonate chemistry
+                  !!
+                  !! Set up required state variables.
+                  !! dissolved inorganic carbon
+                  zdic(ji,jj) = max(0.,trn(ji,jj,jk,jpdic))
+                  !! alkalinity
+                  zalk(ji,jj) = max(0.,trn(ji,jj,jk,jpalk))
+                  !! temperature
+                  ztmp(ji,jj) = tsn(ji,jj,jk,jp_tem)
+                  !! salinity
+                  zsal(ji,jj) = tsn(ji,jj,jk,jp_sal)
+#  if defined key_mocsy
+                  !! silicic acid
+                  zsil(ji,jj) = max(0.,trn(ji,jj,jk,jpsil))
+                  !! phosphate via DIN and Redfield
+                  zpho(ji,jj) = max(0.,trn(ji,jj,jk,jpdin)) / 16.0 
+#  endif
+		  !!
+		  !! AXY (28/02/14): check input fields
+		  if (ztmp(ji,jj) .lt. -3.0 .or. ztmp(ji,jj) .gt. 40.0 ) then
+                     IF (lwp) WRITE(numout,*) ' carb_chem: T WARNING 3D, ',  &
+                        tsb(ji,jj,jk,jp_tem), tsn(ji,jj,jk,jp_tem),          &
+                        ' at (', ji, ',', jj, ',', jk, ') at time', kt
+	             IF(lwp) WRITE(numout,*)                                 &
+                        ' carb_chem: T SWITCHING 3D, ',                      &
+			tsn(ji,jj,jk,jp_tem), ' -> ', tsb(ji,jj,jk,jp_tem)
+                     ztmp(ji,jj) = tsb(ji,jj,jk,jp_tem)     !! temperature
+                  endif
+		  if (zsal(ji,jj) .lt. 0.0 .or. zsal(ji,jj) .gt. 45.0 ) then
+                     IF (lwp) WRITE(numout,*) ' carb_chem: S WARNING 3D, ',  &
+                        tsb(ji,jj,jk,jp_sal), tsn(ji,jj,jk,jp_sal),          &
+                        ' at (', ji, ',', jj, ',', jk, ') at time', kt
+                  endif
+               ENDIF
+            ENDDO
+         ENDDO
+
+         !! Blank input variables not used at this stage (they 
+         !! relate to air-sea flux)
+         f_kw660(:,:) = 1.0
+         f_pp0(:,:)   = 1.0
+
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk).eq.1) THEN
+                  !! calculate carbonate chemistry at grid cell midpoint
+#  if defined key_mocsy
+                  !! AXY (22/06/15): use Orr & Epitalon (2015) MOCSY-2 carbonate
+                  !!                 chemistry package
+                  CALL mocsy_interface(ztmp(ji,jj),zsal(ji,jj),zalk(ji,jj), &
+                                       zdic(ji,jj),zsil(ji,jj),zpho(ji,jj), &
+                                       f_pp0(ji,jj),fsdept(ji,jj,jk),       &
+                                       gphit(ji,jj),f_kw660(ji,jj),         &
+                                       f_xco2a(ji,jj),1,f_ph(ji,jj),        &
+                                       f_pco2w(ji,jj),f_fco2w_dum,          &
+                                       f_h2co3(ji,jj),f_hco3(ji,jj),        &
+                                       f_co3(ji,jj),f_omarg(ji,jj),         &
+                                       f_omcal(ji,jj),f_BetaD_dum,          &
+                                       f_rhosw,f_opres_dum,                 &
+                                       f_insitut_dum,f_pco2atm(ji,jj),      &
+                                       f_fco2atm_dum,f_schmidtco2_dum,      &
+                                       f_kwco2_dum,f_K0_dum,                &
+                                       f_co2starair_dum,f_co2flux(ji,jj),   & 
+                                       f_dpco2_dum)
+                  !!
+                  !! mmol / m3 -> umol / kg
+                  f_TDIC(ji,jj) = (zdic(ji,jj) / f_rhosw) * 1000.
+                  !! meq / m3 -> ueq / kg
+                  f_TALK(ji,jj) = (zalk(ji,jj) / f_rhosw) * 1000.
+                  f_dcf(ji,jj)  = f_rhosw
+#  else
+                  !! AXY (22/06/15): use old PML carbonate chemistry 
+                  !! package (the MEDUSA-2 default)
+                  CALL trc_co2_medusa(ztmp(ji,jj),zsal(ji,jj),zdic(ji,jj),  &
+                                      zalk(ji,jj),fsdept(ji,jj,jk),         &
+                                      f_kw660(ji,jj),f_xco2a(ji,jj),        &
+                                      f_ph(ji,jj),                          &
+                                      f_pco2w(ji,jj),f_h2co3(ji,jj),        &
+                                      f_hco3(ji,jj),f_co3(ji,jj),           &
+                                      f_omcal(ji,jj),f_omarg(ji,jj),        &
+                                      f_co2flux(ji,jj),f_TDIC(ji,jj),       &
+                                      f_TALK(ji,jj),f_dcf(ji,jj),           &
+                                      f_henry(ji,jj),iters)
+                  !! 
+                  !! AXY (28/02/14): check output fields
+                  IF (iters .eq. 25) THEN
+                     IF(lwp) WRITE(numout,*)                                &
+                        ' carb_chem: 3D ITERS WARNING, ', iters, ' AT (',   &
+                        ji, ', ', jj, ', ', jk, ') AT ', kt
+                  ENDIF
+#  endif
+                  !!
+                  !! store 3D outputs
+                  f3_pH(ji,jj,jk)    = f_ph(ji,jj)
+                  f3_h2co3(ji,jj,jk) = f_h2co3(ji,jj)
+                  f3_hco3(ji,jj,jk)  = f_hco3(ji,jj)
+                  f3_co3(ji,jj,jk)   = f_co3(ji,jj)
+                  f3_omcal(ji,jj,jk) = f_omcal(ji,jj)
+                  f3_omarg(ji,jj,jk) = f_omarg(ji,jj)
+                  !!
+                  !! CCD calculation: calcite
+                  if (i2_omcal(ji,jj) == 0 .and. f_omcal(ji,jj) < 1.0) then
+                     if (jk .eq. 1) then
+                        f2_ccd_cal(ji,jj) = fsdept(ji,jj,jk)
+                     else
+                        fq0 = f3_omcal(ji,jj,jk-1) - f_omcal(ji,jj)
+                        fq1 = f3_omcal(ji,jj,jk-1) - 1.0
+                        fq2 = fq1 / (fq0 + tiny(fq0))
+                        fq3 = fsdept(ji,jj,jk) - fsdept(ji,jj,jk-1)
+                        fq4 = fq2 * fq3
+                        f2_ccd_cal(ji,jj) = fsdept(ji,jj,jk-1) + fq4
+                     endif
+                     i2_omcal(ji,jj)   = 1
+                  endif
+                  if ( i2_omcal(ji,jj) == 0 .and. jk == mbathy(ji,jj) ) then
+                     !! reached seafloor and still no dissolution; set 
+                     !! to seafloor (W-point)
+                     f2_ccd_cal(ji,jj) = fsdepw(ji,jj,jk+1)
+                     i2_omcal(ji,jj)   = 1
+                  endif
+                  !!
+                  !! CCD calculation: aragonite
+                  if (i2_omarg(ji,jj) == 0 .and. f_omarg(ji,jj) < 1.0) then
+                     if (jk .eq. 1) then
+                        f2_ccd_arg(ji,jj) = fsdept(ji,jj,jk)
+                     else
+                        fq0 = f3_omarg(ji,jj,jk-1) - f_omarg(ji,jj)
+                        fq1 = f3_omarg(ji,jj,jk-1) - 1.0
+                        fq2 = fq1 / (fq0 + tiny(fq0))
+                        fq3 = fsdept(ji,jj,jk) - fsdept(ji,jj,jk-1)
+                        fq4 = fq2 * fq3
+                        f2_ccd_arg(ji,jj) = fsdept(ji,jj,jk-1) + fq4
+                     endif
+                     i2_omarg(ji,jj)   = 1
+                  endif
+                  if ( i2_omarg(ji,jj) == 0 .and. jk == mbathy(ji,jj) ) then
+                     !! reached seafloor and still no dissolution; set 
+                     !! to seafloor (W-point)
+                     f2_ccd_arg(ji,jj) = fsdepw(ji,jj,jk+1)
+                     i2_omarg(ji,jj)   = 1
+                  endif
+               ENDIF
+            ENDDO
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE carb_chem
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   None key_roam?
+   !!======================================================================
+CONTAINS
+   SUBROUTINE carb_chem( )                    ! Empty routine
+      WRITE(*,*) 'carb_chem: You should not have seen this print! error?'
+   END SUBROUTINE carb_chem
+#endif 
+
+   !!======================================================================
+END MODULE carb_chem_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/detritus.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/detritus.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/detritus.F90	(revision 9987)
@@ -0,0 +1,165 @@
+MODULE detritus_mod
+   !!======================================================================
+   !!                         ***  MODULE detritus_mod  ***
+   !! Calculates detritus processes and fast-sinking detritus
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   detritus        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE detritus( jk, iball  )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE detritus  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - Calculates detritus processes
+      !!  - Fast-sinking detritus 
+      !!-------------------------------------------------------------------
+      USE bio_medusa_mod,         ONLY: f_sbenin_c, f_sbenin_fe,           &
+                                        f_sbenin_n, fdd,                   &
+                                        idf, idfval,                       &   
+# if defined key_roam
+                                        fddc,                              &
+# endif
+                                        fun_T, fun_Q10, zdet, zdtc
+      USE detritus_fast_sink_mod, ONLY: detritus_fast_sink
+      USE dom_oce,                ONLY: mbathy, tmask
+      USE in_out_manager,         ONLY: lwp, numout
+      USE par_oce,                ONLY: jpim1, jpjm1
+      USE sms_medusa,             ONLY: jmd, jorgben, jsfd, vsed,          &
+                                        xrfn, xmd, xmdc, xthetad
+
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+      !! Fast detritus ballast scheme (0 = no; 1 = yes)
+      INTEGER, INTENT( in ) :: iball
+
+      INTEGER :: ji, jj
+
+      !!------------------------------------------------------------------
+      !! Detritus remineralisation
+      !! Constant or temperature-dependent
+      !!------------------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               if (jmd.eq.1) then
+                  !! temperature-dependent
+                  fdd(ji,jj)  = xmd  * fun_T(ji,jj) * zdet(ji,jj)
+# if defined key_roam
+                  fddc(ji,jj) = xmdc * fun_T(ji,jj) * zdtc(ji,jj)
+# endif
+               elseif (jmd.eq.2) then
+                  !! AXY (16/05/13): add in Q10-based parameterisation 
+                  !! (def in nmlst)
+                  !! temperature-dependent
+                  fdd(ji,jj)  = xmd  * fun_Q10(ji,jj) * zdet(ji,jj)
+#if defined key_roam
+                  fddc(ji,jj) = xmdc * fun_Q10(ji,jj) * zdtc(ji,jj)
+#endif
+               else
+                  !! temperature-independent
+                  fdd(ji,jj)  = xmd  * zdet(ji,jj)
+# if defined key_roam
+                  fddc(ji,jj) = xmdc * zdtc(ji,jj)
+# endif
+               endif
+               !!
+               !! AXY (22/07/09): accelerate detrital remineralisation 
+               !! in the bottom box
+               if ((jk.eq.mbathy(ji,jj)) .and. jsfd.eq.1) then
+                  fdd(ji,jj)  = 1.0  * zdet(ji,jj)
+# if defined key_roam
+                  fddc(ji,jj) = 1.0  * zdtc(ji,jj)
+# endif
+               endif
+               
+# if defined key_debug_medusa
+               !! report plankton mortality and remineralisation
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+! I've removed the lines below, because the variables are not in this
+! routine. If these debug prints need to stay, they should probably be
+! moved - marc 27/4/17
+!                  IF (lwp) write (numout,*) 'fdpn2(',jk,') = ', fdpn2(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdpd2(',jk,') = ', fdpd2(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdpds2(',jk,')= ', fdpds2(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdzmi2(',jk,')= ', fdzmi2(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdzme2(',jk,')= ', fdzme2(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdpn(',jk,')  = ', fdpn(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdpd(',jk,')  = ', fdpd(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdpds(',jk,') = ', fdpds(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdzmi(',jk,') = ', fdzmi(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdzme(',jk,') = ', fdzme(ji,jj)
+                  IF (lwp) write (numout,*) 'fdd(',jk,')   = ', fdd(ji,jj)
+#  if defined key_roam
+                  IF (lwp) write (numout,*) 'fddc(',jk,')  = ', fddc(ji,jj)
+#  endif
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!---------------------------------------------------------
+               !! Detritus addition to benthos
+               !! If activated, slow detritus in the bottom box will enter
+               !! the benthic pool
+               !!---------------------------------------------------------
+               !!
+               if ((jk.eq.mbathy(ji,jj)) .and. jorgben.eq.1) then
+                  !! this is the BOTTOM OCEAN BOX -> into the benthic pool!
+                  !!
+                  f_sbenin_n(ji,jj)  = (zdet(ji,jj) * vsed * 86400.)
+                  f_sbenin_fe(ji,jj) = (zdet(ji,jj) * vsed * 86400. * xrfn)
+# if defined key_roam
+                  f_sbenin_c(ji,jj)  = (zdtc(ji,jj) * vsed * 86400.)
+# else
+                  f_sbenin_c(ji,jj)  = (zdet(ji,jj) * vsed * 86400. * xthetad)
+# endif
+               endif
+
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !!------------------------------------------------------------------
+      !! Fast-sinking detritus
+      !!------------------------------------------------------------------
+      CALL detritus_fast_sink( jk, iball )
+
+   END SUBROUTINE detritus
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE detritus( )                    ! Empty routine
+      WRITE(*,*) 'detritus: You should not have seen this print! error?'
+   END SUBROUTINE detritus
+#endif 
+
+   !!======================================================================
+END MODULE detritus_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/detritus_fast_sink.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/detritus_fast_sink.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/detritus_fast_sink.F90	(revision 9987)
@@ -0,0 +1,973 @@
+MODULE detritus_fast_sink_mod
+   !!======================================================================
+   !!                         ***  MODULE detritus_fast_sink_mod  ***
+   !! Calculates fast-sinking detritus
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   detritus_fast_sink        ! Called in detritus.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE detritus_fast_sink( jk, iball )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE detritus_fast_sink  ***
+      !! This called from DETRITUS and calculates the fast-sinking detritus 
+      !!-------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: b0,                                     &
+                                   f_benout_c, f_benout_ca, f_benout_fe,   &
+                                   f_benout_lyso_ca, f_benout_n,           &
+                                   f_benout_si,                            &
+                                   f_fbenin_c, f_fbenin_ca, f_fbenin_fe,   &
+                                   f_fbenin_n, f_fbenin_si, f_omcal,       &
+                                   fccd, fdep1, fdd,                       &
+                                   fdpd, fdpd2, fdpds, fdpds2,             &
+                                   fdpn, fdpn2,                            &
+                                   fdzme, fdzme2, fdzmi, fdzmi2,           &
+                                   ffast2slowc, ffast2slown,               &
+                                   ffastc, ffastca, ffastfe, ffastn,       &
+                                   ffastsi,                                &
+                                   fgmed, fgmepd, fgmepds, fgmepn,         &
+                                   fgmezmi,                                &
+                                   fgmid, fgmipn,                          &
+                                   ficme, ficmi,                           &
+                                   fifd_fe, fifd_n, fifd_si,               &
+                                   finme, finmi,                           &
+                                   fmeexcr, fmiexcr,                       &
+                                   fofd_fe, fofd_n, fofd_si,               &
+                                   fregen, fregenfast, fregenfastsi,       &
+                                   fregensi,                               &
+                                   freminc, freminca, freminfe,            &
+                                   freminn, freminsi,                      &
+                                   fsdiss,                                 &
+                                   fsedc, fsedca, fsedn, fsedfe, fsedsi,   &
+                                   fslowc, fslowcflux,                     &
+                                   fslown, fslownflux,                     &
+                                   ftempc, ftempca, ftempfe, ftempn,       &
+                                   ftempsi,                                &
+# if defined key_roam
+                                   fifd_c, fofd_c, fregenfastc,            &
+# endif
+                                   idf, idfval,                            &
+                                   zdet, zdtc
+      USE dom_oce,           ONLY: e3t_0, e3t_n, gdepw_0, gdepw_n,         &
+                                   gphit, mbathy, tmask
+      USE in_out_manager,    ONLY: lwp, numout
+      USE oce,               ONLY: tsn
+      USE par_kind,          ONLY: wp
+      USE par_oce,           ONLY: jpi, jpim1, jpj, jpjm1
+      USE sms_medusa,        ONLY: f2_ccd_cal, f3_omcal,                   &
+                                   jexport, jfdfate, jinorgben, jocalccd,  &
+                                   jorgben, jp_tem, jrratio,               &
+                                   ocal_ccd, vsed,                         &
+                                   xbetac, xbetan,                         &
+                                   xcaco3a, xcaco3b,                       &
+                                   xfastc, xfastca, xfastsi,               &
+                                   xfdfrac1, xfdfrac2, xfdfrac3,           &
+                                   xmassc, xmassca, xmasssi,               &
+                                   xphi, xprotca, xprotsi,                 &
+                                   xrfn, xridg_r0,                         &
+                                   xsedc, xsedca, xsedfe,xsedn, xsedsi,    &
+                                   xthetapd, xthetapn,                     &
+                                   xthetazme, xthetazmi,                   &
+                                   zn_sed_c, zn_sed_ca, zn_sed_fe,         &
+                                   zn_sed_n, zn_sed_si
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+      !! Fast detritus ballast scheme (0 = no; 1 = yes)
+      INTEGER, INTENT( in ) :: iball
+
+      !! Loop variables
+      INTEGER :: ji, jj
+
+      REAL(wp) :: fb_val, fl_sst
+      !! Particle flux
+      REAL(wp) :: fcaco3
+      REAL(wp) :: fprotf
+      REAL(wp), DIMENSION(jpi,jpj) :: fccd_dep
+      !! temporary variables
+      REAL(wp) :: fq0,fq1,fq2,fq3,fq4,fq5,fq6,fq7,fq8
+
+      !! The two sections below, slow detritus creation and Nutrient 
+      !! regeneration are moved from just above the CALL to DETRITUS
+      !! in trcbio_medusa.F90.
+      !!---------------------------------------------------------
+      !! Slow detritus creation
+      !!---------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!
+               !! this variable integrates the creation of slow sinking 
+               !! detritus to allow the split between fast and slow 
+               !! detritus to be diagnosed
+               fslown(ji,jj)  = fdpn(ji,jj) + fdzmi(ji,jj) +                 &
+                                ((1.0 - xfdfrac1) * fdpd(ji,jj)) +           &
+                                ((1.0 - xfdfrac2) * fdzme(ji,jj)) +          &
+                                ((1.0 - xbetan) *                            &
+                                 (finmi(ji,jj) + finme(ji,jj)))
+               !!
+               !! this variable records the slow detrital sinking flux at 
+               !! this particular depth; it is used in the output of this 
+               !! flux at standard depths in the diagnostic outputs; 
+               !! needs to be adjusted from per second to per day because 
+               !! of parameter vsed
+               fslownflux(ji,jj) = zdet(ji,jj) * vsed * 86400.
+# if defined key_roam
+               !!
+               !! and the same for detrital carbon
+               fslowc(ji,jj)  = (xthetapn * fdpn(ji,jj)) +                   &
+                                (xthetazmi * fdzmi(ji,jj)) +                 &
+                                (xthetapd * (1.0 - xfdfrac1) *               &
+                                 fdpd(ji,jj)) +                              &
+                                (xthetazme * (1.0 - xfdfrac2) *              &
+                                 fdzme(ji,jj)) +                             &
+                                ((1.0 - xbetac) * (ficmi(ji,jj) +            &
+                                                   ficme(ji,jj)))
+               !!
+               !! this variable records the slow detrital sinking flux 
+               !! at this particular depth; it is used in the output of 
+               !! this flux at standard depths in the diagnostic 
+               !! outputs; needs to be adjusted from per second to per 
+               !! day because of parameter vsed
+               fslowcflux(ji,jj) = zdtc(ji,jj) * vsed * 86400.
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !!---------------------------------------------------------
+      !! Nutrient regeneration
+      !! this variable integrates total nitrogen regeneration down the
+      !! watercolumn; its value is stored and output as a 2D diagnostic;
+      !! the corresponding dissolution flux of silicon (from sources
+      !! other than fast detritus) is also integrated; note that,
+      !! confusingly, the linear loss terms from plankton compartments
+      !! are labelled as fdX2 when one might have expected fdX or fdX1
+      !!---------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !!
+               !! nitrogen
+               fregen(ji,jj) =                                             &
+                                     ! messy feeding
+                               (((xphi * (fgmipn(ji,jj) + fgmid(ji,jj))) + &
+                                 (xphi *                                   &
+                                  (fgmepn(ji,jj) + fgmepd(ji,jj) +         &
+                                   fgmezmi(ji,jj) + fgmed(ji,jj))) +       &
+                                     ! excretion + D remin.
+                                 fmiexcr(ji,jj) + fmeexcr(ji,jj) +         &
+                                 fdd(ji,jj) +                              &
+                                     ! linear mortality
+                                 fdpn2(ji,jj) + fdpd2(ji,jj) +             &
+                                 fdzmi2(ji,jj) + fdzme2(ji,jj)) *          &
+                                fse3t(ji,jj,jk))
+               !!
+               !! silicon
+               fregensi(ji,jj) =                                           &
+                                     ! dissolution + non-lin. mortality
+                                 ((fsdiss(ji,jj) +                         &
+                                   ((1.0 - xfdfrac1) * fdpds(ji,jj)) +     &
+                                     ! egestion by zooplankton
+                                   ((1.0 - xfdfrac3) * fgmepds(ji,jj)) +   &
+                                     ! linear mortality
+                                   fdpds2(ji,jj)) * fse3t(ji,jj,jk))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !!-------------------------------------------------------------------
+      !! Fast-sinking detritus terms
+      !! "local" variables declared so that conservation can be checked;
+      !! the calculated terms are added to the fast-sinking flux later on
+      !! only after the flux entering this level has experienced some
+      !! remineralisation
+      !! note: these fluxes need to be scaled by the level thickness
+      !!-------------------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+
+               !! nitrogen:   diatom and mesozooplankton mortality
+               ftempn(ji,jj)  = b0 * ((xfdfrac1 * fdpd(ji,jj))  +            &
+                                      (xfdfrac2 * fdzme(ji,jj)))
+               !!
+               !! silicon:    diatom mortality and grazed diatoms
+               ftempsi(ji,jj) = b0 * ((xfdfrac1 * fdpds(ji,jj)) +            &
+                                      (xfdfrac3 * fgmepds(ji,jj)))
+               !!
+               !! iron:       diatom and mesozooplankton mortality
+               ftempfe(ji,jj) = b0 * (((xfdfrac1 * fdpd(ji,jj)) +            &
+                                       (xfdfrac2 * fdzme(ji,jj))) * xrfn)
+               !!
+               !! carbon:     diatom and mesozooplankton mortality
+               ftempc(ji,jj)  = b0 * ((xfdfrac1 * xthetapd * fdpd(ji,jj)) +  & 
+                                      (xfdfrac2 * xthetazme * fdzme(ji,jj)))
+               !!
+            ENDIF
+         ENDDO
+      ENDDO
+
+# if defined key_roam
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               if (jrratio.eq.0) then
+                  !! CaCO3:      latitudinally-based fraction of total 
+                  !!             primary production
+                  !!               0.10 at equator; 0.02 at pole
+                  fcaco3 = xcaco3a + ((xcaco3b - xcaco3a) *                  &
+                                      ((90.0 - abs(gphit(ji,jj))) / 90.0))
+               elseif (jrratio.eq.1) then
+                  !! CaCO3:      Ridgwell et al. (2007) submodel, version 1
+                  !!             this uses SURFACE omega calcite to regulate 
+                  !!             rain ratio
+                  if (f_omcal(ji,jj).ge.1.0) then
+                     fq1 = (f_omcal(ji,jj) - 1.0)**0.81
+                  else
+                     fq1 = 0.
+                  endif
+                  fcaco3 = xridg_r0 * fq1
+               elseif (jrratio.eq.2) then
+                  !! CaCO3:      Ridgwell et al. (2007) submodel, version 2
+                  !!             this uses FULL 3D omega calcite to regulate
+                  !!             rain ratio
+                  if (f3_omcal(ji,jj,jk).ge.1.0) then
+                     fq1 = (f3_omcal(ji,jj,jk) - 1.0)**0.81
+                  else
+                     fq1 = 0.
+                  endif
+                  fcaco3 = xridg_r0 * fq1
+               endif
+# else
+               !! CaCO3:      latitudinally-based fraction of total primary
+               !!              production
+               !!               0.10 at equator; 0.02 at pole
+               fcaco3 = xcaco3a + ((xcaco3b - xcaco3a) *                      &
+                                   ((90.0 - abs(gphit(ji,jj))) / 90.0))
+# endif
+               !! AXY (09/03/09): convert CaCO3 production from function of 
+               !! primary production into a function of fast-sinking material; 
+               !! technically, this is what Dunne et al. (2007) do anyway; they 
+               !! convert total primary production estimated from surface 
+               !! chlorophyll to an export flux for which they apply conversion 
+               !! factors to estimate the various elemental fractions (Si, Ca)
+               ftempca(ji,jj) = ftempc(ji,jj) * fcaco3
+
+# if defined key_debug_medusa
+               !! integrate total fast detritus production
+               if (idf.eq.1) then
+                  fifd_n(ji,jj)  = fifd_n(ji,jj)  + (ftempn(ji,jj)  *         &
+                                                     fse3t(ji,jj,jk))
+                  fifd_si(ji,jj) = fifd_si(ji,jj) + (ftempsi(ji,jj) *         &
+                                                     fse3t(ji,jj,jk))
+                  fifd_fe(ji,jj) = fifd_fe(ji,jj) + (ftempfe(ji,jj) *         &
+                                                     fse3t(ji,jj,jk))
+#  if defined key_roam
+                  fifd_c(ji,jj)  = fifd_c(ji,jj)  + (ftempc(ji,jj)  *         &
+                                                     fse3t(ji,jj,jk))
+#  endif
+               endif
+
+               !! report quantities of fast-sinking detritus for each component
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+! These variables are not in this routine - marc 28/4/17
+!                  IF (lwp) write (numout,*) 'fdpd(',jk,')    = ', fdpd(ji,jj)
+!                  IF (lwp) write (numout,*) 'fdzme(',jk,')   = ', fdzme(ji,jj)
+                  IF (lwp) write (numout,*) 'ftempn(',jk,')  = ', ftempn(ji,jj)
+                  IF (lwp) write (numout,*) 'ftempsi(',jk,') = ', ftempsi(ji,jj)
+                  IF (lwp) write (numout,*) 'ftempfe(',jk,') = ', ftempfe(ji,jj)
+                  IF (lwp) write (numout,*) 'ftempc(',jk,')  = ', ftempc(ji,jj)
+                  IF (lwp) write (numout,*) 'ftempca(',jk,') = ', ftempca(ji,jj)
+                  IF (lwp) write (numout,*) 'flat(',jk,')    = ',             &
+                                            abs(gphit(ji,jj))
+                  IF (lwp) write (numout,*) 'fcaco3(',jk,')  = ', fcaco3
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !!----------------------------------------------------------
+      !! This version of MEDUSA offers a choice of three methods for
+      !! handling the remineralisation of fast detritus.  All three
+      !! do so in broadly the same way:
+      !!
+      !!   1.  Fast detritus is stored as a 2D array  [ ffastX  ]
+      !!   2.  Fast detritus is added level-by-level  [ ftempX  ]
+      !!   3.  Fast detritus is not remineralised in the top box 
+      !!       [ freminX ]
+      !!   4.  Remaining fast detritus is remineralised in the 
+      !!       bottom  [ fsedX   ] box
+      !!
+      !! The three remineralisation methods are:
+      !!   
+      !!   1.  Ballast model (i.e. that published in Yool et al., 
+      !!       2011)
+      !!  (1b. Ballast-sans-ballast model)
+      !!   2.  Martin et al. (1987)
+      !!   3.  Henson et al. (2011)
+      !! 
+      !! The first of these couples C, N and Fe remineralisation to
+      !! the remineralisation of particulate Si and CaCO3, but the 
+      !! latter two treat remineralisation of C, N, Fe, Si and CaCO3
+      !! completely separately.  At present a switch within the code
+      !! regulates which submodel is used, but this should be moved
+      !! to the namelist file.
+      !! 
+      !! The ballast-sans-ballast submodel is an original development
+      !! feature of MEDUSA in which the ballast submodel's general
+      !! framework and parameterisation is used, but in which there
+      !! is no protection of organic material afforded by ballasting
+      !! minerals.  While similar, it is not the same as the Martin 
+      !! et al. (1987) submodel.
+      !!
+      !! Since the three submodels behave the same in terms of
+      !! accumulating sinking material and remineralising it all at
+      !! the seafloor, these portions of the code below are common to
+      !! all three.
+      !!----------------------------------------------------------
+      if (jexport.eq.1) then
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  !!=======================================================
+                  !! BALLAST SUBMODEL
+                  !!=======================================================
+                  !! 
+                  !!-------------------------------------------------------
+                  !! Fast-sinking detritus fluxes, pt. 1: REMINERALISATION
+                  !! aside from explicitly modelled, slow-sinking detritus, the
+                  !! model includes an implicit representation of detrital
+                  !! particles that sink too quickly to be modelled with
+                  !! explicit state variables; this sinking flux is instead
+                  !! instantaneously remineralised down the water column using
+                  !! the version of Armstrong et al. (2002)'s ballast model
+                  !! used by Dunne et al. (2007); the version of this model
+                  !! here considers silicon and calcium carbonate ballast
+                  !! minerals; this section of the code redistributes the fast
+                  !! sinking material generated locally down the water column;
+                  !! this differs from Dunne et al. (2007) in that fast sinking
+                  !! material is distributed at *every* level below that it is
+                  !! generated, rather than at every level below some fixed
+                  !! depth; this scheme is also different in that sinking 
+                  !! material generated in one level is aggregated with that 
+                  !! generated by shallower levels; this should make the 
+                  !! ballast model more self-consistent (famous last words)
+                  !!-------------------------------------------------------
+                  !!
+                  if (jk.eq.1) then
+                     !! this is the SURFACE OCEAN BOX (no remineralisation)
+                     !!
+                     freminc(ji,jj)  = 0.0
+                     freminn(ji,jj)  = 0.0
+                     freminfe(ji,jj) = 0.0
+                     freminsi(ji,jj) = 0.0
+                     freminca(ji,jj) = 0.0
+                  elseif (jk.le.mbathy(ji,jj)) then
+                     !! this is an OCEAN BOX (remineralise some material)
+                     !!
+                     !! set up CCD depth to be used depending on user choice
+                     if (jocalccd.eq.0) then
+                        !! use default CCD field
+                        fccd_dep(ji,jj) = ocal_ccd(ji,jj)
+                     elseif (jocalccd.eq.1) then
+                        !! use calculated CCD field
+                        fccd_dep(ji,jj) = f2_ccd_cal(ji,jj)
+                     endif
+                     !!
+                     !! === organic carbon ===
+                     !! how much organic C enters this box        (mol)
+                     fq0      = ffastc(ji,jj)
+                     if (iball.eq.1) then
+                        !! how much it weighs
+                        fq1      = (fq0 * xmassc)
+                        !! how much CaCO3 enters this box
+                        fq2      = (ffastca(ji,jj) * xmassca)
+                        !! how much  opal enters this box
+                        fq3      = (ffastsi(ji,jj) * xmasssi)
+                        !! total protected organic C
+                        fq4      = (fq2 * xprotca) + (fq3 * xprotsi)
+                        !! This next term is calculated for C but used for
+                        !! N and Fe as well
+                        !! It needs to be protected in case ALL C is protected
+                        if (fq4.lt.fq1) then
+                           !! protected fraction of total organic C (non-dim)
+                           fprotf   = (fq4 / (fq1 + tiny(fq1)))
+                        else
+                           !! all organic C is protected (non-dim)
+                           fprotf   = 1.0
+                        endif
+                        !! unprotected fraction of total organic C (non-dim)
+                        fq5      = (1.0 - fprotf)
+                        !! how much organic C is unprotected (mol)
+                        fq6      = (fq0 * fq5)
+                        !! how much unprotected C leaves this box (mol)
+                        fq7      = (fq6 * exp(-(fse3t(ji,jj,jk) / xfastc)))
+                        !! how much total C leaves this box (mol)
+                        fq8      = (fq7 + (fq0 * fprotf))
+                        !! C remineralisation in this box (mol)
+                        freminc(ji,jj)  = (fq0 - fq8) / fse3t(ji,jj,jk)
+                        ffastc(ji,jj) = fq8
+# if defined key_debug_medusa
+                        !! report in/out/remin fluxes of carbon for this level
+                           if (idf.eq.1.AND.idfval.eq.1) then
+                              IF (lwp) write (numout,*)                       &
+                                       '------------------------------'
+                              IF (lwp) write (numout,*) 'totalC(',jk,')  = ', &
+                                       fq1
+                              IF (lwp) write (numout,*) 'prtctC(',jk,')  = ', &
+                                       fq4
+                              IF (lwp) write (numout,*) 'fprotf(',jk,')  = ', &
+                                       fprotf
+                              IF (lwp) write (numout,*)                       &
+                                       '------------------------------'
+                              IF (lwp) write (numout,*) 'IN   C(',jk,')  = ', &
+                                       fq0
+                              IF (lwp) write (numout,*) 'LOST C(',jk,')  = ', &
+                                       freminc(ji,jj) * fse3t(ji,jj,jk)
+                              IF (lwp) write (numout,*) 'OUT  C(',jk,')  = ', &
+                                       fq8
+                              IF (lwp) write (numout,*) 'NEW  C(',jk,')  = ', &
+                                       ftempc(ji,jj) * fse3t(ji,jj,jk)
+                           endif
+# endif
+                        else
+                        !! how much organic C leaves this box (mol)
+                        fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastc))
+                        !! C remineralisation in this box (mol)
+                        freminc(ji,jj)  = (fq0 - fq1) / fse3t(ji,jj,jk)
+                        ffastc(ji,jj)  = fq1
+                     endif
+                     !!
+                     !! === organic nitrogen ===
+                     !! how much organic N enters this box (mol)
+                     fq0      = ffastn(ji,jj)
+                     if (iball.eq.1) then
+                        !! unprotected fraction of total organic N (non-dim)
+                        fq5      = (1.0 - fprotf)
+                        !! how much organic N is unprotected (mol)
+                        fq6      = (fq0 * fq5)
+                        !! how much unprotected N leaves this box (mol)
+                        fq7      = (fq6 * exp(-(fse3t(ji,jj,jk) / xfastc)))
+                        !! how much total N leaves this box (mol)
+                        fq8      = (fq7 + (fq0 * fprotf))
+                        !! N remineralisation in this box (mol)
+                        freminn(ji,jj)  = (fq0 - fq8) / fse3t(ji,jj,jk)
+                        ffastn(ji,jj)  = fq8
+# if defined key_debug_medusa
+                        !! report in/out/remin fluxes of carbon for this level
+                        if (idf.eq.1.AND.idfval.eq.1) then
+                           IF (lwp) write (numout,*)                          &
+                                    '------------------------------'
+                           IF (lwp) write (numout,*) 'totalN(',jk,')  = ', fq1
+                           IF (lwp) write (numout,*) 'prtctN(',jk,')  = ', fq4
+                           IF (lwp) write (numout,*) 'fprotf(',jk,')  = ',    &
+                                    fprotf
+                           IF (lwp) write (numout,*)                          &
+                                    '------------------------------'
+                           if (freminn(ji,jj) < 0.0) then
+                              IF (lwp) write (numout,*) '** FREMIN ERROR **'
+                           endif
+                           IF (lwp) write (numout,*) 'IN   N(',jk,')  = ', fq0
+                           IF (lwp) write (numout,*) 'LOST N(',jk,')  = ',    &
+                                    freminn(ji,jj) * fse3t(ji,jj,jk)
+                           IF (lwp) write (numout,*) 'OUT  N(',jk,')  = ', fq8
+                           IF (lwp) write (numout,*) 'NEW  N(',jk,')  = ',    &
+                                    ftempn(ji,jj) * fse3t(ji,jj,jk)
+                        endif
+# endif
+                     else
+                        !! how much organic N leaves this box (mol)
+                        fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastc))
+                        !! N remineralisation in this box (mol)
+                        freminn(ji,jj)  = (fq0 - fq1) / fse3t(ji,jj,jk)
+                        ffastn(ji,jj)  = fq1
+                     endif
+                     !!
+                     !! === organic iron ===
+                     !! how much organic Fe enters this box (mol)
+                     fq0      = ffastfe(ji,jj)
+                     if (iball.eq.1) then
+                        !! unprotected fraction of total organic Fe (non-dim)
+                        fq5      = (1.0 - fprotf)
+                        !! how much organic Fe is unprotected (mol)
+                        fq6      = (fq0 * fq5)
+                        !! how much unprotected Fe leaves this box (mol)
+                        fq7      = (fq6 * exp(-(fse3t(ji,jj,jk) / xfastc)))
+                        !! how much total Fe leaves this box (mol)
+                        fq8      = (fq7 + (fq0 * fprotf))
+                        !! Fe remineralisation in this box (mol)
+                        freminfe(ji,jj) = (fq0 - fq8) / fse3t(ji,jj,jk)
+                        ffastfe(ji,jj) = fq8
+                     else
+                        !! how much total Fe leaves this box (mol)
+                        fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastc))
+                        !! Fe remineralisation in this box (mol)
+                        freminfe(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                        ffastfe(ji,jj) = fq1
+                     endif
+                     !!
+                     !! === biogenic silicon ===
+                     !! how much  opal centers this box (mol)
+                     fq0      = ffastsi(ji,jj)
+                     !! how much  opal leaves this box (mol)
+                     fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastsi))
+                     !! Si remineralisation in this box (mol)
+                     freminsi(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     ffastsi(ji,jj) = fq1
+                     !!
+                     !! === biogenic calcium carbonate ===
+                     !! how much CaCO3 enters this box (mol)
+                     fq0      = ffastca(ji,jj)
+                     if (fsdepw(ji,jj,jk).le.fccd_dep(ji,jj)) then
+                        !! whole grid cell above CCD
+                        !! above lysocline, no Ca dissolves (mol)
+                        fq1      = fq0
+                        !! above lysocline, no Ca dissolves (mol)
+                        freminca(ji,jj) = 0.0
+                        !! which is the last level above the CCD?    (#)
+                        fccd(ji,jj) = real(jk)
+                     elseif (fsdepw(ji,jj,jk).ge.fccd_dep(ji,jj)) then
+                        !! whole grid cell below CCD
+                        !! how much CaCO3 leaves this box (mol)
+                        fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastca))
+                        !! Ca remineralisation in this box (mol)
+                        freminca(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     else
+                        !! partial grid cell below CCD
+                        !! amount of grid cell below CCD (m)
+                        fq2      = fdep1(ji,jj) - fccd_dep(ji,jj)
+                        !! how much CaCO3 leaves this box (mol)
+                        fq1      = fq0 * exp(-(fq2 / xfastca))
+                        !! Ca remineralisation in this box (mol)
+                        freminca(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     endif
+                     ffastca(ji,jj) = fq1 
+                  else
+                     !! this is BELOW THE LAST OCEAN BOX (do nothing)
+                     freminc(ji,jj)  = 0.0
+                     freminn(ji,jj)  = 0.0
+                     freminfe(ji,jj) = 0.0
+                     freminsi(ji,jj) = 0.0
+                     freminca(ji,jj) = 0.0              
+                  endif
+               ENDIF
+            ENDDO
+         ENDDO
+      elseif (jexport.eq.2.or.jexport.eq.3) then
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  if (jexport.eq.2) then
+                     !!====================================================
+                     !! MARTIN ET AL. (1987) SUBMODEL
+                     !!====================================================
+                     !! 
+                     !!----------------------------------------------------
+                     !! This submodel uses the classic Martin et al. (1987) 
+                     !! curve to determine the attenuation of fast-sinking 
+                     !! detritus down the water column.  All three organic 
+                     !! elements, C, N and Fe, are handled identically, and 
+                     !! their quantities in sinking particles attenuate 
+                     !! according to a power relationship governed by 
+                     !! parameter "b".  This is assigned a canonical value 
+                     !! of -0.858.  Biogenic opal and calcium carbonate are
+                     !! attentuated using the same function as in the
+                     !! ballast submodel
+                     !!----------------------------------------------------
+                     !!
+                     fb_val = -0.858
+                  elseif (jexport.eq.3) then
+                     !!====================================================
+                     !! HENSON ET AL. (2011) SUBMODEL
+                     !!====================================================
+                     !!
+                     !!----------------------------------------------------
+                     !! This submodel reconfigures the Martin et al. (1987) 
+                     !! curve by allowing the "b" value to vary 
+                     !! geographically.  Its value is set, following Henson 
+                     !! et al. (2011), as a function of local sea surface 
+                     !! temperature:
+                     !!   b = -1.06 + (0.024 * SST)
+                     !! This means that remineralisation length scales are 
+                     !! longer in warm, tropical areas and shorter in cold, 
+                     !! polar areas.  This does seem back-to-front (i.e. 
+                     !! one would expect GREATER remineralisation in warmer 
+                     !! waters), but is an outcome of analysis of sediment 
+                     !! trap data, and it may reflect details of ecosystem 
+                     !! structure that pertain to particle production
+                     !! rather than simply Q10.
+                     !!----------------------------------------------------
+                     !!
+                     fl_sst = tsn(ji,jj,1,jp_tem)
+                     fb_val = -1.06 + (0.024 * fl_sst)
+                  endif
+                  !!   
+                  if (jk.eq.1) then
+                     !! this is the SURFACE OCEAN BOX (no remineralisation)
+                     !!
+                     freminc(ji,jj)  = 0.0
+                     freminn(ji,jj)  = 0.0
+                     freminfe(ji,jj) = 0.0
+                     freminsi(ji,jj) = 0.0
+                     freminca(ji,jj) = 0.0
+                  elseif (jk.le.mbathy(ji,jj)) then
+                     !! this is an OCEAN BOX (remineralise some material)
+                     !!
+                     !! === organic carbon ===
+                     !! how much organic C enters this box (mol)
+                     fq0      = ffastc(ji,jj)
+                     !! how much organic C leaves this box (mol)
+                     fq1      = fq0 * ((fdep1(ji,jj)/fsdepw(ji,jj,jk))**fb_val)
+                     !! C remineralisation in this box (mol)
+                     freminc(ji,jj)  = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     ffastc(ji,jj)  = fq1
+                     !!
+                     !! === organic nitrogen ===
+                     !! how much organic N enters this box (mol)
+                     fq0      = ffastn(ji,jj)
+                     !! how much organic N leaves this box (mol)
+                     fq1      = fq0 * ((fdep1(ji,jj)/fsdepw(ji,jj,jk))**fb_val)
+                     !! N remineralisation in this box (mol)
+                     freminn(ji,jj)  = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     ffastn(ji,jj)  = fq1
+                     !!
+                     !! === organic iron ===
+                     !! how much organic Fe enters this box (mol)
+                     fq0      = ffastfe(ji,jj)
+                     !! how much organic Fe leaves this box (mol)
+                     fq1      = fq0 * ((fdep1(ji,jj)/fsdepw(ji,jj,jk))**fb_val)
+                     !! Fe remineralisation in this box (mol)
+                     freminfe(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     ffastfe(ji,jj) = fq1
+                     !!
+                     !! === biogenic silicon ===
+                     !! how much  opal centers this box (mol)
+                     fq0      = ffastsi(ji,jj)
+                     !! how much  opal leaves this box (mol)
+                     fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastsi))
+                     !! Si remineralisation in this box (mol)
+                     freminsi(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     ffastsi(ji,jj) = fq1
+                     !!
+                     !! === biogenic calcium carbonate ===
+                     !! how much CaCO3 enters this box (mol)
+                     fq0      = ffastca(ji,jj)
+                     if (fsdepw(ji,jj,jk).le.ocal_ccd(ji,jj)) then
+                        !! whole grid cell above CCD
+                        !! above lysocline, no Ca dissolves (mol)
+                        fq1      = fq0
+                        !! above lysocline, no Ca dissolves (mol)
+                        freminca(ji,jj) = 0.0
+                        !! which is the last level above the CCD?    (#)
+                        fccd(ji,jj) = real(jk)
+                     elseif (fsdepw(ji,jj,jk).ge.ocal_ccd(ji,jj)) then
+                        !! whole grid cell below CCD
+                        !! how much CaCO3 leaves this box (mol)
+                        fq1      = fq0 * exp(-(fse3t(ji,jj,jk) / xfastca))
+                        !! Ca remineralisation in this box (mol)
+                        freminca(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     else
+                        !! partial grid cell below CCD
+                        !! amount of grid cell below CCD (m)
+                        fq2      = fdep1(ji,jj) - ocal_ccd(ji,jj)
+                        !! how much CaCO3 leaves this box (mol)
+                        fq1      = fq0 * exp(-(fq2 / xfastca))
+                        !! Ca remineralisation in this box (mol)
+                        freminca(ji,jj) = (fq0 - fq1) / fse3t(ji,jj,jk)
+                     endif
+                     ffastca(ji,jj) = fq1 
+                  else
+                     !! this is BELOW THE LAST OCEAN BOX (do nothing)
+                     freminc(ji,jj)  = 0.0
+                     freminn(ji,jj)  = 0.0
+                     freminfe(ji,jj) = 0.0
+                     freminsi(ji,jj) = 0.0
+                     freminca(ji,jj) = 0.0              
+                  endif
+               ENDIF
+            ENDDO
+         ENDDO
+      endif
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Fast-sinking detritus fluxes, pt. 2: UPDATE FAST FLUXES
+               !! here locally calculated additions to the fast-sinking 
+               !! flux are added to the total fast-sinking flux; this is 
+               !! done here such that material produced in a particular 
+               !! layer is only remineralised below this layer
+               !!----------------------------------------------------------
+               !!
+               !! add sinking material generated in this layer to running 
+               !! totals
+               !!
+               !! === organic carbon === 
+               !! (diatom and mesozooplankton mortality)
+               ffastc(ji,jj)  = ffastc(ji,jj)  + (ftempc(ji,jj)  *           &
+                                                  fse3t(ji,jj,jk))
+               !!
+               !! === organic nitrogen ===
+               !! (diatom and mesozooplankton mortality)
+               ffastn(ji,jj)  = ffastn(ji,jj)  + (ftempn(ji,jj)  *           &
+                                                  fse3t(ji,jj,jk))
+               !!
+               !! === organic iron ===
+               !! (diatom and mesozooplankton mortality)
+               ffastfe(ji,jj) = ffastfe(ji,jj) + (ftempfe(ji,jj) *          &
+                                                  fse3t(ji,jj,jk))
+               !!
+               !! === biogenic silicon ===
+               !! (diatom mortality and grazed diatoms)
+               ffastsi(ji,jj) = ffastsi(ji,jj) + (ftempsi(ji,jj) *          &
+                                                  fse3t(ji,jj,jk))
+               !!
+               !! === biogenic calcium carbonate ===
+               !! (latitudinally-based fraction of total primary production)
+               ffastca(ji,jj) = ffastca(ji,jj) + (ftempca(ji,jj) *          &
+                                                  fse3t(ji,jj,jk))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Fast-sinking detritus fluxes, pt. 3: SEAFLOOR
+               !! remineralise all remaining fast-sinking detritus to dissolved
+               !! nutrients; the sedimentation fluxes calculated here allow the
+               !! separation of what's remineralised sinking through the final
+               !! ocean box from that which is added to the final box by the
+               !! remineralisation of material that reaches the seafloor (i.e.
+               !! the model assumes that *all* material that hits the seafloor
+               !! is remineralised and that none is permanently buried; hey,
+               !! this is a giant GCM model that can't be run for long enough
+               !! to deal with burial fluxes!)
+               !!
+               !! in a change to this process, in part so that MEDUSA behaves
+               !! a little more like ERSEM et al., fast-sinking detritus (N, Fe
+               !! and C) is converted to slow sinking detritus at the seafloor
+               !! instead of being remineralised; the rationale is that in
+               !! shallower shelf regions (... that are not fully mixed!) this
+               !! allows the detrital material to return slowly to dissolved 
+               !! nutrient rather than instantaneously as now; the alternative
+               !! would be to explicitly handle seafloor organic material - a
+               !! headache I don't wish to experience at this point; note that
+               !! fast-sinking Si and Ca detritus is just remineralised as 
+               !! per usual
+               !! 
+               !! AXY (13/01/12)
+               !! in a further change to this process, again so that MEDUSA is
+               !! a little more like ERSEM et al., material that reaches the
+               !! seafloor can now be added to sediment pools and stored for
+               !! slow release; there are new 2D arrays for organic nitrogen,
+               !! iron and carbon and inorganic silicon and carbon that allow
+               !! fast and slow detritus that reaches the seafloor to be held
+               !! and released back to the water column more slowly; these
+               !! arrays are transferred via the tracer restart files between
+               !! repeat submissions of the model
+               !!----------------------------------------------------------
+               !! 
+               ffast2slowc(ji,jj)  = 0.0
+               ffast2slown(ji,jj)  = 0.0
+! I don't think this is used - marc 10/4/17
+!               ffast2slowfe(ji,jj) = 0.0
+               !!
+               if (jk.eq.mbathy(ji,jj)) then
+                  !! this is the BOTTOM OCEAN BOX (remineralise everything)
+                  !!
+                  !! AXY (17/01/12): tweaked to include benthos pools
+                  !! 
+                  !! === organic carbon ===
+                  if (jfdfate.eq.0 .and. jorgben.eq.0) then
+                     !! C remineralisation in this box (mol/m3)
+                     freminc(ji,jj)  = freminc(ji,jj) + (ffastc(ji,jj) /     &
+                                                         fse3t(ji,jj,jk))
+                  elseif (jfdfate.eq.1 .and. jorgben.eq.0) then
+                     !! fast C -> slow C (mol/m3)
+                     ffast2slowc(ji,jj) = ffastc(ji,jj) / fse3t(ji,jj,jk)
+                     fslowc(ji,jj)      = fslowc(ji,jj) + ffast2slowc(ji,jj)
+                  elseif (jfdfate.eq.0 .and. jorgben.eq.1) then
+                     !! fast C -> benthic C (mol/m2)
+                     f_fbenin_c(ji,jj)  = ffastc(ji,jj)
+                  endif
+                  !! record seafloor C (mol/m2)
+                  fsedc(ji,jj)   = ffastc(ji,jj)
+                  ffastc(ji,jj)  = 0.0
+                  !!
+                  !! === organic nitrogen ===
+                  if (jfdfate.eq.0 .and. jorgben.eq.0) then
+                     !! N remineralisation in this box (mol/m3)
+                     freminn(ji,jj)  = freminn(ji,jj) + (ffastn(ji,jj) /     &
+                                                         fse3t(ji,jj,jk))
+                  elseif (jfdfate.eq.1 .and. jorgben.eq.0) then
+                     !! fast N -> slow N (mol/m3)
+                     ffast2slown(ji,jj) = ffastn(ji,jj) / fse3t(ji,jj,jk)
+                     fslown(ji,jj)      = fslown(ji,jj) + ffast2slown(ji,jj)
+                  elseif (jfdfate.eq.0 .and. jorgben.eq.1) then
+                     !! fast N -> benthic N (mol/m2)
+                     f_fbenin_n(ji,jj)  = ffastn(ji,jj)
+                  endif
+                  !! record seafloor N (mol/m2)
+                  fsedn(ji,jj)   = ffastn(ji,jj)
+                  ffastn(ji,jj)  = 0.0
+                  !!
+                  !! === organic iron ===
+                  if (jfdfate.eq.0 .and. jorgben.eq.0) then
+                     !! Fe remineralisation in this box (mol/m3)
+                     freminfe(ji,jj) = freminfe(ji,jj) + (ffastfe(ji,jj) /   &
+                                                          fse3t(ji,jj,jk))
+! I don't think ffast2slowfe is used - marc 10/4/17
+!                  elseif (jfdfate.eq.1 .and. jorgben.eq.0) then
+!                     !! fast Fe -> slow Fe (mol/m3)
+!                     ffast2slowfe(ji,jj) = ffastn(ji,jj) / fse3t(ji,jj,jk)
+                  elseif (jfdfate.eq.0 .and. jorgben.eq.1) then
+                     !! fast Fe -> benthic Fe (mol/m2)
+                     f_fbenin_fe(ji,jj) = ffastfe(ji,jj)
+                  endif
+                  !! record seafloor Fe (mol/m2)
+                  fsedfe(ji,jj)  = ffastfe(ji,jj)
+                  ffastfe(ji,jj) = 0.0
+                  !!
+                  !! === biogenic silicon ===
+                  if (jinorgben.eq.0) then
+                     !! Si remineralisation in this box (mol/m3)
+                     freminsi(ji,jj) = freminsi(ji,jj) + (ffastsi(ji,jj) /   &
+                                                          fse3t(ji,jj,jk))
+                  elseif (jinorgben.eq.1) then
+                     !! fast Si -> benthic Si
+                     f_fbenin_si(ji,jj) = ffastsi(ji,jj)
+                  endif
+                  !! record seafloor Si (mol/m2)
+                  fsedsi(ji,jj)   = ffastsi(ji,jj)
+                  ffastsi(ji,jj) = 0.0
+                  !!
+                  !! === biogenic calcium carbonate ===
+                  if (jinorgben.eq.0) then
+                     !! Ca remineralisation in this box (mol/m3)
+                     freminca(ji,jj) = freminca(ji,jj) + (ffastca(ji,jj) /   &
+                                                          fse3t(ji,jj,jk))
+                  elseif (jinorgben.eq.1) then
+                     !! fast Ca -> benthic Ca (mol/m2)
+                     f_fbenin_ca(ji,jj) = ffastca(ji,jj)
+                  endif
+                  !! record seafloor Ca (mol/m2)
+                  fsedca(ji,jj)   = ffastca(ji,jj)
+                  ffastca(ji,jj) = 0.0
+               endif
+
+# if defined key_debug_medusa
+               if (idf.eq.1) then
+                  !!-------------------------------------------------------
+                  !! Integrate total fast detritus remineralisation
+                  !!-------------------------------------------------------
+                  !!
+                  fofd_n(ji,jj)  = fofd_n(ji,jj)  + (freminn(ji,jj)  *       &
+                                                     fse3t(ji,jj,jk))
+                  fofd_si(ji,jj) = fofd_si(ji,jj) + (freminsi(ji,jj) *       &
+                                                     fse3t(ji,jj,jk))
+                  fofd_fe(ji,jj) = fofd_fe(ji,jj) + (freminfe(ji,jj) *       &
+                                                     fse3t(ji,jj,jk))
+#  if defined key_roam
+                  fofd_c(ji,jj)  = fofd_c(ji,jj)  + (freminc(ji,jj)  *       &
+                                                     fse3t(ji,jj,jk))
+#  endif
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Sort out remineralisation tally of fast-sinking detritus
+               !!----------------------------------------------------------
+               !!
+               !! update fast-sinking regeneration arrays
+               fregenfast(ji,jj)   = fregenfast(ji,jj)   +                  &
+                                     (freminn(ji,jj)  * fse3t(ji,jj,jk))
+               fregenfastsi(ji,jj) = fregenfastsi(ji,jj) +                  &
+                                     (freminsi(ji,jj) * fse3t(ji,jj,jk))
+# if defined key_roam
+               fregenfastc(ji,jj)  = fregenfastc(ji,jj)  +                  &
+                                     (freminc(ji,jj)  * fse3t(ji,jj,jk))
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Benthic remineralisation fluxes
+               !!----------------------------------------------------------
+               !!
+               if (jk.eq.mbathy(ji,jj)) then
+                  !!
+                  !! organic components
+                  if (jorgben.eq.1) then
+                     f_benout_n(ji,jj)  = xsedn  * zn_sed_n(ji,jj)
+                     f_benout_fe(ji,jj) = xsedfe * zn_sed_fe(ji,jj)
+                     f_benout_c(ji,jj)  = xsedc  * zn_sed_c(ji,jj)
+                  endif
+                  !!
+                  !! inorganic components
+                  if (jinorgben.eq.1) then
+                     f_benout_si(ji,jj) = xsedsi * zn_sed_si(ji,jj)
+                     f_benout_ca(ji,jj) = xsedca * zn_sed_ca(ji,jj)
+                     !!
+                     !! account for CaCO3 that dissolves when it shouldn't
+                     if ( fsdepw(ji,jj,jk) .le. fccd_dep(ji,jj) ) then
+                        f_benout_lyso_ca(ji,jj) = xsedca * zn_sed_ca(ji,jj)
+                     endif
+                  endif
+               endif
+               CALL flush(numout)
+
+            ENDIF
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE detritus_fast_sink
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE detritus_fast_sink( )                    ! Empty routine
+      WRITE(*,*) 'detritus_fast_sink: You should not have seen this print! error?'
+   END SUBROUTINE detritus_fast_sink
+#endif 
+
+   !!======================================================================
+END MODULE detritus_fast_sink_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/gas_transfer.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/gas_transfer.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/gas_transfer.F90	(revision 9987)
@@ -0,0 +1,154 @@
+MODULE gastransfer
+   !!======================================================================
+   !!                         ***  MODULE trcdms_medusa  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :
+   !!  -   !  2015-06  (A. Yool)             added for UKESM1 project
+   !!----------------------------------------------------------------------
+#if defined key_medusa && defined key_roam
+      USE oce_trc
+      USE trc
+      USE sms_medusa
+      USE lbclnk
+      USE prtctl_trc      ! Print control for debugging
+      USE in_out_manager  ! I/O manager
+
+      IMPLICIT NONE
+      PRIVATE
+
+      PUBLIC   gas_transfer  ! called by trcbio_medusa.F90 module
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+      subroutine gas_transfer(wind, N, eqn, kw660)
+! --------------------------------------------------------------------
+!  Gas transfer velocity
+! --------------------------------------------------------------------
+!
+! Title  : Calculates gas transfer velocity
+! Author : Andrew Yool
+! Date   : 15/10/04
+! 
+! This subroutine uses near-surface wind speed to calculate gas
+! transfer velocity for use in CO2 and O2 exchange calculations.
+!
+! Note that the parameterisation of Wanninkhof quoted here is a
+! truncation of the original equation.  It excludes a chemical
+! enhancement function (based on temperature), although such
+! temperature dependence is reported negligible by Etcheto & 
+! Merlivat (1988).
+!
+! Note also that in calculating scalar wind, the variance of the
+! wind over the period of a timestep is ignored.  Some authors,
+! for instance OCMIP-2, favour including some reference to the
+! variability of wind.  However, their wind fields are averaged
+! over relatively long time periods, and so this issue may be
+! safely (!) ignored here.
+! 
+! AXY (12/06/2015)
+! UPDATED: revised formulation from Wanninkhof (2014) update to
+! original 1992 paper. Full reference is:
+!
+! Wanninkhof, R. (2014). Relationship between wind speed and gas 
+! exchange over the ocean revisited. LIMNOLOGY AND OCEANOGRAPHY-METHODS
+! 12, 351-362, doi:10.4319/lom.2014.12.351
+! 
+! Subroutine inputs are (in order) : 
+!     wind      wind velocity at 10 m (m/s)
+!     N         size of input array (value 1 at this time)
+!     eqn       choice of parameterisation:
+!               1 = Liss & Merlivat (1986)    [approximated]
+!               2 = Wanninkhof (1992)         [sans enhancement]
+!               3 = Nightingale et al. (2000) [good]
+!               4 = Nightingale et al. (2000) [better]
+!               5 = Nightingale et al. (2000) [best]
+!               6 = OCMIP-2                   [sans variability]
+!               7 = Wanninkhof (2014)         [assumes 6h avg winds]
+! (*) k         gas transfer velocity (m/s)
+! 
+! Where (*) is the function output and (+) is a diagnostic output.
+!
+      implicit none
+
+      INTEGER, INTENT(in) :: N, eqn
+! Input variables
+!     real(kind=wp), INTENT(in),  DIMENSION(N) :: wind
+      real(wp), INTENT(in)  :: wind
+!
+! Output variables
+!     real(kind=wp), INTENT(out), DIMENSION(N) :: kw660
+      real(wp), INTENT(out) :: kw660
+!
+!     INTEGER :: eqn
+!
+! Coefficients for various parameterisations
+      real(wp) :: a(7)
+      real(wp) :: b(7)
+!
+!     real(wp), DIMENSION(N) :: tmp_k
+      real(wp) :: tmp_k
+!
+! Values of coefficients
+      data a(1) / 0.166 /  ! Liss & Merlivat (1986)    [approximated]
+      data a(2) / 0.3   /  ! Wanninkhof (1992)         [sans enhancement]
+      data a(3) / 0.23  /  ! Nightingale et al. (2000) [good]
+      data a(4) / 0.23  /  ! Nightingale et al. (2000) [better]
+      data a(5) / 0.222 /  ! Nightingale et al. (2000) [best]
+      data a(6) / 0.337 /  ! OCMIP-2                   [sans variability]
+      data a(7) / 0.251 /  ! Wanninkhof (2014)         [assumes 6h avg winds]
+!
+      data b(1) / 0.133 /
+      data b(2) / 0.0   /
+      data b(3) / 0.0   /
+      data b(4) / 0.1   /
+      data b(5) / 0.333 /
+      data b(6) / 0.0   /
+      data b(7) / 0.0   /
+!
+! Which parameterisation is to be used?
+!     eqn = 7
+!
+! Calculate gas transfer velocity (cm/h)
+      tmp_k = (a(eqn) * wind**2) + (b(eqn) * wind)
+!
+! Convert tmp_k from cm/h to m/s
+      kw660 = tmp_k / (100. * 3600.)
+!
+      return
+
+    end subroutine gas_transfer
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+
+CONTAINS
+
+   SUBROUTINE gas_transfer(wind, N, eqn, kw660)
+      USE par_kind
+
+      REAL(wp), INTENT( in )    :: wind
+      REAL(wp), INTENT( in )    :: kw660
+      INTEGER, INTENT(in) :: N, eqn
+
+      WRITE(*,*) 'gas_transfer: You should not have seen this print! error?', kt
+
+   END SUBROUTINE gas_transfer
+#endif
+
+   !!======================================================================
+END MODULE gastransfer
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/iron_chem_scav.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/iron_chem_scav.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/iron_chem_scav.F90	(revision 9987)
@@ -0,0 +1,546 @@
+MODULE iron_chem_scav_mod
+   !!======================================================================
+   !!                         ***  MODULE iron_chem_scav_mod  ***
+   !! Calculate the iron chemistry and scavenging.
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   iron_chem_scav        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE iron_chem_scav( jk )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE iron_chem_scav  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - 
+      !!-------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: ffastc, ffastca, ffastsi,              &
+                                   ffetop, ffebot, ffescav, xfree,        & 
+                                   zdet, zfer, zphd, zphn, zzme, zzmi,    &
+                                   idf, idfval                          
+      USE dom_oce,           ONLY: e3t_0, e3t_n, gdepw_0, gdepw_n,        &
+                                   mbathy, tmask
+      USE par_kind,          ONLY: wp
+      USE in_out_manager,    ONLY: lwp, numout
+      USE par_oce,           ONLY: jpi, jpim1, jpj, jpjm1
+      USE sms_medusa,        ONLY: i0500, jiron, xfe_sed, xfe_sol,        &
+                                   xfe_mass,                              &
+                                   xk_FeL, xk_sc_Fe, xLgT,                &
+                                   xmassc, xmassca, xmasssi,              &
+                                   xthetad, xthetapd, xthetapn,           &
+                                   xthetazme, xthetazmi,                  &
+                                   zirondep
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+
+      !! iron cycle; includes parameters for Parekh et al. (2005) iron scheme
+      !! state variables for iron-ligand system
+      REAL(wp), DIMENSION(jpi,jpj) :: xFeT, xFeF, xFeL
+      REAL(wp) :: xLgF
+      !! iron-ligand parameters
+      REAL(wp) :: xb_coef_tmp, xb2M4ac
+      !! max Fe' parameters
+      REAL(wp) :: xmaxFeF,fdeltaFe
+      !!
+      !! local parameters for Moore et al. (2004) alternative scavenging 
+      !! scheme
+      REAL(wp) :: fbase_scav,fscal_sink,fscal_part,fscal_scav
+      !!
+      !! local parameters for Moore et al. (2008) alternative scavenging 
+      !! scheme
+      REAL(wp) :: fscal_csink,fscal_sisink,fscal_casink
+      !!
+      !! local parameters for Galbraith et al. (2010) alternative 
+      !! scavenging scheme.
+      !! organic portion of scavenging
+      REAL(wp) :: xCscav1, xCscav2, xk_org, xORGscav
+      !! inorganic portion of scavenging
+      REAL(wp) :: xk_inorg, xINORGscav
+
+      INTEGER :: ji, jj
+
+      !!------------------------------------------------------------------
+      !! Iron chemistry and fractionation
+      !! following the Parekh et al. (2004) scheme adopted by the Met.
+      !! Office, Medusa models total iron but considers "free" and
+      !! ligand-bound forms for the purposes of scavenging (only "free"
+      !! iron can be scavenged
+      !!------------------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! total iron concentration (mmol Fe / m3 -> umol Fe / m3)
+               xFeT(ji,jj) = zfer(ji,jj) * 1.e3
+               !!
+               !! calculate fractionation (based on Diat-HadOCC; in turn 
+               !! based on Parekh et al., 2004)
+               xb_coef_tmp = xk_FeL * (xLgT - xFeT(ji,jj)) - 1.0
+               xb2M4ac     = max(((xb_coef_tmp * xb_coef_tmp) +              &
+                                  (4.0 * xk_FeL * xLgT)), 0.0)
+               !!
+               !! "free" ligand concentration
+               xLgF        = 0.5 * (xb_coef_tmp + (xb2M4ac**0.5)) / xk_FeL
+               !!
+               !! ligand-bound iron concentration
+               xFeL(ji,jj) = xLgT - xLgF
+               !!
+               !! "free" iron concentration (and convert to mmol Fe / m3)
+               xFeF(ji,jj) = (xFeT(ji,jj) - xFeL(ji,jj)) * 1.e-3
+               xFree(ji,jj)= xFeF(ji,jj) / (zfer(ji,jj) + tiny(zfer(ji,jj)))
+            ENDIF
+         ENDDO
+      ENDDO
+
+
+      !!
+      !! scavenging of iron (multiple schemes); I'm only really 
+      !! happy with the first one at the moment - the others 
+      !! involve assumptions (sometimes guessed at by me) that 
+      !! are potentially questionable
+      !!
+      if (jiron.eq.1) then
+         !!------------------------------------------------------
+         !! Scheme 1: Dutkiewicz et al. (2005)
+         !! This scheme includes a single scavenging term based 
+         !! solely on a fixed rate and the availablility of 
+         !! "free" iron
+         !!------------------------------------------------------
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  !! = mmol/m3/d
+                  ffescav(ji,jj)     = xk_sc_Fe * xFeF(ji,jj)
+                  !!
+                  !!------------------------------------------------------
+                  !!
+                  !! Mick's code contains a further (optional) implicit 
+                  !! "scavenging" of iron that sets an upper bound on 
+                  !! "free" iron concentration, and essentially caps the 
+                  !! concentration of total iron as xFeL + "free" iron; 
+                  !! since the former is constrained by a fixed total 
+                  !! ligand concentration (= 1.0 umol/m3), and the latter 
+                  !! isn't allowed above this upper bound, total iron is 
+                  !! constrained to a maximum of ...
+                  !!
+                  !!    xFeL(ji,jj) + min(xFeF(ji,jj), 0.3 umol/m3) = 1.0 + 0.3 
+                  !!                                  = 1.3 umol / m3
+                  !! 
+                  !! In Mick's code, the actual value of total iron is 
+                  !! reset to this sum (i.e. TFe = FeL + Fe'; but 
+                  !! Fe' <= 0.3 umol/m3); this isn't our favoured approach 
+                  !! to tracer updating here (not least because of the 
+                  !! leapfrog), so here the amount scavenged is augmented 
+                  !! by an additional amount that serves to drag total 
+                  !! iron back towards that expected from this limitation 
+                  !! on iron concentration ...
+                  !!
+                  !! = umol/m3
+                  xmaxFeF     = min((xFeF(ji,jj) * 1.e3), 0.3)
+                  !!
+                  !! Here, the difference between current total Fe and 
+                  !! (FeL + Fe') is calculated and added to the scavenging 
+                  !! flux already calculated above ...
+                  !!
+                  !! = mmol/m3
+                  fdeltaFe    = (xFeT(ji,jj) - (xFeL(ji,jj) + xmaxFeF)) * 1.e-3
+                  !!
+                  !! This assumes that the "excess" iron is dissipated 
+                  !! with a time-scale of 1 day; seems reasonable to me 
+                  !! ... (famous last words)
+                  !!
+                  !! = mmol/m3/d
+                  ffescav(ji,jj)     = ffescav(ji,jj) + fdeltaFe
+                  !!
+# if defined key_deep_fe_fix
+                  !! AXY (17/01/13)
+                  !! stop scavenging for iron concentrations below 
+                  !! 0.5 umol / m3 at depths greater than 1000 m; this 
+                  !! aims to end MEDUSA's continual loss of iron at depth 
+                  !! without impacting things at the surface too much; the 
+                  !! justification for this is that it appears to be what 
+                  !! Mick Follows et al. do in their work (as evidenced by 
+                  !! the iron initial condition they supplied me with); to 
+                  !! be honest, it looks like Follow et al. do this at
+                  !! shallower depths than 1000 m, but I'll stick with this
+                  !! for now; I suspect that this seemingly arbitrary
+                  !! approach effectively "parameterises" the 
+                  !! particle-based scavenging rates that other models use 
+                  !! (i.e. at depth there are no sinking particles, so 
+                  !! scavenging stops); it might be fun justifying this in 
+                  !! a paper though!
+                  !!
+                  if ((fsdepw(ji,jj,jk).gt.1000.) .and.                       &
+                       (xFeT(ji,jj).lt.0.5)) then
+                     ffescav(ji,jj) = 0.
+                  endif
+# endif
+               ENDIF
+            ENDDO
+         ENDDO
+      elseif (jiron.eq.2) then
+         !!------------------------------------------------------
+         !! Scheme 2: Moore et al. (2004)
+         !! This scheme includes a single scavenging term that 
+         !! accounts for both suspended and sinking particles in 
+         !! the water column; this term scavenges total iron rather 
+         !! than "free" iron
+         !!------------------------------------------------------
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  !!
+                  !! total iron concentration (mmol Fe / m3 -> umol Fe / m3)
+                  xFeT(ji,jj) = zfer(ji,jj) * 1.e3
+                  !!
+                  !! this has a base scavenging rate (12% / y) which is 
+                  !! modified by local particle concentration and sinking 
+                  !! flux (and dust - but I'm ignoring that here for now) 
+                  !! and which is accelerated when Fe concentration gets
+                  !! 0.6 nM (= 0.6 umol/m3 = 0.0006 mmol/m3), and decreased 
+                  !! as concentrations below 0.4 nM (= 0.4 umol/m3 = 
+                  !! 0.0004 mmol/m3)
+                  !!
+                  !! base scavenging rate (0.12 / y)
+                  fbase_scav = 0.12 / 365.25
+                  !!
+                  !! calculate sinking particle part of scaling factor
+                  !! this takes local fast sinking carbon (mmol C / m2 / d)
+                  !! and gets it into nmol C / cm3 / s ("rdt" below is the 
+                  !! number of seconds in a model timestep)
+                  !!
+                  !! fscal_sink = ffastc(ji,jj) * 1.e2 / (86400.)
+                  !!
+                  !! ... actually, re-reading Moore et al.'s equations, it 
+                  !! looks like he uses his sinking flux directly, without 
+                  !! scaling it by time-step or anything, so I'll copy this 
+                  !! here ...
+                  !!
+                  fscal_sink = ffastc(ji,jj) * 1.e2
+                  !!
+                  !! calculate particle part of scaling factor
+                  !! this totals up the carbon in suspended particles 
+                  !! (Pn, Pd, Zmi, Zme, D),
+                  !! which comes out in mmol C / m3 (= nmol C / cm3), and 
+                  !! then multiplies it by a magic factor, 0.002, to get it 
+                  !! into nmol C / cm2 / s
+                  !!
+                  fscal_part = ( (xthetapn * zphn(ji,jj)) +                  &
+                                 (xthetapd * zphd(ji,jj)) +                  &
+                                 (xthetazmi * zzmi(ji,jj)) +                 &
+                                 (xthetazme * zzme(ji,jj)) +                 &
+                                 (xthetad * zdet(ji,jj)) ) * 0.002
+                  !!
+                  !! calculate scaling factor for base scavenging rate
+                  !! this uses the (now correctly scaled) sinking flux and 
+                  !! standing
+                  !! particle concentration, divides through by some sort 
+                  !! of reference value (= 0.0066 nmol C / cm2 / s) and 
+                  !! then uses this, or not if its too high, to rescale the 
+                  !! base scavenging rate
+                  !!
+                  fscal_scav = fbase_scav *                                  &
+                               min(((fscal_sink + fscal_part) / 0.0066), 4.0)
+                  !!
+                  !! the resulting scavenging rate is then scaled further 
+                  !! according to the local iron concentration (i.e. 
+                  !! diminished in low iron regions; enhanced in high iron 
+                  !! regions; less alone in intermediate iron regions)
+                  !!
+                  if (xFeT(ji,jj).lt.0.4) then
+                     !!
+                     !! low iron region
+                     !!
+                     fscal_scav = fscal_scav * (xFeT(ji,jj) / 0.4)
+                     !!
+                  elseif (xFeT(ji,jj).gt.0.6) then
+                     !!
+                     !! high iron region
+                     !!
+                     fscal_scav = fscal_scav + ((xFeT(ji,jj) / 0.6) *        &
+                                                (6.0 / 1.4))
+                     !!
+                  else
+                     !!
+                     !! intermediate iron region: do nothing
+                     !!
+                  endif
+                  !! 
+                  !! apply the calculated scavenging rate ...
+                  !!
+                  ffescav(ji,jj) = fscal_scav * zfer(ji,jj)
+                  !!
+               ENDIF
+            ENDDO
+         ENDDO
+      elseif (jiron.eq.3) then
+         !!------------------------------------------------------
+         !! Scheme 3: Moore et al. (2008)
+         !! This scheme includes a single scavenging term that 
+         !! accounts for sinking particles in the water column, 
+         !! and includes organic C, biogenic opal, calcium 
+         !! carbonate and dust in this (though the latter is 
+         !! ignored here until I work out what units the incoming
+         !! "dust" flux is in); this term scavenges total iron 
+         !! rather than "free" iron
+         !!------------------------------------------------------
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  !!
+                  !! total iron concentration (mmol Fe / m3 -> umol Fe / m3)
+                  xFeT(ji,jj) = zfer(ji,jj) * 1.e3
+                  !!
+                  !! this has a base scavenging rate which is modified by 
+                  !! local particle sinking flux (including dust - but I'm 
+                  !! ignoring that here for now) and which is accelerated 
+                  !! when Fe concentration is > 0.6 nM (= 0.6 umol/m3 = 
+                  !! 0.0006 mmol/m3), and decreased as concentrations < 
+                  !! 0.5 nM (= 0.5 umol/m3 = 0.0005 mmol/m3)
+                  !!
+                  !! base scavenging rate (Fe_b in paper; units may be 
+                  !! wrong there)
+                  fbase_scav = 0.00384 ! (ng)^-1 cm
+                  !!
+                  !! calculate sinking particle part of scaling factor; 
+                  !! this converts mmol / m2 / d fluxes of organic carbon, 
+                  !! silicon and calcium carbonate into ng / cm2 / s 
+                  !! fluxes; it is assumed here that the mass conversions 
+                  !! simply consider the mass of the main element
+                  !! (C, Si and Ca) and *not* the mass of the molecules 
+                  !! that they are part of; Moore et al. (2008) is unclear 
+                  !! on the conversion that should be used
+                  !!
+                  !! milli -> nano; mol -> gram; /m2 -> /cm2; /d -> /s
+                  !! ng C  / cm2 / s
+                  fscal_csink  = (ffastc(ji,jj)  * 1.e6 * xmassc  *          &
+                                  1.e-4 / 86400.)
+                  !! ng Si / cm2 / s
+                  fscal_sisink = (ffastsi(ji,jj) * 1.e6 * xmasssi *          &
+                                  1.e-4 / 86400.)
+                  !! ng Ca / cm2 / s
+                  fscal_casink = (ffastca(ji,jj) * 1.e6 * xmassca *          &
+                                  1.e-4 / 86400.)
+                  !! 
+                  !! sum up these sinking fluxes and convert to ng / cm 
+                  !! by dividing through by a sinking rate of 
+                  !! 100 m / d = 1.157 cm / s
+                  !! ng / cm
+                  fscal_sink   = ((fscal_csink * 6.) + fscal_sisink +        &
+                                  fscal_casink) / (100. * 1.e3 / 86400)
+                  !!
+                  !! now calculate the scavenging rate based upon the base 
+                  !! rate and this particle flux scaling; according to the 
+                  !! published units, the result actually has *no* units, 
+                  !! but as it must be expressed per unit time for it to 
+                  !! make any sense, I'm assuming a missing "per second"
+                  !! / s
+                  fscal_scav = fbase_scav * fscal_sink
+                  !!
+                  !! the resulting scavenging rate is then scaled further 
+                  !! according to the local iron concentration (i.e. 
+                  !! diminished in low iron regions; enhanced in high iron 
+                  !! regions; less alone in intermediate iron regions)
+                  !!
+                  if (xFeT(ji,jj).lt.0.5) then
+                     !!
+                     !! low iron region (0.5 instead of the 0.4 in Moore 
+                     !! et al., 2004)
+                     !!
+                     fscal_scav = fscal_scav * (xFeT(ji,jj) / 0.5)
+                     !!
+                  elseif (xFeT(ji,jj).gt.0.6) then
+                     !!
+                     !! high iron region (functional form different in 
+                     !! Moore et al., 2004)
+                     !!
+                     fscal_scav = fscal_scav + ((xFeT(ji,jj) - 0.6) * 0.00904)
+                     !!
+                  else
+                     !!
+                     !! intermediate iron region: do nothing
+                     !!
+                  endif
+                  !! 
+                  !! apply the calculated scavenging rate ...
+                  !!
+                  ffescav(ji,jj) = fscal_scav * zfer(ji,jj)
+               ENDIF
+            ENDDO
+         ENDDO
+      elseif (jiron.eq.4) then
+         !!------------------------------------------------------
+         !! Scheme 4: Galbraith et al. (2010)
+         !! This scheme includes two scavenging terms, one for 
+         !! organic, particle-based scavenging, and another for 
+         !! inorganic scavenging; both terms scavenge "free" iron 
+         !! only
+         !!------------------------------------------------------
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  !!
+                  !! Galbraith et al. (2010) present a more straightforward 
+                  !! outline of the scheme in Parekh et al. (2005) ...
+                  !! 
+                  !! sinking particulate carbon available for scavenging
+                  !! this assumes a sinking rate of 100 m / d (Moore & 
+                  !! Braucher, 2008),
+                  xCscav1    = (ffastc(ji,jj) * xmassc) / 100. ! = mg C / m3
+                  !! 
+                  !! scale by Honeyman et al. (1981) exponent coefficient
+                  !! multiply by 1.e-3 to express C flux in g C rather than 
+                  !! mg C
+                  xCscav2    = (xCscav1 * 1.e-3)**0.58
+                  !!
+                  !! multiply by Galbraith et al. (2010) scavenging rate
+                  xk_org     = 0.5 ! ((g C m/3)^-1) / d
+                  xORGscav   = xk_org * xCscav2 * xFeF(ji,jj)
+                  !!
+                  !! Galbraith et al. (2010) also include an inorganic bit ...
+                  !! 
+                  !! this occurs at a fixed rate, again based on the 
+                  !! availability of "free" iron
+                  !!
+                  !! k_inorg = 1000 d**-1 nmol Fe**-0.5 kg**-0.5
+                  !!
+                  !! to implement this here, scale xFeF by 1026 to put in 
+                  !! units of umol/m3 which approximately equal nmol/kg
+                  !!
+                  xk_inorg   = 1000. ! ((nmol Fe / kg)^1.5)
+                  xINORGscav = (xk_inorg * (xFeF(ji,jj) * 1026.)**1.5) * 1.e-3
+                  !!
+                  !! sum these two terms together
+                  ffescav(ji,jj) = xORGscav + xINORGscav
+               ENDIF
+            ENDDO
+         ENDDO
+      else
+         !!------------------------------------------------------
+         !! No Scheme: you coward!
+         !! This scheme puts its head in the sand and eskews any 
+         !! decision about how iron is removed from the ocean; 
+         !! prepare to get deluged in iron you fool!
+         !!------------------------------------------------------
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  ffescav(ji,jj) = 0.
+               ENDIF
+            ENDDO
+         ENDDO
+      endif
+
+      !!---------------------------------------------------------
+      !! Other iron cycle processes
+      !!---------------------------------------------------------
+      !!
+      !! aeolian iron deposition
+      !! zirondep      is in mmol-Fe / m2 / day
+      !! ffetop(ji,jj) is in mmol-dissolved-Fe / m3 / day
+      if (jk == 1) then
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  ffetop(ji,jj)  = zirondep(ji,jj) * xfe_sol / fse3t(ji,jj,jk) 
+               ENDIF
+            ENDDO
+         ENDDO
+      else
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  ffetop(ji,jj)  = 0.0
+                ENDIF
+            ENDDO
+         ENDDO
+      endif
+      !!
+      !! seafloor iron addition
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               !! AXY (10/07/12): amended to only apply sedimentary flux up 
+               !! to ~500 m down
+               !! if (jk.eq.(mbathy(ji,jj)-1).AND.jk.lt.i1100) then
+               if ((jk.eq.mbathy(ji,jj)).AND.jk.le.i0500) then
+                  !! Moore et al. (2004) cite a coastal California value of 
+                  !! 5 umol/m2/d, but adopt a global value of 2 umol/m2/d 
+                  !! for all areas < 1100 m; here we use this latter value
+                  !! but apply it everywhere
+                  !! AXY (21/07/09): actually, let's just apply it below 
+                  !! 1100 m (levels 1-37)
+                  ffebot(ji,jj)  = (xfe_sed / fse3t(ji,jj,jk))
+               else
+                  ffebot(ji,jj)  = 0.0
+               endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !! AXY (16/12/09): remove iron addition/removal processes
+      !! For the purposes of the quarter degree run, the iron 
+      !! cycle is being pegged to the initial condition supplied 
+      !! by Mick Follows via restoration with a 30 day period;
+      !! iron addition at the seafloor is still permitted with 
+      !! the idea that this extra iron will be removed by the 
+      !! restoration away from the source
+      !! ffescav(ji,jj) = 0.0
+      !! ffetop(ji,jj)  = 0.0
+      !! ffebot(ji,jj)  = 0.0
+
+# if defined key_debug_medusa
+      !! report miscellaneous calculations
+      !! report miscellaneous calculations
+      if (idf.eq.1.AND.idfval.eq.1) then
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               IF (tmask(ji,jj,jk) == 1) THEN
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'xfe_sol  = ', xfe_sol
+                  IF (lwp) write (numout,*) 'xfe_mass = ', xfe_mass
+                  IF (lwp) write (numout,*) 'ffetop(',jk,')  = ', ffetop(ji,jj)
+                  IF (lwp) write (numout,*) 'ffebot(',jk,')  = ', ffebot(ji,jj)
+                  IF (lwp) write (numout,*) 'xFree(',jk,')   = ', xFree(ji,jj)
+                  IF (lwp) write (numout,*) 'ffescav(',jk,') = ', ffescav(ji,jj)
+               ENDIF
+            ENDDO
+         ENDDO
+      endif
+# endif
+
+   END SUBROUTINE iron_chem_scav
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE iron_chem_scav( )                    ! Empty routine
+      WRITE(*,*) 'iron_chem_scav: You should not have seen this print! error?'
+   END SUBROUTINE iron_chem_scav
+#endif 
+
+   !!======================================================================
+END MODULE iron_chem_scav_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_gasflux.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_gasflux.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_gasflux.F90	(revision 9987)
@@ -0,0 +1,242 @@
+MODULE mocsy_gasflux
+
+CONTAINS
+
+! --------------------------------------------------------------------
+!  Schmidt CO2 number
+! --------------------------------------------------------------------
+!
+! Title  : Calculates Schmidt number for ocean uptake of CO2
+! Author : Andrew Yool
+! Date   : 14/10/04
+!
+! This function calculates the Schmidt number for CO2 using sea surface
+! temperature.  The code is based upon that developed as part of the
+! OCMIP-2 project (1998-2000).  The coefficients used are taken from
+! Wanninkhof (1992, JGR, 97, 7373-7382).
+!
+! AXY (12/06/2015)
+! UPDATED: coefficients used below are now those from Wanninkhof (2014)
+! update to original 1992 paper. Full reference is:
+!
+! Winninkhof, R. (2014). Relationship between wind speed and gas 
+! exchange over the ocean revisited. LIMNOLOGY AND OCEANOGRAPHY-METHODS
+! 12, 351-362, doi:10.4319/lom.2014.12.351
+!
+! Check answer for the function at 20 degrees C is 668.
+!
+! Function inputs are (in order) :
+!     t            temperature (degrees C)
+! (*) co2_schmidt  carbon dioxide Schmidt number
+!
+! Where (*) is the function output.
+!
+      subroutine schmidt_co2(pt, N, co2_schmidt)
+
+      USE mocsy_singledouble
+
+      implicit none
+!
+      INTEGER, INTENT(in) :: N
+      real(kind=wp), INTENT(in),  DIMENSION(N) :: pt
+      real(kind=wp), INTENT(out), DIMENSION(N) :: co2_schmidt
+!
+      real(kind=wp)              :: a0, a1, a2, a3, a4
+!
+!     data a0 /    2073.1 /
+!     data a1 /   -125.62 /
+!     data a2 /    3.6276 /
+!     data a3 / -0.043219 /
+!
+      data a0 /    2116.8 /
+      data a1 /   -136.25 /
+      data a2 /    4.7353 /
+      data a3 / -0.092307 /
+      data a4 / 0.0007555 /
+!
+! Wanninkhof (1992)
+!     co2_schmidt = a0 + pt*(a1 + pt*(a2 + pt*a3))
+!
+! Wanninkhof (2014) adds in an extra term
+      co2_schmidt = a0 + pt*(a1 + pt*(a2 + pt*(a3 + pt*a4)))
+!
+      return
+
+      end subroutine schmidt_co2
+
+! --------------------------------------------------------------------
+!  Surface K0
+! --------------------------------------------------------------------
+!
+! Title  : Calculates surface K0 from surface T & S
+! Author : Andrew Yool
+! Date   : 18/06/15
+!
+! This function is derived from code included in the MOCSY package
+! produced by Jim Orr.
+!
+      subroutine surface_K0(ptmp, saln, N, K0)
+
+      USE mocsy_singledouble
+
+      implicit none
+!
+      INTEGER, INTENT(in) :: N
+      real(kind=wp), INTENT(in),  DIMENSION(N) :: ptmp, saln
+      real(kind=wp), INTENT(out), DIMENSION(N) :: K0
+!
+      real(kind=wp), DIMENSION(N) :: tk, invtk, tmp
+      real(kind=wp)               :: a0, a1, a2, a3, a4
+!
+      tk    = ptmp + 273.15d0
+      invtk = 1.0d0 / tk
+      tmp = (9345.17d0*invtk) - 60.2409d0 + (23.3585d0 * LOG(tk/100.0d0))
+      K0 = EXP( tmp + saln*(0.023517d0 - (0.00023656d0*tk) + (0.0047036e-4_wp*tk*tk)) )
+!
+      return
+
+      end subroutine surface_K0
+
+! --------------------------------------------------------------------
+!  Calculate xCO2
+! --------------------------------------------------------------------
+!
+!>    Compute xCO2 from arrays of pCO2atm, in situ T, S, & atm pressure
+SUBROUTINE pCO2atm2xCO2(pCO2atm, temp, salt, Patm, N, xCO2)
+  !    Purpose:
+  !    Compute xCO2 from arrays of pCO2atm, in situ T, S, & atm pressure
+
+  USE mocsy_singledouble
+
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> atmospheric partial pressure of CO2 [uatm] 
+  ! AXY (22/06/15): amended this next line to "in" as that's what it should be!
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: pCO2atm
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: temp
+  !> salinity [psu]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: salt
+  !> atmospheric pressure [atm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: Patm
+!f2py optional , depend(temp) :: n=len(temp)
+
+! OUTPUT variables:
+  !> mole fraction of CO2 [ppm]
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: xCO2
+
+! LOCAL variables:
+  REAL(kind=wp) :: dpCO2atm, dPatm
+  REAL(kind=wp), DIMENSION(N) :: pH20
+  REAL(kind=wp) :: dxCO2
+
+  INTEGER :: i
+
+  call vapress(temp, salt, N, pH20)
+
+  DO i = 1,N
+     dpCO2atm  = DBLE(pCO2atm(i))
+     dPatm     = DBLE(Patm(i))
+     dxCO2     = dpCO2atm / (dPatm - pH20(i))
+     xCO2(i) = REAL(dxCO2)
+  END DO
+
+  RETURN
+END SUBROUTINE pCO2atm2xCO2
+
+! --------------------------------------------------------------------
+!  Calculate pCO2atm
+! --------------------------------------------------------------------
+!
+!>    Compute pCO2atm from arrays of xCO2, in situ T, S, & atm pressure
+SUBROUTINE x2pCO2atm(xCO2, temp, salt, Patm, N, pCO2atm)
+  !    Purpose:
+  !    Compute pCO2atm from arrays of xCO2, in situ T, S, & atm pressure
+
+  USE mocsy_singledouble
+
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> mole fraction of CO2 [ppm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: xCO2
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: temp
+  !> salinity [psu]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: salt
+  !> atmospheric pressure [atm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: Patm
+!f2py optional , depend(temp) :: n=len(temp)
+
+! OUTPUT variables:
+  !> oceanic partial pressure of CO2 [uatm] 
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: pCO2atm
+
+! LOCAL variables:
+  REAL(kind=wp) :: dxCO2, dPatm
+  REAL(kind=wp), DIMENSION(N) :: pH20
+  REAL(kind=wp) :: dpCO2atm
+
+  INTEGER :: i
+
+! Compute vapor pressure of seawater [in atm]
+  call vapress(temp, salt, N, pH20)
+
+  DO i = 1,N
+     dxCO2     = DBLE(xCO2(i))
+     dPatm     = DBLE(Patm(i))
+     dpCO2atm = (dPatm - pH20(i)) * dxCO2
+     pCO2atm(i) = REAL(dpCO2atm)
+  END DO
+
+  RETURN
+END SUBROUTINE x2pCO2atm
+
+! --------------------------------------------------------------------
+!  Calculate seawater vapor pressure
+! --------------------------------------------------------------------
+!
+!>    Compute vapor pressure of seawater (atm) following preocedure from Weiss & Price (1980)
+SUBROUTINE vapress(temp, salt, N, vpsw)
+  !    Purpose:
+  !    Compute vapor pressure of seawater (atm) following preocedure from Weiss & Price (1980)
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: temp
+  !> salinity [psu]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: salt
+!f2py optional , depend(temp) :: n=len(temp)
+
+! OUTPUT variables:
+  !> vapor pressure of seawater [atm] 
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: vpsw
+
+! LOCAL variables:
+  REAL(kind=wp) :: tk, dsalt
+
+  INTEGER :: i
+
+  DO i = 1,N
+     dsalt = DBLE(salt(i))
+     tk = 273.15d0 + DBLE(temp(i))     !Absolute temperature (Kelvin)
+     vpsw(i) = exp(24.4543d0 - 67.4509d0*(100.0d0/tk) - 4.8489d0*log(tk/100) - 0.000544d0*dsalt)
+  END DO
+
+  RETURN
+END SUBROUTINE vapress
+
+END MODULE mocsy_gasflux
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_mainmod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_mainmod.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_mainmod.F90	(revision 9987)
@@ -0,0 +1,2061 @@
+MODULE mocsy_mainmod
+
+      USE in_out_manager  ! I/O manager
+
+CONTAINS
+
+! ----------------------------------------------------------------------
+!  SW_ADTG
+! ----------------------------------------------------------------------
+!
+!> \file sw_adtg.f90
+!! \BRIEF 
+!> Module with sw_adtg function - compute adiabatic temp. gradient from S,T,P
+!>  Function to calculate adiabatic temperature gradient as per UNESCO 1983 routines.
+FUNCTION sw_adtg  (s,t,p)
+
+  !     ==================================================================
+  !     Calculates adiabatic temperature gradient as per UNESCO 1983 routines.
+  !     Armin Koehl akoehl@ucsd.edu
+  !     ==================================================================
+  USE mocsy_singledouble
+  IMPLICIT NONE
+  !> salinity [psu (PSU-78)]
+  REAL(kind=wp) :: s
+  !> temperature [degree C (IPTS-68)]
+  REAL(kind=wp) :: t
+  !> pressure [db]
+  REAL(kind=wp) :: p
+
+  REAL(kind=wp) :: a0,a1,a2,a3,b0,b1,c0,c1,c2,c3,d0,d1,e0,e1,e2
+  REAL(kind=wp) :: sref
+
+  REAL(kind=wp) :: sw_adtg
+
+  sref = 35.d0
+  a0 =  3.5803d-5
+  a1 = +8.5258d-6
+  a2 = -6.836d-8
+  a3 =  6.6228d-10
+
+  b0 = +1.8932d-6
+  b1 = -4.2393d-8
+
+  c0 = +1.8741d-8
+  c1 = -6.7795d-10
+  c2 = +8.733d-12
+  c3 = -5.4481d-14
+
+  d0 = -1.1351d-10
+  d1 =  2.7759d-12
+
+  e0 = -4.6206d-13
+  e1 = +1.8676d-14
+  e2 = -2.1687d-16
+
+  sw_adtg =  a0 + (a1 + (a2 + a3*T)*T)*T &
+       + (b0 + b1*T)*(S-sref) &
+       + ( (c0 + (c1 + (c2 + c3*T)*T)*T) + (d0 + d1*T)*(S-sref) )*P &
+       + (  e0 + (e1 + e2*T)*T )*P*P
+
+END FUNCTION sw_adtg
+
+! ----------------------------------------------------------------------
+!  SW_ADTG
+! ----------------------------------------------------------------------
+!
+!> \file sw_ptmp.f90
+!! \BRIEF 
+!> Module with sw_ptmp function - compute potential T from in-situ T
+!> Function to calculate potential temperature [C] from in-situ temperature
+FUNCTION sw_ptmp  (s,t,p,pr)
+
+  !     ==================================================================
+  !     Calculates potential temperature [C] from in-situ Temperature [C]
+  !     From UNESCO 1983 report.
+  !     Armin Koehl akoehl@ucsd.edu
+  !     ==================================================================
+
+  !     Input arguments:
+  !     -------------------------------------
+  !     s  = salinity            [psu      (PSS-78) ]
+  !     t  = temperature         [degree C (IPTS-68)]
+  !     p  = pressure            [db]
+  !     pr = reference pressure  [db]
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+! Input arguments
+  !> salinity [psu (PSS-78)]
+  REAL(kind=wp) :: s
+  !> temperature [degree C (IPTS-68)]
+  REAL(kind=wp) :: t
+  !> pressure [db]
+  REAL(kind=wp) :: p
+  !> reference pressure  [db]  
+  REAL(kind=wp) :: pr
+
+! local arguments
+  REAL(kind=wp) :: del_P ,del_th, th, q
+  REAL(kind=wp) :: onehalf, two, three
+  PARAMETER (onehalf = 0.5d0, two = 2.d0, three = 3.d0 )
+
+! REAL(kind=wp) :: sw_adtg
+! EXTERNAL sw_adtg
+
+! Output 
+  REAL(kind=wp) :: sw_ptmp
+
+  ! theta1
+  del_P  = PR - P
+  del_th = del_P*sw_adtg(S,T,P)
+  th     = T + onehalf*del_th
+  q      = del_th
+
+  ! theta2
+  del_th = del_P*sw_adtg(S,th,P+onehalf*del_P)
+  th     = th + (1.d0 - 1.d0/SQRT(two))*(del_th - q)
+  q      = (two-SQRT(two))*del_th + (-two+three/SQRT(two))*q
+
+  ! theta3
+  del_th = del_P*sw_adtg(S,th,P+onehalf*del_P)
+  th     = th + (1.d0 + 1.d0/SQRT(two))*(del_th - q)
+  q      = (two + SQRT(two))*del_th + (-two-three/SQRT(two))*q
+
+  ! theta4
+  del_th = del_P*sw_adtg(S,th,P+del_P)
+  sw_ptmp     = th + (del_th - two*q)/(two*three)
+
+  RETURN
+END FUNCTION sw_ptmp
+
+
+! ----------------------------------------------------------------------
+!  SW_TEMP
+! ----------------------------------------------------------------------
+!
+!> \file sw_temp.f90
+!! \BRIEF 
+!> Module with sw_temp function - compute in-situ T from potential T
+!> Function to compute in-situ temperature [C] from potential temperature [C]
+FUNCTION sw_temp( s, t, p, pr )
+  !     =============================================================
+  !     SW_TEMP
+  !     Computes in-situ temperature [C] from potential temperature [C]
+  !     Routine available in seawater.f (used for MIT GCM)
+  !     Downloaded seawater.f (on 17 April 2009) from
+  !     http://ecco2.jpl.nasa.gov/data1/beaufort/MITgcm/bin/
+  !     =============================================================
+
+  !     REFERENCES:
+  !     Fofonoff, P. and Millard, R.C. Jr
+  !     Unesco 1983. Algorithms for computation of fundamental properties of
+  !     seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.
+  !     Eqn.(31) p.39
+
+  !     Bryden, H. 1973.
+  !     "New Polynomials for thermal expansion, adiabatic temperature gradient
+  !     and potential temperature of sea water."
+  !     DEEP-SEA RES., 1973, Vol20,401-408.
+  !     =============================================================
+
+  !     Simple modifications: J. C. Orr, 16 April 2009
+  !     - combined fortran code from MITgcm site & simplification in
+  !       CSIRO code (matlab equivalent) from Phil Morgan
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !     Input arguments:
+  !     -----------------------------------------------
+  !     s  = salinity              [psu      (PSS-78) ]
+  !     t  = potential temperature [degree C (IPTS-68)]
+  !     p  = pressure              [db]
+  !     pr = reference pressure    [db]
+
+  !> salinity [psu (PSS-78)]
+  REAL(kind=wp) ::   s
+  !> potential temperature [degree C (IPTS-68)]
+  REAL(kind=wp) ::   t
+  !> pressure [db]
+  REAL(kind=wp) ::   p
+  !> reference pressure [db]
+  REAL(kind=wp) ::   pr
+
+  REAL(kind=wp) ::  ds, dt, dp, dpr
+  REAL(kind=wp) :: dsw_temp
+
+  REAL(kind=wp) ::   sw_temp
+! EXTERNAL sw_ptmp
+! REAL(kind=wp) ::   sw_ptmp
+
+  ds = DBLE(s)
+  dt = DBLE(t)
+  dp = DBLE(p)
+  dpr = DBLE(pr)
+
+  !    Simple solution
+  !    (see https://svn.mpl.ird.fr/us191/oceano/tags/V0/lib/matlab/seawater/sw_temp.m)
+  !    Carry out inverse calculation by swapping P_ref (pr) and Pressure (p)
+  !    in routine that is normally used to compute potential temp from temp
+  dsw_temp = sw_ptmp(ds, dt, dpr, dp)
+  sw_temp = REAL(dsw_temp)
+
+  !    The above simplification works extremely well (compared to Table in 1983 report)
+  !    whereas the sw_temp routine from MIT GCM site does not seem to work right
+
+  RETURN
+END FUNCTION sw_temp
+
+! ----------------------------------------------------------------------
+!  TPOT
+! ----------------------------------------------------------------------
+!
+!> \file tpot.f90
+!! \BRIEF 
+!>    Module with tpot subroutine - compute potential T from in situ T,S,P
+!>    Compute potential temperature from arrays of in situ temp, salinity, and pressure.
+!!    This subroutine is needed because sw_ptmp is a function (using scalars not arrays)
+SUBROUTINE tpot(salt, tempis, press, pressref, N, tempot)
+  !    Purpose:
+  !    Compute potential temperature from arrays of in situ temp, salinity, and pressure.
+  !    Needed because sw_ptmp is a function
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> salinity [psu]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: salt
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: tempis
+  !> pressure [db]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: press
+!f2py optional , depend(salt) :: n=len(salt)
+  !> pressure reference level [db]
+  REAL(kind=wp), INTENT(in) :: pressref
+
+! OUTPUT variables:
+  !> potential temperature [C] for pressref
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: tempot
+
+  REAL(kind=wp) :: dsalt, dtempis, dpress, dpressref
+  REAL(kind=wp) :: dtempot
+
+  INTEGER :: i
+
+! REAL(kind=wp) :: sw_ptmp
+! EXTERNAL sw_ptmp
+
+  DO i = 1,N
+     dsalt     = DBLE(salt(i))
+     dtempis   = DBLE(tempis(i))
+     dpress    = DBLE(press(i))
+     dpressref = DBLE(pressref)
+
+     dtempot   = sw_ptmp(dsalt, dtempis, dpress, dpressref)
+
+     tempot(i) = REAL(dtempot)
+  END DO
+
+  RETURN
+END SUBROUTINE tpot
+
+! ----------------------------------------------------------------------
+!  TIS
+! ----------------------------------------------------------------------
+!
+!> \file tis.f90
+!! \BRIEF 
+!>    Module with tis subroutine - compute in situ T from S,T,P
+!>    Compute in situ temperature from arrays of potential temp, salinity, and pressure.
+!!    This subroutine is needed because sw_temp is a function (using scalars not arrays)
+SUBROUTINE tis(salt, tempot, press, pressref, N, tempis)
+  !    Purpose:
+  !    Compute in situ temperature from arrays of in situ temp, salinity, and pressure.
+  !    Needed because sw_temp is a function
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> salinity [psu]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: salt
+  !> potential temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: tempot
+  !> pressure [db]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: press
+!f2py optional , depend(salt) :: n=len(salt)
+  !> pressure reference level [db]
+  REAL(kind=wp), INTENT(in) :: pressref
+
+! OUTPUT variables:
+  !> in situ temperature [C] 
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: tempis
+
+! REAL(kind=wp) :: dsalt, dtempis, dpress, dpressref
+! REAL(kind=wp) :: dtempot
+
+  INTEGER :: i
+
+! REAL(kind=wp) :: sw_temp
+! REAL(kind=wp) :: sw_temp
+! EXTERNAL sw_temp
+
+  DO i = 1,N
+    !dsalt     = DBLE(salt(i))
+    !dtempot   = DBLE(tempot(i))
+    !dpress    = DBLE(press(i))
+    !dpressref = DBLE(pressref)
+    !dtempis   = sw_temp(dsalt, dtempot, dpress, dpressref)
+    !tempis(i) = REAL(dtempis)
+
+     tempis   = sw_temp(salt(i), tempot(i), press(i), pressref)
+  END DO
+
+  RETURN
+END SUBROUTINE tis
+
+! ----------------------------------------------------------------------
+!  P80
+! ----------------------------------------------------------------------
+!
+!> \file p80.f90
+!! \BRIEF 
+!> Module with p80 function - compute pressure from depth
+!>     Function to compute pressure from depth using Saunder's (1981) formula with eos80.
+FUNCTION p80(dpth,xlat)
+
+  !     Compute Pressure from depth using Saunder's (1981) formula with eos80.
+
+  !     Reference:
+  !     Saunders, Peter M. (1981) Practical conversion of pressure
+  !     to depth, J. Phys. Ooceanogr., 11, 573-574, (1981)
+
+  !     Coded by:
+  !     R. Millard
+  !     March 9, 1983
+  !     check value: p80=7500.004 dbars at lat=30 deg., depth=7321.45 meters
+
+  !     Modified (slight format changes + added ref. details):
+  !     J. Orr, 16 April 2009
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+! Input variables:
+  !> depth [m]
+  REAL(kind=wp), INTENT(in) :: dpth
+  !> latitude [degrees]
+  REAL(kind=wp), INTENT(in) :: xlat
+
+! Output variable:
+  !> pressure [db]
+  REAL(kind=wp) :: p80
+
+! Local variables:
+  REAL(kind=wp) :: pi
+  REAL(kind=wp) :: plat, d, c1
+
+  pi=3.141592654
+
+  plat = ABS(xlat*pi/180.)
+  d  = SIN(plat)
+  c1 = 5.92e-3+d**2 * 5.25e-3
+
+  p80 = ((1-c1)-SQRT(((1-c1)**2)-(8.84e-6*dpth))) / 4.42e-6
+
+  RETURN
+END FUNCTION p80
+
+! ----------------------------------------------------------------------
+!  RHO
+! ----------------------------------------------------------------------
+!
+!> \file rho.f90
+!! \BRIEF 
+!> Module with rho function - computes in situ density from S, T, P
+!> Function to compute in situ density from salinity (psu), in situ temperature (C), & pressure (bar)
+FUNCTION rho(salt, temp, pbar)
+
+  ! Compute in situ density from salinity (psu), in situ temperature (C), & pressure (bar)
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> salinity [psu]
+  REAL(kind=wp) :: salt
+  !> in situ temperature (C)
+  REAL(kind=wp) :: temp
+  !> pressure (bar) [Note units: this is NOT in decibars]
+  REAL(kind=wp) :: pbar
+
+  REAL(kind=wp) :: s, t, p
+! REAL(kind=wp) :: t68
+  REAL(kind=wp) :: X
+  REAL(kind=wp) :: rhow, rho0
+  REAL(kind=wp) :: a, b, c
+  REAL(kind=wp) :: Ksbmw, Ksbm0, Ksbm
+  REAL(kind=wp) :: drho
+
+  REAL(kind=wp) :: rho
+
+  !     Input arguments:
+  !     -------------------------------------
+  !     s  = salinity            [psu      (PSS-78) ]
+  !     t  = in situ temperature [degree C (IPTS-68)]
+  !     p  = pressure            [bar] !!!!  (not in [db]
+
+  s = DBLE(salt)
+  t = DBLE(temp)
+  p = DBLE(pbar)
+
+! Convert the temperature on today's "ITS 90" scale to older IPTS 68 scale
+! (see Dickson et al., Best Practices Guide, 2007, Chap. 5, p. 7, including footnote)
+! According to Best-Practices guide, line above should be commented & 2 lines below should be uncommented
+! Guide's answer of rho (s=35, t=25, p=0) = 1023.343 is for temperature given on ITPS-68 scale
+! t68 = (T - 0.0002) / 0.99975
+! X = t68
+! Finally, don't do the ITS-90 to IPTS-68 conversion (T input var now already on IPTS-68 scale)
+  X = T
+
+! Density of pure water
+  rhow = 999.842594d0 + 6.793952e-2_wp*X          &
+       -9.095290e-3_wp*X*X + 1.001685e-4_wp*X**3  &
+       -1.120083e-6_wp*X**4 + 6.536332e-9_wp*X**5
+
+! Density of seawater at 1 atm, P=0
+  A = 8.24493e-1_wp - 4.0899e-3_wp*X                         &
+       + 7.6438e-5_wp*X*X - 8.2467e-7_wp*X**3 + 5.3875e-9_wp*X**4
+  B = -5.72466e-3_wp + 1.0227e-4_wp*X - 1.6546e-6_wp*X*X
+  C = 4.8314e-4_wp
+
+  rho0 = rhow + A*S + B*S*SQRT(S) + C*S**2.0d0
+
+! Secant bulk modulus of pure water
+! The secant bulk modulus is the average change in pressure
+! divided by the total change in volume per unit of initial volume.
+  Ksbmw = 19652.21d0 + 148.4206d0*X - 2.327105d0*X*X &
+       + 1.360477e-2_wp*X**3 - 5.155288e-5_wp*X**4
+
+! Secant bulk modulus of seawater at 1 atm
+  Ksbm0 = Ksbmw + S*( 54.6746d0 - 0.603459d0*X + 1.09987e-2_wp*X**2 &
+       - 6.1670e-5_wp*X**3) &
+       + S*SQRT(S)*( 7.944e-2_wp + 1.6483e-2_wp*X - 5.3009e-4_wp*X**2)
+
+! Secant bulk modulus of seawater at S,T,P
+  Ksbm = Ksbm0 &
+       + P*(3.239908d0 + 1.43713e-3_wp*X + 1.16092e-4_wp*X**2 - 5.77905e-7_wp*X**3) &
+       + P*S*(2.2838e-3_wp - 1.0981e-5_wp*X - 1.6078e-6_wp*X**2) &
+       + P*S*SQRT(S)*1.91075e-4_wp &
+       + P*P*(8.50935e-5_wp - 6.12293e-6_wp*X + 5.2787e-8_wp*X**2) &
+       + P*P*S*(-9.9348e-7_wp + 2.0816e-8_wp*X + 9.1697e-10_wp*X**2)
+
+! Density of seawater at S,T,P
+  drho = rho0/(1.0d0 - P/Ksbm)
+  rho = REAL(drho)
+
+  RETURN
+END FUNCTION rho
+
+! ----------------------------------------------------------------------
+!  RHOINSITU
+! ----------------------------------------------------------------------
+!
+!> \file rhoinsitu.f90
+!! \BRIEF 
+!> Module with rhoinsitu subroutine - compute in situ density from S, Tis, P
+!>     Compute in situ density from salinity (psu), in situ temperature (C), & pressure (db).
+!!     This subroutine is needed because rho is a function (using scalars not arrays)
+SUBROUTINE rhoinsitu(salt, tempis, pdbar, N, rhois)
+
+  !     Purpose:
+  !     Compute in situ density from salinity (psu), in situ temperature (C), & pressure (db)
+  !     Needed because rho is a function
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  INTEGER :: N
+
+! INPUT variables
+  ! salt   = salinity [psu]
+  ! tempis = in situ temperature [C]
+  ! pdbar  = pressure [db]
+
+  !> salinity [psu]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: salt
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: tempis
+  !> pressure [db]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: pdbar
+!f2py optional , depend(salt) :: n=len(salt)
+
+! OUTPUT variables:
+  ! rhois  = in situ density
+
+  !> in situ density [kg/m3]
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: rhois
+
+! Local variables
+  INTEGER :: i
+
+! REAL(kind=wp) ::  rho
+! EXTERNAL rho
+
+  DO i = 1,N
+     rhois(i) = rho(salt(i), tempis(i), pdbar(i)/10.)
+  END DO
+
+  RETURN
+END SUBROUTINE rhoinsitu
+
+! ----------------------------------------------------------------------
+!  DEPTH2PRESS
+! ----------------------------------------------------------------------
+!
+!> \file depth2press.f90
+!! \BRIEF 
+!> Module with depth2press subroutine - converts depth to pressure
+!! with Saunders (1981) formula
+!>     Compute pressure [db] from depth [m] & latitude [degrees north].
+!!     This subroutine is needed because p80 is a function (using scalars not arrays)
+SUBROUTINE depth2press(depth, lat, pdbar, N)
+
+  !     Purpose:
+  !     Compute pressure [db] from depth [m] & latitude [degrees north].
+  !     Needed because p80 is a function 
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> depth [m]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: depth
+  !> latitude [degrees]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: lat
+!f2py optional , depend(depth) :: n=len(depth)
+
+! OUTPUT variables:
+  !> pressure [db]
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: pdbar
+
+  !     Local variables
+  INTEGER :: i
+
+! REAL(kind=wp) ::  p80
+! EXTERNAL p80
+
+  DO i = 1,N
+     pdbar(i) = p80(depth(i), lat(i))
+  END DO
+
+  RETURN
+END SUBROUTINE depth2press
+
+! ----------------------------------------------------------------------
+!  CONSTANTS
+! ----------------------------------------------------------------------
+!
+!> \file constants.f90
+!! \BRIEF 
+!> Module with contants subroutine - computes carbonate system constants
+!! from S,T,P 
+!> Compute thermodynamic constants
+!! FROM temperature, salinity, and pressure (1D arrays)
+SUBROUTINE constants(K0, K1, K2, Kb, Kw, Ks, Kf, Kspc, Kspa,  &
+                     K1p, K2p, K3p, Ksi,                      &
+                     St, Ft, Bt,                              &
+                     temp, sal, Patm,                         &
+                     depth, lat, N,                           &
+                     optT, optP, optB, optK1K2, optKf, optGAS)
+
+  !   Purpose:
+  !     Compute thermodynamic constants
+  !     FROM: temperature, salinity, and pressure (1D arrays)
+
+  !     INPUT variables:
+  !     ================
+  !     Patm    = atmospheric pressure [atm]
+  !     depth   = depth [m]     (with optP='m', i.e., for a z-coordinate model vertical grid is depth, not pressure)
+  !             = pressure [db] (with optP='db')
+  !     lat     = latitude [degrees] (needed to convert depth to pressure, i.e., when optP='m')
+  !             = dummy array (unused when optP='db')
+  !     temp    = potential temperature [degrees C] (with optT='Tpot', i.e., models carry tempot, not temp)
+  !             = in situ   temperature [degrees C] (with optT='Tinsitu', e.g., for data)
+  !     sal     = salinity in [psu]
+  !     ---------
+  !     optT: choose in situ vs. potential temperature as input
+  !     ---------
+  !     NOTE: Carbonate chem calculations require IN-SITU temperature (not potential Temperature)
+  !       -> 'Tpot' means input is pot. Temperature (in situ Temp "tempis" is computed)
+  !       -> 'Tinsitu' means input is already in-situ Temperature, not pot. Temp ("tempis" not computed)
+  !     ---------
+  !     optP: choose depth (m) vs pressure (db) as input
+  !     ---------
+  !       -> 'm'  means "depth" input is in "m" (thus in situ Pressure "p" [db] is computed)
+  !       -> 'db' means "depth" input is already in situ pressure [db], not m (p = depth)
+  !     ---------
+  !     optB:
+  !     ---------
+  !       -> 'u74' means use classic formulation of Uppström (1974) for total Boron
+  !       -> 'l10' means use newer   formulation of Lee et al. (2010) for total Boron
+  !     ---------
+  !     optK1K2:
+  !     ---------
+  !       -> 'l'   means use Lueker et al. (2000) formulations for K1 & K2 (recommended by Dickson et al. 2007)
+  !                **** BUT this should only be used when 2 < T < 35 and 19 < S < 43
+  !       -> 'm10' means use Millero (2010) formulation for K1 & K2 (see Dickson et al., 2007)
+  !                **** Valid for 0 < T < 50°C and 1 < S < 50 psu
+  !       -> 'w14' means use Waters (2014) formulation for K1 & K2 (see Dickson et al., 2007)
+  !                **** Valid for 0 < T < 50°C and 1 < S < 50 psu
+  !     -----------
+  !     optKf:
+  !     ----------
+  !       -> 'pf' means use Perez & Fraga (1987) formulation for Kf (recommended by Dickson et al., 2007)
+  !               **** BUT Valid for  9 < T < 33°C and 10 < S < 40.
+  !       -> 'dg' means use Dickson & Riley (1979) formulation for Kf (recommended by Dickson & Goyet, 1994)
+  !     -----------
+  !     optGAS: choose in situ vs. potential fCO2 and pCO2
+  !     ---------
+  !       PRESSURE corrections for K0 and the fugacity coefficient (Cf) 
+  !       -> 'Pzero'   = 'zero order' fCO2 and pCO2 (typical approach, which is flawed)
+  !                      considers in situ T & only atm pressure (hydrostatic=0)
+  !       -> 'Ppot'    = 'potential' fCO2 and pCO2 (water parcel brought adiabatically to the surface)
+  !                      considers potential T & only atm pressure (hydrostatic press = 0)
+  !       -> 'Pinsitu' = 'in situ' fCO2 and pCO2 (accounts for huge effects of pressure)
+  !                      considers in situ T & total pressure (atm + hydrostatic)
+  !     ---------
+
+  !     OUTPUT variables:
+  !     =================
+  !     K0, K1, K2, Kb, Kw, Ks, Kf, Kspc, Kspa, K1p, K2p, K3p, Ksi
+  !     St, Ft, Bt
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+! Input variables
+  !>     number of records
+  INTEGER, INTENT(in) :: N
+  !> in <b>situ temperature</b> (when optT='Tinsitu', typical data) 
+  !! OR <b>potential temperature</b> (when optT='Tpot', typical models) [degree C]
+  REAL(kind=wp), INTENT(in),    DIMENSION(N) :: temp
+  !> depth in <b>meters</b> (when optP='m') or <b>decibars</b> (when optP='db')
+  REAL(kind=wp), INTENT(in),    DIMENSION(N) :: depth
+  !> latitude <b>[degrees north]</b>
+  REAL(kind=wp), INTENT(in),    DIMENSION(N) :: lat
+  !> salinity <b>[psu]</b>
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: sal
+!f2py optional , depend(sal) :: n=len(sal)
+
+  !> atmospheric pressure <b>[atm]</b>
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: Patm
+
+  !> for temp input, choose \b 'Tinsitu' for in situ Temp or 
+  !! \b 'Tpot' for potential temperature (in situ Temp is computed, needed for models)
+  CHARACTER(7), INTENT(in) :: optT
+  !> for depth input, choose \b "db" for decibars (in situ pressure) or \b "m" for meters (pressure is computed, needed for models)
+  CHARACTER(2), INTENT(in) :: optP
+  !> for total boron, choose either \b 'u74' (Uppstrom, 1974) or \b 'l10' (Lee et al., 2010).
+  !! The 'l10' formulation is based on 139 measurements (instead of 20),
+  !! uses a more accurate method, and
+  !! generally increases total boron in seawater by 4% 
+!f2py character*3 optional, intent(in) :: optB='l10'
+  CHARACTER(3), OPTIONAL, INTENT(in) :: optB
+  !> for Kf, choose either \b 'pf' (Perez & Fraga, 1987) or \b 'dg' (Dickson & Riley, 1979)
+!f2py character*2 optional, intent(in) :: optKf='pf'
+  CHARACTER(2), OPTIONAL, INTENT(in) :: optKf
+  !> for K1,K2 choose either \b 'l' (Lueker et al., 2000) or \b 'm10' (Millero, 2010) or \b 'w14' (Waters et al., 2014)
+!f2py character*3 optional, intent(in) :: optK1K2='l'
+  CHARACTER(3), OPTIONAL, INTENT(in) :: optK1K2
+  !> for K0,fugacity coefficient choose either \b 'Ppot' (no pressure correction) or \b 'Pinsitu' (with pressure correction) 
+  !! 'Ppot'    - for 'potential' fCO2 and pCO2 (water parcel brought adiabatically to the surface)
+  !! 'Pinsitu' - for 'in situ' values of fCO2 and pCO2, accounting for pressure on K0 and Cf
+  !! with 'Pinsitu' the fCO2 and pCO2 will be many times higher in the deep ocean
+!f2py character*7 optional, intent(in) :: optGAS='Pinsitu'
+  CHARACTER(7), OPTIONAL, INTENT(in) :: optGAS
+
+! Ouput variables
+  !> solubility of CO2 in seawater (Weiss, 1974), also known as K0
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: K0
+  !> K1 for the dissociation of carbonic acid from Lueker et al. (2000) or Millero (2010), depending on optK1K2
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: K1
+  !> K2 for the dissociation of carbonic acid from Lueker et al. (2000) or Millero (2010), depending on optK1K2
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: K2
+  !> equilibrium constant for dissociation of boric acid 
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Kb
+  !> equilibrium constant for the dissociation of water (Millero, 1995)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Kw
+  !> equilibrium constant for the dissociation of bisulfate (Dickson, 1990)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Ks
+  !> equilibrium constant for the dissociation of hydrogen fluoride 
+  !! either from Dickson and Riley (1979) or from Perez and Fraga (1987), depending on optKf
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Kf
+  !> solubility product for calcite (Mucci, 1983)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Kspc
+  !> solubility product for aragonite (Mucci, 1983)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Kspa
+  !> 1st dissociation constant for phosphoric acid (Millero, 1995)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: K1p
+  !> 2nd dissociation constant for phosphoric acid (Millero, 1995)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: K2p
+  !> 3rd dissociation constant for phosphoric acid (Millero, 1995)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: K3p
+  !> equilibrium constant for the dissociation of silicic acid (Millero, 1995)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Ksi
+  !> total sulfate (Morris & Riley, 1966)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: St
+  !> total fluoride  (Riley, 1965)
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Ft
+  !> total boron
+  !! from either Uppstrom (1974) or Lee et al. (2010), depending on optB
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: Bt
+
+! Local variables
+  REAL(kind=wp) :: ssal
+  REAL(kind=wp) :: p
+  REAL(kind=wp) :: tempot, tempis68, tempot68
+  REAL(kind=wp) :: tempis
+  REAL(kind=wp) :: is, invtk, dlogtk, is2, s2, sqrtis
+  REAL(kind=wp) :: Ks_0p, Kf_0p
+  REAL(kind=wp) :: total2free, free2SWS, total2SWS, SWS2total
+  REAL(kind=wp) :: total2free_0p, free2SWS_0p, total2SWS_0p
+! REAL(kind=wp) :: free2SWS, free2SWS_0p
+
+  REAL(kind=wp) :: dtempot, dtempot68
+  REAL(kind=wp) :: R
+
+  REAL(kind=wp) :: pK1o, ma1, mb1, mc1, pK1
+  REAL(kind=wp) :: pK2o, ma2, mb2, mc2, pK2
+
+  REAL(kind=wp), DIMENSION(12) :: a0, a1, a2, b0, b1, b2
+  REAL(kind=wp), DIMENSION(12) :: deltav, deltak, lnkpok0
+  REAL(kind=wp) :: tmp, nK0we74
+
+  INTEGER :: i, icount, ipc
+
+  REAL(kind=wp) :: t, tk, tk0, prb
+  REAL(kind=wp) :: s, sqrts, s15, scl
+
+  REAL(kind=wp) :: Phydro_atm, Patmd, Ptot, Rgas_atm, vbarCO2
+
+! Arrays to pass optional arguments into or use defaults (Dickson et al., 2007)
+  CHARACTER(3) :: opB
+  CHARACTER(2) :: opKf
+  CHARACTER(3) :: opK1K2
+  CHARACTER(7) :: opGAS
+
+  ! CONSTANTS
+  ! =========
+  ! Constants in formulation for Pressure effect on K's (Millero, 95)
+  ! with corrected coefficients for Kb, Kw, Ksi, etc.
+
+  ! index: 1) K1 , 2) K2, 3) Kb, 4) Kw, 5) Ks, 6) Kf, 7) Kspc, 8) Kspa,
+  !            9) K1P, 10) K2P, 11) K3P, 12) Ksi
+
+  DATA a0 /-25.5_wp, -15.82_wp, -29.48_wp, -20.02_wp, &
+          -18.03_wp,  -9.78_wp, -48.76_wp, -45.96_wp, &
+          -14.51_wp, -23.12_wp, -26.57_wp, -29.48_wp/
+  DATA a1 /0.1271_wp, -0.0219_wp, 0.1622_wp, 0.1119_wp, &
+           0.0466_wp, -0.0090_wp, 0.5304_wp, 0.5304_wp, &
+           0.1211_wp, 0.1758_wp, 0.2020_wp, 0.1622_wp/
+  DATA a2 /     0.0_wp,       0.0_wp, -2.608e-3_wp, -1.409e-3_wp, &
+           0.316e-3_wp, -0.942e-3_wp,  0.0_wp,       0.0_wp, &
+          -0.321e-3_wp, -2.647e-3_wp, -3.042e-3_wp, -2.6080e-3_wp/
+  DATA b0 /-3.08e-3_wp, 1.13e-3_wp,  -2.84e-3_wp,   -5.13e-3_wp, &
+           -4.53e-3_wp, -3.91e-3_wp, -11.76e-3_wp, -11.76e-3_wp, &
+           -2.67e-3_wp, -5.15e-3_wp,  -4.08e-3_wp,  -2.84e-3_wp/
+  DATA b1 /0.0877e-3_wp, -0.1475e-3_wp, 0.0_wp,       0.0794e-3_wp, &
+           0.09e-3_wp,    0.054e-3_wp,  0.3692e-3_wp, 0.3692e-3_wp, &
+           0.0427e-3_wp,  0.09e-3_wp,   0.0714e-3_wp, 0.0_wp/
+  DATA b2 /12*0.0_wp/
+
+! Set defaults for optional arguments (in Fortran 90)
+! Note:  Optional arguments with f2py (python) are set above with 
+!        the !f2py statements that precede each type declaraion
+  IF (PRESENT(optB)) THEN
+    opB = optB
+  ELSE
+    opB = 'l10'
+  ENDIF
+  IF (PRESENT(optKf)) THEN
+    opKf = optKf
+  ELSE
+    opKf = 'pf'
+  ENDIF
+  IF (PRESENT(optK1K2)) THEN
+    opK1K2 = optK1K2
+  ELSE
+    opK1K2 = 'l'
+  ENDIF
+  IF (PRESENT(optGAS)) THEN
+    opGAS = optGAS
+  ELSE
+    opGAS = 'Pinsitu'
+  ENDIF
+
+  R = 83.14472_wp
+
+  icount = 0
+  DO i = 1, N
+     icount = icount + 1
+!    ===============================================================
+!    Convert model depth -> press; convert model Theta -> T in situ
+!    ===============================================================
+!    * Model temperature tracer is usually "potential temperature"
+!    * Model vertical grid is usually in meters
+!    BUT carbonate chem routines require pressure & in-situ T
+!    Thus before computing chemistry, if appropriate,
+!    convert these 2 model vars (input to this routine)
+!     - depth [m] => convert to pressure [db]
+!     - potential temperature (C) => convert to in-situ T (C)
+!    -------------------------------------------------------
+!    1)  Compute pressure [db] from depth [m] and latitude [degrees] (if input is m, for models)
+     IF (trim(optP) == 'm' ) THEN
+!       Compute pressure [db] from depth [m] and latitude [degrees]
+        p = p80(depth(i), lat(i))
+     ELSEIF (trim(optP) == 'db' ) THEN
+!       In this case (where optP = 'db'), p is input & output (no depth->pressure conversion needed)
+        p = depth(i)
+     ELSE
+        PRINT *,"optP must be 'm' or 'db'"
+        STOP
+     ENDIF
+
+!    2) Convert potential T to in-situ T (if input is Tpot, i.e. case for models):
+     IF (trim(optT) == 'Tpot' .OR. trim(optT) == 'tpot') THEN
+        tempot = temp(i)
+!       This is the case for most models and some data
+!       a) Convert the pot. temp on today's "ITS 90" scale to older IPTS 68 scale
+!          (see Dickson et al., Best Practices Guide, 2007, Chap. 5, p. 7, including footnote)
+        tempot68 = (tempot - 0.0002) / 0.99975
+!       b) Compute "in-situ Temperature" from "Potential Temperature" (both on IPTS 68)
+        tempis68 = sw_temp(sal(i), tempot68, p, 0.0_wp )
+!       c) Convert the in-situ temp on older IPTS 68 scale to modern scale (ITS 90)
+        tempis = 0.99975*tempis68 + 0.0002
+!       Note: parts (a) and (c) above are tiny corrections;
+!             part  (b) is a big correction for deep waters (but zero at surface)
+     ELSEIF (trim(optT) == 'Tinsitu' .OR. trim(optT) == 'tinsitu') THEN
+!       When optT = 'Tinsitu', tempis is input & output (no tempot needed)
+        tempis    = temp(i)
+        tempis68  = (temp(i) - 0.0002) / 0.99975
+!       dtempot68 = sw_ptmp(DBLE(sal(i)), DBLE(tempis68), DBLE(p), 0.0_wp)
+        dtempot68 = sw_ptmp(sal(i), tempis68, p, 0.0_wp)
+        dtempot   = 0.99975*dtempot68 + 0.0002
+     ELSE
+        PRINT *,"optT must be either 'Tpot' or 'Tinsitu'"
+        PRINT *,"you specified optT =", trim(optT) 
+        STOP
+     ENDIF
+
+!    Compute constants:
+     IF (temp(i) >= -5. .AND. temp(i) < 1.0e+2) THEN
+!       Test to indicate if any of input variables are unreasonable
+        IF (      sal(i) < 0.  .OR.  sal(i) > 1e+3) THEN
+           PRINT *, 'i, icount, temp, sal =', i, icount, temp(i), sal(i)
+        ENDIF
+!       Zero out negative salinity (prev case for OCMIP2 model w/ slightly negative S in some coastal cells)
+        IF (sal(i) < 0.0) THEN
+           ssal = 0.0
+        ELSE
+           ssal = sal(i)
+        ENDIF
+
+!       Absolute temperature (Kelvin) and related values
+        t = DBLE(tempis)
+        tk = 273.15d0 + t
+        invtk=1.0d0/tk
+        dlogtk=LOG(tk)
+
+!       Atmospheric pressure
+        Patmd = DBLE(Patm(i))
+
+!       Hydrostatic pressure (prb is in bars)
+        prb = DBLE(p) / 10.0d0
+
+!       Salinity and simply related values
+        s = DBLE(ssal)
+        s2=s*s
+        sqrts=SQRT(s)
+        s15=s**1.5d0
+        scl=s/1.80655d0
+
+!       Ionic strength:
+        is = 19.924d0*s/(1000.0d0 - 1.005d0*s)
+        is2 = is*is
+        sqrtis = SQRT(is)
+
+!       Total concentrations for sulfate, fluoride, and boron
+
+!       Sulfate: Morris & Riley (1966)
+        St(i) = 0.14d0 * scl/96.062d0
+
+!       Fluoride:  Riley (1965)
+        Ft(i) = 0.000067d0 * scl/18.9984d0
+
+!       Boron:
+        IF (trim(opB) == 'l10') THEN
+!          New formulation from Lee et al (2010)
+           Bt(i) = 0.0002414d0 * scl/10.811d0
+        ELSEIF (trim(opB) == 'u74') THEN
+!          Classic formulation from Uppström (1974)
+           Bt(i) = 0.000232d0  * scl/10.811d0
+        ELSE
+           PRINT *,"optB must be 'l10' or 'u74'"
+           STOP
+        ENDIF
+
+!       K0 (K Henry)
+!       CO2(g) <-> CO2(aq.)
+!       K0  = [CO2]/ fCO2
+!       Weiss (1974)   [mol/kg/atm]
+        IF     (trim(opGAS) == 'Pzero'   .OR. trim(opGAS) == 'pzero') THEN
+           tk0 = tk                   !in situ temperature (K) for K0 calculation
+           Ptot = Patmd               !total pressure (in atm) = atmospheric pressure ONLY
+        ELSEIF (trim(opGAS) == 'Ppot'    .OR. trim(opGAS) == 'ppot') THEN
+           tk0 = dtempot + 273.15d0   !potential temperature (K) for K0 calculation as needed for potential fCO2 & pCO2
+           Ptot = Patmd               !total pressure (in atm) = atmospheric pressure ONLY
+        ELSEIF (trim(opGAS) == 'Pinsitu' .OR. trim(opGAS) == 'pinsitu') THEN
+           tk0 = tk                     !in situ temperature (K) for K0 calculation
+           Phydro_atm = prb / 1.01325d0 !convert hydrostatic pressure from bar to atm (1.01325 bar / atm)
+           Ptot = Patmd + Phydro_atm    !total pressure (in atm) = atmospheric pressure + hydrostatic pressure
+        ELSE
+           PRINT *, "optGAS must be 'Pzero', 'Ppot', or 'Pinsitu'"
+           STOP
+        ENDIF
+        tmp = 9345.17d0/tk0 - 60.2409d0 + 23.3585d0 * LOG(tk0/100.0d0)
+        nK0we74 = tmp + s*(0.023517d0 - 0.00023656d0*tk0 + 0.0047036e-4_wp*tk0*tk0)
+        K0(i) = EXP(nK0we74)
+
+!       K1 = [H][HCO3]/[H2CO3]
+!       K2 = [H][CO3]/[HCO3]
+        IF (trim(opK1K2) == 'l') THEN
+!         Mehrbach et al. (1973) refit, by Lueker et al. (2000) (total pH scale)
+          K1(i) = 10.0d0**(-1.0d0*(3633.86d0*invtk - 61.2172d0 + 9.6777d0*dlogtk  &
+                  - 0.011555d0*s + 0.0001152d0*s2))
+          K2(i) = 10.0d0**(-1*(471.78d0*invtk + 25.9290d0 - 3.16967d0*dlogtk      &
+                  - 0.01781d0*s + 0.0001122d0*s2))
+        ELSEIF (trim(opK1K2) == 'm10') THEN
+!         Millero (2010, Mar. Fresh Wat. Res.) (seawater pH scale)
+          pK1o = 6320.813d0*invtk + 19.568224d0*dlogtk -126.34048d0
+          ma1 = 13.4038d0*sqrts + 0.03206d0*s - (5.242e-5)*s2
+          mb1 = -530.659d0*sqrts - 5.8210d0*s
+          mc1 = -2.0664d0*sqrts
+          pK1 = pK1o + ma1 + mb1*invtk + mc1*dlogtk
+          K1(i) = 10.0d0**(-pK1) 
+
+          pK2o = 5143.692d0*invtk + 14.613358d0*dlogtk -90.18333d0
+          ma2 = 21.3728d0*sqrts + 0.1218d0*s - (3.688e-4)*s2
+          mb2 = -788.289d0*sqrts - 19.189d0*s
+          mc2 = -3.374d0*sqrts
+          pK2 = pK2o + ma2 + mb2*invtk + mc2*dlogtk
+          K2(i) = 10.0d0**(-pK2)
+        ELSEIF (trim(opK1K2) == 'w14') THEN
+!         Waters, Millero, Woosley (Mar. Chem., 165, 66-67, 2014) (seawater scale)
+          pK1o = 6320.813d0*invtk + 19.568224d0*dlogtk -126.34048d0
+          ma1 = 13.409160d0*sqrts + 0.031646d0*s - (5.1895e-5)*s2
+          mb1 = -531.3642d0*sqrts - 5.713d0*s
+          mc1 = -2.0669166d0*sqrts
+          pK1 = pK1o + ma1 + mb1*invtk + mc1*dlogtk
+          K1(i) = 10.0d0**(-pK1) 
+
+          pK2o = 5143.692d0*invtk + 14.613358d0*dlogtk -90.18333d0
+          ma2 = 21.225890d0*sqrts + 0.12450870d0*s - (3.7243e-4_r8)*s2
+          mb2 = -779.3444d0*sqrts - 19.91739d0*s
+          mc2 = -3.3534679d0*sqrts
+          pK2 = pK2o + ma2 + mb2*invtk + mc2*dlogtk
+          K2(i) = 10.0d0**(-pK2)
+        ELSE
+           PRINT *, "optK1K2 must be either 'l' or 'm10', or 'w14'"
+           STOP
+        ENDIF
+
+!       Kb = [H][BO2]/[HBO2]
+!       (total scale)
+!       Millero p.669 (1995) using data from Dickson (1990)
+        Kb(i) = EXP((-8966.90d0 - 2890.53d0*sqrts - 77.942d0*s +  &
+                1.728d0*s15 - 0.0996d0*s2)*invtk +              &
+                (148.0248d0 + 137.1942d0*sqrts + 1.62142d0*s) +   &
+                (-24.4344d0 - 25.085d0*sqrts - 0.2474d0*s) *      &
+                dlogtk + 0.053105d0*sqrts*tk)
+
+!       K1p = [H][H2PO4]/[H3PO4]
+!       (seawater scale)
+!       DOE(1994) eq 7.2.20 with footnote using data from Millero (1974)
+!       Millero (1995), p.670, eq. 65
+!       Use Millero equation's 115.540 constant instead of 115.525 (Dickson et al., 2007).
+!       The latter is only an crude approximation to convert to Total scale (by subtracting 0.015)
+!       And we want to stay on the SWS scale anyway for the pressure correction later.
+        K1p(i) = EXP(-4576.752d0*invtk + 115.540d0 - 18.453d0*dlogtk +  &
+                 (-106.736d0*invtk + 0.69171d0) * sqrts +             &
+                 (-0.65643d0*invtk - 0.01844d0) * s)
+
+!       K2p = [H][HPO4]/[H2PO4]
+!       (seawater scale)
+!       DOE(1994) eq 7.2.23 with footnote using data from Millero (1974))
+!       Millero (1995), p.670, eq. 66
+!       Use Millero equation's 172.1033 constant instead of 172.0833 (Dickson et al., 2007).
+!       The latter is only an crude approximation to convert to Total scale (by subtracting 0.015)
+!       And we want to stay on the SWS scale anyway for the pressure correction later.
+        K2p(i) = EXP(-8814.715d0*invtk + 172.1033d0 - 27.927d0*dlogtk +  &
+                 (-160.340d0*invtk + 1.3566d0)*sqrts +                 &
+                 (0.37335d0*invtk - 0.05778d0)*s)
+
+!       K3p = [H][PO4]/[HPO4]
+!       (seawater scale)
+!       DOE(1994) eq 7.2.26 with footnote using data from Millero (1974)
+!       Millero (1995), p.670, eq. 67
+!       Use Millero equation's 18.126 constant instead of 18.141 (Dickson et al., 2007).
+!       The latter is only an crude approximation to convert to Total scale (by subtracting 0.015)
+!       And we want to stay on the SWS scale anyway for the pressure correction later.
+        K3p(i) = EXP(-3070.75d0*invtk - 18.126d0 +            &
+                 (17.27039d0*invtk + 2.81197d0) *             &
+                 sqrts + (-44.99486d0*invtk - 0.09984d0) * s)
+
+!       Ksi = [H][SiO(OH)3]/[Si(OH)4]
+!       (seawater scale)
+!       Millero (1995), p.671, eq. 72
+!       Use Millero equation's 117.400 constant instead of 117.385 (Dickson et al., 2007).
+!       The latter is only an crude approximation to convert to Total scale (by subtracting 0.015)
+!       And we want to stay on the SWS scale anyway for the pressure correction later.
+        Ksi(i) = EXP(-8904.2d0*invtk  + 117.400d0 - 19.334d0*dlogtk +  &
+                 (-458.79d0*invtk + 3.5913d0) * sqrtis +             &
+                 (188.74d0*invtk - 1.5998d0) * is +                  &
+                 (-12.1652d0*invtk + 0.07871d0) * is2 +              &
+                 LOG(1.0 - 0.001005d0*s))
+
+!       Kw = [H][OH]
+!       (seawater scale)
+!       Millero (1995) p.670, eq. 63 from composite data
+!       Use Millero equation's 148.9802 constant instead of 148.9652 (Dickson et al., 2007).
+!       The latter is only an crude approximation to convert to Total scale (by subtracting 0.015)
+!       And we want to stay on the SWS scale anyway for the pressure correction later.
+        Kw(i) = EXP(-13847.26d0*invtk + 148.9802d0 - 23.6521d0*dlogtk +  &
+               (118.67d0*invtk - 5.977d0 + 1.0495d0 * dlogtk) *          &
+               sqrts - 0.01615d0 * s)
+
+!       Ks = [H][SO4]/[HSO4]
+!       (free scale)
+!       Dickson (1990, J. chem. Thermodynamics 22, 113)
+        Ks_0p = EXP(-4276.1d0*invtk + 141.328d0 - 23.093d0*dlogtk          &
+                + (-13856.d0*invtk + 324.57d0 - 47.986d0*dlogtk) * sqrtis  &
+                + (35474.d0*invtk - 771.54 + 114.723d0*dlogtk) * is      &
+                - 2698.d0*invtk*is**1.5 + 1776.d0*invtk*is2              &
+                + LOG(1.0d0 - 0.001005d0*s))
+
+!       Kf = [H][F]/[HF]
+!       (total scale)
+        IF (trim(opKf) == 'dg') THEN
+!          Dickson and Riley (1979) -- change pH scale to total (following Dickson & Goyet, 1994)
+           Kf_0p = EXP(1590.2d0*invtk - 12.641d0 + 1.525d0*sqrtis +  &
+                   LOG(1.0d0 - 0.001005d0*s) +                     &
+                   LOG(1.0d0 + St(i)/Ks_0p))
+        ELSEIF (trim(opKf) == 'pf') THEN
+!          Perez and Fraga (1987) - Already on Total scale (no need for last line above)
+!          Formulation as given in Dickson et al. (2007)
+           Kf_0p = EXP(874.d0*invtk - 9.68d0 + 0.111d0*sqrts)
+        ELSE
+           PRINT *, "optKf must be either 'dg' or 'pf'"
+           STOP
+        ENDIF
+
+!       Kspc (calcite) - apparent solubility product of calcite
+!       (no scale)
+!       Kspc = [Ca2+] [CO32-] when soln is in equilibrium w/ calcite
+!       Mucci 1983 mol/kg-soln
+        Kspc(i) = 10d0**(-171.9065d0 - 0.077993d0*tk + 2839.319d0/tk    &
+                 + 71.595d0*LOG10(tk)                             &
+                 + (-0.77712d0 + 0.0028426d0*tk + 178.34d0/tk)*sqrts  &
+                 -0.07711d0*s + 0.0041249d0*s15 )
+
+
+!       Kspa (aragonite) - apparent solubility product of aragonite
+!       (no scale)
+!       Kspa = [Ca2+] [CO32-] when soln is in equilibrium w/ aragonite
+!       Mucci 1983 mol/kg-soln
+        Kspa(i) = 10.d0**(-171.945d0 - 0.077993d0*tk + 2903.293d0/tk &
+             +71.595d0*LOG10(tk) &
+             +(-0.068393d0 + 0.0017276d0*tk + 88.135d0/tk)*sqrts &
+             -0.10018d0*s + 0.0059415d0*s15 )
+
+!       Pressure effect on K0 based on Weiss (1974, equation 5)
+        Rgas_atm = 82.05736_wp      ! (cm3 * atm) / (mol * K)  CODATA (2006)
+        vbarCO2 = 32.3_wp           ! partial molal volume (cm3 / mol) from Weiss (1974, Appendix, paragraph 3)
+        K0(i) = K0(i) * exp( ((1-Ptot)*vbarCO2)/(Rgas_atm*tk0) )   ! Weiss (1974, equation 5)
+
+!       Pressure effect on all other K's (based on Millero, (1995)
+!           index: K1(1), K2(2), Kb(3), Kw(4), Ks(5), Kf(6), Kspc(7), Kspa(8),
+!                  K1p(9), K2p(10), K3p(11), Ksi(12)
+        DO ipc = 1, 12
+           deltav(ipc)  =  a0(ipc) + a1(ipc) *t + a2(ipc) *t*t
+           deltak(ipc)   = (b0(ipc)  + b1(ipc) *t + b2(ipc) *t*t)
+           lnkpok0(ipc)  = (-(deltav(ipc)) &
+                +(0.5d0*deltak(ipc) * prb) &
+                )                         * prb/(R*tk)
+        END DO
+
+!       Pressure correction on Ks (Free scale)
+        Ks(i) = Ks_0p*EXP(lnkpok0(5))
+!       Conversion factor total -> free scale
+        total2free     = 1.d0/(1.d0 + St(i)/Ks(i))   ! Kfree = Ktotal*total2free
+!       Conversion factor total -> free scale at pressure zero
+        total2free_0p  = 1.d0/(1.d0 + St(i)/Ks_0p)   ! Kfree = Ktotal*total2free
+
+!       Pressure correction on Kf
+!       Kf must be on FREE scale before correction
+        Kf_0p = Kf_0p * total2free_0p   !Convert from Total to Free scale (pressure 0)
+        Kf(i) = Kf_0p * EXP(lnkpok0(6)) !Pressure correction (on Free scale)
+        Kf(i) = Kf(i)/total2free        !Convert back from Free to Total scale
+
+!       Convert between seawater and total hydrogen (pH) scales
+        free2SWS  = 1.d0 + St(i)/Ks(i) + Ft(i)/(Kf(i)*total2free)  ! using Kf on free scale
+        total2SWS = total2free * free2SWS                          ! KSWS = Ktotal*total2SWS
+        SWS2total = 1.d0 / total2SWS
+!       Conversion at pressure zero
+        free2SWS_0p  = 1.d0 + St(i)/Ks_0p + Ft(i)/(Kf_0p)  ! using Kf on free scale
+        total2SWS_0p = total2free_0p * free2SWS_0p         ! KSWS = Ktotal*total2SWS
+
+!       Convert from Total to Seawater scale before pressure correction
+!       Must change to SEAWATER scale: K1, K2, Kb
+        IF (trim(optK1K2) == 'l') THEN
+          K1(i)  = K1(i)*total2SWS_0p
+          K2(i)  = K2(i)*total2SWS_0p
+          !This conversion is unnecessary for the K1,K2 from Millero (2010),
+          !since we use here the formulation already on the seawater scale
+        ENDIF
+        Kb(i)  = Kb(i)*total2SWS_0p
+
+!       Already on SEAWATER scale: K1p, K2p, K3p, Kb, Ksi, Kw
+
+!       Other contants (keep on another scale):
+!          - K0         (independent of pH scale, already pressure corrected)
+!          - Ks         (already on Free scale;   already pressure corrected)
+!          - Kf         (already on Total scale;  already pressure corrected)
+!          - Kspc, Kspa (independent of pH scale; pressure-corrected below)
+
+!       Perform actual pressure correction (on seawater scale)
+        K1(i)   = K1(i)*EXP(lnkpok0(1))
+        K2(i)   = K2(i)*EXP(lnkpok0(2))
+        Kb(i)   = Kb(i)*EXP(lnkpok0(3))
+        Kw(i)   = Kw(i)*EXP(lnkpok0(4))
+        Kspc(i) = Kspc(i)*EXP(lnkpok0(7))
+        Kspa(i) = Kspa(i)*EXP(lnkpok0(8))
+        K1p(i)  = K1p(i)*EXP(lnkpok0(9))
+        K2p(i)  = K2p(i)*EXP(lnkpok0(10))
+        K3p(i)  = K3p(i)*EXP(lnkpok0(11))
+        Ksi(i)  = Ksi(i)*EXP(lnkpok0(12))
+
+!       Convert back to original total scale:
+        K1(i)  = K1(i) *SWS2total
+        K2(i)  = K2(i) *SWS2total
+        K1p(i) = K1p(i)*SWS2total
+        K2p(i) = K2p(i)*SWS2total
+        K3p(i) = K3p(i)*SWS2total
+        Kb(i)  = Kb(i) *SWS2total
+        Ksi(i) = Ksi(i)*SWS2total
+        Kw(i)  = Kw(i) *SWS2total
+
+     ELSE
+
+        K0(i)   = 1.e20_wp
+        K1(i)   = 1.e20_wp
+        K2(i)   = 1.e20_wp
+        Kb(i)   = 1.e20_wp
+        Kw(i)   = 1.e20_wp
+        Ks(i)   = 1.e20_wp
+        Kf(i)   = 1.e20_wp
+        Kspc(i) = 1.e20_wp
+        Kspa(i) = 1.e20_wp
+        K1p(i)  = 1.e20_wp
+        K2p(i)  = 1.e20_wp
+        K3p(i)  = 1.e20_wp
+        Ksi(i)  = 1.e20_wp
+        Bt(i)   = 1.e20_wp
+        Ft(i)   = 1.e20_wp
+        St(i)   = 1.e20_wp
+
+     ENDIF
+
+  END DO
+
+  RETURN
+END SUBROUTINE constants
+
+! ----------------------------------------------------------------------
+!  VARSOLVER
+! ----------------------------------------------------------------------
+!
+!> \file varsolver.f90
+!! \BRIEF 
+!> Module with varsolver subroutine - solve for pH and other carbonate system variables
+!>    Solve for pH and other carbonate system variables (with input from vars routine)
+SUBROUTINE varsolver(ph, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC,             &
+                    temp, salt, ta, tc, pt, sit,                                 &
+                    Bt, St, Ft,                                                  &
+                    K0, K1, K2, Kb, Kw, Ks, Kf, Kspc, Kspa, K1p, K2p, K3p, Ksi,  & 
+                    Patm, Phydro_bar, rhodum, optGAS                             )
+
+  !   Purpose: Solve for pH and other carbonate system variables (with input from vars routine)
+
+  !     INPUT variables:
+  !     ================
+  !     temp    = in situ temperature [degrees C]
+  !     ta      = total alkalinity                     in [eq/m^3] or [eq/kg]   based on optCON in calling routine (vars)
+  !     tc      = dissolved inorganic carbon           in [mol/m^3] or [mol/kg] based on optCON in calling routine (vars)
+  !     pt      = total dissolved inorganic phosphorus in [mol/m^3] or [mol/kg] based on optCON in calling routine (vars)
+  !     sit     = total dissolved inorganic silicon    in [mol/m^3] or [mol/kg] based on optCON in calling routine (vars)
+  !     Bt      = total dissolved inorganic boron      computed in calling routine (vars)
+  !     St      = total dissolved inorganic sulfur     computed in calling routine (vars)
+  !     Ft      = total dissolved inorganic fluorine   computed in calling routine (vars)
+  !     K's     = K0, K1, K2, Kb, Kw, Ks, Kf, Kspc, Kspa, K1p, K2p, K3p, Ksi 
+  !     Patm    = atmospheric pressure [atm]
+  !     Phydro_bar = hydrostatic pressure [bar]
+  !     rhodum  = density factor as computed in calling routine  (vars)
+  !     -----------
+  !     optGAS: choose in situ vs. potential fCO2 and pCO2 (default optGAS = 'Pinsitu')
+  !     ---------
+  !       PRESSURE & T corrections for K0 and the fugacity coefficient (Cf) 
+  !       -> 'Pzero'   = 'zero order' fCO2 and pCO2 (typical approach, which is flawed)
+  !                      considers in situ T & only atm pressure (hydrostatic=0)
+  !       -> 'Ppot'    = 'potential' fCO2 and pCO2 (water parcel brought adiabatically to the surface)
+  !                      considers potential T & only atm pressure (hydrostatic press = 0)
+  !       -> 'Pinsitu' = 'in situ' fCO2 and pCO2 (accounts for huge effects of pressure)
+  !                      considers in situ T & total pressure (atm + hydrostatic)
+  !     ---------
+
+  !     OUTPUT variables:
+  !     =================
+  !     ph   = pH on total scale
+  !     pco2 = CO2 partial pressure (uatm)
+  !     fco2 = CO2 fugacity (uatm)
+  !     co2  = aqueous CO2 concentration in [mol/kg] or [mol/m^3] determined by rhodum (depends on optCON in calling routine)
+  !     hco3 = bicarbonate (HCO3-) concentration in [mol/kg] or [mol/m^3] determined by rhodum
+  !     co3  = carbonate (CO3--) concentration in [mol/kg] or [mol/m^3] determined by rhodum
+  !     OmegaA = Omega for aragonite, i.e., the aragonite saturation state
+  !     OmegaC = Omega for calcite, i.e., the   calcite saturation state
+
+  USE mocsy_singledouble
+  USE mocsy_phsolvers
+
+  IMPLICIT NONE
+
+! Input variables
+  !> <b>in situ temperature</b> [degrees C]
+  REAL(kind=wp), INTENT(in) :: temp
+  !> <b>salinity</b> [on the practical salinity scale, dimensionless]
+  REAL(kind=wp), INTENT(in) :: salt
+  !> total alkalinity in <b>[eq/m^3]</b> OR in <b>[eq/kg]</b>, depending on optCON in calling routine
+  REAL(kind=wp), INTENT(in) :: ta
+  !> dissolved inorganic carbon in <b>[mol/m^3]</b> OR in <b>[mol/kg]</b>, depending on optCON in calling routine
+  REAL(kind=wp), INTENT(in) :: tc
+  !> phosphate concentration in <b>[mol/m^3]</b> OR in <b>[mol/kg]</b>, depending on optCON in calling routine
+  REAL(kind=wp), INTENT(in) :: pt
+  !> total dissolved inorganic silicon concentration in <b>[mol/m^3]</b> OR in <b>[mol/kg]</b>, depending on optCON in calling routine
+  REAL(kind=wp), INTENT(in) :: sit
+  !> total boron from either Uppstrom (1974) or Lee et al. (2010), depending on optB in calling routine
+  REAL(kind=wp), INTENT(in) :: Bt
+  !> total sulfate (Morris & Riley, 1966)
+  REAL(kind=wp), INTENT(in) :: St
+  !> total fluoride  (Riley, 1965)
+  REAL(kind=wp), INTENT(in) :: Ft
+  !> solubility of CO2 in seawater (Weiss, 1974), also known as K0
+  REAL(kind=wp), INTENT(in) :: K0
+  !> K1 for the dissociation of carbonic acid from Lueker et al. (2000) or Millero (2010), depending on optK1K2
+  REAL(kind=wp), INTENT(in) :: K1
+  !> K2 for the dissociation of carbonic acid from Lueker et al. (2000) or Millero (2010), depending on optK1K2
+  REAL(kind=wp), INTENT(in) :: K2
+  !> equilibrium constant for dissociation of boric acid 
+  REAL(kind=wp), INTENT(in) :: Kb
+  !> equilibrium constant for the dissociation of water (Millero, 1995)
+  REAL(kind=wp), INTENT(in) :: Kw
+  !> equilibrium constant for the dissociation of bisulfate (Dickson, 1990)
+  REAL(kind=wp), INTENT(in) :: Ks
+  !> equilibrium constant for the dissociation of hydrogen fluoride 
+  !! from Dickson and Riley (1979) or Perez and Fraga (1987), depending on optKf
+  REAL(kind=wp), INTENT(in) :: Kf
+  !> solubility product for calcite (Mucci, 1983)
+  REAL(kind=wp), INTENT(in) :: Kspc
+  !> solubility product for aragonite (Mucci, 1983)
+  REAL(kind=wp), INTENT(in) :: Kspa
+  !> 1st dissociation constant for phosphoric acid (Millero, 1995)
+  REAL(kind=wp), INTENT(in) :: K1p
+  !> 2nd dissociation constant for phosphoric acid (Millero, 1995)
+  REAL(kind=wp), INTENT(in) :: K2p
+  !> 3rd dissociation constant for phosphoric acid (Millero, 1995)
+  REAL(kind=wp), INTENT(in) :: K3p
+  !> equilibrium constant for the dissociation of silicic acid (Millero, 1995)
+  REAL(kind=wp), INTENT(in) :: Ksi
+  !> total atmospheric pressure <b>[atm]</b>
+  REAL(kind=wp), INTENT(in) :: Patm
+  !> total hydrostatic pressure <b>[bar]</b>
+  REAL(kind=wp), INTENT(in) :: Phydro_bar
+  !> density factor as computed incalling routine  (vars)
+  REAL(kind=wp), INTENT(in) :: rhodum
+  !> for K0,fugacity coefficient choose either \b 'Ppot' (no pressure correction) or \b 'Pinsitu' (with pressure correction) 
+  !! 'Ppot'    - for 'potential' fCO2 and pCO2 (water parcel brought adiabatically to the surface)
+  !! 'Pinsitu' - for 'in situ' values of fCO2 and pCO2, accounting for pressure on K0 and Cf
+  !! with 'Pinsitu' the fCO2 and pCO2 will be many times higher in the deep ocean
+!f2py character*7 optional, intent(in) :: optGAS='Pinsitu'
+  CHARACTER(7), OPTIONAL, INTENT(in) :: optGAS
+
+! Output variables:
+  !> pH on the <b>total scale</b>
+  REAL(kind=wp), INTENT(out) :: ph
+  !> CO2 partial pressure <b>[uatm]</b>
+  REAL(kind=wp), INTENT(out) :: pco2
+  !> CO2 fugacity <b>[uatm]</b>
+  REAL(kind=wp), INTENT(out) :: fco2
+  !> aqueous CO2* concentration, either in <b>[mol/m^3]</b> or <b>[mol/kg</b>] depending on choice for optCON
+  REAL(kind=wp), INTENT(out) :: co2
+  !> bicarbonate ion (HCO3-) concentration, either in <b>[mol/m^3]</b> or <b>[mol/kg]</b> depending on choice for optCON
+  REAL(kind=wp), INTENT(out) :: hco3
+  !> carbonate ion (CO3--) concentration, either in <b>[mol/m^3]</b> or <b>[mol/kg]</b> depending on choice for optCON
+  REAL(kind=wp), INTENT(out) :: co3
+  !> Omega for aragonite, i.e., the aragonite saturation state
+  REAL(kind=wp), INTENT(out) :: OmegaA
+  !> Omega for calcite, i.e., the calcite saturation state
+  REAL(kind=wp), INTENT(out) :: OmegaC
+
+! Local variables
+  REAL(kind=wp) :: Phydro_atm, Ptot
+  REAL(kind=wp) :: Rgas_atm, B, Del, xCO2approx, xc2, fugcoeff
+  REAL(kind=wp) :: tk, tk0
+  real(kind=wp) :: temp68, tempot, tempot68
+  REAL(kind=wp) :: Hinit, H
+  REAL(kind=wp) :: HSO4, HF, HSI, HPO4
+  REAL(kind=wp) :: ab, aw, ac
+  REAL(kind=wp) :: cu, cb, cc
+  REAL(kind=wp) :: Ca
+! Array to pass optional arguments
+  CHARACTER(7) :: opGAS
+
+  IF (PRESENT(optGAS)) THEN
+    opGAS = optGAS
+  ELSE
+    opGAS = 'Pinsitu'
+  ENDIF
+
+! Compute pH from constants and total concentrations
+! - use SolveSAPHE v1.0.1 routines from Munhoven (2013, GMD) modified to use mocsy's Ks instead of its own
+! 1) Compute best starting point for H+ calculation
+  call ahini_for_at(ta, tc, Bt, K1, K2, Kb, Hinit)
+! 2) Solve for H+ using above result as the initial H+ value
+  H = solve_at_general(ta, tc, Bt,                                         & 
+                       pt,     sit,                                        &
+                       St, Ft,                                             &
+                       K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi,     &
+                       Hinit)
+! 3) Calculate pH from from H+ concentration (mol/kg)
+  IF (H > 0.d0) THEN
+     pH = -1.*LOG10(H)
+  ELSE
+     pH = 1.e20_wp
+  ENDIF
+
+! Compute carbonate Alk (Ac) by difference: from total Alk and other Alk components
+  HSO4 = St/(1.0d0 + Ks/(H/(1.0d0 + St/Ks)))
+  HF = 1.0d0/(1.0d0 + Kf/H)
+  HSI = 1.0d0/(1.0d0 + H/Ksi)
+  HPO4 = (K1p*K2p*(H + 2.*K3p) - H**3) /                &
+  (H**3 + K1p*H**2 + K1p*K2p*H + K1p*K2p*K3p)
+  ab = Bt/(1.0d0 + H/Kb)
+  aw = Kw/H - H/(1.0d0 + St/Ks)
+  ac = ta + hso4 - sit*hsi - ab - aw + Ft*hf - pt*hpo4
+
+! Calculate CO2*, HCO3-, & CO32- (in mol/kg soln) from Ct, Ac, H+, K1, & K2
+  cu = (2.0d0 * tc - ac) / (2.0d0 + K1 / H)
+  cb = K1 * cu / H
+  cc = K2 * cb / H
+
+! When optCON = 'mol/m3' in calling routine (vars), then:
+! convert output var concentrations from mol/kg to mol/m^3
+! e.g., for case when drho = 1028, multiply by [1.028 kg/L  x  1000 L/m^3])
+  co2  = cu * rhodum
+  hco3 = cb * rhodum
+  co3  = cc * rhodum
+
+! Determine CO2 fugacity [uatm]
+! NOTE: equation just below requires CO2* in mol/kg
+  fCO2 = cu * 1.e6_wp/K0
+
+! Determine CO2 partial pressure from CO2 fugacity [uatm]
+  tk = 273.15d0 + temp
+  !Compute EITHER "potential pCO2" OR "in situ pCO2" (T and P used for calculations will differ)
+  IF     (trim(opGAS) == 'Pzero'   .OR. trim(opGAS) == 'pzero') THEN
+     tk0 = tk                 !in situ temperature (K) for K0 calculation
+     Ptot = Patm              !total pressure (in atm) = atmospheric pressure ONLY
+  ELSEIF (trim(opGAS) == 'Ppot' .OR. trim(opGAS) == 'ppot') THEN
+     !Use potential temperature and atmospheric pressure (water parcel adiabatically brought back to surface)
+     !temp68 = (temp - 0.0002d0) / 0.99975d0          !temp = in situ T; temp68 is same converted to ITPS-68 scale
+     !tempot68 = sw_ptmp(salt, temp68, Phydro_bar*10d0, 0.0d0) !potential temperature (C)
+     !tempot   = 0.99975*tempot68 + 0.0002
+     !tk0 = tempot + 273.15d0  !potential temperature (K) for fugacity coeff. calc as needed for potential fCO2 & pCO2
+     tempot = sw_ptmp(salt, temp, Phydro_bar*10._wp, 0.0_wp) !potential temperature (C)
+     tk0 = tempot + 273.15d0  !potential temperature (K) for fugacity coeff. calc as needed for potential fCO2 & pCO2
+     Ptot = Patm              !total pressure (in atm) = atmospheric pressure ONLY
+  ELSEIF (trim(opGAS) == 'Pinsitu' .OR. trim(opGAS) == 'pinsitu') THEN
+     !Use in situ temperature and total pressure 
+     tk0 = tk                             !in situ temperature (K) for fugacity coefficient calculation
+     Phydro_atm = Phydro_bar / 1.01325d0  !convert hydrostatic pressure from bar to atm (1.01325 bar / atm)
+     Ptot = Patm + Phydro_atm            !total pressure (in atm) = atmospheric pressure + hydrostatic pressure
+  ELSE
+     PRINT *, "optGAS must be 'Pzero', 'Ppot', or 'Pinsitu'"
+     STOP
+  ENDIF
+
+! Now that we have T and P in the right form, continue with calculation of fugacity coefficient (and pCO2)
+  Rgas_atm = 82.05736_wp      ! (cm3 * atm) / (mol * K)  CODATA (2006)
+! To compute fugcoeff, we need 3 other terms (B, Del, xc2) in addition to 3 others above (tk, Ptot, Rgas_atm)
+  B = -1636.75d0 + 12.0408d0*tk0 - 0.0327957d0*(tk0*tk0) + 0.0000316528d0*(tk0*tk0*tk0)
+  Del = 57.7d0 - 0.118d0*tk0
+! "x2" term often neglected (assumed = 1) in applications of Weiss's (1974) equation 9
+! x2 = 1 - x1 = 1 - xCO2 (it is very close to 1, but not quite)
+! Let's assume that xCO2 = fCO2. Resulting fugcoeff is identical to 8th digit after the decimal.
+  xCO2approx = fCO2 * 1.e-6_wp
+  IF (trim(opGAS) == 'Pinsitu' .OR. trim(opGAS) == 'pinsitu') THEN
+!    xCO2approx = 400.0e-6_wp      !a simple test (gives about same result as seacarb for pCO2insitu)
+!    approximate surface xCO2 ~ surface fCO2 (i.e., in situ fCO2 d by exponential pressure correction)
+     xCO2approx = xCO2approx * exp( ((1-Ptot)*32.3_wp)/(82.05736_wp*tk0) )   ! of K0 press. correction, see Weiss (1974, equation 5)
+  ENDIF
+  xc2 = (1.0d0 - xCO2approx)**2 
+  fugcoeff = exp( Ptot*(B + 2.0d0*xc2*Del)/(Rgas_atm*tk0) )
+  pCO2 = fCO2 / fugcoeff
+
+! Determine Omega Calcite et Aragonite
+! OmegaA = ((0.01028d0*salt/35.0d0)*cc) / Kspa
+! OmegaC = ((0.01028d0*salt/35.0d0)*cc) / Kspc
+! - see comments from Munhoven on the best value "0.02128" which differs slightly from the best practices guide (0.02127)
+  Ca = (0.02128d0/40.078d0) * salt/1.80655d0
+  OmegaA = (Ca*cc) / Kspa
+  OmegaC = (Ca*cc) / Kspc
+
+  RETURN
+END SUBROUTINE varsolver
+
+! ----------------------------------------------------------------------
+!  VARS
+! ----------------------------------------------------------------------
+!
+!> \file vars.f90
+!! \BRIEF 
+!> Module with vars subroutine - compute carbonate system vars from DIC,Alk,T,S,P,nuts
+!>    Computes standard carbonate system variables (pH, CO2*, HCO3- and CO32-, OmegaA, OmegaC, R)
+!!    as 1D arrays FROM
+!!    temperature, salinity, pressure,
+!!    total alkalinity (ALK), dissolved inorganic carbon (DIC),
+!!    silica and phosphate concentrations (all 1-D arrays)
+SUBROUTINE vars(ph, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, rhoSW, p, tempis,  &
+                temp, sal, alk, dic, sil, phos, Patm, depth, lat, N,                      &
+                optCON, optT, optP, optB, optK1K2, optKf, optGAS                          )
+
+  !   Purpose:
+  !     Computes other standard carbonate system variables (pH, CO2*, HCO3- and CO32-, OmegaA, OmegaC, R)
+  !     as 1D arrays
+  !     FROM:
+  !     temperature, salinity, pressure,
+  !     total alkalinity (ALK), dissolved inorganic carbon (DIC),
+  !     silica and phosphate concentrations (all 1-D arrays)
+
+  !     INPUT variables:
+  !     ================
+  !     Patm    = atmospheric pressure [atm]
+  !     depth   = depth [m]     (with optP='m', i.e., for a z-coordinate model vertical grid is depth, not pressure)
+  !             = pressure [db] (with optP='db')
+  !     lat     = latitude [degrees] (needed to convert depth to pressure, i.e., when optP='m')
+  !             = dummy array (unused when optP='db')
+  !     temp    = potential temperature [degrees C] (with optT='Tpot', i.e., models carry tempot, not in situ temp)
+  !             = in situ   temperature [degrees C] (with optT='Tinsitu', e.g., for data)
+  !     sal     = salinity in [psu]
+  !     alk     = total alkalinity in [eq/m^3] with optCON = 'mol/m3'
+  !             =               [eq/kg]  with optCON = 'mol/kg'
+  !     dic     = dissolved inorganic carbon [mol/m^3] with optCON = 'mol/m3'
+  !             =                            [mol/kg]  with optCON = 'mol/kg'
+  !     sil     = silica    [mol/m^3] with optCON = 'mol/m3'
+  !             =           [mol/kg]  with optCON = 'mol/kg'
+  !     phos    = phosphate [mol/m^3] with optCON = 'mol/m3'
+  !             =           [mol/kg]  with optCON = 'mol/kg'
+  !     INPUT options:
+  !     ==============
+  !     -----------
+  !     optCON: choose input & output concentration units - mol/kg (data) vs. mol/m^3 (models)
+  !     -----------
+  !       -> 'mol/kg' for DIC, ALK, sil, & phos given on mokal scale, i.e., in mol/kg  (std DATA units)
+  !       -> 'mol/m3' for DIC, ALK, sil, & phos given in mol/m^3 (std MODEL units)
+  !     -----------
+  !     optT: choose in situ vs. potential temperature as input
+  !     ---------
+  !     NOTE: Carbonate chem calculations require IN-SITU temperature (not potential Temperature)
+  !       -> 'Tpot' means input is pot. Temperature (in situ Temp "tempis" is computed)
+  !       -> 'Tinsitu' means input is already in-situ Temperature, not pot. Temp ("tempis" not computed)
+  !     ---------
+  !     optP: choose depth (m) vs pressure (db) as input
+  !     ---------
+  !       -> 'm'  means "depth" input is in "m" (thus in situ Pressure "p" [db] is computed)
+  !       -> 'db' means "depth" input is already in situ pressure [db], not m (thus p = depth)
+  !     ---------
+  !     optB: choose total boron formulation - Uppström (1974) vs. Lee et al. (2010)
+  !     ---------
+  !       -> 'u74' means use classic formulation of Uppström (1974) for total Boron
+  !       -> 'l10' means use newer   formulation of Lee et al. (2010) for total Boron
+  !     ---------
+  !     optK1K2:
+  !     ---------
+  !       -> 'l'   means use Lueker et al. (2000) formulations for K1 & K2 (recommended by Dickson et al. 2007)
+  !                **** BUT this should only be used when 2 < T < 35 and 19 < S < 43
+  !       -> 'm10' means use Millero (2010) formulation for K1 & K2 (see Dickson et al., 2007)
+  !                **** Valid for 0 < T < 50°C and 1 < S < 50 psu
+  !     ----------
+  !     optKf:
+  !     ----------
+  !       -> 'pf' means use Perez & Fraga (1987) formulation for Kf (recommended by Dickson et al., 2007)
+  !               **** BUT Valid for  9 < T < 33°C and 10 < S < 40.
+  !       -> 'dg' means use Dickson & Riley (1979) formulation for Kf (recommended by Dickson & Goyet, 1994)
+  !     -----------
+  !     optGAS: choose in situ vs. potential fCO2 and pCO2
+  !     ---------
+  !       PRESSURE corrections for K0 and the fugacity coefficient (Cf) 
+  !       -> 'Pzero'   = 'zero order' fCO2 and pCO2 (typical approach, which is flawed)
+  !                      considers in situ T & only atm pressure (hydrostatic=0)
+  !       -> 'Ppot'    = 'potential' fCO2 and pCO2 (water parcel brought adiabatically to the surface)
+  !                      considers potential T & only atm pressure (hydrostatic press = 0)
+  !       -> 'Pinsitu' = 'in situ' fCO2 and pCO2 (accounts for huge effects of pressure)
+  !                      considers in situ T & total pressure (atm + hydrostatic)
+  !     ---------
+
+  !     OUTPUT variables:
+  !     =================
+  !     ph   = pH on total scale
+  !     pco2 = CO2 partial pressure (uatm)
+  !     fco2 = CO2 fugacity (uatm)
+  !     co2  = aqueous CO2 concentration in [mol/kg] or [mol/m^3] depending on optCON
+  !     hco3 = bicarbonate (HCO3-) concentration in [mol/kg] or [mol/m^3] depending on optCON
+  !     co3  = carbonate (CO3--) concentration in [mol/kg] or [mol/m^3] depending on optCON
+  !     OmegaA = Omega for aragonite, i.e., the aragonite saturation state
+  !     OmegaC = Omega for calcite, i.e., the   calcite saturation state
+  !     BetaD = Revelle factor   dpCO2/pCO2 / dDIC/DIC
+  !     rhoSW  = in-situ density of seawater; rhoSW = f(s, t, p)
+  !     p = pressure [decibars]; p = f(depth, latitude) if computed from depth [m] OR p = depth if [db]
+  !     tempis  = in-situ temperature [degrees C]
+
+  USE mocsy_singledouble
+
+  IMPLICIT NONE
+
+! Input variables
+  !>     number of records
+  INTEGER, INTENT(in) :: N
+  !> either <b>in situ temperature</b> (when optT='Tinsitu', typical data) 
+  !! OR <b>potential temperature</b> (when optT='Tpot', typical models) <b>[degree C]</b>
+  REAL(kind=wp), INTENT(in),    DIMENSION(N) :: temp
+  !> salinity <b>[psu]</b>
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: sal
+  !> total alkalinity in <b>[eq/m^3]</b> (when optCON = 'mol/m3') OR in <b>[eq/kg]</b>  (when optCON = 'mol/kg')
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: alk
+  !> dissolved inorganic carbon in <b>[mol/m^3]</b> (when optCON = 'mol/m3') OR in <b>[mol/kg]</b> (when optCON = 'mol/kg')
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: dic
+  !> SiO2 concentration in <b>[mol/m^3]</b> (when optCON = 'mol/m3') OR in <b>[mol/kg]</b> (when optCON = 'mol/kg')
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: sil
+  !> phosphate concentration in <b>[mol/m^3]</b> (when optCON = 'mol/m3') OR in <b>[mol/kg]</b> (when optCON = 'mol/kg')
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: phos
+!f2py optional , depend(sal) :: n=len(sal)
+  !> atmospheric pressure <b>[atm]</b>
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: Patm
+  !> depth in \b meters (when optP='m') or \b decibars (when optP='db')
+  REAL(kind=wp), INTENT(in),    DIMENSION(N) :: depth
+  !> latitude <b>[degrees north]</b>
+  REAL(kind=wp), INTENT(in),    DIMENSION(N) :: lat
+
+  !> choose either \b 'mol/kg' (std DATA units) or \b 'mol/m3' (std MODEL units) to select 
+  !! concentration units for input (for alk, dic, sil, phos) & output (co2, hco3, co3)
+  CHARACTER(6), INTENT(in) :: optCON
+  !> choose \b 'Tinsitu' for in situ temperature or \b 'Tpot' for potential temperature (in situ Temp is computed, needed for models)
+  CHARACTER(7), INTENT(in) :: optT
+  !> for depth input, choose \b "db" for decibars (in situ pressure) or \b "m" for meters (pressure is computed, needed for models)
+  CHARACTER(2), INTENT(in) :: optP
+  !> for total boron, choose either \b 'u74' (Uppstrom, 1974) or \b 'l10' (Lee et al., 2010).
+  !! The 'l10' formulation is based on 139 measurements (instead of 20), 
+  !! uses a more accurate method, and
+  !! generally increases total boron in seawater by 4% 
+!f2py character*3 optional, intent(in) :: optB='l10'
+  CHARACTER(3), OPTIONAL, INTENT(in) :: optB
+  !> for Kf, choose either \b 'pf' (Perez & Fraga, 1987) or \b 'dg' (Dickson & Riley, 1979)
+!f2py character*2 optional, intent(in) :: optKf='pf'
+  CHARACTER(2), OPTIONAL, INTENT(in) :: optKf
+  !> for K1,K2 choose either \b 'l' (Lueker et al., 2000) or \b 'm10' (Millero, 2010) 
+!f2py character*3 optional, intent(in) :: optK1K2='l'
+  CHARACTER(3), OPTIONAL, INTENT(in) :: optK1K2
+  !> for K0,fugacity coefficient choose either \b 'Ppot' (no pressure correction) or \b 'Pinsitu' (with pressure correction) 
+  !! 'Ppot'    - for 'potential' fCO2 and pCO2 (water parcel brought adiabatically to the surface)
+  !! 'Pinsitu' - for 'in situ' values of fCO2 and pCO2, accounting for pressure on K0 and Cf
+  !! with 'Pinsitu' the fCO2 and pCO2 will be many times higher in the deep ocean
+!f2py character*7 optional, intent(in) :: optGAS='Pinsitu'
+  CHARACTER(7), OPTIONAL, INTENT(in) :: optGAS
+
+! Output variables:
+  !> pH on the <b>total scale</b>
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: ph
+  !> CO2 partial pressure <b>[uatm]</b>
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: pco2
+  !> CO2 fugacity <b>[uatm]</b>
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: fco2
+  !> aqueous CO2* concentration, either in <b>[mol/m^3]</b> or <b>[mol/kg</b>] depending on choice for optCON
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: co2
+  !> bicarbonate ion (HCO3-) concentration, either in <b>[mol/m^3]</b> or <b>[mol/kg]</b> depending on choice for optCON
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: hco3
+  !> carbonate ion (CO3--) concentration, either in <b>[mol/m^3]</b> or <b>[mol/kg]</b> depending on choice for optCON
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: co3
+  !> Omega for aragonite, i.e., the aragonite saturation state
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: OmegaA
+  !> Omega for calcite, i.e., the calcite saturation state
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: OmegaC
+  !> Revelle factor, i.e., dpCO2/pCO2 / dDIC/DIC
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: BetaD
+  !> in-situ density of seawater; rhoSW = f(s, t, p) in <b>[kg/m3]</b>
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: rhoSW
+  !> pressure <b>[decibars]</b>; p = f(depth, latitude) if computed from depth [m] (when optP='m') OR p = depth [db] (when optP='db')
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: p
+  !> in-situ temperature \b <b>[degrees C]</b>
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: tempis
+
+! Local variables
+  REAL(kind=wp) :: ssal, salk, sdic, ssil, sphos
+  REAL(kind=wp) :: tempot, tempis68, tempot68
+  REAL(kind=wp) :: drho
+
+  REAL(kind=wp) :: K0, K1, K2, Kb, Kw, Ks, Kf, Kspc
+  REAL(kind=wp) :: Kspa, K1p, K2p, K3p, Ksi
+  REAL(kind=wp) :: St, Ft, Bt
+
+  REAL(kind=wp), DIMENSION(1) :: aK0, aK1, aK2, aKb, aKw, aKs, aKf, aKspc
+  REAL(kind=wp), DIMENSION(1) :: aKspa, aK1p, aK2p, aK3p, aKsi
+  REAL(kind=wp), DIMENSION(1) :: aSt, aFt, aBt
+
+  REAL(kind=wp) :: Patmd, Ptot, Rgas_atm, B, Del, xCO2approx, xc2, fugcoeff
+  REAL(kind=wp) :: Phydro_atm
+
+  INTEGER :: i, icount
+
+  REAL(kind=wp) :: t, tk, prb
+  REAL(kind=wp) :: s
+  REAL(kind=wp) :: tc, ta
+  REAL(kind=wp) :: sit, pt
+  REAL(kind=wp) :: Hinit
+  REAL(kind=wp) :: ah1
+
+  REAL(kind=wp) :: HSO4, HF, HSI, HPO4
+  REAL(kind=wp) :: ab, aw, ac, ah2, erel
+
+  REAL(kind=wp) :: cu, cb, cc
+
+  REAL(kind=wp), DIMENSION(2) :: dicdel, pco2del
+  REAL(kind=wp) :: dx, Rf
+  REAL(kind=wp) :: dph, dpco2, dfco2, dco2, dhco3, dco3, dOmegaA, dOmegaC
+
+  INTEGER :: kcomp
+  INTEGER :: j, minusplus
+
+! Arrays to pass optional arguments into or use defaults (Dickson et al., 2007)
+  CHARACTER(3) :: opB
+  CHARACTER(2) :: opKf
+  CHARACTER(3) :: opK1K2
+  CHARACTER(7) :: opGAS
+
+! Set defaults for optional arguments (in Fortran 90)
+! Note:  Optional arguments with f2py (python) are set above with 
+!        the !f2py statements that precede each type declaraion
+  IF (PRESENT(optB)) THEN
+!   print *,"optB present:"
+!   print *,"optB = ", optB 
+    opB = optB
+  ELSE
+!   Default is Lee et al (2010) for total boron
+!   print *,"optB NOT present:"
+    opB = 'l10'
+!   print *,"opB = ", opB 
+  ENDIF
+  IF (PRESENT(optKf)) THEN
+!   print *,"optKf = ", optKf
+    opKf = optKf
+  ELSE
+!   print *,"optKf NOT present:"
+!   Default is Perez & Fraga (1987) for Kf
+    opKf = 'pf'
+!   print *,"opKf = ", opKf
+  ENDIF
+  IF (PRESENT(optK1K2)) THEN
+!   print *,"optK1K2 = ", optK1K2
+    opK1K2 = optK1K2
+  ELSE
+!   print *,"optK1K2 NOT present:"
+!   Default is Lueker et al. 2000) for K1 & K2
+    opK1K2 = 'l'
+!   print *,"opK1K2 = ", opK1K2
+  ENDIF
+  IF (PRESENT(optGAS)) THEN
+    opGAS = optGAS
+  ELSE
+    opGAS = 'Pinsitu'
+  ENDIF
+
+  icount = 0
+  DO i = 1, N
+     icount = icount + 1
+!    ===============================================================
+!    Convert model depth -> press; convert model Theta -> T in situ
+!    ===============================================================
+!    * Model temperature tracer is usually "potential temperature"
+!    * Model vertical grid is usually in meters
+!    BUT carbonate chem routines require pressure & in-situ T
+!    Thus before computing chemistry, if appropriate,
+!    convert these 2 model vars (input to this routine)
+!    - depth [m] => convert to pressure [db]
+!    - potential temperature (C) => convert to in-situ T (C)
+!    -------------------------------------------------------
+!    1)  Compute pressure [db] from depth [m] and latitude [degrees] (if input is m, for models)
+     !print *,"optP =", optP, "end"
+     IF (trim(optP) == 'm' ) THEN
+!       Compute pressure [db] from depth [m] and latitude [degrees]
+        p(i) = p80(depth(i), lat(i))
+     ELSEIF (trim(optP) == 'db') THEN
+!       In this case (where optP = 'db'), p is input & output (no depth->pressure conversion needed)
+        p(i) = depth(i)
+     ELSE
+        !print *,"optP =", optP, "end"
+        PRINT *,"optP must be either 'm' or 'db'"
+        STOP
+     ENDIF
+
+!    2) Convert potential T to in-situ T (if input is Tpot, i.e. case for models):
+     IF (trim(optT) == 'Tpot' .OR. trim(optT) == 'tpot') THEN
+        tempot = temp(i)
+!       This is the case for most models and some data
+!       a) Convert the pot. temp on today's "ITS 90" scale to older IPTS 68 scale
+!          (see Dickson et al., Best Practices Guide, 2007, Chap. 5, p. 7, including footnote)
+        tempot68 = (tempot - 0.0002) / 0.99975
+!       b) Compute "in-situ Temperature" from "Potential Temperature" (both on IPTS 68)
+        tempis68 = sw_temp(sal(i), tempot68, p(i), 0.0_wp )
+!       c) Convert the in-situ temp on older IPTS 68 scale to modern scale (ITS 90)
+        tempis(i) = 0.99975*tempis68 + 0.0002
+!       Note: parts (a) and (c) above are tiny corrections;
+!             part  (b) is a big correction for deep waters (but zero at surface)
+     ELSEIF (trim(optT) == 'Tinsitu' .OR. trim(optT) == 'tinsitu') THEN
+!       When optT = 'Tinsitu', tempis is input & output (no tempot needed)
+        tempis(i) = temp(i)
+        tempis68  = (temp(i) - 0.0002) / 0.99975
+!       dtempot68 = sw_ptmp(DBLE(sal(i)), DBLE(tempis68), DBLE(p), 0.0d0)
+!       dtempot   = 0.99975*dtempot68 + 0.0002
+     ELSE
+        PRINT *,"optT must be either 'Tpot' or 'Tinsitu'"
+        PRINT *,"you specified optT =", trim(optT) 
+        STOP
+     ENDIF
+
+!    ================================================================
+!    Carbonate chemistry computations
+!    ================================================================
+     IF (dic(i) > 0. .AND. dic(i) < 1.0e+4) THEN
+!       Test to indicate if any of input variables are unreasonable
+        IF (       sal(i) < 0.   &
+             .OR.  alk(i) < 0.   &
+             .OR.  dic(i) < 0.   &
+             .OR.  sil(i) < 0.   &
+             .OR. phos(i) < 0.   &
+             .OR.  sal(i) > 1e+3 &
+             .OR.  alk(i) > 1e+3 &
+             .OR.  dic(i) > 1e+3 &
+             .OR.  sil(i) > 1e+3 &
+             .OR. phos(i) > 1e+3) THEN
+           PRINT *, 'i, icount, tempot, sal,    alk,    dic,    sil,    phos =', &
+                     i, icount, tempot, sal(i), alk(i), dic(i), sil(i), phos(i)
+        ENDIF
+!       Zero out any negative salinity, phosphate, silica, dic, and alk
+        IF (sal(i) < 0.0) THEN
+           ssal = 0.0
+        ELSE
+           ssal = sal(i)
+        ENDIF
+        IF (phos(i) < 0.0) THEN
+           sphos = 0.0
+        ELSE
+           sphos = phos(i)
+        ENDIF
+        IF (sil(i) < 0.0) THEN
+           ssil = 0.0
+        ELSE
+           ssil = sil(i)
+        ENDIF
+        IF (dic(i) < 0.0) THEN
+          sdic = 0.0
+        ELSE
+          sdic = dic(i)
+        ENDIF
+        IF (alk(i) < 0.0) THEN
+          salk = 0.0
+        ELSE
+          salk = alk(i)
+        ENDIF
+
+!       Absolute temperature (Kelvin) & related variables
+        t  = DBLE(tempis(i))
+        tk = 273.15d0 + t
+
+!       Atmospheric pressure
+        Patmd = DBLE(Patm(i))
+!       Hydrostatic pressure (prb is in bars)
+        prb = DBLE(p(i)) / 10.0d0
+        Phydro_atm = prb / 1.01325d0  ! convert hydrostatic pressure from bar to atm (1.01325 bar / atm)
+!       Total pressure [atm]
+        IF     (trim(opGAS) == 'Pzero'     .OR. trim(opGAS) == 'pzero') THEN
+           Ptot = Patmd               ! total pressure (in atm) = atmospheric pressure ONLY
+        ELSEIF (trim(opGAS) == 'Ppot'    .OR. trim(opGAS) == 'ppot') THEN
+           Ptot = Patmd               ! total pressure (in atm) = atmospheric pressure ONLY
+        ELSEIF (trim(opGAS) == 'Pinsitu' .OR. trim(opGAS) == 'pinsitu') THEN
+           Ptot = Patmd + Phydro_atm   ! total pressure (in atm) = atmospheric pressure + hydrostatic pressure
+        ELSE
+           PRINT *, "optGAS must be 'Pzero', 'Ppot', or 'Pinsitu'"
+           STOP
+        ENDIF
+
+!       Salinity (equivalent array in double precision)
+        s = DBLE(ssal)
+
+!       Get all equilibrium constants and total concentrations of SO4, F, B
+        CALL constants(aK0, aK1, aK2, aKb, aKw, aKs, aKf, aKspc, aKspa,  &
+                       aK1p, aK2p, aK3p, aKsi,                           &
+                       aSt, aFt, aBt,                                    &
+                       temp(i), sal(i), Patm(i),                         &
+                       depth(i), lat(i), 1,                              &
+                       optT, optP, opB, opK1K2, opKf, opGAS              )
+
+!       Unlike f77, in F90 we can't assign an array (dimen=1) to a scalar in a routine argument
+!       Thus, set scalar constants equal to array (dimension=1) values required as arguments
+        K0 = aK0(1) ; K1 = aK1(1) ; K2 = aK2(1) ; Kb = aKb(1) ; Kw = aKw(1) 
+        Ks = aKs(1) ; Kf = aKs(1) ; Kspc = aKspc(1) ; Kspa = aKspa(1) 
+        K1p = aK1p(1) ; K2p = aK2p(1) ; K3p = aK3p(1) ; Ksi = aKsi(1)
+        St = aSt(1) ; Ft = aFt(1) ; Bt = aBt(1)
+
+!       Compute in-situ density [kg/m^3]
+        rhoSW(i) =  rho(ssal, tempis68, prb)
+
+!       Either convert units of DIC and ALK (MODEL case) or not (DATA case)
+        IF     (trim(optCON) == 'mol/kg') THEN
+!          No conversion:
+!          print *,'DIC and ALK already given in mol/kg (std DATA units)'
+           drho = 1.
+        ELSEIF (trim(optCON) == 'mol/m3') THEN
+!          Do conversion:
+!          print *,"DIC and ALK given in mol/m^3 (std MODEL units)"
+           drho = DBLE(rhoSW(i))
+        ELSE
+           PRINT *,"optCON must be either 'mol/kg' or 'mol/m3'"
+           STOP
+        ENDIF
+
+        tc  = DBLE(sdic)/drho
+        ta  = DBLE(salk)/drho
+        sit = DBLE(ssil)/drho
+        pt  = DBLE(sphos)/drho
+
+!       Solve for pH and all other variables
+!       ------------------------------------
+        CALL varsolver(dph, dpco2, dfco2, dco2, dhco3, dco3, dOmegaA, dOmegaC,     &
+                      t, s, ta, tc, pt, sit,                                       &
+                      Bt, St, Ft,                                                  &
+                      K0, K1, K2, Kb, Kw, Ks, Kf, Kspc, Kspa, K1p, K2p, K3p, Ksi,  & 
+                      Patmd, prb, drho, opGAS                                     )
+
+!       Convert all output variables from double to single precision
+        pH(i)     = REAL(dph)
+        co2(i)    = REAL(dco2)
+        hco3(i)   = REAL(dhco3)
+        co3(i)    = REAL(dco3)
+        fCO2(i)   = REAL(dfCO2)
+        pCO2(i)   = REAL(dpCO2)
+        OmegaA(i) = REAL(dOmegaA)
+        OmegaC(i) = REAL(dOmegaC)
+
+!       Compute Revelle factor numerically (derivative using centered-difference scheme)
+        DO j=1,2
+           minusplus = (-1)**j
+           dx = 0.1 * 1e-6         ! Numerical tests found for DIC that optimal dx = 0.1 umol/kg (0.1e-6 mol/kg)
+           dicdel(j) = tc + DBLE(minusplus)*dx/2.0d0
+            CALL varsolver(dph, dpco2, dfco2, dco2, dhco3, dco3, dOmegaA, dOmegaC, &
+               t, s, ta, dicdel(j), pt, sit,                                       &
+               Bt, St, Ft,                                                         &
+               K0, K1, K2, Kb, Kw, Ks, Kf, Kspc, Kspa, K1p, K2p, K3p, Ksi,         & 
+               Patmd, prb, drho, optGAS                                            )
+            pco2del(j) = dpco2
+        END DO
+       !Classic finite centered difference formula for derivative (2nd order accurate)
+        Rf = (pco2del(2) - pco2del(1)) / (dicdel(2) - dicdel(1))       ! dpCO2/dDIC
+       !Rf = (pco2del(2) - pco2del(1)) / (dx)                          ! dpCO2/dDIC (same as just above)
+        Rf = Rf * tc / dpco2                                           ! R = (dpCO2/dDIC) * (DIC/pCO2)
+
+        BetaD(i) = REAL(Rf)
+
+     ELSE
+
+        ph(i)     = 1.e20_wp
+        pco2(i)   = 1.e20_wp
+        fco2(i)   = 1.e20_wp
+        co2(i)    = 1.e20_wp
+        hco3(i)   = 1.e20_wp
+        co3(i)    = 1.e20_wp
+        OmegaA(i) = 1.e20_wp
+        OmegaC(i) = 1.e20_wp
+        BetaD(i)  = 1.e20_wp
+        rhoSW(i)  = 1.e20_wp
+        p(i)      = 1.e20_wp
+        tempis(i) = 1.e20_wp
+
+     ENDIF
+
+  END DO
+
+  RETURN
+END SUBROUTINE vars
+
+! ----------------------------------------------------------------------
+!  P2FCO2
+! ----------------------------------------------------------------------
+!
+!> \file p2fCO2.f90
+!! \BRIEF 
+!>    Module with p2fCO2 subroutine - compute fCO2 from pCO2, in situ T, atm pressure, hydrostatic pressure
+!>    Compute fCO2 from arrays of pCO2, in situ temp, atm pressure, & hydrostatic pressure
+SUBROUTINE p2fCO2(pCO2, temp, Patm, p, N, fCO2)
+  !    Purpose:
+  !    Compute fCO2 from arrays of pCO2, in situ temp, atm pressure, & hydrostatic pressure
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, INTENT(in) :: N
+
+! INPUT variables
+  !> oceanic partial pressure of CO2 [uatm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: pCO2
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: temp
+  !> atmospheric pressure [atm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: Patm
+  !> hydrostatic pressure [db]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: p
+
+! OUTPUT variables:
+  !> fugacity of CO2 [uatm] 
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: fCO2
+
+! LOCAL variables:
+  REAL(kind=wp) :: dpCO2, dtemp, tk, dPatm, prb
+  REAL(kind=wp) :: Ptot, Rgas_atm, B, Del, xCO2approx, xc2, fugcoeff
+  REAL(kind=wp) :: dfCO2
+
+  INTEGER :: i
+
+! REAL(kind=wp) :: sw_ptmp
+! EXTERNAL sw_ptmp
+
+  DO i = 1,N
+     dpCO2     = DBLE(pCO2(i))
+     dtemp     = DBLE(temp(i))
+     dPatm     = DBLE(Patm(i))
+     tk = 273.15d0 + DBLE(temp(i))     !Absolute temperature (Kelvin)
+     prb = DBLE(p(i)) / 10.0d0         !Pressure effect (prb is in bars)
+     Ptot = dPatm + prb/1.01325d0      !Total pressure (atmospheric + hydrostatic) [atm]
+     Rgas_atm = 82.05736_wp            !R in (cm3 * atm) / (mol * K)  from CODATA (2006)
+!    To compute fugcoeff, we need 3 other terms (B, Del, xc2) as well as 3 others above (tk, Ptot, Rgas_atm)
+     B = -1636.75d0 + 12.0408d0*tk - 0.0327957d0*(tk*tk) + 0.0000316528d0*(tk*tk*tk)
+     Del = 57.7d0 - 0.118d0*tk
+!    "x2" term often neglected (assumed = 1) in applications of Weiss's (1974) equation 9
+!    x2 = 1 - x1 = 1 - xCO2 (it is very close to 1, but not quite)
+!    Let's assume that xCO2 = pCO2. Resulting fugcoeff is identical to 8th digit after the decimal.
+     xCO2approx = dpCO2 * 1.e-6_wp
+     xc2 = (1.0d0 - xCO2approx)**2 
+     fugcoeff = EXP( Ptot*(B + 2.0d0*xc2*Del)/(Rgas_atm*tk) )
+     dfCO2 = dpCO2 * fugcoeff
+     fCO2(i) = REAL(dfCO2)
+  END DO
+
+  RETURN
+END SUBROUTINE p2fCO2
+
+! ----------------------------------------------------------------------
+!  P2FCO2
+! ----------------------------------------------------------------------
+!
+!> \file f2pCO2.f90
+!! \BRIEF 
+!>    Module with f2pCO2 subroutine - compute pCO2 from fCO2, in situ T, atm pressure, hydrostatic pressure
+!>    Compute pCO2 from arrays of fCO2, in situ temp, atm pressure, & hydrostatic pressure
+SUBROUTINE f2pCO2(fCO2, temp, Patm, p, N, pCO2)
+  !    Purpose:
+  !    Compute pCO2 from arrays of fCO2, in situ temp, atm pressure, & hydrostatic pressure
+
+  USE mocsy_singledouble
+  IMPLICIT NONE
+
+  !> number of records
+  INTEGER, intent(in) :: N
+
+! INPUT variables
+  !> oceanic fugacity of CO2 [uatm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: fCO2
+  !> in situ temperature [C]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: temp
+  !> atmospheric pressure [atm]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: Patm
+  !> hydrostatic pressure [db]
+  REAL(kind=wp), INTENT(in), DIMENSION(N) :: p
+
+! OUTPUT variables:
+  !> oceanic partial pressure of CO2 [uatm] 
+  REAL(kind=wp), INTENT(out), DIMENSION(N) :: pCO2
+
+! LOCAL variables:
+  REAL(kind=wp) :: dfCO2, dtemp, tk, dPatm, prb
+  REAL(kind=wp) :: Ptot, Rgas_atm, B, Del, xCO2approx, xc2, fugcoeff
+  REAL(kind=wp) :: dpCO2
+
+  INTEGER :: i
+
+! REAL(kind=wp) :: sw_ptmp
+! EXTERNAL sw_ptmp
+
+  DO i = 1,N
+     dfCO2     = DBLE(fCO2(i))
+     dtemp     = DBLE(temp(i))
+     dPatm     = DBLE(Patm(i))
+     tk = 273.15d0 + DBLE(temp(i))     !Absolute temperature (Kelvin)
+     prb = DBLE(p(i)) / 10.0d0         !Pressure effect (prb is in bars)
+     Ptot = dPatm + prb/1.01325d0      !Total pressure (atmospheric + hydrostatic) [atm]
+     Rgas_atm = 82.05736_wp            !R in (cm3 * atm) / (mol * K)  from CODATA (2006)
+!    To compute fugcoeff, we need 3 other terms (B, Del, xc2) as well as 3 others above (tk, Ptot, Rgas_atm)
+     B = -1636.75d0 + 12.0408d0*tk - 0.0327957d0*(tk*tk) + 0.0000316528d0*(tk*tk*tk)
+     Del = 57.7d0 - 0.118d0*tk
+!    "x2" term often neglected (assumed = 1) in applications of Weiss's (1974) equation 9
+!    x2 = 1 - x1 = 1 - xCO2 (it is very close to 1, but not quite)
+!    Let's assume that xCO2 = fCO2. Resulting fugcoeff is identical to 8th digit after the decimal.
+     xCO2approx = dfCO2 * 1.e-6_wp
+     xc2 = (1.0d0 - xCO2approx)**2 
+     fugcoeff = exp( Ptot*(B + 2.0d0*xc2*Del)/(Rgas_atm*tk) )
+     dpCO2 = dfCO2 / fugcoeff
+     pCO2(i) = REAL(dpCO2)
+  END DO
+
+  RETURN
+END SUBROUTINE f2pCO2
+
+END MODULE mocsy_mainmod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_phsolvers.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_phsolvers.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_phsolvers.F90	(revision 9987)
@@ -0,0 +1,860 @@
+!> \file mocsy_phsolvers.f90
+!! \BRIEF 
+!> Module with routines needed to solve pH-total alkalinity equation (Munhoven, 2013, GMD)
+MODULE mocsy_phsolvers
+!   Module of fastest solvers from Munhoven (2013, Geosci. Model Dev., 6, 1367-1388)
+!   ! Taken from SolveSAPHE (mod_phsolvers.F90) & adapted very slightly for use with mocsy
+!   ! SolveSaphe is distributed under the GNU Lesser General Public License
+!   ! mocsy is distributed under the MIT License
+!
+! Modifications J. C. Orr, LSCE/IPSL, CEA-CNRS-UVSQ, France, 11 Sep 2014:
+! 1) kept only the 3 fastest solvers (atgen, atsec, atfast) and routines which they call
+! 2) reduced vertical white space: deleted many blank lines & comment lines that served as divisions
+! 3) converted name from .F90 to .f90, deleting a few optional preprocesse if statements
+! 4) read in mocsy computed equilibrium constants (as arguments) instead of USE MOD_CHEMCONST
+! 5) converted routine names from upper case to lower case
+! 6) commented out arguments and equations for NH4 and H2S acid systems
+
+USE mocsy_singledouble
+IMPLICIT NONE
+
+! General parameters
+REAL(KIND=wp), PARAMETER :: pp_rdel_ah_target = 1.E-8_wp
+REAL(KIND=wp), PARAMETER :: pp_ln10 = 2.302585092994045684018_wp
+
+! Maximum number of iterations for each method
+INTEGER, PARAMETER :: jp_maxniter_atgen    = 50
+INTEGER, PARAMETER :: jp_maxniter_atsec    = 50
+INTEGER, PARAMETER :: jp_maxniter_atfast   = 50
+
+! Bookkeeping variables for each method
+! - SOLVE_AT_GENERAL
+INTEGER :: niter_atgen    = jp_maxniter_atgen
+
+! - SOLVE_AT_GENERAL_SEC
+INTEGER :: niter_atsec    = jp_maxniter_atsec
+
+! - SOLVE_AT_FAST (variant of SOLVE_AT_GENERAL w/o bracketing
+INTEGER :: niter_atfast   = jp_maxniter_atfast
+
+! Keep the following functions private to avoid conflicts with
+! other modules that provide similar ones.
+!PRIVATE AHINI_FOR_AT
+
+CONTAINS
+!===============================================================================
+SUBROUTINE anw_infsup(p_dictot, p_bortot,                                     &
+                      p_po4tot, p_siltot,                                     &
+                      p_so4tot, p_flutot,                                     &
+                      p_alknw_inf, p_alknw_sup)
+
+! Subroutine returns the lower and upper bounds of "non-water-selfionization"
+! contributions to total alkalinity (the infimum and the supremum), i.e
+! inf(TA - [OH-] + [H+]) and sup(TA - [OH-] + [H+])
+
+USE mocsy_singledouble
+IMPLICIT NONE
+
+! Argument variables
+REAL(KIND=wp), INTENT(IN)  :: p_dictot
+REAL(KIND=wp), INTENT(IN)  :: p_bortot
+REAL(KIND=wp), INTENT(IN)  :: p_po4tot
+REAL(KIND=wp), INTENT(IN)  :: p_siltot
+!REAL(KIND=wp), INTENT(IN)  :: p_nh4tot
+!REAL(KIND=wp), INTENT(IN)  :: p_h2stot
+REAL(KIND=wp), INTENT(IN)  :: p_so4tot
+REAL(KIND=wp), INTENT(IN)  :: p_flutot
+REAL(KIND=wp), INTENT(OUT) :: p_alknw_inf
+REAL(KIND=wp), INTENT(OUT) :: p_alknw_sup
+
+p_alknw_inf =  -p_po4tot - p_so4tot - p_flutot
+p_alknw_sup =   p_dictot + p_dictot + p_bortot &
+              + p_po4tot + p_po4tot + p_siltot !&
+!             + p_nh4tot + p_h2stot
+
+RETURN
+END SUBROUTINE anw_infsup
+
+!===============================================================================
+
+FUNCTION equation_at(p_alktot, p_h,       p_dictot, p_bortot,                 &
+                     p_po4tot, p_siltot,                                      &
+                     p_so4tot, p_flutot,                                      &
+                     K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi,          &
+                     p_deriveqn)
+
+USE mocsy_singledouble
+IMPLICIT NONE
+REAL(KIND=wp) :: equation_at
+
+! Argument variables
+REAL(KIND=wp), INTENT(IN)            :: p_alktot
+REAL(KIND=wp), INTENT(IN)            :: p_h
+REAL(KIND=wp), INTENT(IN)            :: p_dictot
+REAL(KIND=wp), INTENT(IN)            :: p_bortot
+REAL(KIND=wp), INTENT(IN)            :: p_po4tot
+REAL(KIND=wp), INTENT(IN)            :: p_siltot
+!REAL(KIND=wp), INTENT(IN)            :: p_nh4tot
+!REAL(KIND=wp), INTENT(IN)            :: p_h2stot
+REAL(KIND=wp), INTENT(IN)            :: p_so4tot
+REAL(KIND=wp), INTENT(IN)            :: p_flutot
+REAL(KIND=wp), INTENT(IN)            :: K0, K1, K2, Kb, Kw, Ks, Kf
+REAL(KIND=wp), INTENT(IN)            :: K1p, K2p, K3p, Ksi
+REAL(KIND=wp), INTENT(OUT), OPTIONAL :: p_deriveqn
+
+! Local variables 
+!-----------------
+REAL(KIND=wp) :: znumer_dic, zdnumer_dic, zdenom_dic, zalk_dic, zdalk_dic
+REAL(KIND=wp) :: znumer_bor, zdnumer_bor, zdenom_bor, zalk_bor, zdalk_bor
+REAL(KIND=wp) :: znumer_po4, zdnumer_po4, zdenom_po4, zalk_po4, zdalk_po4
+REAL(KIND=wp) :: znumer_sil, zdnumer_sil, zdenom_sil, zalk_sil, zdalk_sil
+REAL(KIND=wp) :: znumer_nh4, zdnumer_nh4, zdenom_nh4, zalk_nh4, zdalk_nh4
+REAL(KIND=wp) :: znumer_h2s, zdnumer_h2s, zdenom_h2s, zalk_h2s, zdalk_h2s
+REAL(KIND=wp) :: znumer_so4, zdnumer_so4, zdenom_so4, zalk_so4, zdalk_so4
+REAL(KIND=wp) :: znumer_flu, zdnumer_flu, zdenom_flu, zalk_flu, zdalk_flu
+REAL(KIND=wp) ::                                      zalk_wat, zdalk_wat
+REAL(KIND=wp) :: aphscale
+
+! TOTAL H+ scale: conversion factor for Htot = aphscale * Hfree
+aphscale = 1._wp + p_so4tot/Ks
+
+! H2CO3 - HCO3 - CO3 : n=2, m=0
+znumer_dic = 2._wp*K1*K2 + p_h*       K1
+zdenom_dic =       K1*K2 + p_h*(      K1 + p_h)
+zalk_dic   = p_dictot * (znumer_dic/zdenom_dic)
+
+! B(OH)3 - B(OH)4 : n=1, m=0
+znumer_bor =       Kb
+zdenom_bor =       Kb + p_h
+zalk_bor   = p_bortot * (znumer_bor/zdenom_bor)
+
+! H3PO4 - H2PO4 - HPO4 - PO4 : n=3, m=1
+znumer_po4 = 3._wp*K1p*K2p*K3p + p_h*(2._wp*K1p*K2p + p_h* K1p)
+zdenom_po4 =       K1p*K2p*K3p + p_h*(      K1p*K2p + p_h*(K1p + p_h))
+zalk_po4   = p_po4tot * (znumer_po4/zdenom_po4 - 1._wp) ! Zero level of H3PO4 = 1
+
+! H4SiO4 - H3SiO4 : n=1, m=0
+znumer_sil =       Ksi
+zdenom_sil =       Ksi + p_h
+zalk_sil   = p_siltot * (znumer_sil/zdenom_sil)
+
+! NH4 - NH3 : n=1, m=0
+!znumer_nh4 =       api1_nh4
+!zdenom_nh4 =       api1_nh4 + p_h
+!zalk_nh4   = p_nh4tot * (znumer_nh4/zdenom_nh4)
+! Note: api1_nh4 = Knh4
+
+! H2S - HS : n=1, m=0
+!znumer_h2s =       api1_h2s
+!zdenom_h2s =       api1_h2s + p_h
+!zalk_h2s   = p_h2stot * (znumer_h2s/zdenom_h2s)
+! Note: api1_h2s = Kh2s
+
+! HSO4 - SO4 : n=1, m=1
+znumer_so4 =       Ks
+zdenom_so4 =       Ks + p_h
+zalk_so4   = p_so4tot * (znumer_so4/zdenom_so4 - 1._wp)
+
+! HF - F : n=1, m=1
+znumer_flu =       Kf
+zdenom_flu =       Kf + p_h
+zalk_flu   = p_flutot * (znumer_flu/zdenom_flu - 1._wp)
+
+! H2O - OH
+zalk_wat   = Kw/p_h - p_h/aphscale
+
+equation_at =    zalk_dic + zalk_bor + zalk_po4 + zalk_sil &
+               + zalk_so4 + zalk_flu                       &
+               + zalk_wat - p_alktot
+
+IF(PRESENT(p_deriveqn)) THEN
+   ! H2CO3 - HCO3 - CO3 : n=2
+   zdnumer_dic = K1*K1*K2 + p_h*(4._wp*K1*K2               &
+                          + p_h*       K1    )
+   zdalk_dic   = -p_dictot*(zdnumer_dic/zdenom_dic**2)
+
+   ! B(OH)3 - B(OH)4 : n=1
+   zdnumer_bor = Kb
+   zdalk_bor   = -p_bortot*(zdnumer_bor/zdenom_bor**2)
+
+   ! H3PO4 - H2PO4 - HPO4 - PO4 : n=3
+   zdnumer_po4 = K1p*K2p*K1p*K2p*K3p + p_h*(4._wp*K1p*K1p*K2p*K3p                &
+                                     + p_h*(9._wp*K1p*K2p*K3p + K1p*K1p*K2p      &
+                                     + p_h*(4._wp*K1p*K2p                        &
+                                     + p_h*       K1p)))
+   zdalk_po4   = -p_po4tot * (zdnumer_po4/zdenom_po4**2)
+
+   ! H4SiO4 - H3SiO4 : n=1
+   zdnumer_sil = Ksi
+   zdalk_sil   = -p_siltot * (zdnumer_sil/zdenom_sil**2)
+
+!  ! NH4 - NH3 : n=1
+!  zdnumer_nh4 = Knh4
+!  zdalk_nh4   = -p_nh4tot * (zdnumer_nh4/zdenom_nh4**2)
+
+!  ! H2S - HS : n=1
+!  zdnumer_h2s = api1_h2s
+!  zdalk_h2s   = -p_h2stot * (zdnumer_h2s/zdenom_h2s**2)
+
+   ! HSO4 - SO4 : n=1
+   zdnumer_so4 = Ks
+   zdalk_so4   = -p_so4tot * (zdnumer_so4/zdenom_so4**2)
+
+   ! HF - F : n=1
+   zdnumer_flu = Kf
+   zdalk_flu   = -p_flutot * (zdnumer_flu/zdenom_flu**2)
+
+!  p_deriveqn =   zdalk_dic + zdalk_bor + zdalk_po4 + zdalk_sil &
+!               + zdalk_nh4 + zdalk_h2s + zdalk_so4 + zdalk_flu &
+!               - Kw/p_h**2 - 1._wp/aphscale
+   p_deriveqn =   zdalk_dic + zdalk_bor + zdalk_po4 + zdalk_sil &
+                                        + zdalk_so4 + zdalk_flu &
+                - Kw/p_h**2 - 1._wp/aphscale
+ENDIF
+RETURN
+END FUNCTION equation_at
+
+!===============================================================================
+
+SUBROUTINE ahini_for_at(p_alkcb, p_dictot, p_bortot, K1, K2, Kb, p_hini)
+
+! Subroutine returns the root for the 2nd order approximation of the
+! DIC -- B_T -- A_CB equation for [H+] (reformulated as a cubic polynomial)
+! around the local minimum, if it exists.
+
+! Returns * 1E-03_wp if p_alkcb <= 0
+!         * 1E-10_wp if p_alkcb >= 2*p_dictot + p_bortot
+!         * 1E-07_wp if 0 < p_alkcb < 2*p_dictot + p_bortot
+!                    and the 2nd order approximation does not have a solution
+
+!USE MOD_CHEMCONST, ONLY : api1_dic, api2_dic, api1_bor
+
+USE mocsy_singledouble
+IMPLICIT NONE
+
+! Argument variables 
+!--------------------
+REAL(KIND=wp), INTENT(IN)   ::  p_alkcb, p_dictot, p_bortot
+REAL(KIND=wp), INTENT(IN)   ::  K1, K2, Kb
+REAL(KIND=wp), INTENT(OUT)  ::  p_hini
+
+! Local variables 
+!-----------------
+REAL(KIND=wp)  ::  zca, zba
+REAL(KIND=wp)  ::  zd, zsqrtd, zhmin
+REAL(KIND=wp)  ::  za2, za1, za0
+
+IF (p_alkcb <= 0._wp) THEN
+  p_hini = 1.e-3_wp
+ELSEIF (p_alkcb >= (2._wp*p_dictot + p_bortot)) THEN
+  p_hini = 1.e-10_wp
+ELSE
+  zca = p_dictot/p_alkcb
+  zba = p_bortot/p_alkcb
+
+  ! Coefficients of the cubic polynomial
+  za2 = Kb*(1._wp - zba) + K1*(1._wp-zca)
+  za1 = K1*Kb*(1._wp - zba - zca) + K1*K2*(1._wp - (zca+zca))
+  za0 = K1*K2*Kb*(1._wp - zba - (zca+zca))
+                                        ! Taylor expansion around the minimum
+  zd = za2*za2 - 3._wp*za1              ! Discriminant of the quadratic equation
+                                        ! for the minimum close to the root
+
+  IF(zd > 0._wp) THEN                   ! If the discriminant is positive
+    zsqrtd = SQRT(zd)
+    IF(za2 < 0) THEN
+      zhmin = (-za2 + zsqrtd)/3._wp
+    ELSE
+      zhmin = -za1/(za2 + zsqrtd)
+    ENDIF
+    p_hini = zhmin + SQRT(-(za0 + zhmin*(za1 + zhmin*(za2 + zhmin)))/zsqrtd)
+  ELSE
+    p_hini = 1.e-7_wp
+  ENDIF
+
+ENDIF
+RETURN
+END SUBROUTINE ahini_for_at
+
+!===============================================================================
+
+FUNCTION solve_at_general(p_alktot, p_dictot, p_bortot,                       &
+                          p_po4tot, p_siltot,                                 &
+                          p_so4tot, p_flutot,                                 &
+                          K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi,     &
+                          p_hini,   p_val)
+
+! Universal pH solver that converges from any given initial value,
+! determines upper an lower bounds for the solution if required
+
+USE mocsy_singledouble
+IMPLICIT NONE
+REAL(KIND=wp) :: SOLVE_AT_GENERAL
+
+! Argument variables 
+!--------------------
+REAL(KIND=wp), INTENT(IN)            :: p_alktot
+REAL(KIND=wp), INTENT(IN)            :: p_dictot
+REAL(KIND=wp), INTENT(IN)            :: p_bortot
+REAL(KIND=wp), INTENT(IN)            :: p_po4tot
+REAL(KIND=wp), INTENT(IN)            :: p_siltot
+!REAL(KIND=wp), INTENT(IN)            :: p_nh4tot
+!REAL(KIND=wp), INTENT(IN)            :: p_h2stot
+REAL(KIND=wp), INTENT(IN)            :: p_so4tot
+REAL(KIND=wp), INTENT(IN)            :: p_flutot
+REAL(KIND=wp), INTENT(IN)            :: K0, K1, K2, Kb, Kw, Ks, Kf
+REAL(KIND=wp), INTENT(IN)            :: K1p, K2p, K3p, Ksi
+REAL(KIND=wp), INTENT(IN), OPTIONAL  :: p_hini
+REAL(KIND=wp), INTENT(OUT), OPTIONAL :: p_val
+
+! Local variables 
+!-----------------
+REAL(KIND=wp)  ::  zh_ini, zh, zh_prev, zh_lnfactor
+REAL(KIND=wp)  ::  zalknw_inf, zalknw_sup
+REAL(KIND=wp)  ::  zh_min, zh_max
+REAL(KIND=wp)  ::  zdelta, zh_delta
+REAL(KIND=wp)  ::  zeqn, zdeqndh, zeqn_absmin
+REAL(KIND=wp)  ::  aphscale
+LOGICAL        :: l_exitnow
+REAL(KIND=wp), PARAMETER :: pz_exp_threshold = 1.0_wp
+
+! TOTAL H+ scale: conversion factor for Htot = aphscale * Hfree
+aphscale = 1._wp + p_so4tot/Ks
+
+IF(PRESENT(p_hini)) THEN
+   zh_ini = p_hini
+ELSE
+   CALL ahini_for_at(p_alktot, p_dictot, p_bortot, K1, K2, Kb, zh_ini)
+ENDIF
+
+ CALL anw_infsup(p_dictot, p_bortot,                                           &
+                 p_po4tot, p_siltot,                                           &
+                 p_so4tot, p_flutot,                                           &
+                 zalknw_inf, zalknw_sup)
+
+zdelta = (p_alktot-zalknw_inf)**2 + 4._wp*Kw/aphscale
+
+IF(p_alktot >= zalknw_inf) THEN
+   zh_min = 2._wp*Kw /( p_alktot-zalknw_inf + SQRT(zdelta) )
+ELSE
+   zh_min = aphscale*(-(p_alktot-zalknw_inf) + SQRT(zdelta) ) / 2._wp
+ENDIF
+
+zdelta = (p_alktot-zalknw_sup)**2 + 4._wp*Kw/aphscale
+
+IF(p_alktot <= zalknw_sup) THEN
+   zh_max = aphscale*(-(p_alktot-zalknw_sup) + SQRT(zdelta) ) / 2._wp
+ELSE
+   zh_max = 2._wp*Kw /( p_alktot-zalknw_sup + SQRT(zdelta) )
+ENDIF
+
+zh = MAX(MIN(zh_max, zh_ini), zh_min)
+niter_atgen        = 0                 ! Reset counters of iterations
+zeqn_absmin        = HUGE(1._wp)
+
+DO
+   IF(niter_atgen >= jp_maxniter_atgen) THEN
+      zh = -1._wp
+      EXIT
+   ENDIF
+
+   zh_prev = zh
+   zeqn = equation_at(p_alktot, zh,       p_dictot, p_bortot,                  &
+                      p_po4tot, p_siltot,                                      &
+                      p_so4tot, p_flutot,                                      &
+                      K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi,          &
+                      P_DERIVEQN = zdeqndh)
+
+   ! Adapt bracketing interval
+   IF(zeqn > 0._wp) THEN
+      zh_min = zh_prev
+   ELSEIF(zeqn < 0._wp) THEN
+      zh_max = zh_prev
+   ELSE
+      ! zh is the root; unlikely but, one never knows
+      EXIT
+   ENDIF
+
+   ! Now determine the next iterate zh
+   niter_atgen = niter_atgen + 1
+
+   IF(ABS(zeqn) >= 0.5_wp*zeqn_absmin) THEN
+      ! if the function evaluation at the current point is
+      ! not decreasing faster than with a bisection step (at least linearly)
+      ! in absolute value take one bisection step on [ph_min, ph_max]
+      ! ph_new = (ph_min + ph_max)/2d0
+      !
+      ! In terms of [H]_new:
+      ! [H]_new = 10**(-ph_new)
+      !         = 10**(-(ph_min + ph_max)/2d0)
+      !         = SQRT(10**(-(ph_min + phmax)))
+      !         = SQRT(zh_max * zh_min)
+      zh = SQRT(zh_max * zh_min)
+      zh_lnfactor = (zh - zh_prev)/zh_prev ! Required to test convergence below
+   ELSE
+      ! dzeqn/dpH = dzeqn/d[H] * d[H]/dpH
+      !           = -zdeqndh * LOG(10) * [H]
+      ! \Delta pH = -zeqn/(zdeqndh*d[H]/dpH) = zeqn/(zdeqndh*[H]*LOG(10))
+      !
+      ! pH_new = pH_old + \deltapH
+      !
+      ! [H]_new = 10**(-pH_new)
+      !         = 10**(-pH_old - \Delta pH)
+      !         = [H]_old * 10**(-zeqn/(zdeqndh*[H]_old*LOG(10)))
+      !         = [H]_old * EXP(-LOG(10)*zeqn/(zdeqndh*[H]_old*LOG(10)))
+      !         = [H]_old * EXP(-zeqn/(zdeqndh*[H]_old))
+
+      zh_lnfactor = -zeqn/(zdeqndh*zh_prev)
+
+      IF(ABS(zh_lnfactor) > pz_exp_threshold) THEN
+         zh          = zh_prev*EXP(zh_lnfactor)
+      ELSE
+         zh_delta    = zh_lnfactor*zh_prev
+         zh          = zh_prev + zh_delta
+      ENDIF
+
+      IF( zh < zh_min ) THEN
+         ! if [H]_new < [H]_min
+         ! i.e., if ph_new > ph_max then
+         ! take one bisection step on [ph_prev, ph_max]
+         ! ph_new = (ph_prev + ph_max)/2d0
+         ! In terms of [H]_new:
+         ! [H]_new = 10**(-ph_new)
+         !         = 10**(-(ph_prev + ph_max)/2d0)
+         !         = SQRT(10**(-(ph_prev + phmax)))
+         !         = SQRT([H]_old*10**(-ph_max))
+         !         = SQRT([H]_old * zh_min)
+         zh                = SQRT(zh_prev * zh_min)
+         zh_lnfactor       = (zh - zh_prev)/zh_prev ! Required to test convergence below
+      ENDIF
+
+      IF( zh > zh_max ) THEN
+         ! if [H]_new > [H]_max
+         ! i.e., if ph_new < ph_min, then
+         ! take one bisection step on [ph_min, ph_prev]
+         ! ph_new = (ph_prev + ph_min)/2d0
+         ! In terms of [H]_new:
+         ! [H]_new = 10**(-ph_new)
+         !         = 10**(-(ph_prev + ph_min)/2d0)
+         !         = SQRT(10**(-(ph_prev + ph_min)))
+         !         = SQRT([H]_old*10**(-ph_min))
+         !         = SQRT([H]_old * zhmax)
+         zh                = SQRT(zh_prev * zh_max)
+         zh_lnfactor       = (zh - zh_prev)/zh_prev ! Required to test convergence below
+      ENDIF
+   ENDIF
+
+   zeqn_absmin = MIN( ABS(zeqn), zeqn_absmin)
+
+   ! Stop iterations once |\delta{[H]}/[H]| < rdel
+   ! <=> |(zh - zh_prev)/zh_prev| = |EXP(-zeqn/(zdeqndh*zh_prev)) -1| < rdel
+   ! |EXP(-zeqn/(zdeqndh*zh_prev)) -1| ~ |zeqn/(zdeqndh*zh_prev)|
+
+   ! Alternatively:
+   ! |\Delta pH| = |zeqn/(zdeqndh*zh_prev*LOG(10))|
+   !             ~ 1/LOG(10) * |\Delta [H]|/[H]
+   !             < 1/LOG(10) * rdel
+
+   ! Hence |zeqn/(zdeqndh*zh)| < rdel
+
+   ! rdel <-- pp_rdel_ah_target
+
+   l_exitnow = (ABS(zh_lnfactor) < pp_rdel_ah_target)
+
+   IF(l_exitnow) EXIT
+ENDDO
+
+solve_at_general = zh
+
+IF(PRESENT(p_val)) THEN
+   IF(zh > 0._wp) THEN
+      p_val = equation_at(p_alktot, zh,       p_dictot, p_bortot,              &
+                          p_po4tot, p_siltot,                                  &
+                          p_so4tot, p_flutot,                                  &
+                          K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi)    
+   ELSE
+      p_val = HUGE(1._wp)
+   ENDIF
+ENDIF
+RETURN
+END FUNCTION solve_at_general
+
+!===============================================================================
+
+FUNCTION solve_at_general_sec(p_alktot, p_dictot, p_bortot,                   &
+                              p_po4tot, p_siltot,                             &
+                              p_so4tot, p_flutot,                             &
+                              K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi, &
+                              p_hini,   p_val) 
+
+! Universal pH solver that converges from any given initial value,
+! determines upper an lower bounds for the solution if required
+
+!USE MOD_CHEMCONST, ONLY: api1_wat, aphscale
+USE mocsy_singledouble
+IMPLICIT NONE
+REAL(KIND=wp) :: SOLVE_AT_GENERAL_SEC
+
+! Argument variables 
+REAL(KIND=wp), INTENT(IN)            :: p_alktot
+REAL(KIND=wp), INTENT(IN)            :: p_dictot
+REAL(KIND=wp), INTENT(IN)            :: p_bortot
+REAL(KIND=wp), INTENT(IN)            :: p_po4tot
+REAL(KIND=wp), INTENT(IN)            :: p_siltot
+!REAL(KIND=wp), INTENT(IN)            :: p_nh4tot
+!REAL(KIND=wp), INTENT(IN)            :: p_h2stot
+REAL(KIND=wp), INTENT(IN)            :: p_so4tot
+REAL(KIND=wp), INTENT(IN)            :: p_flutot
+REAL(KIND=wp), INTENT(IN)            :: K0, K1, K2, Kb, Kw, Ks, Kf
+REAL(KIND=wp), INTENT(IN)            :: K1p, K2p, K3p, Ksi
+REAL(KIND=wp), INTENT(IN), OPTIONAL  :: p_hini
+REAL(KIND=wp), INTENT(OUT), OPTIONAL :: p_val
+
+! Local variables
+REAL(KIND=wp)  ::  zh_ini, zh, zh_1, zh_2, zh_delta
+REAL(KIND=wp)  ::  zalknw_inf, zalknw_sup
+REAL(KIND=wp)  ::  zh_min, zh_max
+REAL(KIND=wp)  ::  zeqn, zeqn_1, zeqn_2, zeqn_absmin
+REAL(KIND=wp)  ::  zdelta
+REAL(KIND=wp)  ::  aphscale
+LOGICAL        ::  l_exitnow
+
+! TOTAL H+ scale: conversion factor for Htot = aphscale * Hfree
+aphscale = 1._wp + p_so4tot/Ks
+
+IF(PRESENT(p_hini)) THEN
+   zh_ini = p_hini
+ELSE
+   CALL ahini_for_at(p_alktot, p_dictot, p_bortot, K1, K2, Kb, zh_ini)
+ENDIF
+
+ CALL anw_infsup(p_dictot, p_bortot,                                      &
+                 p_po4tot, p_siltot,                                      &
+                 p_so4tot, p_flutot,                                      &
+                 zalknw_inf, zalknw_sup)
+
+zdelta = (p_alktot-zalknw_inf)**2 + 4._wp*Kw/aphscale
+
+IF(p_alktot >= zalknw_inf) THEN
+   zh_min = 2._wp*Kw /( p_alktot-zalknw_inf + SQRT(zdelta) )
+ELSE
+   zh_min = aphscale*(-(p_alktot-zalknw_inf) + SQRT(zdelta) ) / 2._wp
+ENDIF
+
+zdelta = (p_alktot-zalknw_sup)**2 + 4._wp*Kw/aphscale
+
+IF(p_alktot <= zalknw_sup) THEN
+   zh_max = aphscale*(-(p_alktot-zalknw_sup) + SQRT(zdelta) ) / 2._wp
+ELSE
+   zh_max = 2._wp*Kw /( p_alktot-zalknw_sup + SQRT(zdelta) )
+ENDIF
+
+zh = MAX(MIN(zh_max, zh_ini), zh_min)
+niter_atsec        = 0                 ! Reset counters of iterations
+
+! Prepare the secant iterations: two initial (zh, zeqn) pairs are required
+! We have the starting value, that needs to be completed by the evaluation
+! of the equation value it produces.
+
+! Complete the initial value with its equation evaluation
+! (will take the role of the $n-2$ iterate at the first secant evaluation)
+
+niter_atsec = 0                        ! zh_2 is the initial value;
+
+zh_2   = zh
+zeqn_2 = equation_at(p_alktot, zh_2,     p_dictot, p_bortot,                 &
+                     p_po4tot, p_siltot,                                     &
+                     p_so4tot, p_flutot,                                     &
+                     K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi)
+
+zeqn_absmin        = ABS(zeqn_2)
+
+! Adapt bracketing interval and heuristically set zh_1
+IF(zeqn_2 < 0._wp) THEN
+                                       ! If zeqn_2 < 0, then we adjust zh_max:
+                                       ! we can be sure that zh_min < zh_2 < zh_max.
+   zh_max = zh_2
+                                       ! for zh_1, try 25% (0.1 pH units) below the current zh_max,
+                                       ! but stay above SQRT(zh_min*zh_max), which would be equivalent
+                                       ! to a bisection step on [pH@zh_min, pH@zh_max]
+   zh_1   = MAX(zh_max/1.25_wp, SQRT(zh_min*zh_max))
+ELSEIF(zeqn_2 > 0._wp) THEN
+                                       ! If zeqn_2 < 0, then we adjust zh_min:
+                                       ! we can be sure that zh_min < zh_2 < zh_max.
+   zh_min = zh_2
+                                       ! for zh_1, try 25% (0.1 pH units) above the current zh_min,
+                                       ! but stay below SQRT(zh_min*zh_max) which would be equivalent
+                                       ! to a bisection step on [pH@zh_min, pH@zh_max]
+   zh_1   = MIN(zh_min*1.25_wp, SQRT(zh_min*zh_max))
+ELSE ! we have got the root; unlikely, but one never knows
+   solve_at_general_sec = zh_2
+   IF(PRESENT(p_val)) p_val = zeqn_2
+   RETURN
+ENDIF
+
+! We now have the first pair completed (zh_2, zeqn_2).
+! Define the second one (zh_1, zeqn_1), which is also the first iterate.
+! zh_1 has already been set above
+niter_atsec = 1                        ! Update counter of iterations
+
+zeqn_1 = equation_at(p_alktot, zh_1,       p_dictot, p_bortot,                 &
+                     p_po4tot, p_siltot,                                       &
+                     p_so4tot, p_flutot,                                       &
+                     K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi)
+
+! Adapt bracketing interval: we know that zh_1 <= zh <= zh_max (if zeqn_1 > 0)
+! or zh_min <= zh <= zh_1 (if zeqn_1 < 0), so this can always be done
+IF(zeqn_1 > 0._wp) THEN
+   zh_min = zh_1
+ELSEIF(zeqn_1 < 0._wp) THEN
+   zh_max = zh_1
+ELSE ! zh_1 is the root
+   solve_at_general_sec = zh_1
+   IF(PRESENT(p_val)) p_val = zeqn_1
+ENDIF
+
+IF(ABS(zeqn_1) > zeqn_absmin) THEN     ! Swap zh_2 and zh_1 if ABS(zeqn_2) < ABS(zeqn_1)
+                                       ! so that zh_2 and zh_1 lead to decreasing equation
+                                       ! values (in absolute value)
+   zh     = zh_1
+   zeqn   = zeqn_1
+   zh_1   = zh_2
+   zeqn_1 = zeqn_2
+   zh_2   = zh
+   zeqn_2 = zeqn
+ELSE
+   zeqn_absmin = ABS(zeqn_1)
+ENDIF
+
+! Pre-calculate the first secant iterate (this is the second iterate)
+niter_atsec = 2
+
+zh_delta = -zeqn_1/((zeqn_2-zeqn_1)/(zh_2 - zh_1))
+zh = zh_1 + zh_delta
+
+! Make sure that zh_min < zh < zh_max (if not,
+! bisect around zh_1 which is the best estimate)
+IF (zh > zh_max) THEN                  ! this can only happen if zh_2 < zh_1
+                                       ! and zeqn_2 > zeqn_1 > 0
+   zh = SQRT(zh_1*zh_max)
+ENDIF
+
+IF (zh < zh_min) THEN                  ! this can only happen if zh_2 > zh_1
+                                       ! and zeqn_2 < zeqn_1 < 0
+   zh = SQRT(zh_1*zh_min)
+ENDIF
+
+DO
+   IF(niter_atsec >= jp_maxniter_atsec) THEN
+      zh = -1._wp
+      EXIT
+   ENDIF
+
+   zeqn = equation_at(p_alktot, zh,       p_dictot, p_bortot,                  &
+                      p_po4tot, p_siltot,                                      &
+                      p_so4tot, p_flutot,                                      &
+                      K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi)
+
+   ! Adapt bracketing interval: since initially, zh_min <= zh <= zh_max
+   ! we are sure that zh will improve either bracket, depending on the sign
+   ! of zeqn
+   IF(zeqn > 0._wp) THEN
+     zh_min = zh
+   ELSEIF(zeqn < 0._wp) THEN
+     zh_max = zh
+   ELSE
+     ! zh is the root
+     EXIT
+   ENDIF
+
+   ! start calculation of next iterate
+   niter_atsec = niter_atsec + 1
+
+   zh_2   = zh_1
+   zeqn_2 = zeqn_1
+   zh_1   = zh
+   zeqn_1 = zeqn
+
+   IF(ABS(zeqn) >= 0.5_wp*zeqn_absmin) THEN
+      ! if the function evaluation at the current point
+      ! is not decreasing faster in absolute value than
+      ! we may expect for a bisection step, then take
+      ! one bisection step on [ph_min, ph_max]
+      ! ph_new = (ph_min + ph_max)/2d0
+      ! In terms of [H]_new:
+      ! [H]_new = 10**(-ph_new)
+      !         = 10**(-(ph_min + ph_max)/2d0)
+      !         = SQRT(10**(-(ph_min + phmax)))
+      !         = SQRT(zh_max * zh_min)
+      zh                = SQRT(zh_max * zh_min)
+      zh_delta           = zh - zh_1
+   ELSE
+      ! \Delta H = -zeqn_1*(h_2 - h_1)/(zeqn_2 - zeqn_1) 
+      ! H_new = H_1 + \Delta H
+      zh_delta = -zeqn_1/((zeqn_2-zeqn_1)/(zh_2 - zh_1))
+      zh       = zh_1 + zh_delta
+
+      IF( zh < zh_min ) THEN
+         ! if [H]_new < [H]_min
+         ! i.e., if ph_new > ph_max then
+         ! take one bisection step on [ph_prev, ph_max]
+         ! ph_new = (ph_prev + ph_max)/2d0
+         ! In terms of [H]_new:
+         ! [H]_new = 10**(-ph_new)
+         !         = 10**(-(ph_prev + ph_max)/2d0)
+         !         = SQRT(10**(-(ph_prev + phmax)))
+         !         = SQRT([H]_old*10**(-ph_max))
+         !         = SQRT([H]_old * zh_min)
+         zh                = SQRT(zh_1 * zh_min)
+         zh_delta          = zh - zh_1
+      ENDIF
+
+      IF( zh > zh_max ) THEN
+         ! if [H]_new > [H]_max
+         ! i.e., if ph_new < ph_min, then
+         ! take one bisection step on [ph_min, ph_prev]
+         ! ph_new = (ph_prev + ph_min)/2d0
+         ! In terms of [H]_new:
+         ! [H]_new = 10**(-ph_new)
+         !         = 10**(-(ph_prev + ph_min)/2d0)
+         !         = SQRT(10**(-(ph_prev + ph_min)))
+         !         = SQRT([H]_old*10**(-ph_min))
+         !         = SQRT([H]_old * zhmax)
+         zh                 = SQRT(zh_1 * zh_max)
+         zh_delta           = zh - zh_1
+      ENDIF
+   ENDIF
+
+   zeqn_absmin = MIN(ABS(zeqn), zeqn_absmin)
+
+   ! Stop iterations once |([H]-[H_1])/[H_1]| < rdel
+   l_exitnow = (ABS(zh_delta) < pp_rdel_ah_target*zh_1)
+
+   IF(l_exitnow) EXIT
+ENDDO
+
+SOLVE_AT_GENERAL_SEC = zh
+
+IF(PRESENT(p_val)) THEN
+   IF(zh > 0._wp) THEN
+      p_val = equation_at(p_alktot, zh,       p_dictot, p_bortot,              &
+                          p_po4tot, p_siltot,                                  &
+                          p_so4tot, p_flutot,                                  &
+                          K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi)
+   ELSE
+     p_val = HUGE(1._wp)
+   ENDIF
+ENDIF
+
+RETURN
+END FUNCTION SOLVE_AT_GENERAL_SEC
+
+!===============================================================================
+
+FUNCTION SOLVE_AT_FAST(p_alktot, p_dictot, p_bortot,                          &
+                       p_po4tot, p_siltot,                                    &
+                       p_so4tot, p_flutot,                                    & 
+                       K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi,        &
+                       p_hini,   p_val)
+
+! Fast version of SOLVE_AT_GENERAL, without any bounds checking.
+
+USE mocsy_singledouble
+IMPLICIT NONE
+REAL(KIND=wp) :: SOLVE_AT_FAST
+
+! Argument variables 
+REAL(KIND=wp), INTENT(IN)            :: p_alktot
+REAL(KIND=wp), INTENT(IN)            :: p_dictot
+REAL(KIND=wp), INTENT(IN)            :: p_bortot
+REAL(KIND=wp), INTENT(IN)            :: p_po4tot
+REAL(KIND=wp), INTENT(IN)            :: p_siltot
+!REAL(KIND=wp), INTENT(IN)            :: p_nh4tot
+!REAL(KIND=wp), INTENT(IN)            :: p_h2stot
+REAL(KIND=wp), INTENT(IN)            :: p_so4tot
+REAL(KIND=wp), INTENT(IN)            :: p_flutot
+REAL(KIND=wp), INTENT(IN)            :: K0, K1, K2, Kb, Kw, Ks, Kf
+REAL(KIND=wp), INTENT(IN)            :: K1p, K2p, K3p, Ksi
+REAL(KIND=wp), INTENT(IN), OPTIONAL  :: p_hini
+REAL(KIND=wp), INTENT(OUT), OPTIONAL :: p_val
+
+! Local variables
+REAL(KIND=wp)  ::  zh_ini, zh, zh_prev, zh_lnfactor
+REAL(KIND=wp)  ::  zhdelta
+REAL(KIND=wp)  ::  zeqn, zdeqndh
+!REAL(KIND=wp)  ::  aphscale
+LOGICAL        :: l_exitnow
+REAL(KIND=wp), PARAMETER :: pz_exp_threshold = 1.0_wp
+
+! TOTAL H+ scale: conversion factor for Htot = aphscale * Hfree
+!aphscale = 1._wp + p_so4tot/Ks
+
+IF(PRESENT(p_hini)) THEN
+   zh_ini = p_hini
+ELSE
+   CALL AHINI_FOR_AT(p_alktot, p_dictot, p_bortot, K1, K2, Kb, zh_ini)
+ENDIF
+zh = zh_ini
+
+niter_atfast    = 0                 ! Reset counters of iterations
+DO
+   niter_atfast = niter_atfast + 1
+   IF(niter_atfast > jp_maxniter_atfast) THEN
+      zh = -1._wp
+      EXIT
+   ENDIF
+
+   zh_prev = zh
+
+   zeqn = equation_at(p_alktot, zh,       p_dictot, p_bortot,                  &
+                      p_po4tot, p_siltot,                                      &
+                      p_so4tot, p_flutot,                                      & 
+                      K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi,          &
+                      P_DERIVEQN = zdeqndh)
+
+   IF(zeqn == 0._wp) EXIT               ! zh is the root
+
+   zh_lnfactor = -zeqn/(zdeqndh*zh_prev)
+   IF(ABS(zh_lnfactor) > pz_exp_threshold) THEN
+      zh          = zh_prev*EXP(zh_lnfactor)
+   ELSE
+      zhdelta     = zh_lnfactor*zh_prev
+      zh          = zh_prev + zhdelta
+   ENDIF
+
+   ! Stop iterations once |\delta{[H]}/[H]| < rdel
+   ! <=> |(zh - zh_prev)/zh_prev| = |EXP(-zeqn/(zdeqndh*zh_prev)) -1| < rdel
+   ! |EXP(-zeqn/(zdeqndh*zh_prev)) -1| ~ |zeqn/(zdeqndh*zh_prev)|
+
+   ! Alternatively:
+   ! |\Delta pH| = |zeqn/(zdeqndh*zh_prev*LOG(10))|
+   !             ~ 1/LOG(10) * |\Delta [H]|/[H]
+   !             < 1/LOG(10) * rdel
+
+   ! Hence |zeqn/(zdeqndh*zh)| < rdel
+
+   ! rdel <- pp_rdel_ah_target
+
+   l_exitnow = (ABS(zh_lnfactor) < pp_rdel_ah_target)
+
+   IF(l_exitnow) EXIT
+ENDDO
+
+SOLVE_AT_FAST = zh
+
+IF(PRESENT(p_val)) THEN
+   IF(zh > 0._wp) THEN
+      p_val = equation_at(p_alktot, zh,       p_dictot, p_bortot,              &
+                          p_po4tot, p_siltot,                                  &
+                          p_so4tot, p_flutot,                                  &
+                          K0, K1, K2, Kb, Kw, Ks, Kf, K1p, K2p, K3p, Ksi)
+   ELSE
+      p_val = HUGE(1._wp)
+   ENDIF
+ENDIF
+
+RETURN
+END FUNCTION solve_at_fast
+!===============================================================================
+
+END MODULE mocsy_phsolvers
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_singledouble.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_singledouble.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_singledouble.F90	(revision 9987)
@@ -0,0 +1,11 @@
+!> \file mocsy_singledouble.f90
+!! \BRIEF 
+!> Module that defines single and double precision - used by all other modules
+MODULE mocsy_singledouble
+! INTEGER, PARAMETER :: r4 = SELECTED_REAL_KIND(6)
+! INTEGER, PARAMETER :: r8 = SELECTED_REAL_KIND(12)
+  INTEGER, PARAMETER :: r4 = KIND(1.0)
+  INTEGER, PARAMETER :: r8 = KIND(1.0d0)
+! INTEGER, PARAMETER :: wp = KIND(1.0d0)
+  INTEGER, PARAMETER :: wp = SELECTED_REAL_KIND(12,307)
+END MODULE mocsy_singledouble
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_wrapper.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_wrapper.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/mocsy_wrapper.F90	(revision 9987)
@@ -0,0 +1,357 @@
+MODULE mocsy_wrapper
+   !!======================================================================
+   !!                         ***  MODULE mocsy_wrapper  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :
+   !!  -   !  2015-06  (A. Yool)             added for UKESM project
+   !!  -   !  2017-04  (A. Yool)             alter optK1K2 to 'w14' option
+   !!----------------------------------------------------------------------
+#if defined key_medusa && defined key_roam
+   !!----------------------------------------------------------------------
+   !!                                        MEDUSA carbonate chemistry
+   !!----------------------------------------------------------------------
+   !!   mocsy_wrapper
+   !!----------------------------------------------------------------------
+
+   USE mocsy_mainmod
+   USE mocsy_gasflux
+   USE in_out_manager  ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC mocsy_interface  ! called in trc_bio_medusa
+   PUBLIC mocsy_carbchem   ! called in trc_bio_medusa
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+! The following is a map of the subroutines contained within this module
+! - mocsy_interface
+!    - CALLS mocsy_carbchem
+!
+! - mocsy_carbchem
+!    - CALLS vars
+!      - CALLS p80
+!      - CALLS constants
+!      - CALLS rho
+!      - CALLS varsolver
+!        - CALLS [phsolvers routines]
+!      - CALLS varsolver (again)
+!    - CALLS x2pCO2atm
+!    - CALLS p2fCO2
+!    - CALLS schmidt_co2
+!    - CALLS surface_K0
+
+CONTAINS
+
+!=======================================================================
+!
+      SUBROUTINE mocsy_interface( temp, sal, alk, dic, sil, phos, &
+           Patm, depth, lat, kw660, xco2, N,                      &
+           ph, pco2, fco2, co2, hco3, co3, OmegaA,                &
+           OmegaC, BetaD, rhoSW, p, tempis,                       &
+           pco2atm, fco2atm, schmidtco2, kwco2, K0,               &
+           co2starair, co2flux, dpco2 )
+!
+!=======================================================================
+!
+! AXY (26/06/15): to preserve both MEDUSA's scalar variables and
+!                 MOCSY's vector variables on code traceability
+!                 grounds, this additional wrapper does a rather
+!                 superfluous conversion between the two; in the
+!                 fullness of time, this should be dispensed with
+!                 and MOCSY used in its full vector form
+!
+        USE mocsy_singledouble
+        IMPLICIT NONE
+
+!> ======================================================================
+!  VARIABLES
+!> ======================================================================
+!
+   INTEGER, INTENT(in) :: N
+!
+!  MEDUSA-side
+!  Input variables
+   REAL(kind=wp), INTENT(in)  :: temp, sal, alk, dic, sil, phos
+   REAL(kind=wp), INTENT(in)  :: Patm, depth, lat, kw660, xco2
+!
+!  Output variables
+   REAL(kind=wp), INTENT(out) :: ph, pco2, fco2, co2, hco3, co3, OmegaA
+   REAL(kind=wp), INTENT(out) :: OmegaC, BetaD, rhoSW, p, tempis
+   REAL(kind=wp), INTENT(out) :: pco2atm, fco2atm, schmidtco2, kwco2, K0
+   REAL(kind=wp), INTENT(out) :: co2starair, co2flux, dpco2
+!
+!  MOCSY-side
+!  Input variables
+   REAL(kind=wp), DIMENSION(N) :: mtemp, msal, malk, mdic, msil, mphos
+   REAL(kind=wp), DIMENSION(N) :: mPatm, mdepth, mlat, mkw660, mxco2
+!
+!  Output variables
+   REAL(kind=wp), DIMENSION(N) :: mph, mpco2, mfco2, mco2, mhco3, mco3, mOmegaA
+   REAL(kind=wp), DIMENSION(N) :: mOmegaC, mBetaD, mrhoSW, mp, mtempis
+   REAL(kind=wp), DIMENSION(N) :: mpco2atm, mfco2atm, mschmidtco2, mkwco2, mK0
+   REAL(kind=wp), DIMENSION(N) :: mco2starair, mco2flux, mdpco2
+!
+!> ----------------------------------------------------------------------
+!  Set MOCSY inputs to equal MEDUSA inputs (amend units here)
+!> ----------------------------------------------------------------------
+!
+      mtemp(1)  = temp         ! degrees C
+      msal(1)   = sal          ! PSU
+      malk(1)   = alk / 1000.  ! meq  / m3 -> eq  / m3
+      mdic(1)   = dic / 1000.  ! mmol / m3 -> mol / m3
+      msil(1)   = sil / 1000.  ! mmol / m3 -> mol / m3
+      mphos(1)  = phos / 1000. ! mmol / m3 -> mol / m3
+      mPatm(1)  = Patm         ! atm
+      mdepth(1) = depth        ! m
+      mlat(1)   = lat          ! degrees N
+      mkw660(1) = kw660        ! m / s
+      mxco2(1)  = xco2         ! ppm
+!
+!> ----------------------------------------------------------------------
+!  Call MOCSY
+!> ----------------------------------------------------------------------
+!
+      CALL mocsy_carbchem( mtemp, msal, malk, mdic, msil, mphos, & ! inputs
+      mPatm, mdepth, mlat, mkw660, mxco2, 1,                     & ! inputs
+      mph, mpco2, mfco2, mco2, mhco3, mco3, mOmegaA,             & ! outputs
+      mOmegaC, mBetaD, mrhoSW, mp, mtempis,                      & ! outputs
+      mpco2atm, mfco2atm, mschmidtco2, mkwco2, mK0,              & ! outputs
+      mco2starair, mco2flux, mdpco2 ) ! outputs
+!
+!> ----------------------------------------------------------------------
+!  Set MOCSY outputs to equal MEDUSA outputs (amend units here)
+!> ----------------------------------------------------------------------
+!
+      ph         = mph(1)                 ! standard units
+      pco2       = mpco2(1)               ! uatm
+      fco2       = mfco2(1)               ! uatm
+      co2        = mco2(1) * 1000.        ! mol / m3 -> mmol / m3
+      hco3       = mhco3(1) * 1000.       ! mol / m3 -> mmol / m3
+      co3        = mco3(1) * 1000.        ! mol / m3 -> mmol / m3
+      OmegaA     = mOmegaA(1)             ! dimensionless
+      OmegaC     = mOmegaC(1)             ! dimensionless
+      BetaD      = mBetaD(1)              ! dimensionless
+      rhoSW      = mrhoSW(1)              ! kg / m3
+      p          = mp(1)                  ! db
+      tempis     = mtempis(1)             ! degrees C
+      pco2atm    = mpco2atm(1)            ! uatm
+      fco2atm    = mfco2atm(1)            ! uatm
+      schmidtco2 = mschmidtco2(1)         ! dimensionless
+      kwco2      = mkwco2(1)              ! m / s
+      K0         = mK0(1)                 ! (mol/kg) / atm
+      co2starair = mco2starair(1) * 1000. ! mol / m3 -> mmol / m3 
+      co2flux    = mco2flux(1) * 1000.    ! mol / m2 / s -> mmol / m2 / s 
+      dpco2      = mdpco2(1)              ! uatm
+
+  RETURN
+
+  END SUBROUTINE
+
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!
+      SUBROUTINE mocsy_carbchem( temp, sal, alk, dic, sil, phos,  &
+           Patm, depth, lat, kw660, xco2, N,                      &
+           ph, pco2, fco2, co2, hco3, co3, OmegaA,                &
+           OmegaC, BetaD, rhoSW, p, tempis,                       &
+           pco2atm, fco2atm, schmidtco2, kwco2, K0,               &
+           co2starair, co2flux, dpco2 )
+!
+!=======================================================================
+! 
+! AXY (23/06/15): MOCSY introduced to MEDUSA to update carbonate
+!                 chemistry for UKESM1 project
+!
+! Orr, J. C. and Epitalon, J.-M.: Improved routines to model the 
+! ocean carbonate system: mocsy 2.0, Geosci. Model Dev., 8, 485-499, 
+! doi:10.5194/gmd-8-485-2015, 2015.
+!
+! "mocsy is a Fortran 95 package designed to compute all ocean
+! carbonate system variables from DIC and total Alk, particularly
+! from models.  It updates previous OCMIP code, avoids 3 common 
+! model approximations, and offers the best-practice constants as 
+! well as more recent options. Its results agree with those from 
+! CO2SYS-MATLAB within 0.005%."
+!
+! Where possible the code remains identical to that published by
+! Orr & Epitalon (2015; henceforth OE15); some consolidation of 
+! MOCSY files has taken place, and the resulting package is 
+! comprised of four modules:
+!                 
+! 1. mocsy_wrapped.f90
+!    - This module contains the interface between MEDUSA and the
+!      main MOCSY routines; it draws from (but is very different
+!      from) the test_mocsy.f90 routine provided by OE15
+!
+! 2. mocsy_singledouble.f90
+!    - This module contains only precision definitions; it is
+!      based on the singledouble.f90 routine provided by OE15
+!
+! 3. mocsy_phsolvers.f90
+!    - This module contains a suite of solvers derived from
+!      Munhoven (2013) and modified by OE15; it is based on the
+!      phsolver.f90 routine provided by OE15
+!
+! 4. mocsy_gasflux.f90
+!    - This module contains a series of subroutines used to 
+!      calculate the air-sea flux of CO2; it consolidates four
+!      MOCSY routines with an OCMIP-2 Schmidt number routine
+!      updated with the new parameterisations of Wanninkhof (2014)
+!
+! 5. mocsy_mainmod.f90
+!    - This module consolidates all of the remaining MOCSY 
+!      functions and subroutines from OE15 into a single file
+!      for convenience
+!
+! NOTE: it is still possible to run PML's carbonate chemistry
+! routine in MEDUSA; at present this remains the default, if
+! less-preferred, routine (i.e. is used if key_mocsy is not
+! present)
+!
+!=======================================================================
+!
+! AXY (05/04/17): alter options to include optK1K2 = 'w14'
+!
+! In conversation with Jim Orr, Waters (2014) is now the 
+! preferred option for optK1K2 in the case of global scale 
+! simulations since this formulation works over broader ranges
+! of temperature (0 < T < 50) and salinity (1 < S < 50).
+!
+! NOTE: *contrary* to the notice above, MEDUSA has now been
+! revised to remove the PML carbonate chemistry routine as part
+! of a wider code review. This routine is not anticipated to be 
+! used again, and has several out of date parameterisations 
+! relative to MOCSY. As a result, key_mocsy is no longer required.
+!
+        USE mocsy_singledouble
+        IMPLICIT NONE
+
+!> ======================================================================
+!  VARIABLES
+!> ======================================================================
+!
+!  Input variables
+   REAL(kind=wp), INTENT(in),  DIMENSION(N) :: temp, sal, alk, dic, sil, phos
+   REAL(kind=wp), INTENT(in),  DIMENSION(N) :: Patm, depth, lat, kw660, xco2
+   INTEGER, INTENT(in) :: N
+!
+!  Output variables
+   REAL(kind=wp), INTENT(out), DIMENSION(N) :: ph, pco2, fco2, co2, hco3, co3, OmegaA
+   REAL(kind=wp), INTENT(out), DIMENSION(N) :: OmegaC, BetaD, rhoSW, p, tempis
+   REAL(kind=wp), INTENT(out), DIMENSION(N) :: pco2atm, fco2atm, schmidtco2, kwco2, K0
+   REAL(kind=wp), INTENT(out), DIMENSION(N) :: co2starair, co2flux, dpco2
+!
+!  Local variables
+   REAL(kind=wp), DIMENSION(N) :: depth0, co2star
+   INTEGER :: i, totdat
+!
+!  "vars" Input options
+   CHARACTER(10) :: optCON, optT, optP, optB, optKf, optK1K2
+!   
+!  initialise depth0 to 0
+   depth0 = 0.0
+   
+!> ======================================================================
+!  CONFIGURE OPTIONS
+!> ======================================================================
+!> OPTIONS: see complete documentation in 'vars' subroutine (in mocsy_mainmod.F90)
+!> AXY (05/04/17): optK1K2 switched from 'm10' to 'w14'
+!> Typical options for MODELS
+   optCON  = 'mol/m3' ! input concentrations are in MOL/M3
+   optT    = 'Tpot'   ! input temperature, variable 'temp', is POTENTIAL temp [°C]
+   optP    = 'm'      ! input variable 'depth' is in METERS
+   optB    = 'l10'    ! Lee et al. (2010) formulation for total boron
+   optK1K2 = 'w14'    ! Lueker et al. (2000) formulations for K1 & K2 (best practices)
+   optKf   = 'dg'     ! Dickson & Riley (1979) formulation for Kf (recommended by Dickson & Goyet, 1994)
+!> optK1K2 = 'l'      ! Lueker et al. (2000) formulations for K1 & K2 (best practices)
+!> optKf   = 'dg'     ! Dickson & Riley (1979) formulation for Kf (recommended by Dickson & Goyet, 1994)
+
+!> ======================================================================
+!  CARBONATE CHEMISTRY CALCULATIONS
+!> ======================================================================
+!> Call mocsy's main subroutine to compute carbonate system variables: 
+!> pH, pCO2, fCO2, CO2*, HCO3- and CO32-, OmegaA, OmegaC, R
+!> FROM temperature, salinity, total alkalinity, dissolved inorganic 
+!> carbon, silica, phosphate, depth (or pressure) (1-D arrays)
+   call vars(ph, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, rhoSW, p, tempis,  &  ! OUTPUT
+             temp, sal, alk, dic, sil, phos, Patm, depth, lat, N,                      &  ! INPUT
+             optCON, optT, optP)
+!            optCON, optT, optP, optB, optK1K2, optKf)                                    ! INPUT OPTIONS
+
+!> ======================================================================
+!  GAS EXCHANGE CALCULATIONS
+!> ======================================================================
+!>
+!> Only calculate gas exchange fields if depth = 0
+   if (depth(1) .eq. 0.0) then
+!
+!     Compute pCO2atm [uatm] from xCO2 [ppm], atmospheric pressure [atm], & vapor pressure of seawater
+!     pCO2atm = (Patm - pH20(i)) * xCO2,   where pH20 is the vapor pressure of seawater [atm]
+      CALL x2pCO2atm(xco2, temp, sal, Patm, N, & ! INPUT
+      pco2atm)                                   ! OUTPUT
+
+!     Compute fCO2atm [uatm] from pCO2atm [uatm] & fugacity coefficient [unitless]
+!     fCO2atm = pCO2atm * fugcoeff,   where fugcoeff= exp(Patm*(B + 2.0*xc2*Del)/(R*tk) )
+      CALL p2fCO2(pco2atm, temp, Patm, depth0, N, & ! INPUT
+      fco2atm)                                      ! OUTPUT
+
+!     Compute Schmidt number for CO2 from potential temperature
+      CALL schmidt_co2(temp, N, & ! INPUT
+      schmidtco2)                 ! OUTPUT
+
+!     Compute transfer velocity for CO2 in m/s (see equation [4] in OCMIP2 design document & OCMIP2 Abiotic HOWTO)
+      kwco2 = kw660 * (660./schmidtco2)**0.5
+
+!     Surface K0 [(mol/kg) / atm] at T, S of surface water
+      CALL surface_K0(temp, sal, N, & ! INPUT
+      K0)                             ! OUTPUT
+
+!     "Atmospheric" [CO2*], air-sea CO2 flux, sfc DIC rate of change, & Delta pCO2
+!     all "lifted" from the gasx.f90 function of MOCSY
+      co2starair = K0 * fco2atm * 1.0e-6_wp * rhoSW ! Equil. [CO2*] for atm CO2 at Patm & sfc-water T,S [mol/m3]
+      co2star    = co2                              ! Oceanic [CO2*] in [mol/m3] from vars.f90
+      co2flux    = kwco2 * (co2starair - co2star)   ! Air-sea CO2 flux [mol/(m2 * s)]
+!     co2ex      = co2flux / dz1                    ! Change in sfc DIC due to gas exchange [mol/[m3 * s)]
+      dpco2      = pco2 - pco2atm                   ! Delta pCO2 (oceanic - atmospheric pCO2) [uatm]
+!     
+   endif
+
+  RETURN
+
+  END SUBROUTINE
+
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+#  else
+   !!======================================================================
+   !!  Dummy module :                         No MOCSY carbonate chemistry
+   !!======================================================================
+
+CONTAINS
+
+   SUBROUTINE mocsy_interface( kt )                   ! Empty routine
+
+      INTEGER, INTENT( in ) ::   kt
+
+      WRITE(*,*) 'mocsy_interface: You should not have seen this print! error?', kt
+
+   END SUBROUTINE mocsy_interface
+#endif 
+
+   !!======================================================================
+
+END MODULE mocsy_wrapper
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/par_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/par_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/par_medusa.F90	(revision 9987)
@@ -0,0 +1,106 @@
+MODULE par_medusa
+   !!======================================================================
+   !!                        ***  par_medusa  ***
+   !! TOP :   set the MEDUSA parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!              -   !  2011-04  (A. Yool) updated for ROAM project
+   !!		   -   !  2013-03  (A. Yool) updated for v3.5 NEMO
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+   USE par_pisces , ONLY : jp_pisces       !: number of tracers in PISCES
+   USE par_pisces , ONLY : jp_pisces_2d    !: number of 2D diag in PISCES
+   USE par_pisces , ONLY : jp_pisces_3d    !: number of 3D diag in PISCES
+   USE par_pisces , ONLY : jp_pisces_trd   !: number of biological diag in PISCES
+
+   IMPLICIT NONE
+
+   INTEGER, PARAMETER ::   jp_lm      =  jp_pisces      !: 
+   INTEGER, PARAMETER ::   jp_lm_2d   =  jp_pisces_2d   !:
+   INTEGER, PARAMETER ::   jp_lm_3d   =  jp_pisces_3d   !:
+   INTEGER, PARAMETER ::   jp_lm_trd  =  jp_pisces_trd  !:
+
+#if defined key_medusa
+   !!---------------------------------------------------------------------
+   !!   'key_medusa'                     user defined tracers (MEDUSA)
+   !!---------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_medusa     = .TRUE.   !: PTS flag 
+# if defined key_roam
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa     =  15      !: number of PTS tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_2d  =  225     !: additional 2d output arrays (used if ln_diatrc=T)
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_3d  =  5       !: additional 3d output arrays (used if ln_diatrc=T)
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_trd =  0       !: number of sms trends for MEDUSA
+# else
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa     =  11      !: number of PTS tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_2d  =  90      !: additional 2d output arrays (used if ln_diatrc=T)
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_3d  =  4       !: additional 3d output arrays (used if ln_diatrc=T)
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_trd =  0       !: number of sms trends for MEDUSA
+# endif
+
+   ! assign an index in trc arrays for each PTS prognostic variables
+   INTEGER, PUBLIC, PARAMETER ::   jpchn  =  jp_lm + 1      !: non-diatom chlorophyll concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpchd  =  jp_lm + 2      !: diatom     chlorophyll concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpphn  =  jp_lm + 3      !: non-diatom concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpphd  =  jp_lm + 4      !: diatom     concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpzmi  =  jp_lm + 5      !: microzooplankton concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpzme  =  jp_lm + 6      !: mesozooplankton  concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpdin  =  jp_lm + 7      !: dissolved inorganic nitrogen concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpsil  =  jp_lm + 8      !: silicic acid concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpfer  =  jp_lm + 9      !: total iron concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpdet  =  jp_lm + 10     !: slow-sinking detritus concentration
+   INTEGER, PUBLIC, PARAMETER ::   jppds  =  jp_lm + 11     !: diatom silicon concentration
+# if defined key_roam
+   INTEGER, PUBLIC, PARAMETER ::   jpdtc  =  jp_lm + 12     !: slow-sinking detritus carbon concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpdic  =  jp_lm + 13     !: dissolved inorganic carbon concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpalk  =  jp_lm + 14     !: alkalinity
+   INTEGER, PUBLIC, PARAMETER ::   jpoxy  =  jp_lm + 15     !: dissolved oxygen concentration
+# endif
+
+   ! assign an index in trc arrays for each PTS prognostic variables
+   INTEGER, PUBLIC, PARAMETER ::   jpchn_lc  =  1      !: non-diatom chlorophyll concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpchd_lc  =  2      !: diatom     chlorophyll concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpphn_lc  =  3      !: non-diatom concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpphd_lc  =  4      !: diatom     concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpzmi_lc  =  5      !: microzooplankton concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpzme_lc  =  6      !: mesozooplankton  concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpdin_lc  =  7      !: dissolved inorganic nitrogen concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpsil_lc  =  8      !: silicic acid concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpfer_lc  =  9      !: total iron concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpdet_lc  =  10     !: slow-sinking detritus concentration
+   INTEGER, PUBLIC, PARAMETER ::   jppds_lc  =  11     !: diatom silicon concentration
+# if defined key_roam
+   INTEGER, PUBLIC, PARAMETER ::   jpdtc_lc  =  12     !: slow-sinking detritus carbon concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpdic_lc  =  13     !: dissolved inorganic carbon concentration
+   INTEGER, PUBLIC, PARAMETER ::   jpalk_lc  =  14     !: alkalinity
+   INTEGER, PUBLIC, PARAMETER ::   jpoxy_lc  =  15     !: dissolved oxygen concentration
+# endif
+
+#else
+   !!---------------------------------------------------------------------
+   !!   Default                           No user defined tracers (MEDUSA)
+   !!---------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_medusa     = .FALSE.  !: MEDUSA flag 
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa     =  0       !: No MEDUSA tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_2d  =  0       !: No MEDUSA additional 2d output arrays 
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_3d  =  0       !: No MEDUSA additional 3d output arrays 
+   INTEGER, PUBLIC, PARAMETER ::   jp_medusa_trd =  0       !: number of sms trends for MEDUSA
+#endif
+
+   ! Starting/ending PISCES do-loop indices (N.B. no PISCES : jpl_pcs < jpf_pcs the do-loop are never done)
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa0     = jp_lm     + 1              !: First index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa1     = jp_lm     + jp_medusa      !: Last  index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa0_2d  = jp_lm_2d  + 1              !: First index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa1_2d  = jp_lm_2d  + jp_medusa_2d   !: Last  index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa0_3d  = jp_lm_3d  + 1              !: First index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa1_3d  = jp_lm_3d  + jp_medusa_3d   !: Last  index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa0_trd = jp_lm_trd + 1              !: First index of MEDUSA passive tracers
+   INTEGER, PUBLIC, PARAMETER ::   jp_msa1_trd = jp_lm_trd + jp_medusa_trd  !: Last  index of MEDUSA passive tracers
+
+   !!======================================================================
+END MODULE par_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/phytoplankton.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/phytoplankton.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/phytoplankton.F90	(revision 9987)
@@ -0,0 +1,465 @@
+MODULE phytoplankton_mod
+   !!======================================================================
+   !!                         ***  MODULE phytoplankton_mod  ***
+   !! Calculates the phytoplankton growth
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   phytoplankton        ! Called in plankton.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE phytoplankton( jk )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE phytoplankton  ***
+      !! This called from PLANKTON and calculates the phytoplankton
+      !! growth.
+      !!----------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: fdep1, ffld, ffln2,                   &
+                                   fjlim_pd, fjlim_pn,                   &
+                                   fnld, fnln,                           &
+                                   fprd, fprd_ml, fprds,                 &
+                                   fprn, fprn_ml, frd, frn,              &
+                                   fsin, fsld, fsld2, fthetad, fthetan,  & 
+                                   ftot_det, ftot_dtc, ftot_pd,          &
+                                   ftot_pn, ftot_zme, ftot_zmi,          &
+                                   fun_Q10, fun_T, idf, idfval,          &
+                                   zchd, zchn, zdet, zdin, zdtc,         &
+                                   zfer, zpds, zphd, zphn, zsil,         &
+                                   zzme, zzmi
+      USE dom_oce,           ONLY: e3t_0, e3t_n, gdepw_0, gdepw_n, tmask
+      USE in_out_manager,    ONLY: lwp, numout
+      USE oce,               ONLY: tsn
+      USE par_kind,          ONLY: wp
+      USE par_oce,           ONLY: jp_tem, jpi, jpim1, jpj, jpjm1
+      USE phycst,            ONLY: rsmall
+      USE sms_medusa,        ONLY: jliebig, jphy, jq10,                  &
+                                   xald, xaln, xfld, xfln,               &
+                                   xnld, xnln, xnsi0, xpar,              &
+                                   xsin0, xsld, xthetam, xthetamd, xuif, &
+                                   xvpd, xvpn, xxi
+      USE zdfmxl,            ONLY: hmld
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+
+      INTEGER :: ji, jj
+
+      REAL(wp), DIMENSION(jpi,jpj) :: faln, fchn, fjln
+      REAL(wp), DIMENSION(jpi,jpj) :: fald, fchd, fjld
+      REAL(wp)                     :: fchn1, fchd1
+      !! AXY (03/02/11): add in Liebig terms
+      REAL(wp)                     :: fpnlim, fpdlim
+      !! AXY (16/07/09): add in Eppley curve functionality
+      REAL(wp)                     :: xvpnT,xvpdT
+      !! silicon cycle
+      REAL(wp)                     :: fnsi
+
+      REAL(wp)                     :: fsin1, fnsi1, fnsi2
+      REAL(wp)                     :: fq0
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Chlorophyll calculations
+               !!----------------------------------------------------------
+               !!
+               !! non-diatoms
+	       if (zphn(ji,jj).GT.rsmall) then
+                  fthetan(ji,jj) = max(tiny(zchn(ji,jj)),                    &
+                                       (zchn(ji,jj) * xxi) /                 &
+                                       (zphn(ji,jj) + tiny(zphn(ji,jj))))
+                  faln(ji,jj)    = xaln * fthetan(ji,jj)
+               else
+                  fthetan(ji,jj) = 0.
+                  faln(ji,jj)    = 0.
+               endif
+               !!
+               !! diatoms
+	       if (zphd(ji,jj).GT.rsmall) then
+                  fthetad(ji,jj) = max(tiny(zchd(ji,jj)),                   &
+                                       (zchd(ji,jj) * xxi) /                &
+                                       (zphd(ji,jj) + tiny(zphd(ji,jj))))
+                  fald(ji,jj)    = xald * fthetad(ji,jj)
+               else
+                  fthetad(ji,jj) = 0.
+                  fald(ji,jj)    = 0.
+               endif
+
+# if defined key_debug_medusa
+               !! report biological calculations
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'faln(',jk,') = ', faln(ji,jj)
+                  IF (lwp) write (numout,*) 'fald(',jk,') = ', fald(ji,jj)
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Phytoplankton light limitation
+               !!----------------------------------------------------------
+               !!
+               !! It is assumed xpar is the depth-averaged (vertical layer) PAR 
+               !! Light limitation (check self-shading) in W/m2
+               !!
+               !! Note that there is no temperature dependence in phytoplankton
+               !! growth rate or any other function. 
+               !! In calculation of Chl/Phy ratio tiny(phyto) is introduced to 
+               !! avoid NaNs in case of Phy==0.  
+               !!
+               !! fthetad and fthetan are Chl:C ratio (gChl/gC) in diat and 
+               !! non-diat: 
+               !! for 1:1 Chl:P ratio (mgChl/mmolN) theta=0.012
+               !!
+               !! AXY (16/07/09)
+               !! temperature for new Eppley style phytoplankton growth
+               fun_T(ji,jj)   = 1.066**(1.0 * tsn(ji,jj,jk,jp_tem))
+               !! AXY (16/05/11): add in new Q10 (1.5, not 2.0) for
+               !!                 phytoplankton growth; remin. unaffected
+               fun_Q10(ji,jj) = jq10**((tsn(ji,jj,jk,jp_tem) - 0.0) / 10.0)
+               if (jphy.eq.1) then
+                  xvpnT = xvpn * fun_T(ji,jj)
+                  xvpdT = xvpd * fun_T(ji,jj)
+               elseif (jphy.eq.2) then
+                  xvpnT = xvpn * fun_Q10(ji,jj)
+                  xvpdT = xvpd * fun_Q10(ji,jj)
+               else
+                  xvpnT = xvpn
+                  xvpdT = xvpd
+               endif
+               !!
+               !! non-diatoms
+               fchn1 = (xvpnT * xvpnT) +                                     &
+                       (faln(ji,jj) * faln(ji,jj) * xpar(ji,jj,jk) *         &
+                        xpar(ji,jj,jk))
+               if (fchn1.GT.rsmall) then
+                  fchn(ji,jj) = xvpnT / (sqrt(fchn1) + tiny(fchn1))
+               else
+                  fchn(ji,jj) = 0.
+               endif
+               !! non-diatom J term
+               fjln(ji,jj)     = fchn(ji,jj) * faln(ji,jj) * xpar(ji,jj,jk)
+               fjlim_pn(ji,jj) = fjln(ji,jj) / xvpnT
+               !!
+               !! diatoms
+               fchd1 = (xvpdT * xvpdT) +                                     &
+                       (fald(ji,jj) * fald(ji,jj) * xpar(ji,jj,jk) *         &
+                        xpar(ji,jj,jk))
+               if (fchd1.GT.rsmall) then
+                  fchd(ji,jj) = xvpdT / (sqrt(fchd1) + tiny(fchd1))
+               else
+                  fchd(ji,jj) = 0.
+               endif
+               !! diatom J term
+               fjld(ji,jj)    = fchd(ji,jj) * fald(ji,jj) * xpar(ji,jj,jk)
+               fjlim_pd(ji,jj) = fjld(ji,jj) / xvpdT
+      
+# if defined key_debug_medusa
+               !! report phytoplankton light limitation
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fchn(',jk,') = ', fchn(ji,jj)
+                  IF (lwp) write (numout,*) 'fchd(',jk,') = ', fchd(ji,jj)
+                  IF (lwp) write (numout,*) 'fjln(',jk,') = ', fjln(ji,jj)
+                  IF (lwp) write (numout,*) 'fjld(',jk,') = ', fjld(ji,jj)
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Phytoplankton nutrient limitation
+               !!----------------------------------------------------------
+               !!
+               !! non-diatoms (N, Fe).
+               !! non-diatom Qn term
+               fnln(ji,jj)  = zdin(ji,jj) / (zdin(ji,jj) + xnln)
+               !! non-diatom Qf term
+               ffln2(ji,jj) = zfer(ji,jj) / (zfer(ji,jj) + xfln)
+               !!
+               !! diatoms (N, Si, Fe).
+               !! diatom Qn term
+               fnld(ji,jj) = zdin(ji,jj) / (zdin(ji,jj) + xnld)
+               !! diatom Qs term
+               fsld(ji,jj) = zsil(ji,jj) / (zsil(ji,jj) + xsld)
+               !! diatom Qf term
+               ffld(ji,jj) = zfer(ji,jj) / (zfer(ji,jj) + xfld)
+
+# if defined key_debug_medusa
+               !! report phytoplankton nutrient limitation
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fnln(',jk,') = ', fnln(ji,jj)
+                  IF (lwp) write (numout,*) 'fnld(',jk,') = ', fnld(ji,jj)
+                  IF (lwp) write (numout,*) 'ffln2(',jk,') = ', ffln2(ji,jj)
+                  IF (lwp) write (numout,*) 'ffld(',jk,') = ', ffld(ji,jj)
+                  IF (lwp) write (numout,*) 'fsld(',jk,') = ', fsld(ji,jj)
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Primary production (non-diatoms)
+               !! (note: still needs multiplying by phytoplankton 
+               !! concentration)
+               !!----------------------------------------------------------
+               !!
+               if (jliebig .eq. 0) then
+                  !! multiplicative nutrient limitation
+                  fpnlim = fnln(ji,jj) * ffln2(ji,jj)
+               elseif (jliebig .eq. 1) then
+                  !! Liebig Law (= most limiting) nutrient limitation
+                  fpnlim = min(fnln(ji,jj), ffln2(ji,jj))
+               endif
+               fprn(ji,jj) = fjln(ji,jj) * fpnlim
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Primary production (diatoms)
+               !! (note: still needs multiplying by phytoplankton 
+               !! concentration)
+               !!
+               !! Production here is split between nitrogen production and 
+               !! that of silicon; depending upon the "intracellular" ratio 
+               !! of Si:N, model diatoms will uptake nitrogen/silicon 
+               !! differentially; this borrows from the diatom model of 
+               !! Mongin et al. (2006)
+               !!----------------------------------------------------------
+               !!
+               if (jliebig .eq. 0) then
+                  !! multiplicative nutrient limitation
+                  fpdlim = fnld(ji,jj) * ffld(ji,jj)
+               elseif (jliebig .eq. 1) then
+                  !! Liebig Law (= most limiting) nutrient limitation
+                  fpdlim = min(fnld(ji,jj), ffld(ji,jj))
+               endif
+               !!
+	       if (zphd(ji,jj).GT.rsmall .AND. zpds(ji,jj).GT.rsmall) then
+                  !! "intracellular" elemental ratios
+                  ! fsin(ji,jj)  = zpds(ji,jj) / (zphd(ji,jj) +              &
+                  !                               tiny(zphd(ji,jj)))
+                  ! fnsi         = zphd(ji,jj) / (zpds(ji,jj) +              &
+                  !                               tiny(zpds(ji,jj)))
+                  fsin(ji,jj) = 0.0
+                  IF( zphd(ji,jj) .GT. rsmall) fsin(ji,jj)  = zpds(ji,jj) /  &
+                                                              zphd(ji,jj)
+                  fnsi = 0.0
+                  IF( zpds(ji,jj) .GT. rsmall) fnsi  = zphd(ji,jj) /         &
+                                                       zpds(ji,jj)
+                  !! AXY (23/02/10): these next variables derive from 
+                  !! Mongin et al. (2003)
+                  fsin1 = 3.0 * xsin0 !! = 0.6
+                  fnsi1 = 1.0 / fsin1 !! = 1.667
+                  fnsi2 = 1.0 / xsin0 !! = 5.0
+                  !!
+                  !! conditionalities based on ratios
+                  !! nitrogen (and iron and carbon)
+                  if (fsin(ji,jj).le.xsin0) then
+                     fprd(ji,jj)  = 0.0
+                     fsld2(ji,jj) = 0.0
+                  elseif (fsin(ji,jj).lt.fsin1) then
+                     fprd(ji,jj)  = xuif * ((fsin(ji,jj) - xsin0) /          &
+                                            (fsin(ji,jj) +                   &
+                                             tiny(fsin(ji,jj)))) *           &
+                                    (fjld(ji,jj) * fpdlim)
+                     fsld2(ji,jj) = xuif * ((fsin(ji,jj) - xsin0) /          &
+                                            (fsin(ji,jj) +                   &
+                                             tiny(fsin(ji,jj))))
+                  elseif (fsin(ji,jj).ge.fsin1) then
+                     fprd(ji,jj)  = (fjld(ji,jj) * fpdlim)
+                     fsld2(ji,jj) = 1.0
+                  endif
+                  !!
+                  !! silicon
+                  if (fsin(ji,jj).lt.fnsi1) then
+                     fprds(ji,jj) = (fjld(ji,jj) * fsld(ji,jj))
+                  elseif (fsin(ji,jj).lt.fnsi2) then
+                     fprds(ji,jj) = xuif * ((fnsi - xnsi0) /          &
+                                            (fnsi + tiny(fnsi))) *           &
+                                    (fjld(ji,jj) * fsld(ji,jj))
+                  else
+                     fprds(ji,jj) = 0.0
+                  endif     
+               else
+                  fsin(ji,jj)  = 0.0
+                  fnsi         = 0.0
+                  fprd(ji,jj)  = 0.0
+                  fsld2(ji,jj) = 0.0
+                  fprds(ji,jj) = 0.0
+               endif
+
+# if defined key_debug_medusa
+               !! report phytoplankton growth (including diatom silicon 
+               !! submodel)
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fsin(',jk,')   = ', fsin(ji,jj)
+                  IF (lwp) write (numout,*) 'fnsi(',jk,')   = ', fnsi
+                  IF (lwp) write (numout,*) 'fsld2(',jk,')  = ', fsld2(ji,jj)
+                  IF (lwp) write (numout,*) 'fprn(',jk,')   = ', fprn(ji,jj)
+                  IF (lwp) write (numout,*) 'fprd(',jk,')   = ', fprd(ji,jj)
+                  IF (lwp) write (numout,*) 'fprds(',jk,')  = ', fprds(ji,jj)
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Mixed layer primary production
+               !! this block calculates the amount of primary production 
+               !! that occurs within the upper mixed layer; this allows the 
+               !! separate diagnosis of "sub-surface" primary production; it 
+               !! does assume that short-term variability in mixed layer 
+               !! depth doesn't mess with things though
+               !!----------------------------------------------------------
+               !!
+               if (fdep1(ji,jj).le.hmld(ji,jj)) then
+                  !! this level is entirely in the mixed layer
+                  fq0 = 1.0
+               elseif (fsdepw(ji,jj,jk).ge.hmld(ji,jj)) then
+                  !! this level is entirely below the mixed layer
+                  fq0 = 0.0
+               else
+                  !! this level straddles the mixed layer
+                  fq0 = (hmld(ji,jj) - fsdepw(ji,jj,jk)) / fse3t(ji,jj,jk)
+               endif
+               !!
+               fprn_ml(ji,jj) = fprn_ml(ji,jj) + (fprn(ji,jj) * zphn(ji,jj) * &
+                                                  fse3t(ji,jj,jk) * fq0)
+               fprd_ml(ji,jj) = fprd_ml(ji,jj) + (fprd(ji,jj) * zphd(ji,jj) * &
+                                                  fse3t(ji,jj,jk) * fq0)
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Vertical Integral --
+               !!----------------------------------------------------------
+               !! vertical integral non-diatom phytoplankton
+               ftot_pn(ji,jj)  = ftot_pn(ji,jj)  + (zphn(ji,jj) *             &
+                                                    fse3t(ji,jj,jk))
+               !! vertical integral diatom phytoplankton
+               ftot_pd(ji,jj)  = ftot_pd(ji,jj)  + (zphd(ji,jj) *             &
+                                                    fse3t(ji,jj,jk))
+               !! vertical integral microzooplankton
+               ftot_zmi(ji,jj) = ftot_zmi(ji,jj) + (zzmi(ji,jj) *             &
+                                                    fse3t(ji,jj,jk))
+               !! vertical integral mesozooplankton
+               ftot_zme(ji,jj) = ftot_zme(ji,jj) + (zzme(ji,jj) *             &
+                                                    fse3t(ji,jj,jk))
+               !! vertical integral slow detritus, nitrogen
+               ftot_det(ji,jj) = ftot_det(ji,jj) + (zdet(ji,jj) *             &
+                                                    fse3t(ji,jj,jk))
+               !! vertical integral slow detritus, carbon
+               ftot_dtc(ji,jj) = ftot_dtc(ji,jj) + (zdtc(ji,jj) *             &
+                                                    fse3t(ji,jj,jk))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! More chlorophyll calculations
+               !!----------------------------------------------------------
+               !!
+               !! frn(ji,jj) = (xthetam / fthetan(ji,jj)) *                   &
+               !!              (fprn(ji,jj) / (fthetan(ji,jj) * xpar(ji,jj,jk)))
+               !! frd(ji,jj) = (xthetam / fthetad(ji,jj)) *                   &
+               !!              (fprd(ji,jj) / (fthetad(ji,jj) * xpar(ji,jj,jk)))
+               frn(ji,jj) = (xthetam * fchn(ji,jj) * fnln(ji,jj) *            &
+                             ffln2(ji,jj)) / (fthetan(ji,jj) +                &
+                                             tiny(fthetan(ji,jj)))
+               !! AXY (12/05/09): there's potentially a problem here; fsld, 
+               !!   silicic acid limitation, is used in the following line 
+               !!   to regulate chlorophyll growth in a manner that is 
+               !!   inconsistent with its use in the regulation of biomass 
+               !!   growth; the Mongin term term used in growth is more
+               !!   complex than the simple multiplicative function used
+               !!   below
+               !! frd(ji,jj) = (xthetam * fchd(ji,jj) * fnld(ji,jj) *        &
+               !!               ffld(ji,jj) * fsld(ji,jj)) /                 &
+               !!               (fthetad(ji,jj) + tiny(fthetad(ji,jj)))
+               !! AXY (12/05/09): this replacement line uses the new 
+               !!   variable, fsld2, to regulate chlorophyll growth
+               frd(ji,jj) = (xthetamd * fchd(ji,jj) * fnld(ji,jj) *          &
+                             ffld(ji,jj) * fsld2(ji,jj)) /                   &
+                             (fthetad(ji,jj) + tiny(fthetad(ji,jj)))
+
+# if defined key_debug_medusa
+               !! report chlorophyll calculations
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fthetan(',jk,') = ', fthetan(ji,jj)
+                  IF (lwp) write (numout,*) 'fthetad(',jk,') = ', fthetad(ji,jj)
+                  IF (lwp) write (numout,*) 'frn(',jk,')     = ', frn(ji,jj)
+                  IF (lwp) write (numout,*) 'frd(',jk,')     = ', frd(ji,jj)
+               endif
+# endif
+
+            ENDIF
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE phytoplankton
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE phytoplankton( )                    ! Empty routine
+      WRITE(*,*) 'phytoplankton: You should not have seen this print! error?'
+   END SUBROUTINE phytoplankton
+#endif 
+
+   !!======================================================================
+END MODULE phytoplankton_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/plankton.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/plankton.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/plankton.F90	(revision 9987)
@@ -0,0 +1,203 @@
+MODULE plankton_mod
+   !!======================================================================
+   !!                         ***  MODULE plankton_mod  ***
+   !! Calculate the carbon chemistry for the whole ocean
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   plankton        ! Called in trcbio_medusa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE plankton( jk )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE plankton  ***
+      !! This called from TRC_BIO_MEDUSA and 
+      !!  - Calculates phytoplankton growth
+      !!  - Zooplankton grazing
+      !!  - Plankton losses
+      !!-------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: fdpd, fdpd2, fdpds, fdpds2,             &
+                                   fdpn, fdpn2, fdzme, fdzme2,             &
+                                   fdzmi, fdzmi2, fsdiss, fsin,            &
+                                   zphd, zphn, zpds, zzme, zzmi
+      USE dom_oce,           ONLY: tmask
+      USE par_oce,           ONLY: jpim1, jpjm1
+      USE phytoplankton_mod, ONLY: phytoplankton
+      USE sms_medusa,        ONLY: jmpd, jmpn, jmzme, jmzmi,               &
+                                   xkphd, xkphn, xkzme, xkzmi,             &
+                                   xmetapd, xmetapn, xmetazme, xmetazmi,   &
+                                   xmpd, xmpn, xmzme, xmzmi, xsdiss
+      USE zooplankton_mod,   ONLY: zooplankton
+
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+
+      INTEGER :: ji, jj
+
+      !!-------------------------------------------------------------------
+      !! Calculate phytoplankton growth
+      !!-------------------------------------------------------------------
+      CALL phytoplankton( jk )
+
+      !!-------------------------------------------------------------------
+      !! Calculate zooplankton grazing
+      !!-------------------------------------------------------------------
+      CALL zooplankton( jk )
+
+      !!-------------------------------------------------------------------
+      !! Miscellaneous plankton losses
+      !!-------------------------------------------------------------------
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Plankton metabolic losses
+               !! Linear loss processes assumed to be metabolic in origin
+               !!----------------------------------------------------------
+               !!
+               fdpn2(ji,jj)  = xmetapn  * zphn(ji,jj)
+               fdpd2(ji,jj)  = xmetapd  * zphd(ji,jj)
+               fdpds2(ji,jj) = xmetapd  * zpds(ji,jj)
+               fdzmi2(ji,jj) = xmetazmi * zzmi(ji,jj)
+               fdzme2(ji,jj) = xmetazme * zzme(ji,jj)
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Plankton mortality losses
+               !! EKP (26/02/09): phytoplankton hyperbolic mortality term 
+               !! introduced 
+               !! to improve performance in gyres
+               !!----------------------------------------------------------
+               !!
+               !! non-diatom phytoplankton
+               !! linear
+               if (jmpn.eq.1) fdpn(ji,jj) = xmpn * zphn(ji,jj)
+               !! quadratic
+               if (jmpn.eq.2) fdpn(ji,jj) = xmpn * zphn(ji,jj) * zphn(ji,jj)
+               !! hyperbolic
+               if (jmpn.eq.3) fdpn(ji,jj) = xmpn * zphn(ji,jj) *             &
+                                            (zphn(ji,jj) /                   &
+                                             (xkphn + zphn(ji,jj)))
+               !! sigmoid
+               if (jmpn.eq.4) fdpn(ji,jj) = xmpn * zphn(ji,jj) *             &
+                                            ((zphn(ji,jj) * zphn(ji,jj)) /   &
+                                             (xkphn + (zphn(ji,jj) *         &
+                                                       zphn(ji,jj))))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! diatom phytoplankton
+               !! linear
+               if (jmpd.eq.1) fdpd(ji,jj) = xmpd * zphd(ji,jj)
+               !! quadratic
+               if (jmpd.eq.2) fdpd(ji,jj) = xmpd * zphd(ji,jj) * zphd(ji,jj)
+               !! hyperbolic
+               if (jmpd.eq.3) fdpd(ji,jj) = xmpd * zphd(ji,jj) *             &
+                                            (zphd(ji,jj) / (xkphd +          &
+                                                            zphd(ji,jj)))
+               !! sigmoid
+               if (jmpd.eq.4) fdpd(ji,jj) = xmpd * zphd(ji,jj) *             &
+                                            ((zphd(ji,jj) * zphd(ji,jj)) /   &
+                                             (xkphd + (zphd(ji,jj) *         &
+                                                       zphd(ji,jj))))
+               fdpds(ji,jj) = fdpd(ji,jj) * fsin(ji,jj)
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! microzooplankton
+               !! linear
+               if (jmzmi.eq.1) fdzmi(ji,jj) = xmzmi * zzmi(ji,jj)
+               !! quadratic
+               if (jmzmi.eq.2) fdzmi(ji,jj) = xmzmi * zzmi(ji,jj) *          &
+                                              zzmi(ji,jj)
+               !! hyperbolic
+               if (jmzmi.eq.3) fdzmi(ji,jj) = xmzmi * zzmi(ji,jj) *          &
+                                              (zzmi(ji,jj) / (xkzmi +        &
+                                                              zzmi(ji,jj)))
+               !! sigmoid
+               if (jmzmi.eq.4) fdzmi(ji,jj) = xmzmi * zzmi(ji,jj) * &
+                  ((zzmi(ji,jj) * zzmi(ji,jj)) / (xkzmi + (zzmi(ji,jj) *     &
+                                                           zzmi(ji,jj))))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! mesozooplankton
+               !! linear
+               if (jmzme.eq.1) fdzme(ji,jj) = xmzme * zzme(ji,jj)
+               !! quadratic
+               if (jmzme.eq.2) fdzme(ji,jj) = xmzme * zzme(ji,jj) *          &
+                                              zzme(ji,jj)
+               !! hyperbolic
+               if (jmzme.eq.3) fdzme(ji,jj) = xmzme * zzme(ji,jj) *          &
+                                              (zzme(ji,jj) / (xkzme +        &
+                                                              zzme(ji,jj)))
+               !! sigmoid
+               if (jmzme.eq.4) fdzme(ji,jj) = xmzme * zzme(ji,jj) *          &
+                                              ((zzme(ji,jj) * zzme(ji,jj)) / &
+                                               (xkzme + (zzme(ji,jj) *       &
+                                                         zzme(ji,jj))))
+            ENDIF
+         ENDDO
+      ENDDO
+
+      !! diatom frustule dissolution. This section is moved from just
+      !! below CALL to iron_chem_scav in trcbio_medusa.F90 - marc 9/5/17
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            IF (tmask(ji,jj,jk) == 1) THEN
+               fsdiss(ji,jj)  = xsdiss * zpds(ji,jj)
+            ENDIF
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE plankton
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE plankton( )                    ! Empty routine
+      WRITE(*,*) 'plankton: You should not have seen this print! error?'
+   END SUBROUTINE plankton
+#endif 
+
+   !!======================================================================
+END MODULE plankton_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/sms_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/sms_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/sms_medusa.F90	(revision 9987)
@@ -0,0 +1,521 @@
+MODULE sms_medusa 
+   !!----------------------------------------------------------------------
+   !!                     ***  sms_medusa.F90  ***  
+   !! TOP :   MEDUSA  Source Minus Sink variables
+   !!----------------------------------------------------------------------
+   !! History :    -   !  1999-09 (M. Levy)  original code
+   !!              -   !  2000-12 (O. Aumont, E. Kestenare)  add sediment 
+   !!             1.0  !  2005-10 (C. Ethe) F90
+   !!             1.0  !  2005-03  (A-S Kremeur) add fphylab, fzoolab, fdetlab, fdbod
+   !!              -   !  2005-06  (A-S Kremeur) add sedpocb, sedpocn, sedpoca
+   !!             2.0  !  2007-04  (C. Deltel, G. Madec)  Free form and modules
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!              -   !  2011-04  (A. Yool) updated for ROAM project
+   !!----------------------------------------------------------------------
+
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                         MEDUSA model
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE par_trc
+
+   IMPLICIT NONE
+   PUBLIC
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 1.0 , LOCEAN-IPSL (2005) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+   INTEGER ::   numnatp_ref = -1           !! Logical units for namelist medusa
+   INTEGER ::   numnatp_cfg = -1           !! Logical units for namelist medusa
+   INTEGER ::   numonp      = -1           !! Logical unit for namelist medusa output
+
+!!----------------------------------------------------------------------
+!! Biological parameters
+!!----------------------------------------------------------------------
+!!
+!! Primary production and chl related quantities
+   REAL(wp) ::  xxi       !:  conversion factor from gC to mmolN 
+   REAL(wp) ::  xaln      !:  Chl-a specific initial slope of P-I curve for non-diatoms 
+   REAL(wp) ::  xald      !:  Chl-a specific initial slope of P-I curve for diatoms
+   INTEGER  ::  jphy      !:  phytoplankton T-dependent growth switch
+   REAL(wp) ::  xvpn      !:  maximum growth rate for non-diatoms
+   REAL(wp) ::  xvpd      !:  maximum growth rate for diatoms
+   REAL(wp) ::  xthetam   !:  maximum Chl to C ratio for non-diatoms      
+   REAL(wp) ::  xthetamd  !:  maximum Chl to C ratio for diatoms    
+   REAL(wp) ::  jq10      !:  specific Q10 value (jphy==2)    
+!!
+!! Diatom silicon parameters
+   REAL(wp) ::  xsin0     !:  minimum diatom Si:N ratio
+   REAL(wp) ::  xnsi0     !:  minimum diatom N:Si ratio
+   REAL(wp) ::  xuif      !:  hypothetical growth ratio at infinite Si:N ratio
+!!
+!! Nutrient limitation
+   INTEGER  ::  jliebig   !:  Liebig nutrient uptake switch
+   REAL(wp) ::  xnln      !:  half-sat constant for DIN uptake by non-diatoms 
+   REAL(wp) ::  xnld      !:  half-sat constant for DIN uptake by diatoms 
+   REAL(wp) ::  xsld      !:  half-sat constant for Si uptake by diatoms 
+   REAL(wp) ::  xfln      !:  half-sat constant for Fe uptake by non-diatoms 
+   REAL(wp) ::  xfld      !:  half-sat constant for Fe uptake by diatoms  
+!!
+!! Grazing
+   REAL(wp) ::  xgmi      !:  microzoo maximum growth rate 
+   REAL(wp) ::  xgme      !:  mesozoo maximum growth rate 
+   REAL(wp) ::  xkmi      !:  microzoo grazing half-sat parameter
+   REAL(wp) ::  xkme      !:  mesozoo grazing half-sat parameter
+   REAL(wp) ::  xphi      !:  micro/mesozoo grazing inefficiency
+   REAL(wp) ::  xbetan    !:  micro/mesozoo N assimilation efficiency
+   REAL(wp) ::  xbetac    !:  micro/mesozoo C assimilation efficiency
+   REAL(wp) ::  xkc       !:  micro/mesozoo net C growth efficiency
+   REAL(wp) ::  xpmipn    !:  grazing preference of microzoo for non-diatoms
+   REAL(wp) ::  xpmid     !:  grazing preference of microzoo for diatoms
+   REAL(wp) ::  xpmepn    !:  grazing preference of mesozoo for non-diatoms 
+   REAL(wp) ::  xpmepd    !:  grazing preference of mesozoo for diatoms
+   REAL(wp) ::  xpmezmi   !:  grazing preference of mesozoo for microzoo
+   REAL(wp) ::  xpmed     !:  grazing preference of mesozoo for detritus
+!!
+!! Metabolic losses
+   REAL(wp) ::  xmetapn   !:  non-diatom metabolic loss rate
+   REAL(wp) ::  xmetapd   !:  diatom     metabolic loss rate
+   REAL(wp) ::  xmetazmi  !:  microzoo   metabolic loss rate
+   REAL(wp) ::  xmetazme  !:  mesozoo    metabolic loss rate
+!!
+!! Mortality losses
+   INTEGER  ::  jmpn      !:  non-diatom mortality functional form
+   REAL(wp) ::  xmpn      !:  non-diatom mortality rate
+   REAL(wp) ::  xkphn     !:  non-diatom mortality half-sat constant
+   INTEGER  ::  jmpd      !:  diatom     mortality functional form
+   REAL(wp) ::  xmpd      !:  diatom     mortality rate
+   REAL(wp) ::  xkphd     !:  diatom     mortality half-sat constant
+   INTEGER  ::  jmzmi     !:  microzoo   mortality functional form
+   REAL(wp) ::  xmzmi     !:  microzoo   mortality rate
+   REAL(wp) ::  xkzmi     !:  microzoo   mortality half-sat constant
+   INTEGER  ::  jmzme     !:  mesozoo    mortality functional form
+   REAL(wp) ::  xmzme     !:  mesozoo    mortality rate
+   REAL(wp) ::  xkzme     !:  mesozoo    mortality half-sat constant
+!!
+!! Remineralisation
+   INTEGER  ::  jmd       !:  detritus T-dependent remineralisation switch
+   INTEGER  ::  jsfd      !:  accelerate seafloor detritus remin. switch
+   REAL(wp) ::  xmd       !:  detrital nitrogen remineralisation rate 
+   REAL(wp) ::  xmdc      !:  detrital carbon remineralisation rate 
+!!
+!! Stochiometric ratios
+   REAL(wp) ::  xthetapn  !:  non-diatom C:N ratio
+   REAL(wp) ::  xthetapd  !:  diatom C:N ratio
+   REAL(wp) ::  xthetazmi !:  microzoo C:N ratio
+   REAL(wp) ::  xthetazme !:  mesozoo C:N ratio
+   REAL(wp) ::  xthetad   !:  detritus C:N ratio
+   REAL(wp) ::  xrfn      !:  phytoplankton Fe:N ratio
+   REAL(wp) ::  xrsn      !:  diatom Si:N ratio (NOT USED HERE; RETAINED FOR LOBSTER)
+!!
+!! Iron parameters
+   INTEGER  ::  jiron     !:  iron scavenging submodel switch
+   REAL(wp) ::  xfe_mass  !:  iron atomic mass
+   REAL(wp) ::  xfe_sol   !:  aeolian iron solubility
+   REAL(wp) ::  xfe_sed   !:  sediment iron input
+   REAL(wp) ::  xLgT      !:  total ligand concentration (umol/m3)
+   REAL(wp) ::  xk_FeL    !:  dissociation constant for (Fe + L)
+   REAL(wp) ::  xk_sc_Fe  !:  scavenging rate of "free" iron
+!!
+!! Gravitational sinking      
+   REAL(wp) ::  vsed      !:  detritus gravitational sinking rate 
+   REAL(wp) ::  xhr       !:  coefficient for Martin et al. (1987) remineralisation
+!!
+!! Fast-sinking detritus parameters
+   INTEGER  ::  jexport   !:  fast detritus remineralisation switch
+   INTEGER  ::  jfdfate   !:  fate of fast detritus at seafloor switch
+   INTEGER  ::  jrratio   !:  rain ratio switch
+   INTEGER  ::  jocalccd  !:  CCD switch
+   REAL(wp) ::  xridg_r0  !:  Ridgwell rain ratio coefficient
+   REAL(wp) ::  xfdfrac1  !:  fast-sinking fraction of diatom nat. mort. losses
+   REAL(wp) ::  xfdfrac2  !:  fast-sinking fraction of mesozooplankton mort. losses
+   REAL(wp) ::  xfdfrac3  !:  fast-sinking fraction of diatom silicon grazing losses
+   REAL(wp) ::  xcaco3a   !:  polar (high latitude) CaCO3 fraction
+   REAL(wp) ::  xcaco3b   !:  equatorial (low latitude) CaCO3 fraction
+   REAL(wp) ::  xmassc    !:  organic C mass:mole ratio, C106 H175 O40 N16 P1
+   REAL(wp) ::  xmassca   !:  calcium carbonate mass:mole ratio, CaCO3
+   REAL(wp) ::  xmasssi   !:  biogenic silicon mass:mole ratio, (H2SiO3)n
+   REAL(wp) ::  xprotca   !:  calcium carbonate protection ratio
+   REAL(wp) ::  xprotsi   !:  biogenic silicon protection ratio
+   REAL(wp) ::  xfastc    !:  organic C remineralisation length scale
+   REAL(wp) ::  xfastca   !:  calcium carbonate dissolution length scale
+   REAL(wp) ::  xfastsi   !:  biogenic silicon dissolution length scale
+!!
+!! Benthos parameters
+   INTEGER  ::  jorgben   !:  does   organic detritus go to the benthos?
+   INTEGER  ::  jinorgben !:  does inorganic detritus go to the benthos?
+!!
+   REAL(wp) ::  xsedn     !:  organic   nitrogen sediment remineralisation rate 
+   REAL(wp) ::  xsedfe    !:  organic   iron     sediment remineralisation rate 
+   REAL(wp) ::  xsedsi    !:  inorganic silicon  sediment dissolution      rate 
+   REAL(wp) ::  xsedc     !:  organic   carbon   sediment remineralisation rate 
+   REAL(wp) ::  xsedca    !:  inorganic carbon   sediment dissolution      rate 
+   REAL(wp) ::  xburial   !:  burial rate of seafloor detritus
+!!
+!! River parameters
+   INTEGER  ::  jriver_n  !:  riverine nitrogen?   0 = no, 1 = conc, 2 = flux
+   INTEGER  ::  jriver_si !:  riverine silicon?    0 = no, 1 = conc, 2 = flux
+   INTEGER  ::  jriver_c  !:  riverine carbon?     0 = no, 1 = conc, 2 = flux
+   INTEGER  ::  jriver_alk!:  riverine alkalinity? 0 = no, 1 = conc, 2 = flux
+   INTEGER  ::  jriver_dep!:  depth river input added to?  1 = surface, >1 possible
+!!
+!! Miscellaneous
+   REAL(wp) ::  xsdiss    !:  diatom frustule dissolution rate
+!!
+!! Additional parameters
+   INTEGER  ::  jpkb      !:  vertical layer for diagnostic of the vertical flux 
+!!
+!! UKESM diagnostics
+   INTEGER  ::  jdms         !: include DMS diagnostics ? Jpalm (27-08-2014) 
+   INTEGER  ::  jdms_input   !: use instant (0) or diel-average (1) inputs (AXY, 08/07/2015)
+   INTEGER  ::  jdms_model   !: choice of DMS model passed to atmosphere
+!!                              1 = ANDR, 2 = SIMO, 3 = ARAN, 4 = HALL
+!!
+!!
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   remdmp   !: depth dependent damping coefficient of passive tracers 
+!!
+!! AXY (27/07/10): add in indices for depth horizons (for sinking flux
+!!                 and seafloor iron inputs)
+   INTEGER  ::    i0100, i0150, i0200, i0500, i1000, i1100
+#if defined key_roam
+!!
+!! ROAM carbon, alkalinity and oxygen cycle parameters
+   REAL(wp) ::  xthetaphy    !:  oxygen evolution/consumption by phytoplankton 
+   REAL(wp) ::  xthetazoo    !:  oxygen consumption by zooplankton 
+   REAL(wp) ::  xthetanit    !:  oxygen consumption by nitrogen remineralisation
+   REAL(wp) ::  xthetarem    !:  oxygen consumption by carbon remineralisation
+   REAL(wp) ::  xo2min       !:  oxygen minimum concentration
+!! 
+!! 3D fields of carbonate system parameters
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: f3_pH       !: 3D pH
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: f3_h2co3    !: 3D carbonic acid
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: f3_hco3     !: 3D bicarbonate
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: f3_co3      !: 3D carbonate
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: f3_omcal    !: 3D omega calcite
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: f3_omarg    !: 3D omega aragonite
+!! 
+!! 2D fields of calcium carbonate compensation depth
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: f2_ccd_cal  !: 2D calcite CCD depth
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: f2_ccd_arg  !: 2D aragonite CCD depth
+!!
+!! 2D fields of organic and inorganic material sedimented on the seafloor
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_sed_n    !: 2D organic nitrogen   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_sed_n    !: 2D organic nitrogen   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_sed_n    !: 2D organic nitrogen   (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_sed_fe   !: 2D organic iron       (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_sed_fe   !: 2D organic iron       (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_sed_fe   !: 2D organic iron       (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_sed_si   !: 2D inorganic silicon  (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_sed_si   !: 2D inorganic silicon  (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_sed_si   !: 2D inorganic silicon  (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_sed_c    !: 2D organic carbon     (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_sed_c    !: 2D organic carbon     (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_sed_c    !: 2D organic carbon     (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_sed_ca   !: 2D inorganic carbon   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_sed_ca   !: 2D inorganic carbon   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_sed_ca   !: 2D inorganic carbon   (after)
+!!
+!! 2D fields of temporally averaged properties for DMS calculations (AXY, 07/07/15)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_dms_chn  !: 2D avg CHN   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_dms_chn  !: 2D avg CHN   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_dms_chn  !: 2D avg CHN   (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_dms_chd  !: 2D avg CHD   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_dms_chd  !: 2D avg CHD   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_dms_chd  !: 2D avg CHD   (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_dms_mld  !: 2D avg MLD   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_dms_mld  !: 2D avg MLD   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_dms_mld  !: 2D avg MLD   (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_dms_qsr  !: 2D avg QSR   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_dms_qsr  !: 2D avg QSR   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_dms_qsr  !: 2D avg QSR   (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_dms_din  !: 2D avg DIN   (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_dms_din  !: 2D avg DIN   (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_dms_din  !: 2D avg DIN   (after)
+!!
+!! 2D fields needing to be knows at first tstp for coupling with atm - UKEMS(Jpalm,14-06-2016)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_co2_flx  !: 2D avg fx co2 (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_co2_flx  !: 2D avg fx co2 (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_co2_flx  !: 2D avg fx co2 (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zb_dms_srf  !: 2D avg sfr dms (before)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_dms_srf  !: 2D avg sfr dms (now)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: za_dms_srf  !: 2D avg srf dms (after)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: zn_chl_srf  !: 2D avg srf chl (now)
+
+#endif
+
+!!----------------------------------------------------------------------
+!! CCD parameter
+!!----------------------------------------------------------------------
+!!
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ocal_ccd  !: CCD depth
+
+!!----------------------------------------------------------------------
+!! Dust parameters
+!!----------------------------------------------------------------------
+!!
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dust      !: dust parameter 1
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   zirondep  !! Fe deposition
+
+!!----------------------------------------------------------------------
+!! River parameters
+!!----------------------------------------------------------------------
+!!
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   riv_n      !: riverine N
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   riv_si     !: riverine Si
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   riv_c      !: riverine C
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   riv_alk    !: riverine alkalinity
+   !! AXY (19/07/12): add this to permit river fluxes to be added below top box
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   friver_dep !: where river fluxes added
+
+#if defined key_roam
+!!----------------------------------------------------------------------
+!! Atmospheric pCO2 data (1859 to 2100 inclusive)
+!!----------------------------------------------------------------------
+!!
+   REAL(wp), DIMENSION(242)         ::   hist_pco2 !: pCO2
+
+# if defined key_rcp26
+      !! UKMO, run AJKKH + KAAEC, RCP 2.6, pCO2 time evolution
+      DATA hist_pco2 / 286.0230, 286.1730, 286.3230, 286.4480, 286.5730, &
+      & 286.7230, 286.8480, 286.9480, 287.0480, 287.1730, &
+      & 287.3230, 287.4730, 287.6480, 287.8480, 288.0730, &
+      & 288.3480, 288.6480, 288.9730, 289.3470, 289.7470, &
+      & 290.1730, 290.6470, 291.1470, 291.6220, 292.0720, &
+      & 292.5220, 292.9220, 293.2470, 293.5220, 293.7470, &
+      & 293.9470, 294.1220, 294.2720, 294.4220, 294.5470, &
+      & 294.6470, 294.7470, 294.8470, 294.9710, 295.1710, &
+      & 295.4460, 295.7470, 296.0720, 296.4210, 296.7710, &
+      & 297.1460, 297.5710, 298.0210, 298.4460, 298.8460, &
+      & 299.2460, 299.6450, 300.0210, 300.3710, 300.7200, &
+      & 301.0450, 301.3460, 301.6710, 302.0200, 302.3450, &
+      & 302.6450, 302.9700, 303.3450, 303.7200, 304.0700, &
+      & 304.4700, 304.9200, 305.3440, 305.7700, 306.2450, &
+      & 306.7190, 307.1700, 307.6440, 308.1190, 308.5440, &
+      & 308.9440, 309.3440, 309.6940, 309.9440, 310.1190, &
+      & 310.2440, 310.3190, 310.3190, 310.2440, 310.1440, &
+      & 310.0690, 310.0440, 310.0690, 310.1440, 310.2690, &
+      & 310.4440, 310.6940, 311.0430, 311.4440, 311.8690, &
+      & 312.3680, 312.9430, 313.5430, 314.1680, 314.7900, &
+      & 315.4430, 316.2150, 317.0170, 317.7370, 318.3400, &
+      & 318.8680, 319.5900, 320.5890, 321.5470, 322.5770, &
+      & 323.8440, 324.9260, 325.7960, 327.0810, 328.6180, &
+      & 329.6830, 330.5250, 331.6880, 333.2120, 334.7870, &
+      & 336.4640, 338.2990, 339.6660, 340.7310, 342.1360, &
+      & 343.7200, 345.2200, 346.7350, 348.5820, 350.6740, &
+      & 352.4230, 353.7910, 354.9530, 355.8210, 356.7130, &
+      & 358.0630, 359.7720, 361.3970, 363.0900, 365.2560, &
+      & 367.2810, 368.7980, 370.4000, 372.4550, 374.6920, &
+      & 376.7440, 378.7440, 380.7580, 382.7080, 384.7300, &
+      & 386.9310, 389.2150, 391.4910, 393.7710, 396.0460, &
+      & 398.3240, 400.6080, 402.8950, 405.1780, 407.4550, &
+      & 409.7260, 411.9930, 414.2500, 416.4410, 418.5280, &
+      & 420.5250, 422.4390, 424.2720, 426.0200, 427.6750, &
+      & 429.2360, 430.7050, 432.0850, 433.3580, 434.5140, &
+      & 435.5740, 436.5490, 437.4420, 438.2550, 438.9810, &
+      & 439.6110, 440.1430, 440.5770, 440.9450, 441.2660, &
+      & 441.5410, 441.7840, 442.0050, 442.2040, 442.3780, &
+      & 442.5210, 442.6200, 442.6720, 442.6810, 442.6540, &
+      & 442.5830, 442.4670, 442.3270, 442.1680, 441.9960, &
+      & 441.8060, 441.5930, 441.3440, 441.0540, 440.7230, &
+      & 440.3510, 439.9300, 439.4650, 438.9730, 438.4630, &
+      & 437.9400, 437.4020, 436.8400, 436.2640, 435.6850, &
+      & 435.1030, 434.5160, 433.9170, 433.3060, 432.7010, &
+      & 432.1110, 431.5380, 430.9810, 430.4320, 429.8860, &
+      & 429.3370, 428.7810, 428.2220, 427.6490, 427.0660, &
+      & 426.4890, 425.9270, 425.3840, 424.8610, 424.3540, &
+      & 423.8540, 423.3540, 422.8530, 422.3510, 421.8410, &
+      & 421.3250, 420.8190 /
+# else
+      !! UKMO, run AJKKH + KAAEF, RCP 8.5, pCO2 time evolution
+      DATA hist_pco2 / 286.0230, 286.1730, 286.3230, 286.4480, 286.5730, &
+      & 286.7230, 286.8480, 286.9480, 287.0480, 287.1730, &
+      & 287.3230, 287.4730, 287.6480, 287.8480, 288.0730, &
+      & 288.3480, 288.6480, 288.9730, 289.3470, 289.7470, &
+      & 290.1730, 290.6470, 291.1470, 291.6220, 292.0720, &
+      & 292.5220, 292.9220, 293.2470, 293.5220, 293.7470, &
+      & 293.9470, 294.1220, 294.2720, 294.4220, 294.5470, &
+      & 294.6470, 294.7470, 294.8470, 294.9710, 295.1710, &
+      & 295.4460, 295.7470, 296.0720, 296.4210, 296.7710, &
+      & 297.1460, 297.5710, 298.0210, 298.4460, 298.8460, &
+      & 299.2460, 299.6450, 300.0210, 300.3710, 300.7200, &
+      & 301.0450, 301.3460, 301.6710, 302.0200, 302.3450, &
+      & 302.6450, 302.9700, 303.3450, 303.7200, 304.0700, &
+      & 304.4700, 304.9200, 305.3440, 305.7700, 306.2450, &
+      & 306.7190, 307.1700, 307.6440, 308.1190, 308.5440, &
+      & 308.9440, 309.3440, 309.6940, 309.9440, 310.1190, &
+      & 310.2440, 310.3190, 310.3190, 310.2440, 310.1440, &
+      & 310.0690, 310.0440, 310.0690, 310.1440, 310.2690, &
+      & 310.4440, 310.6940, 311.0430, 311.4440, 311.8690, &
+      & 312.3680, 312.9430, 313.5430, 314.1680, 314.7900, &
+      & 315.4430, 316.2150, 317.0170, 317.7370, 318.3400, &
+      & 318.8680, 319.5900, 320.5890, 321.5470, 322.5770, &
+      & 323.8440, 324.9260, 325.7960, 327.0810, 328.6180, &
+      & 329.6830, 330.5250, 331.6880, 333.2120, 334.7870, &
+      & 336.4640, 338.2990, 339.6660, 340.7310, 342.1360, &
+      & 343.7200, 345.2200, 346.7350, 348.5820, 350.6740, &
+      & 352.4230, 353.7910, 354.9530, 355.8210, 356.7130, &
+      & 358.0630, 359.7720, 361.3970, 363.0900, 365.2560, &
+      & 367.2810, 368.7980, 370.4000, 372.4550, 374.6920, &
+      & 376.7440, 378.7440, 380.7580, 382.7080, 384.7300, &
+      & 386.9420, 389.2540, 391.5670, 393.9370, 396.3920, &
+      & 398.9320, 401.5550, 404.2550, 407.0220, 409.8530, &
+      & 412.7470, 415.7050, 418.7210, 421.7880, 424.9180, &
+      & 428.1200, 431.3970, 434.7470, 438.1650, 441.6410, &
+      & 445.1700, 448.7530, 452.3920, 456.0950, 459.8810, &
+      & 463.7680, 467.7660, 471.8750, 476.0960, 480.4210, &
+      & 484.8390, 489.3470, 493.9430, 498.6400, 503.4380, &
+      & 508.3410, 513.3630, 518.5160, 523.8050, 529.2290, &
+      & 534.7780, 540.4450, 546.2230, 552.1120, 558.1110, &
+      & 564.2110, 570.4130, 576.7390, 583.1990, 589.7980, &
+      & 596.5390, 603.4110, 610.4060, 617.4940, 624.6500, &
+      & 631.8800, 639.1750, 646.5360, 653.9800, 661.5230, &
+      & 669.1840, 676.9570, 684.8290, 692.7790, 700.7690, &
+      & 708.8050, 716.8870, 725.0020, 733.1770, 741.3900, &
+      & 749.6700, 758.0480, 766.5050, 775.0350, 783.6110, &
+      & 792.2200, 800.8740, 809.5680, 818.2760, 827.0090, &
+      & 835.8020, 844.6550, 853.5730, 862.5690, 871.6190, &
+      & 880.7020, 889.8240, 898.9590, 908.1270, 917.3080, &
+      & 926.4960, 935.7040 /
+# endif
+#endif
+
+!!----------------------------------------------------------------------
+!! Optical parameters
+!!----------------------------------------------------------------------
+!!
+   REAL(wp) ::   xkr0       !: water coefficient absorption in red      (NAMELIST)
+   REAL(wp) ::   xkg0       !: water coefficient absorption in green    (NAMELIST)
+   REAL(wp) ::   xkrp       !: pigment coefficient absorption in red    (NAMELIST)
+   REAL(wp) ::   xkgp       !: pigment coefficient absorption in green  (NAMELIST)
+   REAL(wp) ::   xlr        !: exposant for pigment absorption in red   (NAMELIST)
+   REAL(wp) ::   xlg        !: exposant for pigment absorption in green (NAMELIST)
+   REAL(wp) ::   rpig       !: chla/chla+phea ratio                     (NAMELIST)
+                                                        
+   INTEGER , ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   neln    !: number of levels in the euphotic layer
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   xze     !: euphotic layer depth
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xpar    !: par (photosynthetic available radiation)
+
+!!----------------------------------------------------------------------
+!! Sediment parameters                               
+!! 
+!! AXY (16/01/12): these parameters were originally part of the pre-
+!!                 cursor model on which MEDUSA's code was grounded;
+!!                 they do not relate to the sediment/benthos submodel
+!!                 added as part of the ROAM project; they have only
+!!                 been retained because they are distributed through
+!!                 MEDUSA and require a proper clean-up to purge
+!!----------------------------------------------------------------------
+!!
+   REAL(wp) ::   sedlam       !: time coefficient of POC remineralization in sediments
+   REAL(wp) ::   sedlostpoc   !: ???
+   REAL(wp) ::   areacot      !: ???
+                                                        
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: dminl       !: fraction of sinking POC released in sediments
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: dmin3       !: fraction of sinking POC released at each level
+                                                        
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: sedpocb     !: mass of POC in sediments
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: sedpocn     !: mass of POC in sediments
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: sedpoca     !: mass of POC in sediments
+                                                        
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: fbodf       !: rapid sinking particles
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: fbods       !: rapid sinking particles
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: fbodn       !: rapid sinking particles
+                                                        
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: ffln        !: 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: fflf        !: 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: ffls        !: 
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   :: cmask       !: ???
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sms_medusa_alloc()
+      !!----------------------------------------------------------------------
+      !!        *** ROUTINE sms_medusa_alloc ***
+      !!----------------------------------------------------------------------
+      USE lib_mpp , ONLY: ctl_warn
+      INTEGER ::   ierr(8)        ! Local variables
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+#if defined key_medusa
+      !* depth-dependent damping coefficient
+      ALLOCATE( remdmp(jpk,jp_medusa),                           STAT=ierr(1) )
+# if defined key_roam
+      !* 2D and 3D fields of carbonate system parameters
+      ALLOCATE( f2_ccd_cal(jpi,jpj)  , f2_ccd_arg(jpi,jpj)  ,       &
+         &      f3_pH(jpi,jpj,jpk)   , f3_h2co3(jpi,jpj,jpk),       &
+         &      f3_hco3(jpi,jpj,jpk) , f3_co3(jpi,jpj,jpk)  ,       &
+         &      f3_omcal(jpi,jpj,jpk), f3_omarg(jpi,jpj,jpk),    STAT=ierr(2) )
+      !* 2D fields of organic and inorganic material sedimented on the seafloor
+      ALLOCATE( zb_sed_n(jpi,jpj)    , zn_sed_n(jpi,jpj)    ,       &
+         &      za_sed_n(jpi,jpj)    ,                              &
+         &      zb_sed_fe(jpi,jpj)   , zn_sed_fe(jpi,jpj)   ,       &
+         &      za_sed_fe(jpi,jpj)   ,                              &
+         &      zb_sed_si(jpi,jpj)   , zn_sed_si(jpi,jpj)   ,       &
+         &      za_sed_si(jpi,jpj)   ,                              &
+         &      zb_sed_c(jpi,jpj)    , zn_sed_c(jpi,jpj)    ,       &
+         &      za_sed_c(jpi,jpj)    ,                              &
+         &      zb_sed_ca(jpi,jpj)   , zn_sed_ca(jpi,jpj)   ,       &
+         &      za_sed_ca(jpi,jpj)   ,                           STAT=ierr(3) )
+      !* 2D fields of temporally averaged properties for DMS calculations (AXY, 07/07/15)
+      ALLOCATE( zb_dms_chn(jpi,jpj)  , zn_dms_chn(jpi,jpj)  ,       &
+         &      za_dms_chn(jpi,jpj)  ,                              &
+         &      zb_dms_chd(jpi,jpj)  , zn_dms_chd(jpi,jpj)  ,       &		  
+         &      za_dms_chd(jpi,jpj)  ,                              &
+         &      zb_dms_mld(jpi,jpj)  , zn_dms_mld(jpi,jpj)  ,       &		  
+         &      za_dms_mld(jpi,jpj)  ,                              &
+         &      zb_dms_qsr(jpi,jpj)  , zn_dms_qsr(jpi,jpj)  ,       &		  
+         &      za_dms_qsr(jpi,jpj)  ,                              &
+         &      zb_dms_din(jpi,jpj)  , zn_dms_din(jpi,jpj)  ,       &		  
+         &      za_dms_din(jpi,jpj)  ,                           STAT=ierr(4) )
+      !* 2D fields needing to be knows at first tstp for coupling with atm -
+      !UKEMSi (Jpalm,14-06-2016) 
+      ALLOCATE( zb_co2_flx(jpi,jpj)  , zn_co2_flx(jpi,jpj)  ,       &
+         &      za_co2_flx(jpi,jpj)  ,                              &
+         &      zb_dms_srf(jpi,jpj)  , zn_dms_srf(jpi,jpj)  ,       &           
+         &      za_dms_srf(jpi,jpj)  , zn_chl_srf(jpi,jpj)  ,    STAT=ierr(5) )
+# endif
+      !* 2D fields of miscellaneous parameters
+      ALLOCATE( ocal_ccd(jpi,jpj)    , dust(jpi,jpj)        ,       &
+         &      zirondep(jpi,jpj)                           ,       &
+         &      riv_n(jpi,jpj)                              ,       &
+         &      riv_si(jpi,jpj)      , riv_c(jpi,jpj)       ,       &
+         &      riv_alk(jpi,jpj)     , friver_dep(jpk,jpk)  ,    STAT=ierr(6) )
+      !* 2D and 3D fields of light parameters
+      ALLOCATE( neln(jpi,jpj)        , xze(jpi,jpj)         ,       &
+         &      xpar(jpi,jpj,jpk)    ,                           STAT=ierr(7) )
+      !* 2D and 3D fields of sediment-associated parameters
+      ALLOCATE( dminl(jpi,jpj)       , dmin3(jpi,jpj,jpk)   ,       &
+         &      sedpocb(jpi,jpj)     , sedpocn(jpi,jpj)     ,       &
+         &      sedpoca(jpi,jpj)     , fbodn(jpi,jpj)       ,       &
+         &      fbodf(jpi,jpj)       , fbods(jpi,jpj)       ,       &
+         &      ffln(jpi,jpj,jpk)    , fflf(jpi,jpj,jpk)    ,       &
+         &      ffls(jpi,jpj,jpk)    , cmask(jpi,jpj)       ,    STAT=ierr(8) ) 
+#endif
+      !
+      sms_medusa_alloc = MAXVAL( ierr )
+      !
+      IF( sms_medusa_alloc /= 0 )   CALL ctl_warn('sms_medusa_alloc: failed to allocate arrays')
+      !
+   END FUNCTION sms_medusa_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Empty module :                                     NO MEDUSA model 
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE sms_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcavg_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcavg_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcavg_medusa.F90	(revision 9987)
@@ -0,0 +1,128 @@
+MODULE trcavg_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcavg_medusa  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :    -   !  2015-07  (A. Yool) Original code
+   !!----------------------------------------------------------------------
+#if defined key_medusa && defined key_roam
+   !!----------------------------------------------------------------------
+   !!                                        MEDUSA rolling averages
+   !!----------------------------------------------------------------------
+   !!   trc_avg_medusa        :  
+   !!----------------------------------------------------------------------
+      USE oce_trc
+      USE trc
+      USE sms_medusa
+      USE lbclnk
+      USE prtctl_trc      ! Print control for debugging
+      USE in_out_manager  ! I/O manager
+
+      IMPLICIT NONE
+      PRIVATE
+
+      PUBLIC   trc_avg_medusa    ! called in trc_sms_medusa
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+!=======================================================================
+!
+      SUBROUTINE trc_avg_medusa( kt )
+!      
+!=======================================================================
+      !!
+      !! Title  : Calculates rolling averages of variables
+      !! Author : Andrew Yool
+      !! Date   : 23/07/15
+      !!
+      !! Calculates and updates rolling averages of properties such
+      !! as surface irradiance and mixed layer depth that are used
+      !! in functions that require average rather than instantaneous
+      !! values.
+      !!
+      !! This functionality was originally added to support the
+      !! calculation of surface DMS concentrations - and was done so
+      !! within the trcbio_meduse.F90 routine - but was moved to
+      !! this separate module so that its calculations could be used
+      !! to inform MEDUSA's submarine irradiance field
+      !!
+!=======================================================================
+!
+      IMPLICIT NONE
+!
+      INTEGER, INTENT( in ) ::   kt   ! index of the time stepping
+! 
+!=======================================================================
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) ' MEDUSA inside trc_avg_medusa'
+         CALL flush(numout)
+# endif
+      !! AXY (24/07/15): alter this to report on first MEDUSA call
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_avg_medusa: MEDUSA rolling average'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+         IF(lwp) WRITE(numout,*) ' kt =',kt
+      ENDIF
+      !!
+      !!----------------------------------------------------------------------
+      !! Process average fields
+      !! The empirical formulae used for estimating surface DMS concentrations
+      !! require temporally averaged input fields; this block calculates these
+      !! averages based on diel averages; note that rdt 
+      !!----------------------------------------------------------------------
+      !!
+      zn_dms_chn(:,:) = ( zb_dms_chn(:,:) * ((86400. - rdt) / 86400.) ) &
+      &                  + ( trn(:,:,1,jpchn) * (rdt / 86400.) )
+      zb_dms_chn(:,:) = zn_dms_chn(:,:)
+      zn_dms_chd(:,:) = ( zb_dms_chd(:,:) * ((86400. - rdt) / 86400.) ) &
+      &                  + ( trn(:,:,1,jpchd) * (rdt / 86400.) )
+      zb_dms_chd(:,:) = zn_dms_chd(:,:)
+      zn_dms_mld(:,:) = ( zb_dms_mld(:,:) * ((86400. - rdt) / 86400.) ) &
+      &                  + (        hmld(:,:) * (rdt / 86400.) )
+      zb_dms_mld(:,:) = zn_dms_mld(:,:)
+      zn_dms_qsr(:,:) = ( zb_dms_qsr(:,:) * ((86400. - rdt) / 86400.) ) &
+      &                  + (         qsr(:,:) * (rdt / 86400.) )
+      zb_dms_qsr(:,:) = zn_dms_qsr(:,:)
+      zn_dms_din(:,:) = ( zb_dms_din(:,:) * ((86400. - rdt) / 86400.) ) &
+      &                  + ( trn(:,:,1,jpdin) * (rdt / 86400.) )
+      zb_dms_din(:,:) = zn_dms_din(:,:)
+
+  END SUBROUTINE trc_avg_medusa
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+
+CONTAINS
+
+!=======================================================================
+!
+   SUBROUTINE trc_avg_medusa( kt )                                        !! EMPTY Routine
+!      
+!
+      INTEGER, INTENT( in ) ::   kt
+!
+
+      WRITE(*,*) 'trc_avg_medusa: You should not have seen this print! error?'
+
+   END SUBROUTINE trc_avg_medusa
+#endif
+
+   !!======================================================================
+END MODULE  trcavg_medusa
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcbio_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcbio_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcbio_medusa.F90	(revision 9987)
@@ -0,0 +1,671 @@
+MODULE trcbio_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcbio  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :
+   !!  -   !  1999-07  (M. Levy)              original code
+   !!  -   !  2000-12  (E. Kestenare)         assign parameters to name 
+   !!                                         individual tracers
+   !!  -   !  2001-03  (M. Levy)              LNO3 + dia2d 
+   !! 2.0  !  2007-12  (C. Deltel, G. Madec)  F90
+   !!  -   !  2008-08  (K. Popova)            adaptation for MEDUSA
+   !!  -   !  2008-11  (A. Yool)              continuing adaptation for MEDUSA
+   !!  -   !  2010-03  (A. Yool)              updated for branch inclusion
+   !!  -   !  2011-08  (A. Yool)              updated for ROAM (see below)
+   !!  -   !  2013-03  (A. Yool)              updated for iMARNET
+   !!  -   !  2013-05  (A. Yool)              updated for v3.5
+   !!  -   !  2014-08  (A. Yool, J. Palm)     Add DMS module for UKESM1 model
+   !!  -   !  2015-06  (A. Yool)              Update to include MOCSY
+   !!  -   !  2015-07  (A. Yool)              Update for rolling averages
+   !!  -   !  2015-10  (J. Palm)              Update for diag outputs through 
+   !!                                         iom_use  
+   !!  -   !  2016-11  (A. Yool)              Updated diags for CMIP6
+   !!  -   !  2017-05  (A. Yool)              Added extra DMS calculation
+   !!----------------------------------------------------------------------
+   !!
+#if defined key_roam
+   !!----------------------------------------------------------------------
+   !! Updates for the ROAM project include:
+   !!   - addition of DIC, alkalinity, detrital carbon and oxygen tracers
+   !!   - addition of air-sea fluxes of CO2 and oxygen
+   !!   - periodic (monthly) calculation of full 3D carbonate chemistry 
+   !!   - detrital C:N ratio now free to evolve dynamically
+   !!   - benthic storage pools
+   !! 
+   !! Opportunity also taken to add functionality:
+   !!   - switch for Liebig Law (= most-limiting) nutrient uptake
+   !!   - switch for accelerated seafloor detritus remineralisation
+   !!   - switch for fast -> slow detritus transfer at seafloor
+   !!   - switch for ballast vs. Martin vs. Henson fast detritus remin.
+   !!   - per GMD referee remarks, xfdfrac3 introduced for grazed PDS
+   !!----------------------------------------------------------------------
+#endif
+   !!
+#if defined key_mocsy
+   !!----------------------------------------------------------------------
+   !! Updates with the addition of MOCSY include:
+   !!   - option to use PML or MOCSY carbonate chemistry (the latter is 
+   !!     preferred)
+   !!   - central calculation of gas transfer velocity, f_kw660; previously
+   !!     this was done separately for CO2 and O2 with predictable results
+   !!   - distribution of f_kw660 to both PML and MOCSY CO2 air-sea flux 
+   !!     calculations and to those for O2 air-sea flux
+   !!   - extra diagnostics included for MOCSY
+   !!----------------------------------------------------------------------
+#endif
+   !!
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                        MEDUSA bio-model
+   !!----------------------------------------------------------------------
+   !!   trc_bio_medusa        :  
+   !!----------------------------------------------------------------------
+      !! AXY (30/01/14): necessary to find NaNs on HECTOR
+      USE, INTRINSIC :: ieee_arithmetic 
+
+      USE bio_medusa_mod,             ONLY: b0, fdep1,                      & 
+                                            ibenthic, idf, idfval,          &
+# if defined key_roam
+                                            f_xco2a,                        &
+                                            zalk, zdic, zoxy, zsal, ztmp,   &
+# endif
+# if defined key_mocsy
+                                            zpho,                           &
+# endif
+                                            zchd, zchn, zdet, zdin, zdtc,   &
+                                            zfer, zpds, zphd, zphn, zsil,   &
+                                            zzme, zzmi
+      USE dom_oce,                    ONLY: e3t_0, e3t_n,                   &
+                                            gdept_0, gdept_n,               &
+                                            gdepw_0, gdepw_n,               &
+                                            nday_year, nsec_day, nyear,     &
+                                            rdt, tmask
+      USE in_out_manager,             ONLY: lwp, numout, nn_date0
+# if defined key_iomput
+      USE iom,                        ONLY: lk_iomput
+# endif
+      USE lbclnk,                     ONLY: lbc_lnk
+      USE lib_mpp,                    ONLY: ctl_stop
+      USE oce,                        ONLY: tsb, tsn
+      USE par_kind,                   ONLY: wp
+      USE par_medusa,                 ONLY: jpalk, jpchd, jpchn, jpdet,     &
+                                            jpdic, jpdin, jpdtc, jpfer,     &
+                                            jpoxy, jppds, jpphd, jpphn,     &
+                                            jpsil, jpzme, jpzmi
+      USE par_oce,                    ONLY: jp_sal, jp_tem, jpi, jpim1,     &
+                                            jpj, jpjm1, jpk
+      !! JPALM (27-06-2016): add lk_oasis for CO2 and DMS coupling with atm
+      USE sbc_oce,                    ONLY: lk_oasis
+      USE sms_medusa,                 ONLY: hist_pco2
+      USE trc,                        ONLY: ln_rsttr, nittrc000, trn
+      USE bio_medusa_init_mod,        ONLY: bio_medusa_init
+      USE carb_chem_mod,              ONLY: carb_chem
+      USE air_sea_mod,                ONLY: air_sea
+      USE plankton_mod,               ONLY: plankton
+      USE iron_chem_scav_mod,         ONLY: iron_chem_scav
+      USE detritus_mod,               ONLY: detritus
+      USE bio_medusa_update_mod,      ONLY: bio_medusa_update
+      USE bio_medusa_diag_mod,        ONLY: bio_medusa_diag
+      USE bio_medusa_diag_slice_mod,  ONLY: bio_medusa_diag_slice
+      USE bio_medusa_fin_mod,         ONLY: bio_medusa_fin
+
+      IMPLICIT NONE
+      PRIVATE
+      
+      PUBLIC   trc_bio_medusa    ! called in trcsms_medusa.F90
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_bio_medusa( kt )
+      !!------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_bio  ***
+      !!
+      !! ** Purpose : compute the now trend due to biogeochemical processes
+      !!              and add it to the general trend of passive tracers 
+      !!              equations
+      !!
+      !! ** Method  : each now biological flux is calculated in function of
+      !!              now concentrations of tracers.
+      !!              depending on the tracer, these fluxes are sources or 
+      !!              sinks.
+      !!              The total of the sources and sinks for each tracer
+      !!              is added to the general trend.
+      !!        
+      !!                      tra = tra + zf...tra - zftra...
+      !!                                     |         |
+      !!                                     |         |
+      !!                                  source      sink
+      !!        
+      !!              IF 'key_trc_diabio' defined , the biogeochemical trends
+      !!              for passive tracers are saved for futher diagnostics.
+      !!------------------------------------------------------------------
+      !!
+      !!
+      !!------------------------------------------------------------------
+      !! Variable conventions
+      !!------------------------------------------------------------------
+      !!
+      !! names: z*** - state variable 
+      !!        f*** - function (or temporary variable used in part of 
+      !!               a function)
+      !!        x*** - parameter
+      !!        b*** - right-hand part (sources and sinks)
+      !!        i*** - integer variable (usually used in yes/no flags)
+      !!
+      !! time (integer timestep)
+      INTEGER, INTENT( in ) ::    kt
+      !!
+      !! spatial array indices
+      INTEGER  ::    ji,jj,jk,jn
+      !!
+      INTEGER  ::    iball
+# if defined key_roam
+      !!
+      INTEGER  ::    iyr1, iyr2
+      !!
+# endif
+      !! 
+      !! temporary variables
+      REAL(wp) ::    fq0,fq1,fq2,fq3,fq4
+      !!
+      !!------------------------------------------------------------------
+
+# if defined key_debug_medusa
+      IF (lwp) write (numout,*) 'trc_bio_medusa: variables defined'
+      CALL flush(numout)
+# endif 
+
+      !! AXY (20/11/14): alter this to report on first MEDUSA call
+      !! IF( kt == nit000 ) THEN
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_bio: MEDUSA bio-model'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+	 IF(lwp) WRITE(numout,*) ' kt =',kt
+      ENDIF
+
+      !! AXY (13/01/12): is benthic model properly interactive? 0 = no, 1 = yes
+      ibenthic = 1
+
+      !!------------------------------------------------------------------
+      !! b0 is present for debugging purposes; using b0 = 0 sets the tendency
+      !! terms of all biological equations to 0.
+      !!------------------------------------------------------------------
+      !!
+      !! AXY (03/09/14): probably not the smartest move ever, but it'll fit
+      !!                 the bill for now; another item on the things-to-sort-
+      !!		 out-in-the-future list ...
+# if defined key_kill_medusa
+      b0 = 0.
+# else
+      b0 = 1.
+# endif
+      !!------------------------------------------------------------------
+      !! fast detritus ballast scheme (0 = no; 1 = yes)
+      !! alternative to ballast scheme is same scheme but with no ballast
+      !! protection (not dissimilar to Martin et al., 1987)
+      !!------------------------------------------------------------------
+      !!
+      iball = 1
+
+      !!------------------------------------------------------------------
+      !! full flux diagnostics (0 = no; 1 = yes); appear in ocean.output
+      !! these should *only* be used in 1D since they give comprehensive
+      !! output for ecological functions in the model; primarily used in
+      !! debugging
+      !!------------------------------------------------------------------
+      !!
+      idf    = 0
+      !!
+      !! timer mechanism
+      if (kt/120*120.eq.kt) then
+         idfval = 1
+      else
+         idfval = 0
+      endif
+
+      !!------------------------------------------------------------------
+      !! Initialise arrays to zero and set up arrays for diagnostics
+      !!------------------------------------------------------------------
+      CALL bio_medusa_init( kt )
+
+# if defined key_axy_nancheck
+       DO jn = jp_msa0,jp_msa1
+          !! fq0 = MINVAL(trn(:,:,:,jn))
+          !! fq1 = MAXVAL(trn(:,:,:,jn))
+          fq2 = SUM(trn(:,:,:,jn))
+          !! if (lwp) write (numout,'(a,2i6,3(1x,1pe15.5))') 'NAN-CHECK',     &
+          !!                kt, jn, fq0, fq1, fq2
+          !! AXY (30/01/14): much to our surprise, the next line doesn't 
+          !!                 work on HECTOR and has been replaced here with 
+          !!                 a specialist routine
+          !! if (fq2 /= fq2 ) then
+          if ( ieee_is_nan( fq2 ) ) then
+             !! there's a NaN here
+             if (lwp) write(numout,*) 'NAN detected in field', jn,           &
+                                      'at time', kt, 'at position:'
+             DO jk = 1,jpk
+                DO jj = 1,jpj
+                   DO ji = 1,jpi
+                      !! AXY (30/01/14): "isnan" problem on HECTOR
+                      !! if (trn(ji,jj,jk,jn) /= trn(ji,jj,jk,jn)) then
+                      if ( ieee_is_nan( trn(ji,jj,jk,jn) ) ) then
+                         if (lwp) write (numout,'(a,1pe12.2,4i6)')           &
+                            'NAN-CHECK', tmask(ji,jj,jk), ji, jj, jk, jn
+                      endif
+                   enddo
+                enddo
+             enddo
+             CALL ctl_stop( 'trcbio_medusa, NAN in incoming tracer field' )
+          endif
+       ENDDO
+       CALL flush(numout)
+# endif
+
+# if defined key_debug_medusa
+      IF (lwp) write (numout,*)                                              &
+                     'trc_bio_medusa: variables initialised and checked'
+      CALL flush(numout)
+# endif 
+
+# if defined key_roam
+      !!------------------------------------------------------------------
+      !! calculate atmospheric pCO2
+      !!------------------------------------------------------------------
+      !!
+      !! what's atmospheric pCO2 doing? (data start in 1859)
+      iyr1  = nyear - 1859 + 1
+      iyr2  = iyr1 + 1
+      if (iyr1 .le. 1) then
+         !! before 1860
+         f_xco2a(:,:) = hist_pco2(1)
+      elseif (iyr2 .ge. 242) then
+         !! after 2099
+         f_xco2a(:,:) = hist_pco2(242)
+      else
+         !! just right
+         fq0 = hist_pco2(iyr1)
+         fq1 = hist_pco2(iyr2)
+         fq2 = real(nsec_day) / (60.0 * 60.0 * 24.0)
+         !! AXY (14/06/12): tweaked to make more sense (and be correct)
+#  if defined key_bs_axy_yrlen
+         !! bugfix: for 360d year with HadGEM2-ES forcing
+         fq3 = (real(nday_year) - 1.0 + fq2) / 360.0  
+#  else
+         !! original use of 365 days (not accounting for leap year or 
+         !! 360d year)
+         fq3 = (real(nday_year) - 1.0 + fq2) / 365.0
+#  endif
+         fq4 = (fq0 * (1.0 - fq3)) + (fq1 * fq3)
+         f_xco2a(:,:) = fq4
+      endif
+#  if defined key_axy_pi_co2
+      !! OCMIP pre-industrial pCO2
+      !! f_xco2a(:,:) = 284.725  !! CMIP5 pre-industrial pCO2
+      f_xco2a = 284.317          !! CMIP6 pre-industrial pCO2 
+#  endif
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA nyear     =', nyear
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA nsec_day  =', real(nsec_day)
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA nday_year =', real(nday_year)
+      !! AXY (29/01/14): remove surplus diagnostics
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA fq0       =', fq0
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA fq1       =', fq1
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA fq2       =', fq2
+      !! IF(lwp) WRITE(numout,*) ' MEDUSA fq3       =', fq3
+      IF(lwp) WRITE(numout,*) ' MEDUSA atm pCO2  =', f_xco2a(1,1)
+# endif
+
+# if defined key_debug_medusa
+      IF (lwp) write (numout,*) 'trc_bio_medusa: ready for carbonate chemistry'
+      IF (lwp) write (numout,*) 'trc_bio_medusa: kt = ', kt
+      IF (lwp) write (numout,*) 'trc_bio_medusa: nittrc000 = ', nittrc000
+      CALL flush(numout)
+# endif 
+
+# if defined key_roam
+      !! AXY (20/11/14): alter to call on first MEDUSA timestep and then every
+      !!                 month (this is hardwired as 960 timesteps but should
+      !!                 be calculated and done properly
+      !! IF( kt == nit000 .or. mod(kt,1920) == 0 ) THEN
+      !! IF( kt == nittrc000 .or. mod(kt,960) == 0 ) THEN 
+      !!=============================
+      !! Jpalm -- 07-10-2016 -- need to change carb-chem frequency call :
+      !!          we don't want to call on the first time-step of all run 
+      !!          submission, but only on the very first time-step, and 
+      !!          then every month. So we call on nittrc000 if not 
+      !!          restarted run, else if one month after last call.
+      !!          Assume one month is 30d --> 3600*24*30 : 2592000s
+      !!          try to call carb-chem at 1st month's tm-stp : 
+      !!          x * 30d + 1*rdt(i.e: mod = rdt)   
+      !!          ++ need to pass carb-chem output var through restarts
+      If ( (kt == nittrc000 .AND. .NOT.ln_rsttr) .OR.                        &
+           ((86400*mod(nn_date0,100) + mod(kt*rdt,2592000.)) == rdt) ) THEN
+         !!---------------------------------------------------------------
+         !! Calculate the carbonate chemistry for the whole ocean on the first
+         !! simulation timestep and every month subsequently; the resulting 3D
+         !! field of omega calcite is used to determine the depth of the CCD
+         !!---------------------------------------------------------------
+         CALL carb_chem( kt )
+
+      ENDIF
+# endif
+
+# if defined key_debug_medusa
+      IF (lwp) write (numout,*) 'trc_bio_medusa: ready for full domain calculations'
+      CALL flush(numout)
+# endif 
+
+      !!------------------------------------------------------------------
+      !! MEDUSA has unified equation through the water column
+      !! (Diff. from LOBSTER which has two sets: bio- and non-bio layers) 
+      !! Statement below in LOBSTER is different: DO jk = 1, jpkbm1          
+      !!------------------------------------------------------------------
+      !!
+      !! NOTE: the ordering of the loops below differs from that of some other
+      !! models; looping over the vertical dimension is the outermost loop and
+      !! this complicates some calculations (e.g. storage of vertical fluxes
+      !! that can otherwise be done via a singular variable require 2D fields
+      !! here); however, these issues are relatively easily resolved, but the
+      !! loops CANNOT be reordered without potentially causing code efficiency
+      !! problems (e.g. array indexing means that reordering the loops would
+      !! require skipping between widely-spaced memory location; potentially
+      !! outside those immediately cached)
+      !!
+      !! OPEN vertical loop
+      DO jk = 1,jpk
+         !! OPEN horizontal loops
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               !! OPEN wet point IF..THEN loop
+               if (tmask(ji,jj,jk) == 1) then               
+                  !!======================================================
+                  !! SETUP LOCAL GRID CELL
+                  !!======================================================
+                  !!
+                  !!------------------------------------------------------
+                  !! Some notes on grid vertical structure
+                  !! - fsdepw(ji,jj,jk) is the depth of the upper surface of 
+                  !!   level jk
+                  !! - fsde3w(ji,jj,jk) is *approximately* the midpoint of 
+                  !!   level jk
+                  !! - fse3t(ji,jj,jk)  is the thickness of level jk
+                  !!------------------------------------------------------
+                  !!
+                  !! AXY (01/03/10): set up level depth (bottom of level)
+                  fdep1(ji,jj) = fsdepw(ji,jj,jk) + fse3t(ji,jj,jk)
+                  !!
+                  !! set up model tracers
+                  !! negative values of state variables are not allowed to
+                  !! contribute to the calculated fluxes
+                  !! non-diatom chlorophyll
+                  zchn(ji,jj) = max(0.,trn(ji,jj,jk,jpchn))
+                  !! diatom chlorophyll
+                  zchd(ji,jj) = max(0.,trn(ji,jj,jk,jpchd))
+                  !! non-diatoms
+                  zphn(ji,jj) = max(0.,trn(ji,jj,jk,jpphn))
+                  !! diatoms
+                  zphd(ji,jj) = max(0.,trn(ji,jj,jk,jpphd))
+                  !! diatom silicon
+                  zpds(ji,jj) = max(0.,trn(ji,jj,jk,jppds))
+                  !! AXY (28/01/10): probably need to take account of 
+                  !! chl/biomass connection
+                  if (zchn(ji,jj).eq.0.) zphn(ji,jj) = 0.
+                  if (zchd(ji,jj).eq.0.) zphd(ji,jj) = 0.
+                  if (zphn(ji,jj).eq.0.) zchn(ji,jj) = 0.
+                  if (zphd(ji,jj).eq.0.) zchd(ji,jj) = 0.
+	          !! AXY (23/01/14): duh - why did I forget diatom silicon?
+	          if (zpds(ji,jj).eq.0.) zphd(ji,jj) = 0.
+	          if (zphd(ji,jj).eq.0.) zpds(ji,jj) = 0.
+               ENDIF
+            ENDDO
+         ENDDO
+
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  !! microzooplankton
+                  zzmi(ji,jj) = max(0.,trn(ji,jj,jk,jpzmi))
+                  !! mesozooplankton
+                  zzme(ji,jj) = max(0.,trn(ji,jj,jk,jpzme))
+                  !! detrital nitrogen
+                  zdet(ji,jj) = max(0.,trn(ji,jj,jk,jpdet))
+                  !! dissolved inorganic nitrogen
+                  zdin(ji,jj) = max(0.,trn(ji,jj,jk,jpdin))
+                  !! dissolved silicic acid
+                  zsil(ji,jj) = max(0.,trn(ji,jj,jk,jpsil))
+                  !! dissolved "iron"
+                  zfer(ji,jj) = max(0.,trn(ji,jj,jk,jpfer))
+               ENDIF
+            ENDDO
+         ENDDO
+
+# if defined key_roam
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  !! detrital carbon
+                  zdtc(ji,jj) = max(0.,trn(ji,jj,jk,jpdtc))
+                  !! dissolved inorganic carbon
+                  zdic(ji,jj) = max(0.,trn(ji,jj,jk,jpdic))
+                  !! alkalinity
+                  zalk(ji,jj) = max(0.,trn(ji,jj,jk,jpalk))
+                  !! oxygen
+                  zoxy(ji,jj) = max(0.,trn(ji,jj,jk,jpoxy))
+#  if defined key_axy_carbchem && defined key_mocsy
+                  !! phosphate via DIN and Redfield
+                  zpho(ji,jj) = max(0.,trn(ji,jj,jk,jpdin)) / 16.0
+#  endif
+                  !!
+                  !! also need physical parameters for gas exchange 
+                  !! calculations
+                  ztmp(ji,jj) = tsn(ji,jj,jk,jp_tem)
+                  zsal(ji,jj) = tsn(ji,jj,jk,jp_sal)
+                  !!
+	          !! AXY (28/02/14): check input fields
+                  if (ztmp(ji,jj) .lt. -3.0 .or. ztmp(ji,jj) .gt. 40.0 ) then
+                     IF(lwp) WRITE(numout,*)                                 &
+                        ' trc_bio_medusa: T WARNING 2D, ',                   &
+                        tsb(ji,jj,jk,jp_tem), tsn(ji,jj,jk,jp_tem),          &
+                        ' at (', ji, ',', jj, ',', jk, ') at time', kt
+		     IF(lwp) WRITE(numout,*)                                 &
+                        ' trc_bio_medusa: T SWITCHING 2D, ',                 &
+                        tsn(ji,jj,jk,jp_tem), ' -> ', tsb(ji,jj,jk,jp_tem)
+                     !! temperatur
+                     ztmp(ji,jj) = tsb(ji,jj,jk,jp_tem)
+                  endif
+                  if (zsal(ji,jj) .lt. 0.0 .or. zsal(ji,jj) .gt. 45.0 ) then
+                     IF(lwp) WRITE(numout,*)                                 &
+                        ' trc_bio_medusa: S WARNING 2D, ',                   &
+                        tsb(ji,jj,jk,jp_sal), tsn(ji,jj,jk,jp_sal),          &
+                        ' at (', ji, ',', jj, ',', jk, ') at time', kt
+                  endif
+               ENDIF
+            ENDDO
+         ENDDO
+# else
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  !! implicit detrital carbon
+                  zdtc(ji,jj) = zdet(ji,jj) * xthetad
+               ENDIF
+            ENDDO
+         ENDDO
+# endif
+# if defined key_debug_medusa
+         DO jj = 2,jpjm1
+            DO ji = 2,jpim1
+               if (tmask(ji,jj,jk) == 1) then
+                  if (idf.eq.1) then
+                     !! AXY (15/01/10)
+                     if (trn(ji,jj,jk,jpdin).lt.0.) then
+                        IF (lwp) write (numout,*)                            &
+                           '------------------------------'
+                        IF (lwp) write (numout,*) 'NEGATIVE DIN ERROR =',    &
+                           trn(ji,jj,jk,jpdin)
+                        IF (lwp) write (numout,*) 'NEGATIVE DIN ERROR @',    &
+                           ji, jj, jk, kt
+                     endif
+                     if (trn(ji,jj,jk,jpsil).lt.0.) then
+                        IF (lwp) write (numout,*)                            &
+                           '------------------------------'
+                        IF (lwp) write (numout,*) 'NEGATIVE SIL ERROR =',    &
+                           trn(ji,jj,jk,jpsil)
+                        IF (lwp) write (numout,*) 'NEGATIVE SIL ERROR @',    &
+                           ji, jj, jk, kt
+                     endif
+#  if defined key_roam
+                     if (trn(ji,jj,jk,jpdic).lt.0.) then
+                        IF (lwp) write (numout,*)                            &
+                           '------------------------------'
+                        IF (lwp) write (numout,*) 'NEGATIVE DIC ERROR =',    &
+                           trn(ji,jj,jk,jpdic)
+                        IF (lwp) write (numout,*) 'NEGATIVE DIC ERROR @',    &
+                           ji, jj, jk, kt
+                     endif
+                     if (trn(ji,jj,jk,jpalk).lt.0.) then
+                        IF (lwp) write (numout,*)                            &
+                           '------------------------------'
+                        IF (lwp) write (numout,*) 'NEGATIVE ALK ERROR =',    &
+                           trn(ji,jj,jk,jpalk)
+                        IF (lwp) write (numout,*) 'NEGATIVE ALK ERROR @',    &
+                           ji, jj, jk, kt
+                     endif
+                     if (trn(ji,jj,jk,jpoxy).lt.0.) then
+                        IF (lwp) write (numout,*)                            &
+                           '------------------------------'
+                        IF (lwp) write (numout,*) 'NEGATIVE OXY ERROR =',    &
+                           trn(ji,jj,jk,jpoxy)
+                        IF (lwp) write (numout,*) 'NEGATIVE OXY ERROR @',    &
+                           ji, jj, jk, kt
+                     endif
+#  endif
+                  endif
+               ENDIF
+            ENDDO
+         ENDDO
+# endif
+# if defined key_debug_medusa
+! I'M NOT SURE THIS IS USEFUL NOW THAT I'VE SPLIT THE DO LOOP - marc 8/5/17
+!         if (idf.eq.1.AND.idfval.eq.1) then
+!            DO jj = 2,jpjm1
+!               DO ji = 2,jpim1
+!                  if (tmask(ji,jj,jk) == 1) then
+!                     !! report state variable values
+!                     IF (lwp) write (numout,*)                               &
+!                        '------------------------------'
+!                     IF (lwp) write (numout,*) 'fthk(',jk,') = ',            &
+!                        fse3t(ji,jj,jk)
+!                     IF (lwp) write (numout,*) 'zphn(',jk,') = ', zphn(ji,jj)
+!                     IF (lwp) write (numout,*) 'zphd(',jk,') = ', zphd(ji,jj)
+!                     IF (lwp) write (numout,*) 'zpds(',jk,') = ', zpds(ji,jj)
+!                     IF (lwp) write (numout,*) 'zzmi(',jk,') = ', zzmi(ji,jj)
+!                     IF (lwp) write (numout,*) 'zzme(',jk,') = ', zzme(ji,jj)
+!                     IF (lwp) write (numout,*) 'zdet(',jk,') = ', zdet(ji,jj)
+!                     IF (lwp) write (numout,*) 'zdin(',jk,') = ', zdin(ji,jj)
+!                     IF (lwp) write (numout,*) 'zsil(',jk,') = ', zsil(ji,jj)
+!                     IF (lwp) write (numout,*) 'zfer(',jk,') = ', zfer(ji,jj)
+#  if defined key_roam
+!                     IF (lwp) write (numout,*) 'zdtc(',jk,') = ', zdtc(ji,jj)
+!                     IF (lwp) write (numout,*) 'zdic(',jk,') = ', zdic(ji,jj)
+!                     IF (lwp) write (numout,*) 'zalk(',jk,') = ', zalk(ji,jj)
+!                     IF (lwp) write (numout,*) 'zoxy(',jk,') = ', zoxy(ji,jj)
+#  endif
+!                  ENDIF
+!               ENDDO
+!            ENDDO
+!         endif
+# endif
+
+# if defined key_debug_medusa
+! I'M NOT SURE THIS IS USEFUL NOW THAT I'VE SPLIT THE DO LOOP - marc 8/5/17
+!         if (idf.eq.1.AND.idfval.eq.1.AND.jk.eq.1) then
+!            DO jj = 2,jpjm1
+!               DO ji = 2,jpim1
+!                  if (tmask(ji,jj,jk) == 1) then
+!                     IF (lwp) write (numout,*)                               &
+!                       '------------------------------'
+!                     IF (lwp) write (numout,*) 'dust      = ', dust(ji,jj)
+!                  ENDIF
+!               ENDDO
+!            ENDDO
+!         endif
+# endif
+
+         !!---------------------------------------------------------------
+         !! Calculate air-sea gas exchange and river inputs
+         !!---------------------------------------------------------------
+         IF ( jk == 1 ) THEN
+            CALL air_sea( kt )
+         ENDIF
+
+         !!---------------------------------------------------------------
+         !! Phytoplankton growth, zooplankton grazing and miscellaneous
+         !! plankton losses. 
+         !!---------------------------------------------------------------
+         CALL plankton( jk )
+
+         !!---------------------------------------------------------------
+         !! Iron chemistry and scavenging
+         !!---------------------------------------------------------------
+         CALL iron_chem_scav( jk )
+
+         !!---------------------------------------------------------------
+         !! Detritus processes
+         !!---------------------------------------------------------------
+         CALL detritus( jk, iball )
+
+         !!---------------------------------------------------------------
+         !! Updating tracers
+         !!---------------------------------------------------------------
+         CALL bio_medusa_update( kt, jk )
+
+         !!---------------------------------------------------------------
+         !! Diagnostics
+         !!---------------------------------------------------------------
+         CALL bio_medusa_diag( jk )
+
+         !!-------------------------------------------------------
+         !! 2d specific k level diags
+         !!-------------------------------------------------------
+         IF( lk_iomput ) THEN
+            CALL bio_medusa_diag_slice( jk )
+         ENDIF
+
+      !! CLOSE vertical loop
+      ENDDO
+
+      !!------------------------------------------------------------------
+      !! Final calculations for diagnostics
+      !!------------------------------------------------------------------
+      CALL bio_medusa_fin( kt )
+
+# if defined key_debug_medusa
+       IF(lwp) WRITE(numout,*) ' MEDUSA exiting trc_bio_medusa at kt =', kt
+       CALL flush(numout)
+# endif
+
+   END SUBROUTINE trc_bio_medusa
+
+#else
+   !!=====================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!=====================================================================
+CONTAINS
+   SUBROUTINE trc_bio_medusa( kt )                   ! Empty routine
+      INTEGER, INTENT( in ) ::   kt
+      WRITE(*,*) 'trc_bio_medusa: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_bio_medusa
+#endif 
+
+   !!=====================================================================
+END MODULE  trcbio_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcco2_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcco2_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcco2_medusa.F90	(revision 9987)
@@ -0,0 +1,1136 @@
+MODULE trcco2_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcco2_medusa  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :
+   !!  -   !  2010-12  (A. Yool)             added for ROAM project
+   !!----------------------------------------------------------------------
+#if defined key_medusa && defined key_roam
+   !!----------------------------------------------------------------------
+   !!                                        MEDUSA carbonate chemistry
+   !!----------------------------------------------------------------------
+   !!   trc_co2_medusa        :  
+   !!----------------------------------------------------------------------
+      USE oce_trc
+      USE trc
+      USE sms_medusa
+      USE lbclnk
+      USE prtctl_trc      ! Print control for debugging
+      USE in_out_manager  ! I/O manager
+
+      IMPLICIT NONE
+      PRIVATE
+      
+      PUBLIC   trc_co2_medusa    ! called in trc_bio_medusa
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+! The following is a map of the subroutines contained within this module
+! - trc_co2_medusa
+!      - CALLS CO2_dynamics
+!           - CALLS CO2DYN
+!		 - CALLS POLYCO
+!		      - CALLS CO2SET
+!		      - CALLS CO2CLC
+!           - CALLS CaCO3_Saturation
+!      - CALLS Air_sea_exchange
+
+CONTAINS
+
+!=======================================================================
+!
+      SUBROUTINE trc_co2_medusa( Temp, Sal, DIC, ALK, Depth, xkw, pCO2a, &
+      pH, pCO2w, h2co3, hco3, co3, om_cal, om_arg, co2flux, TDIC, TALK,  &
+      dcf, henry, iters )
+!      
+!=======================================================================
+!  
+! This file contains a set of FORTRAN subroutines that calculate the carbonate system 
+! at any given point in marine space time, given values for 
+! temperature, salinity, DIC, depth (pressure). 
+! This is essentially an implimentation of the Haltafall speciation code
+! (Ingri et al 1967, Talanta 14, 1261 - if it ain't broke don't fix it)
+! Another routine calulates the air sea exchange of CO2 given wind speed and atmospheric pCO2.
+! Code developed by Jerry blackford and others at PML, based on pre-existing code.
+! We accept no liability for errors or inaccuracies.
+! See Zeebe & Wolf-Gladrow, 2001. CO2 in seawater: equilibrium, kinetics and isotopes. 
+! Elsevier Oceanography Series 65, 346. for a reasonable overview. 
+! Many other packages exist, replicating the same functionality in different languages.
+! See http://cdiac.ornl.gov/oceans/co2rprt.html (CO2sys)
+! or  http://neon.otago.ac.nz/research/mfc/people/keith_hunter/software/swco2/
+! reference for prior usage of this code: Blackford & Gilbert, 2007. J Mar Sys 64, 229-241.
+! 
+! Modifications
+! 17/02/2010. Added conversion factor from per m3 to per kg (line 108-133)
+! 17/02/2010. Update calculation of K1, K2, Kb to make consistant with the OCMIP protocols.
+! 29/07/2011. Merged into MEDUSA with a raft of changes to this subroutine; less elsewhere
+! 23/06/2015. Modified to take gas transfer velocity as an input (rather than wind speed); 
+!             alter CO2 flux to /s rather than /d for consistency with other schemes
+!
+! Changes for MEDUSA include: 
+!     - making the program a module
+!     - passing in input variables (obvious given the last point)
+!     - making alkalinity a state variable (rather than a function of salinity)
+!
+      IMPLICIT NONE
+
+      REAL(wp), INTENT( in )    :: Temp       ! degrees C
+      REAL(wp), INTENT( in )    :: Sal        ! PSU
+      REAL(wp), INTENT( in )    :: DIC        ! mmol / m3
+      REAL(wp), INTENT( in )    :: ALK        ! meq  / m3
+      REAL(wp), INTENT( in )    :: Depth      ! m
+!     REAL(wp), INTENT( in )    :: Wnd        ! m / s
+      REAL(wp), INTENT( in )    :: xkw        ! m / s
+      REAL(wp), INTENT( in )    :: pCO2a      ! uatm
+!----------------------------------------------------------------------
+      REAL(wp), INTENT( inout ) :: pH         ! "normal" pH units
+      REAL(wp), INTENT( inout ) :: pCO2w      ! uatm
+      REAL(wp), INTENT( inout ) :: h2co3      ! mmol / m3
+      REAL(wp), INTENT( inout ) :: hco3       ! mmol / m3
+      REAL(wp), INTENT( inout ) :: co3        ! mmol / m3
+      REAL(wp), INTENT( inout ) :: om_cal     ! normalised
+      REAL(wp), INTENT( inout ) :: om_arg     ! normalised
+      REAL(wp), INTENT( inout ) :: co2flux    ! mmol / m2 / s
+      REAL(wp), INTENT( inout ) :: TDIC       ! umol / kg
+      REAL(wp), INTENT( inout ) :: TALK       ! ueq  / kg
+      REAL(wp), INTENT( inout ) :: dcf        ! m3 / kg
+      REAL(wp), INTENT( inout ) :: henry      ! ?
+      INTEGER,  INTENT( inout ) :: iters      ! # iterations to convergence
+!----------------------------------------------------------------------
+!     REAL(wp) :: cco2,bicarb,carb,henry
+      REAL(wp) :: cco2,bicarb,carb
+! ======================================================================
+
+! write inputs to screen
+!  WRITE(*,*) " "
+!  WRITE(*,'(A28)')       "    .........Inputs........."
+!  WRITE(*,'(A24,F10.3)') "    Temperature   (C) = ", Temp
+!  WRITE(*,'(A24,F10.3)') "    Salinity    (psu) = ", Sal
+!  WRITE(*,'(A24,F10.3)') "    Depth         (m) = ", Depth
+!  WRITE(*,'(A24,F10.3)') "    DIC     (mmol/m3) = ", DIC
+!  WRITE(*,'(A24,F10.3)') "    ALK      (ueq/m3) = ", ALK
+!  WRITE(*,'(A24,F10.3)') "    Wind speed  (m/s) = ", Wnd
+!  WRITE(*,'(A24,F10.3)') "    pCO2 atmos (uatm) = ", pCO2a
+
+! AXY (07/05/13) ==================================================
+! set total number of iterations to zero
+      iters = 0
+! AXY (07/05/13) ==================================================
+  
+   call CO2_dynamics( Temp, Sal, Depth, DIC, ALK, pCO2a, &                  ! inputs
+      pco2w, ph, h2co3, hco3, co3, henry, om_cal, om_arg, TDIC, TALK, &     ! outputs
+      dcf, iters)                                                           ! outputs
+
+   ! AXY (18/08/11): only do air-sea exchange calculation if depth = 0 
+   !                 (i.e. surface calculations being performed)
+   if (Depth .eq. 0.0) then
+      call Air_sea_exchange( Temp, xkw, pCO2w, pCO2a, henry, dcf, &         ! inputs
+         co2flux )                                                          ! output
+   else
+      co2flux = 0.0
+   endif      
+
+! AXY (09/01/14) ==================================================
+! check for non-convergence and NaNs
+   !!
+   if (iters .eq. 25) then
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: ITERS WARNING, ', &
+      iters, ' AT depth =', Depth
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: ztmp    =', Temp
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: zsal    =', Sal
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: zdic    =', DIC
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: zalk    =', ALK
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: f_kw660 =', xkw
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: f_ph    =', ph
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: f_pco2w =', pCO2w
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: f_h2co3 =', h2co3
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: f_hco3  =', hco3
+      IF(lwp) WRITE(numout,*) ' trc_co2_medusa: f_co3   =', co3
+   endif
+   !!
+   !! AXY (29/10/13): NaN checks
+   if (co2flux /= co2flux) then
+      !! if (lwp) write (numout,'(a,1pe10.2,4i6)') 'CO2FLUX-NAN', &
+      !! &        tmask(ji,jj,jk), kt, ji, jj, jk
+      if (lwp) write (numout,'(a,a,f10.3,a,f10.3)') 'CO2FLUX-NAN', &
+      &        ' TMP', Temp, ' SAL', Sal
+      if (lwp) write (numout,'(a,a,f10.3,a,f10.3)') 'CO2FLUX-NAN', &
+      &        ' DIC', DIC, ' ALK', ALK
+      if (lwp) write (numout,'(a,a,f10.3,a,f10.3)') 'CO2FLUX-NAN', &
+      &        ' XKW', xkw, ' PH ', ph
+      if (lwp) write (numout,'(a,a,i6)') 'CO2FLUX-NAN', &
+      &        ' ITERS', iters
+   endif
+   !!
+   !! AXY (09/01/14): NaN fudges
+   if (co2flux /= co2flux) then
+      ph      = 8.1
+      pCO2w   = pCO2a
+      h2co3   = 0.005 * DIC
+      hco3    = 0.865 * DIC
+      co3     = 0.130 * DIC
+      om_cal  = 4.
+      om_arg  = 2.
+      co2flux = 0.
+      TDIC    = DIC
+      TALK    = ALK
+      dcf     = 1.
+      henry   = 1.
+   endif
+! AXY (09/01/14) ==================================================
+
+! write outputs to screen
+!  WRITE(*,*) " "
+!  WRITE(*,'(A32,F10.3)') "    ..........Outputs..........."
+!  WRITE(*,'(A27,F10.3)') "    pH                 (pH) = ", pH
+!  WRITE(*,'(A27,F10.3)') "    DIC           (umol/kg) = ", TDIC
+!  WRITE(*,'(A27,F10.3)') "    TALK           (ueq/kg) = ", TALK
+!  WRITE(*,'(A27,F10.3)') "    pco2w            (uatm) = ", pco2w
+!  WRITE(*,'(A27,F10.3)') "    carbonic acid (mmol/m3) = ", h2co3
+!  WRITE(*,'(A27,F10.3)') "    bicarbonate   (mmol/m3) = ", bicarb
+!  WRITE(*,'(A27,F10.3)') "    carbonate     (mmol/m3) = ", carb
+!  WRITE(*,'(A27,F10.3)') "    Omega calcite       (~) = ", om_cal
+!  WRITE(*,'(A27,F10.3)') "    Omega aragonite     (~) = ", om_arg
+!  WRITE(*,'(A27,F10.3)') "    air sea flux(mmol/m2/s) = ", flux
+!  WRITE(*,*) " "
+
+   END SUBROUTINE trc_co2_medusa
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      subroutine CO2_dynamics( T, S, Z, DIC, TALK, pco2a, &
+      pco2w, ph, h2co3, bicarb, carb, henry, om_cal, om_arg, TCO2, TA, &
+      dcf, iters )
+!      
+!=======================================================================
+!  
+   IMPLICIT NONE
+
+      REAL(wp), INTENT( in )    :: T          ! temperature (C)
+      REAL(wp), INTENT( in )    :: S          ! salinity (psu)
+      REAL(wp), INTENT( in )    :: Z          ! depth (metres)
+      REAL(wp), INTENT( in )    :: DIC        ! total dissolved inorganic carbon (mmol.m-3)
+      REAL(wp), INTENT( in )    :: TALK       ! total alkalinity (meq.m-3)
+      REAL(wp), INTENT( in )    :: pco2a      ! atmospheric pCO2
+!----------------------------------------------------------------------
+      REAL(wp), INTENT( inout ) :: pco2w      ! seawater pCO2
+      REAL(wp), INTENT( inout ) :: ph         ! seawater pH
+      REAL(wp), INTENT( inout ) :: h2co3      ! seawater carbonic acid (H2CO3)
+      REAL(wp), INTENT( inout ) :: bicarb     ! seawater bicarbonate ion (HCO3)
+      REAL(wp), INTENT( inout ) :: carb       ! seawater carbonate ion (CO3)
+      REAL(wp), INTENT( inout ) :: henry      ! Henry constant
+      REAL(wp), INTENT( inout ) :: om_cal     ! Omega calcite
+      REAL(wp), INTENT( inout ) :: om_arg     ! Omega aragonite
+      REAL(wp), INTENT( inout ) :: TCO2       ! total dissolved inorganic carbon (mol.kg-1)
+      REAL(wp), INTENT( inout ) :: TA         ! total alkalinity (eq.kg-1)
+      REAL(wp), INTENT( inout ) :: dcf        ! density conversion factor
+      INTEGER,  INTENT( inout ) :: iters      ! # iterations to convergence
+!----------------------------------------------------------------------
+      REAL(wp) :: a, b, c
+      REAL(wp) :: ca, bc, cb
+      REAL(wp) :: pco2water, fairco2
+
+! ======================================================================
+
+! Adjust to correct units.
+! Haltafall uses mol/kg rather than umol/kg necessitating a scaling factor of /1.0D6
+! DIC (mmol/m3) needs to be converted to umol/kg via the calculation of water density at prevailing T&S
+! sea-water density (Millero & Poisson, Deep-Sea Research, 1981, also known as UNESCO, 1981)
+! with T: Temperature in degree Celsius; S: Salinity in practical units, density in kg/m3
+! valid for 0<T<40 and 0.5<S<43. Density Conversion factor (dcf) = * density * 1.0D3
+
+          a   =  8.24493d-1 - 4.0899d-3*T +  7.6438d-5*T**2 - 8.2467d-7*T**3 + 5.3875d-9*T**4
+          b   = -5.72466d-3 + 1.0227d-4*T - 1.6546d-6*T**2 
+          c   = 4.8314d-4
+          dcf = (999.842594 + 6.793952d-2*T- 9.095290d-3*T**2 + 1.001685d-4*T**3 &
+                - 1.120083d-6*T**4 + 6.536332d-9*T**5+a*S+b*S**1.5+c*S**2)/1.0D3
+
+          TA    = TALK / (1.0D6*dcf)
+          TCO2  = DIC  / (1.0D6*dcf)
+
+! Call the parent routine for the carbonate system
+          CALL CO2DYN ( TCO2, TA, T, S, pco2a, &     ! inputs
+          pco2water, pH, HENRY, ca, bc, cb, iters )  ! outputs
+
+! Adjust outputs back to units used in the parent model code (e.g. mmol/m3) if appropriate
+
+          pco2w  = pco2water * (1.0D6) 	! partial pressure of co2 in water 
+          TA     = TA * (1.0D6)         ! total alkalinity (umol/kg)
+          h2co3  = ca * (1.0D6*dcf)     ! carbonic acid concentration (mmol/m3)
+          bicarb = bc * (1.0D6*dcf)     ! bicarbonate ion concentration (mmol/m3)
+          carb   = cb * (1.0D6*dcf)     ! carbonate ion concentration (mmol/m3)
+          TCO2   = TCO2 * (1.0D6)       ! total C or DIC in units of umol/kg
+
+! Call carbonate saturation state subroutine to calculate calcite and aragonite calcification states
+
+          CALL CaCO3_Saturation ( T, S, Z, cb, &  ! inputs
+          om_cal, om_arg )                        ! outputs
+
+   RETURN
+
+   END SUBROUTINE CO2_dynamics
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      SUBROUTINE Air_sea_exchange( T, xkw, pco2w, pco2a, henry, dcf, &
+      flux )
+!      
+!=======================================================================
+!  
+!  This routine should be called for the surface box only (like, duh)
+!  Uses the Nightingale and Liss parameterisation (GBC 14, 373-388 (2000).
+!  SC is the Schmidt number from Wanninkhof (1992, JGR 97,7373-7382), the Nightingale et al (2000)
+!  transfer velocity being for Sc=600 and the dependence of tranfer velocity on Sc coming 
+!  from Jahne et al (1987, J. Geophys Res 92, 1937-1949).
+
+!  Inputs
+!  pCO2w    partial pressure of CO2 in the water (from carbonate system subroutine call)
+!  pCO2a    partial pressure of CO2 in the atmosphere (usually external forcing).
+!  T        temperature (C)
+!  Wnd      wind speed, metres (DELETED)
+!  xkw      gas transfer velocity
+!  Henry    henry's constant
+!  density  the density of water for conversion between mmol/m3 and umol/kg
+
+!  Outputs are
+!  flux     flux of CO2 in mmol C /m2/d 
+!           +ve is in-gassing (air to sea), -ve is outgassing (sea to air).
+
+   IMPLICIT NONE
+
+      REAL(wp), INTENT( in )    :: T, xkw, pco2w, pco2a, henry, dcf ! INPUT PARAMETERS:
+!-----------------------------------------------------------------------
+      REAL(wp), INTENT( inout ) :: flux                             ! OUTPUT Variables
+!-----------------------------------------------------------------------
+      REAL(wp)                  :: sc, fwind                        ! LOCAL VARIABLES:
+
+! calculate the Schmidt number and unit conversions
+          sc    = 2073.1-125.62*T+3.6276*T**2.0-0.0432190*T**3.0
+!         fwind = (0.222d0 * wnd**2d0 + 0.333d0 * wnd)*(sc/660.d0)**(-0.5)
+          fwind = xkw * (sc/660.d0)**(-0.5)
+          fwind = fwind*24.d0/100.d0   ! convert to m/day
+
+! flux depends on the difference in partial pressures, wind and henry
+! here it is rescaled to mmol/m2/d
+          flux = fwind * henry * ( pco2a - pco2w ) * dcf
+
+! AXY (23/06/15): let's get it from /d to /s
+          flux = flux / ( 86400. )
+
+  RETURN 
+
+  END SUBROUTINE Air_sea_exchange
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      SUBROUTINE CO2dyn ( TCO2, TA, T, S, PCO2A, PCO2, PH, HENRY, ca, bc, cb, iters )
+!      
+!=======================================================================
+!
+!     This subroutine acts as an interface to the Haltafall iteration, setting options etc.
+
+      REAL(wp), INTENT( in )    :: TCO2, TA, T, S, PCO2A
+!-----------------------------------------------------------------------
+      REAL(wp), INTENT( inout ) :: PCO2, PH, HENRY, ca, bc, cb
+      INTEGER,  INTENT( inout ) :: iters
+!-----------------------------------------------------------------------
+      REAL(wp) :: PRSS
+      INTEGER  :: MCONC, MKVAL, ICONST, ICALC
+
+      PARAMETER ( MCONC = 9,MKVAL = 4 )
+
+      REAL(wp), DIMENSION(MKVAL) :: AKVAL
+      REAL(wp), DIMENSION(MCONC) :: CONCS
+
+      ICONST = 6
+      PRSS = 1.0D0
+      CONCS(1) = TCO2
+      CONCS(2) = TA
+      ICALC = 1
+      
+      CALL POLYCO(PRSS,T,S,CONCS,MCONC,AKVAL,MKVAL,ICALC,ICONST,iters)
+
+      if(iters.eq.25) then
+         ! AXY (13/05/13): this location has failed to converge; use
+         !                 some standard values to plug the hole
+         CONCS(3) = PCO2A * 1E-06 ! atmospheric value
+         CONCS(4) = 8.1           ! global average pH
+         CONCS(5) = TCO2 * 0.005  ! some "standard" values plucked
+         CONCS(6) = TCO2 * 0.865  ! from pages 5-6 of Zeebe & Wolf-
+         CONCS(7) = TCO2 * 0.130  ! Gladow (2001)
+         AKVAL(1) = 0.5E-01       ! trial-and-error value
+         IF(lwp) THEN
+            WRITE(numout,*) ' CO2DYN : reset failed outputs'
+         ENDIF
+      endif
+
+      PCO2  = CONCS(3)
+      PH    = CONCS(4)
+      ca    = CONCS(5)
+      bc    = CONCS(6)
+      cb    = CONCS(7)
+      HENRY = AKVAL(1)
+    
+      RETURN
+
+      END SUBROUTINE
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      SUBROUTINE POLYCO(PD,TD,SD,CONCS,NCONC,AKVAL,NKVAL,ICALC,ICONST,iters)
+!      
+!=======================================================================
+!
+! MASTER SUBROUTINE FOR CALCULATION OF THE CO2 SYSTEM THERMODYNAMICS
+!
+! EXPLANATION OF POLYCO PARAMETERS
+!       AXY (16/08/11): Yuri change for non-surface carbonate chemistry 
+!       P - PRESSURE IN ATMOSPHERES (P<>1 CODED only for ICONST=3 and ICONST=6)
+!       T - TEMPERATURE IN DEG.C
+!       S - SALINITY IN PPT
+!      CONCS(1) - TOTAL C (MOL/KG)
+!      CONCS(2) - TOTAL ALKALINITY (MOL/KG)
+!      CONCS(3) - PCO2 (ATM)
+!      CONCS(4) - PH
+!      CONCS(5) - {H2CO3} (MOL/KG)
+!      CONCS(6) - {HCO3} (MOL/KG)
+!      CONCS(7) - {CO3} (MOL/KG)
+!        CONCS(8) - CARBONATE ALKALINITY  ) FOR ICONST = 4,5,6
+!        CONCS(9) - BORATE ALKALINITY     )       ONLY
+!         NCONC - SIZE OF CONCS ARRAY (7 FOR ICONST=1,2,3; 9 FOR ICONST
+!     AKVAL(1) - KP (HENRY'S LAW CONSTANT) (MOL/KG/ATM)
+!     AKVAL(2) - K1C (H2CO3 DISSOCIATION) (MOL/KG)
+!       AKVAL(3) - K2C (HCO3 DISSOCIATION) (MOL/KG)
+!       AKVAL(4) - KB (B(OH)3 DISSOCIATION) (MOL/KG)  FOR ICONST=4,5,6
+!        NKVAL - SIZE OF AKVAL ARRAY (3 FOR ICONST=1,2,3; 4 FOR ICONST=
+!        ICALC - SELECTION OF THE TWO INPUT PARAMETERS:
+!       ICALC = 1  TOTAL C AND ALKALINITY
+!       ICALC = 2  TOTAL C AND PCO2
+!       ICALC = 3  TOTAL C AND PH
+!       ICALC = 4  ALKALINITY AND PCO2
+!       ICALC = 5  ALKALINITY AND PH
+!       ICALC = 6  PCO2 AND PH
+!       ICALC = 7  CALCULATE CONSTANTS AKVAL ONLY
+!       ICONST - SELECTION OF PH SCALE AND COMPONENTS:
+!       ICONST = 1  NBS PH SCALE
+!       ICONST = 2  HANSSON'S SCALE (SWS WITHOUT FLUORIDE)
+!       ICONST = 3  SWS PH SCALE
+!       ICONST = 4  AS 1 BUT INCLUDING BORATE IN THE CALCULATION
+!       ICONST = 5  AS 2 BUT INCLUDING BORATE IN THE CALCULATION
+!       ICONST = 6  AS 3 BUT INCLUDING BORATE IN THE CALCULATION
+
+!  NOTE: FOR ICONST=1,2,3 CONCS(2) REPRESENTS CARBONATE ALKALINITY SINC
+!        BORATE IS NOT INCLUDED IN THE CALCULATION. FOR ICONST=4,5,6 CO
+!        REPRESENTS TOTAL ALKALINITY (CARBONATE + BORATE), THE COMPONEN
+!        WHICH ARE GIVEN IN CONCS(8) AND CONCS(9)
+
+      REAL(wp) :: PMIN, PMAX, SMIN, SMAX, TMIN, TMAX, & 
+     &     PD, TD, SD, P, T, S, BTOT
+      INTEGER  :: MINJC, MAXJC, MINJK, MAXJK, MINCAL, MAXCAL, MINCON,  &
+     &     MAXCON, NCONC, NKVAL, ICALC, ICONST, IC, iters
+      LOGICAL  :: BORON
+
+      PARAMETER(MINJC=7,MAXJC=9,MINJK=3,MAXJK=4)
+      PARAMETER(MINCAL=1,MAXCAL=7,MINCON=1,MAXCON=6)
+      !! AXY (11/08/11): TMIN changed to -2 to stop error messages in polar regions
+      !! AXY (09/01/14): TMIN changed to -3 to stop error messages in polar regions
+      !! AXY (03/03/14): SMAX changed to 42 to stop error messages in salty regions (the Great Answer ...)
+      !! AXY (05/03/14): SMAX changed to 45 to stop error messages in salty regions
+      PARAMETER(PMIN=0.99999D0,PMAX=1.00001D0,SMIN=0.0D0,  &
+     &  SMAX=45.0D0,TMIN=-3.0D0,TMAX=40.0D0)
+      REAL(wp), DIMENSION(NKVAL) :: AKVAL
+      REAL(wp), DIMENSION(NCONC) :: CONCS
+
+      P = PD
+      S = SD
+      T = TD
+      
+      !! AXY (09/08/11): STOP statements commented out and WARNING messages added
+      IF(lwp) THEN
+         IF(T.LT.TMIN.OR.T.GT.TMAX) WRITE(numout,*) ' trc_co2_medusa: T WARNING, ', T, TMIN, TMAX, S, P
+         IF(S.LT.SMIN.OR.S.GT.SMAX) WRITE(numout,*) ' trc_co2_medusa: S WARNING, ', S, SMIN, SMAX, T, P
+         IF(P.LT.PMIN.OR.P.GT.PMAX) WRITE(numout,*) ' trc_co2_medusa: P WARNING, ', P, PMIN, PMAX, T, S
+      ENDIF
+      ! IF(T.LT.TMIN.OR.T.GT.TMAX)WRITE (*,*) P, S, T, TMIN, TMAX
+      ! IF(P.LT.PMIN.OR.P.GT.PMAX) STOP'POLYCO - PRESSURE OUT OF RANGE'
+      ! IF(S.LT.SMIN.OR.S.GT.SMAX) STOP'POLYCO - SALINITY OUT OF RANGE'
+      ! IF(T.LT.TMIN.OR.T.GT.TMAX) STOP'POLYCO - TEMP. OUT OF RANGE'
+
+      !! AXY (17/04/13): iMARNET climate change simulation appears to be compromised
+      !!                 by excessive Caspian Sea salinity (> 45 PSU); this may be
+      !!                 a runoff glitch that doesn't manifest on local instance of
+      !!                 NEMO; fudging this here by replacing excessively high
+      !!                 salinity values with maximum salinity value for the purpose
+      !!                 of carbonate chemistry calculations; if this works, a more
+      !!                 sensible solution might be to kill Caspian, etc.
+      IF(lwp) THEN
+         IF(S.LT.SMIN) THEN
+            WRITE(numout,*) ' trc_co2_medusa: S RESET, ', S, '->', SMIN
+            S = SMIN
+         ENDIF
+         IF(S.GT.SMAX) THEN
+            WRITE(numout,*) ' trc_co2_medusa: S RESET, ', S, '->', SMAX
+            S = SMAX
+         ENDIF
+      ENDIF
+      
+      !! AXY (28/02/13): as above, but for T; this has been done for 1/4-degree
+      !!                 simulations to provide a temporary fix to a strange
+      !!                 glitch in ocean temperature; basically, T has been found
+      !!                 to spike upwards arbitrarily (e.g. 24C -> 53C); this 
+      !!                 causes the carbonate chemistry calculations to fail;
+      !!                 this fix aims to stop the problem so that we can estimate
+      !!                 how frequent a problem this is; it's suggestive of a
+      !!                 memory leak
+      IF(lwp) THEN
+         IF(T.LT.TMIN) THEN
+            WRITE(numout,*) ' trc_co2_medusa: T RESET, ', T, '->', TMIN
+            T = TMIN
+         ENDIF
+         IF(T.GT.TMAX) THEN
+            WRITE(numout,*) ' trc_co2_medusa: T RESET, ', T, '->', TMAX
+            T = TMAX
+         ENDIF
+      ENDIF
+     
+      IF(ICALC.LT.MINCAL.OR.ICALC.GT.MAXCAL) STOP 'POLYCO - ICALC OUT OR RANGE'
+      IF(ICONST.LT.MINCON.OR.ICONST.GT.MAXCON) STOP 'POLYCO - ICONST OUT OF RANGE'
+      BORON=(ICONST.GT.3)
+      IF(BORON) THEN
+        IC=ICONST-3
+        BTOT=0.0004128D0*S/35.0D0
+        IF(NCONC.NE.MAXJC) STOP 'POLYCO - WRONG NCONC VALUE'
+        IF(NKVAL.NE.MAXJK) STOP 'POLYCO - WRONG NKVAL VALUE'
+      ELSE
+        IC=ICONST
+        IF(NCONC.NE.MINJC) STOP 'POLYCO - WRONG NCONC VALUE'
+        IF(NKVAL.NE.MINJK) STOP 'POLYCO - WRONG NKVAL VALUE'
+      ENDIF
+
+      CALL CO2SET(P,T,S,AKVAL,NKVAL,IC)
+
+      IF(ICALC.LT.MAXCAL)  &
+     & CALL CO2CLC(CONCS,NCONC,AKVAL,NKVAL,ICALC,BORON,BTOT,iters)
+
+      RETURN
+
+      END SUBROUTINE
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      SUBROUTINE CO2SET(P,T,S,AKVAL,NKVAL,IC)
+!      
+!=======================================================================
+!
+! Routine to calculate CO2 system constants under the conditions set by
+! P,S,T     (NOTE: PRESSURE <> 1ATM IS NOT YET CODED)
+
+! I. Calculate constants at P=1 and S=0 using
+
+!      ln K0  =  A + B/TK + C ln TK
+!                                   (where TK is in Kelvin)
+
+! II. Calculate constants at P=1 and salinity S using
+
+!    ln K  =  ln K0 + (a0 + a1/TK + a2 ln TK) S**1/2
+!                 + (b0 + b1TK + b2TK**2) S
+
+! The sources of the coefficients are as follows:
+
+!  IC=                  1                    2                  3
+!               (NBS pH scale)        (SWS pH scale       (SWS pH scale
+!                                       with no F)
+
+!  KP            WEISS (1974)           WEISS(1974)          WEISS(1974
+
+!  K1C )      MEHRBACH ACC. TO       HANSSON ACC. TO    HANSSON AND MEH
+!  K2C )       MILLERO (1979)         MILLERO (1979)      ACC. TO DICKS
+!   KB )                                                 AND MILLERO (1
+!                                                         (K1C AND K2C
+!                                                           HANSSON ACC
+!                                                            MILLERO (1
+!                                                              (KB ONLY
+
+! ***
+!      IMPLICIT real*8 (A-H,O-Z)
+
+!     Modified by jcb 17/02/10 to use OCMIP calculations of K1, K2, Kb. 
+!     Differences are subtle rather than significant
+
+      INTEGER             :: MAXK, MAXCON, NKVAL, ICON, IC, IK
+! ***
+      PARAMETER(MAXK=4,MAXCON=3)
+      REAL(wp), DIMENSION(MAXK)        :: A, B, C
+      REAL(wp), DIMENSION(MAXK,MAXCON) :: A0, A1, A2
+      REAL(wp), DIMENSION(MAXK,MAXCON) :: B0, B1, B2
+      REAL(wp), DIMENSION(NKVAL)       :: AKVAL
+!     AXY (16/08/11): Yuri change for non-surface carbonate chemistry 
+!     REAL(wp)            :: P,T,S,VAL,TK
+      REAL(wp)            :: P,T,S,VAL,TK, delta, kappa, Rgas
+      REAL(wp)            :: dlogTK, S2, sqrtS, S15, k1, k2, kb
+! ***
+!     AXY (16/08/11): Yuri change for non-surface carbonate chemistry 
+      DATA Rgas/83.131/
+
+      DATA A/-167.8108D0, 290.9097D0, 207.6548D0, 148.0248D0/
+      DATA B/9345.17D0, -14554.21D0, -11843.79D0, -8966.9D0/
+      DATA C/23.3585D0, -45.0575D0, -33.6485D0, -24.4344D0/
+      DATA (A0(1,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (A0(2,ICON),ICON=1,MAXCON) /0.0221D0, 0.5709D0, -45.8076D0/
+      DATA (A0(3,ICON),ICON=1,MAXCON) /0.9805D0, 1.4853D0, -39.5492D0/
+      DATA (A0(4,ICON),ICON=1,MAXCON) /0.0473D0, 0.5998D0, 0.5998D0/
+      DATA (A1(1,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (A1(2,ICON),ICON=1,MAXCON) /34.02D0, -84.25D0, 1935.07D0/
+      DATA (A1(3,ICON),ICON=1,MAXCON) /-92.65D0, -192.69D0, 1590.14D0/
+      DATA (A1(4,ICON),ICON=1,MAXCON) /49.10D0, -75.25D0, -75.25D0/
+      DATA (A2(1,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (A2(2,ICON),ICON=1,MAXCON) /2*0.0D0,6.9513D0/
+      DATA (A2(3,ICON),ICON=1,MAXCON) /2*0.0D0,6.1523D0/
+      DATA (A2(4,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (B0(1,ICON),ICON=1,MAXCON) /3*0.023517D0/
+      DATA (B0(2,ICON),ICON=1,MAXCON) /0.0D0,-0.01632D0,-0.01566D0/
+      DATA (B0(3,ICON),ICON=1,MAXCON) /-0.03294D0,-0.05058D0,-0.04997D0/
+      DATA (B0(4,ICON),ICON=1,MAXCON) /0.0D0, -0.01767D0, -0.01767D0/
+      DATA (B1(1,ICON),ICON=1,MAXCON) /3*-2.3656D-4/
+      DATA (B1(2,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (B1(3,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (B1(4,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (B2(1,ICON),ICON=1,MAXCON) /3*4.7036D-7/
+      DATA (B2(2,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (B2(3,ICON),ICON=1,MAXCON) /3*0.0D0/
+      DATA (B2(4,ICON),ICON=1,MAXCON) /3*0.0D0/
+
+      TK=T+273.15D0
+      DO 100 IK=1,NKVAL
+        VAL=A(IK) + B(IK)/TK + C(IK)*LOG(TK)
+        VAL=VAL + (A0(IK,IC) + A1(IK,IC)/TK + A2(IK,IC)*LOG(TK))*SQRT(S)
+        VAL=VAL + (B0(IK,IC) + B1(IK,IC)*TK + B2(IK,IC)*TK*TK)*S
+        AKVAL(IK)=EXP(VAL)
+100    CONTINUE
+
+      IF (IC .EQ. 3) THEN
+!  Calculation of constants as used in the OCMIP process for ICONST = 3 or 6
+!  see http://www.ipsl.jussieu.fr/OCMIP/
+!  added jcb 17/02/10
+
+!  Derive simple terms used more than once
+	dlogTK = log(TK)
+	S2 = S*S
+	sqrtS = sqrt(S)
+	S15 = S**1.5
+! k1 = [H][HCO3]/[H2CO3]
+! k2 = [H][CO3]/[HCO3]
+! Millero p.664 (1995) using Mehrbach et al. data on seawater scale 
+	k1=10**(-1*(3670.7/TK - 62.008 + 9.7944*dlogTK - &
+     &		0.0118 * S + 0.000116*S2))
+	k2=10**(-1*(1394.7/TK + 4.777 - &
+     &		0.0184*S + 0.000118*S2))
+! AXY (16/08/11): Yuri change for non-surface carbonate chemistry 
+! Correction for high pressure (from Millero 1995)
+! added YA 04/10/2010
+        delta=-25.5+0.1271*T
+        kappa=(-3.08+0.0877*T)/1000.0
+        k1=k1*exp((-delta+0.5*kappa*P)*P/(Rgas*TK))
+        delta=-15.82-0.0219*T
+        kappa=(1.13-0.1475*T)/1000.0
+        k2=k2*exp((-delta+0.5*kappa*P)*P/(Rgas*TK))
+
+! kb = [H][BO2]/[HBO2]
+! Millero p.669 (1995) using data from Dickson (1990)
+	kb=exp((-8966.90 - 2890.53*sqrtS - 77.942*S + &
+     &		1.728*S15 - 0.0996*S2)/TK + &
+     &		(148.0248 + 137.1942*sqrtS + 1.62142*S) + &
+     &		(-24.4344 - 25.085*sqrtS - 0.2474*S) * &
+     &		dlogTK + 0.053105*sqrtS*TK)
+! AXY (16/08/11): Yuri change for non-surface carbonate chemistry 
+! Correction for high pressure (from Millero, 1995)
+! added YA 04/10/2010
+        delta=-29.48+0.1622*T-0.002608*T**2.0
+        kappa=-2.84/1000.0
+        kb=kb*exp((-delta+0.5*kappa*P)*P/(Rgas*TK))
+! Correction for high pressure of Kw (from Millero 1995)
+! added YA 04/10/2010
+        delta=-25.60+0.2324*T-0.0036246*T**2
+        kappa=(-5.13+0.0794*T)/1000.0
+        AKVAL(1)=AKVAL(1)*exp((-delta+0.5*kappa*P)*P/(Rgas*TK))
+
+! replace haltafall calculations with OCMIP calculations
+      AKVAL(2) = k1
+      AKVAL(3) = k2
+      AKVAL(4) = kb
+      END IF ! section implimenting OCMIP coefficients
+
+      RETURN
+      END SUBROUTINE
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      SUBROUTINE CO2CLC(CONCS,NCONC,AKVAL,NKVAL,ICALC,BORON,BTOT,iters)
+!      
+!=======================================================================
+! 
+! ROUTINE TO CARRY OUT CO2 CALCULATIONS WITH 2 FIXED PARAMETERS ACCORDI
+! THE EQUATIONS GIVEN BY PARKS(1969) AND SKIRROW (1975)
+! WITH ADDITIONS FOR INCLUDING BORON IF BORON=.TRUE.
+
+
+!      IMPLICIT real*8 (A-H,O-Z)
+      INTEGER             :: NCONC, NKVAL, ICALC, II, KARL, LQ, iters
+! AXY (07/05/13) ==================================================
+! put counter in to check duration in convergence loop
+      INTEGER             :: COUNTER,C_CHECK,C_SW,III
+! AXY (07/05/13) ==================================================
+      REAL(wp)            :: CTOT,ALK,PCO2,PH,H2CO3,HCO3,CO3,ALKC
+      REAL(wp)            :: ALKB,AKP,AK1C,AK2C,AKB,BTOT
+      REAL(wp)            :: AKR,AHPLUS
+      REAL(wp)            :: PROD,tol1,tol2,tol3,tol4,steg,fak
+      REAL(wp)            :: STEGBY,Y,X,W,X1,Y1,X2,Y2,FACTOR,TERM,Z
+      REAL(wp), DIMENSION(NCONC) :: CONCS
+      REAL(wp), DIMENSION(NKVAL) :: AKVAL
+      REAL(wp), DIMENSION(9)     :: CONCS2
+      REAL(wp), DIMENSION(4)     :: AKVAL2
+
+! AXY (07/05/13) ==================================================
+! setup array to store old values of concs
+      real(wp),DIMENSION(:) :: old_CONCS(NCONC)
+! AXY (07/05/13) ==================================================
+
+      EQUIVALENCE (CTOT  , CONCS2(1)), (ALK   , CONCS2(2)),  &
+     &            (PCO2  , CONCS2(3)), (PH    , CONCS2(4)),  &
+     &            (H2CO3 , CONCS2(5)), (HCO3  , CONCS2(6)),  &
+     &            (CO3   , CONCS2(7)), (ALKC  , CONCS2(8)),  &
+     &            (ALKB  , CONCS2(9)),                       &
+     &            (AKP   , AKVAL2(1)), (AK1C  , AKVAL2(2)),  &
+     &            (AK2C  , AKVAL2(3)), (AKB   , AKVAL2(4))
+      LOGICAL             :: BORON,DONE
+
+! AXY (07/05/13) ==================================================
+!  DERIVING PH REQUIRES FOLLOWING LOOP TO CONVERGE.
+!  THIS SUBROUTINE RELIES ON CONVERGENCE.  IF THE ENVIRONMENTAL
+!  CONDITIONS DO NOT ALLOW FOR CONVERGENCE (IN 3D MODEL THIS IS
+!  LIKELY TO OCCUR NEAR LOW SALINITY REGIONS) THE MODEL WILL 
+!  BE STUCK IN THE LOOP.  TO AVOID THIS A CONVERGENCE CONDITION
+!  IS PUT IN PLACE TO SET A FLAGG OF -99 IN THE PH VAR FOR NON CONVEGENCE. 
+!  THE MODEL IS THEN ALLOWED TO CONTINUE. 'COUNTER, C_SW,C_CHECK' ARE 
+!  THE LOCAL VARS USED.
+! C_SW = condition of convergence 0=yes, 1= no
+! COUNTER = number of iterations
+! C_CHECK = maximum number of iterations
+
+! SET COUNTER AND SWITCH TO ZERO AND OFF
+      COUNTER=0
+      C_SW=0
+! FROM EXPERIENCE IF THE ITERATIONS IN THE FOLLOWING DO LOOP
+! EXCEEDS 15 CONVERGENCE WILL NOT OCCUR.  THE OVERHEAD OF 25 ITERATIONS 
+! IS OK FOR SMALL DOMAINS WITH 1/10 AND 1/15 DEG RESOLUTION.
+! I RECOMMEND A LOWER VALUE OF 15 FOR HIGHER RESOLUTION OR LARGER DOMAINS.
+      C_CHECK=25
+! AXY (07/05/13) ==================================================
+
+      DO 100 II=1,NCONC
+        CONCS2(II)=CONCS(II)
+
+! AXY (07/05/13) ==================================================
+! IF CONVERGENCE IS NOT ACHIEVED THE LOCAL ARRAY CONCS MUST BE STORED TO 
+! ALLOW THE MODEL TO CONTINUE. THEREFORE ....
+! UPDATE OLD_CONCS
+        old_CONCS(II)=CONCS(II)
+! AXY (07/05/13) ==================================================
+
+100    CONTINUE
+      DO 110 II=1,NKVAL
+        AKVAL2(II)=AKVAL(II)
+110    CONTINUE
+      AKR = AK1C/AK2C
+      AHPLUS=10.0D0**(-PH)
+      PROD=AKR*AKP*PCO2
+     
+      IF(BORON) THEN
+
+        IF(ICALC.EQ.1.OR.ICALC.EQ.4) THEN
+!         *** ALK, BTOT AND CTOT OR PCO2 FIXED ***
+!         *** ITERATIVE CALCULATION NECESSARY HERE
+
+!         SET INITIAL GUESSES AND TOLERANCE
+          H2CO3=PCO2*AKP
+          CO3=ALK/10.0D0
+          AHPLUS=1.0D-8
+          ALKB=BTOT
+          TOL1=ALK/1.0D5
+          TOL2=H2CO3/1.0D5
+          TOL3=CTOT/1.0D5
+          TOL4=BTOT/1.0D5
+
+!         HALTAFALL iteration to determine CO3, ALKB, AHPLUS
+          KARL=1
+          STEG=2.0D0
+          FAK=1.0D0
+          STEGBY=0.4D0
+10        DONE=.TRUE.
+
+! AXY (07/05/13) ==================================================
+! SET COUNTER UPDATE. FLAG 10 IS THE POINT OF RETURN FOR 
+! THE CONVERGENCE CONDITION
+          COUNTER=COUNTER+1
+	  iters  = COUNTER
+! CHECK IF CONVERGENCE HAS OCCURED IN THE NUMBER OF 
+! ACCEPTABLE ITTERATIONS.  SET C_SW TO LET MODEL KNOW
+! WHAT TO DO AT THE END OF THE SUBROUTINE
+          if(counter.ge.c_check)then
+             IF(lwp) THEN
+                WRITE(numout,*) ' CO2CLC : ITERS WARNING, ', iters
+             ENDIF
+             c_sw=1
+             GOTO 123
+          endif
+! AXY (07/05/13) ==================================================
+
+          IF(ICALC.EQ.4) THEN
+!         *** PCO2 IS FIXED ***
+            Y=AHPLUS*AHPLUS*CO3/(AK1C*AK2C)
+            IF(ABS(Y-H2CO3).GT.TOL2) THEN
+              CO3=CO3*H2CO3/Y
+              DONE=.FALSE.
+            ENDIF
+          ELSEIF(ICALC.EQ.1) THEN
+!           *** CTOT IS FIXED ***
+            Y=CO3*(1.0D0+AHPLUS/AK2C+AHPLUS*AHPLUS/(AK1C*AK2C))
+            IF(ABS(Y-CTOT).GT.TOL3) THEN
+              CO3=CO3*CTOT/Y
+              DONE=.FALSE.
+            ENDIF
+          ENDIF
+          Y=ALKB*(1.0D0+AHPLUS/AKB)
+          IF(ABS(Y-BTOT).GT.TOL4) THEN
+            ALKB=ALKB*BTOT/Y
+            DONE=.FALSE.
+          ENDIF
+
+! Alkalinity is equivalent to -(total H+), so the sign of W is opposite
+! to that normally used
+
+          Y=CO3*(2.0D0+AHPLUS/AK2C)+ALKB
+          IF(ABS(Y-ALK).GT.TOL1) THEN
+            DONE=.FALSE.
+            X=LOG(AHPLUS)
+!           W=SIGN(1.0D0,Y-ALK)
+            IF ( Y-ALK .GE. 0.0D0 ) THEN
+            W=1.0D0
+            ELSE
+            W=-1.0D0
+            ENDIF
+            IF(W.GE.0.0D0) THEN
+              X1=X
+              Y1=Y
+            ELSE
+              X2=X
+              Y2=Y
+            ENDIF
+            LQ=KARL
+            IF(LQ.EQ.1) THEN
+              KARL=2*NINT(W)
+            ELSEIF(IABS(LQ).EQ.2.AND.(LQ*W).LT.0.) THEN
+              FAK=0.5D0
+              KARL=3
+            ENDIF
+            IF(KARL.EQ.3.AND.STEG.LT.STEGBY) THEN
+              W=(X2-X1)/(Y2-Y1)
+              X=X1+W*(ALK-Y1)
+            ELSE
+              STEG=STEG*FAK
+              X=X+STEG*W
+            ENDIF
+            AHPLUS=EXP(X)  
+          ENDIF
+          IF(.NOT.DONE) GOTO 10
+          
+          HCO3=CO3*AHPLUS/AK2C
+          IF(ICALC.EQ.4) THEN
+            CTOT=H2CO3+HCO3+CO3
+          ELSEIF(ICALC.EQ.1) THEN
+            H2CO3=HCO3*AHPLUS/AK1C
+            PCO2=H2CO3/AKP
+          ENDIF
+          PH=-LOG10(AHPLUS)
+          ALKC=ALK-ALKB
+        ELSEIF(ICALC.EQ.2) THEN
+!         *** CTOT, PCO2, AND BTOT FIXED ***
+          Y=SQRT(PROD*(PROD-4.0D0*AKP*PCO2+4.0D0*CTOT))
+          H2CO3=PCO2*AKP
+          HCO3=(Y-PROD)/2.0D0
+          CO3=CTOT-H2CO3-HCO3
+          ALKC=HCO3+2.0D0*CO3
+          AHPLUS=AK1C*H2CO3/HCO3
+          PH=-LOG10(AHPLUS)
+          ALKB=BTOT/(1.0D0+AHPLUS/AKB)
+          ALK=ALKC+ALKB
+        ELSEIF(ICALC.EQ.3) THEN
+!         *** CTOT, PH AND BTOT FIXED ***
+          FACTOR=CTOT/(AHPLUS*AHPLUS+AK1C*AHPLUS+AK1C*AK2C)
+          CO3=FACTOR*AK1C*AK2C
+          HCO3=FACTOR*AK1C*AHPLUS
+          H2CO3=FACTOR*AHPLUS*AHPLUS
+          PCO2=H2CO3/AKP
+          ALKC=HCO3+2.0D0*CO3
+          ALKB=BTOT/(1.0D0+AHPLUS/AKB)
+          ALK=ALKC+ALKB
+        ELSEIF(ICALC.EQ.5) THEN
+!         *** ALK, PH AND BTOT FIXED ***
+          ALKB=BTOT/(1.0D0+AHPLUS/AKB)
+          ALKC=ALK-ALKB
+          HCO3=ALKC/(1.0D0+2.0D0*AK2C/AHPLUS)
+          CO3=HCO3*AK2C/AHPLUS
+          H2CO3=HCO3*AHPLUS/AK1C
+          PCO2=H2CO3/AKP
+          CTOT=H2CO3+HCO3+CO3
+        ELSEIF(ICALC.EQ.6) THEN
+!         *** PCO2, PH AND BTOT FIXED ***
+          ALKB=BTOT/(1.0D0+AHPLUS/AKB)
+          H2CO3=PCO2*AKP
+          HCO3=H2CO3*AK1C/AHPLUS
+          CO3=HCO3*AK2C/AHPLUS
+          CTOT=H2CO3+HCO3+CO3
+          ALKC=HCO3+2.0D0*CO3
+          ALK=ALKC+ALKB
+        ENDIF
+      ELSE
+        IF(ICALC.EQ.1) THEN
+!         *** CTOT AND ALK FIXED ***
+          TERM=4.0D0*ALK+CTOT*AKR-ALK*AKR
+          Z=SQRT(TERM*TERM+4.0D0*(AKR-4.0D0)*ALK*ALK)
+          CO3=(ALK*AKR-CTOT*AKR-4.0D0*ALK+Z)/(2.0D0*(AKR-4.0D0))
+          HCO3=(CTOT*AKR-Z)/(AKR-4.0D0)
+          H2CO3=CTOT-ALK+CO3
+          PCO2=H2CO3/AKP
+          PH=-LOG10(AK1C*H2CO3/HCO3)
+        ELSEIF(ICALC.EQ.2) THEN
+!         *** CTOT AND PCO2 FIXED ***
+          Y=SQRT(PROD*(PROD-4.0D0*AKP*PCO2+4.0D0*CTOT))
+          H2CO3=PCO2*AKP
+          HCO3=(Y-PROD)/2.0D0
+          CO3=CTOT-H2CO3-HCO3
+          ALK=HCO3+2.0D0*CO3
+          PH=-LOG10(AK1C*H2CO3/HCO3)
+        ELSEIF(ICALC.EQ.3) THEN
+!         *** CTOT AND PH FIXED ***
+          FACTOR=CTOT/(AHPLUS*AHPLUS+AK1C*AHPLUS+AK1C*AK2C)
+          CO3=FACTOR*AK1C*AK2C
+          HCO3=FACTOR*AK1C*AHPLUS
+          H2CO3=FACTOR*AHPLUS*AHPLUS
+          PCO2=H2CO3/AKP
+          ALK=HCO3+2.0D0*CO3
+        ELSEIF(ICALC.EQ.4) THEN
+!         *** ALK AND PCO2 FIXED ***
+          TERM=SQRT((8.0D0*ALK+PROD)*PROD)
+          CO3=ALK/2.0D0+PROD/8.0D0-TERM/8.0D0
+          HCO3=-PROD/4.0D0+TERM/4.0D0
+          H2CO3=PCO2*AKP
+          CTOT=CO3+HCO3+H2CO3
+          PH=-LOG10(AK1C*H2CO3/HCO3)
+        ELSEIF(ICALC.EQ.5) THEN
+!         *** ALK AND PH FIXED ***
+          HCO3=ALK/(1.0D0+2.0D0*AK2C/AHPLUS)
+          CO3=HCO3*AK2C/AHPLUS
+          H2CO3=HCO3*AHPLUS/AK1C
+          PCO2=H2CO3/AKP
+          CTOT=H2CO3+HCO3+CO3
+        ELSEIF(ICALC.EQ.6) THEN
+!         *** PCO2 AND PH FIXED ***
+          H2CO3=PCO2*AKP
+          HCO3=H2CO3*AK1C/AHPLUS
+          CO3=HCO3*AK2C/AHPLUS
+          CTOT=H2CO3+HCO3+CO3
+          ALK=HCO3+2.0D0*CO3
+        ENDIF
+      ENDIF
+
+      DO 120 II=1,NCONC
+        CONCS(II)=CONCS2(II)
+120    CONTINUE
+
+! AXY (07/05/13) ==================================================
+! C_SW IS SET AT 0 TO START
+! THEN IF NON CONVERGENCE C_SW SET TO 1
+123   IF(C_SW.EQ.1)THEN
+! IF NON CONVERGENCE, THE MODEL REQUIRES CONCS TO CONTAIN USABLE VALUES.
+! BEST OFFER BEING THE OLD CONCS VALUES WHEN CONVERGENCE HAS BEEN 
+! ACHIEVED
+        DO II=1,NCONC
+           CONCS(II)=OLD_CONCS(II)
+        END DO
+
+! SPECIFIC CARBONATE VALUES TO PUSH CODE ON THROUGH THE
+! NON CONVERGENCE CONDITIONS
+! PCO2W = 0 SO CO2 UPTAKE WILL BE ENCOURAGED
+!       CONCS(3)=O3C(III)*0.005_fp8/1.e6_fp8
+! -99 IS A FLAG TO SHOW WHEN AND WHERE NON CONVERGENCE OCCURED
+! CONCS(4)=PH, OUTPUT OF -99 MEANS NON-CONVERGENCE
+!       CONCS(4)=-99._fp8
+! 
+! AXY (10/05/13): remove this -99 flag; this is handled instead up in
+!                 trcbio_medusa.F90 where the iters variable is both 
+!                 output and may be used to trigger action
+!
+! RESET SWITCH FOR NEXT CALL TO THIS SUBROUTINE
+        C_SW=0
+      ENDIF
+! AXY (07/05/13) ==================================================
+
+
+      RETURN
+
+      END SUBROUTINE
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+      SUBROUTINE CaCO3_Saturation (Tc, S, D, CO3, &
+      Om_cal, Om_arg)
+!      
+!=======================================================================
+!
+! Routine to calculate the saturation state of calcite and aragonite    
+! Inputs:                                                               
+!               Tc      Temperature (C)                                 
+!               S       Salinity                                        
+!               D       Depth (m)                                       
+!               CO3     Carbonate ion concentration (mol.kg-1 ie /1D6)
+!                                                                       
+! Outputs                                                               
+!               Om_cal  Calite saturation                               
+!               Om_arg  Aragonite saturation                            
+!                                                                       
+! Intermediates                                                         
+!               K_cal   Stoichiometric solubility product for calcite   
+!               K_arg   Stoichiometric solubility product for aragonite 
+!               Ca      Calcium 2+ concentration (mol.kg-1) 
+!               P       Pressure (bars)
+!                                                                       
+! Source                                                                
+!       Zeebe & Wolf-Gladrow 2001 following Mucci (1983)                
+!       with pressure corrections from Millero (1995)                   
+!       Code tested against reference values given in Z & W-G
+!       Built Jerry Blackford, 2008
+!=======================================================================
+
+        IMPLICIT None
+        REAL(wp), INTENT( in )    :: Tc, S, D, CO3
+        REAL(wp), INTENT( inout ) :: Om_cal, Om_arg
+        REAL(wp) :: Tk, Kelvin, Ca
+        REAL(wp) :: logKspc, Kspc
+        REAL(wp) :: logKspa, Kspa
+        REAL(wp) :: tmp1, tmp2, tmp3
+        REAL(wp) :: dV, dK, P, R
+               
+! setup
+        Kelvin = 273.15
+        Tk = Tc + Kelvin 
+        Ca = 0.01028    ! Currently oceanic mean value at S=25, needs refining)
+        Ca = 0.010279 * (S / 35.0)  ! Ca varies with salinity (cf. Feeley et al., 2004; Yool et al., 2010)
+        R = 83.131      !(cm3.bar.mol-1.K-1)
+        P = D / 10.0    !pressure in bars
+
+! calculate K for calcite
+        tmp1 = -171.9065 - (0.077993*Tk) + (2839.319/Tk) + 71.595*log10(Tk) 
+        tmp2 = + (-0.77712 + (0.0028426*Tk) + (178.34/Tk))*SQRT(S) 
+        tmp3 = - (0.07711*S) + (0.0041249*(S**1.5))
+        logKspc = tmp1 + tmp2 + tmp3
+        Kspc = 10.0**logKspc
+      
+! correction for pressure for calcite
+        IF ( D .GT. 0) THEN
+          dV = -48.76 + 0.5304*Tc
+          dK = -11.76/1.0D3 + (0.3692/1.0D3) * Tc
+          tmp1 = -(dV/(R*Tk))*P + (0.5*dK/(R*Tk))*P*P
+          Kspc = Kspc*exp(tmp1)
+          logKspc = log10(Kspc)
+        END IF
+        
+! calculate K for aragonite
+        tmp1 = -171.945 - 0.077993*Tk + 2903.293 / Tk + 71.595* log10(Tk)
+        tmp2 = + (-0.068393 + 0.0017276*Tk + 88.135/Tk)*SQRT(S)    
+        tmp3 = - 0.10018*S + 0.0059415*S**1.5
+        logKspa = tmp1 + tmp2 + tmp3
+        Kspa = 10.0**logKspa
+     
+! correction for pressure for aragonite
+        IF ( D .GT. 0) THEN
+          dV = -46.00 + 0.5304*Tc
+          dK = -11.76/1.0D3 + (0.3692/1.0D3) * Tc
+          tmp1 = -(dV/(R*Tk))*P + (0.5*dK/(R*Tk))*P*P
+          Kspa = Kspa*exp(tmp1)
+          logKspa = log10(Kspa)
+        END IF
+        
+! calculate saturation states
+        Om_cal = (CO3 * Ca) / Kspc
+        Om_arg = (CO3 * Ca) / Kspa
+      
+      RETURN
+
+      END SUBROUTINE
+!-----------------------------------------------------------------------
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+#  else
+   !!======================================================================
+   !!  Dummy module :                         No MEDUSA carbonate chemistry
+   !!======================================================================
+
+CONTAINS
+
+   SUBROUTINE trc_co2_medusa( kt )                   ! Empty routine
+
+      INTEGER, INTENT( in ) ::   kt
+
+      WRITE(*,*) 'trc_co2_medusa: You should not have seen this print! error?', kt
+
+   END SUBROUTINE trc_co2_medusa
+#endif 
+
+   !!======================================================================
+END MODULE  trcco2_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcctl_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcctl_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcctl_medusa.F90	(revision 9987)
@@ -0,0 +1,83 @@
+MODULE trcctl_medusa
+   !!======================================================================
+   !!                         ***  trcctl_medusa.F90  ***
+   !! TOP :                Control of MEDUSA_TRC biogeochemical model
+   !!======================================================================
+   !!----------------------------------------------------------------------
+   !! History :   1.0  !  2000-12 (C. Ethe) assign a parameter to name individual tracers
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!----------------------------------------------------------------------
+
+#if defined key_medusa
+
+   USE oce_trc
+   USE trc
+   USE in_out_manager
+   USE par_medusa
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_ctl_medusa     ! called by ???
+
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 1.0 , LOCEAN-IPSL (2005) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_ctl_medusa
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ctl_medusa  ***
+      !!
+      !! ** Purpose :   control the cpp options, namelist and files 
+      !!----------------------------------------------------------------------
+
+!      IF(lwp) WRITE(numout,*)
+!      IF(lwp) WRITE(numout,*) 'use MEDUSA biological model  '
+
+! Check number of tracers
+! -----------------------
+# if defined key_roam
+      IF (jp_medusa /= 15) THEN 
+          IF (lwp) THEN 
+              WRITE (numout,*) ' ===>>>> : W A R N I N G '
+              WRITE (numout,*) ' =======   ============= '
+              WRITE (numout,*)                             &
+              &   ' STOP, change jp_medusa to 15 in '      &
+              &  ,' par_medusa.F90 '  
+          END IF 
+          STOP 'TRC_CTL'
+      END IF 
+# else
+      IF (jp_medusa /= 11) THEN 
+          IF (lwp) THEN 
+              WRITE (numout,*) ' ===>>>> : W A R N I N G '
+              WRITE (numout,*) ' =======   ============= '
+              WRITE (numout,*)                             &
+              &   ' STOP, change jp_medusa to 11 in '      &
+              &  ,' par_medusa.F90 '  
+          END IF 
+          STOP 'TRC_CTL'
+      END IF 
+# endif
+
+   END SUBROUTINE trc_ctl_medusa
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Empty module :                                            No MEDUSA
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ctl_medusa               ! Dummy routine
+   END SUBROUTINE trc_ctl_medusa
+#endif
+
+   !!======================================================================
+END MODULE trcctl_medusa
+      
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcdms_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcdms_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcdms_medusa.F90	(revision 9987)
@@ -0,0 +1,201 @@
+MODULE trcdms_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcdms_medusa  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :
+   !!  -   !  2014-08  (J. Palmieri - A. Yool)    added for UKESM1 project
+   !!  -   !  2017-05  (A. Yool)                  add extra Anderson scheme
+   !!----------------------------------------------------------------------
+#if defined key_medusa && defined key_roam
+   !!----------------------------------------------------------------------
+   !!                                        MEDUSA DMS surface concentration
+   !!----------------------------------------------------------------------
+   !!   trc_dms_medusa        :  
+   !!----------------------------------------------------------------------
+      USE oce_trc
+      USE trc
+      USE sms_medusa
+      USE lbclnk
+      USE prtctl_trc      ! Print control for debugging
+      USE in_out_manager  ! I/O manager
+
+      IMPLICIT NONE
+      PRIVATE
+
+      PUBLIC   trc_dms_medusa    ! called in trc_bio_medusa
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+
+CONTAINS
+
+!=======================================================================
+!
+   SUBROUTINE trc_dms_medusa( chn, chd, mld, xqsr, xdin, xlim,  &  !! inputs
+     &  dms_andr, dms_simo, dms_aran, dms_hall, dms_andm)           !! outputs
+!      
+!=======================================================================
+      !!
+      !! Title  : Calculates DMS ocean surface concentration
+      !! Author : Julien Palmieri and Andrew Yool
+      !! Date   : 08/08/14 
+      !!
+      !! DMS module is called in trc_bio's huge jk,jj,ji loop
+      !! --> DMS concentration is calculated in a specific cell 
+      !! (no need of ji,jj,jk)
+      !!
+      !! AXY (13/03/15): amend to include all four schemes tested
+      !!                 during winter/spring 2015; these are:
+      !!
+      !!                 1. Anderson et al. (2001); this uses fields
+      !!                    of surface chl, irradiance and nutrients
+      !!                    to empirically estimate DMS via a broken
+      !!                    stick approach
+      !!
+      !!                 2. Simo & Dachs (2002); this uses fields of
+      !!                    surface chl and mixed layer depth
+      !!
+      !!                 3. Aranami & Tsunogai (2004); this is an
+      !!                    embellishment of Simo & Dachs
+      !!
+      !!                 4. Halloran et al. (2010); this is an
+      !!                    alternative embellishment of Sim & Dachs
+      !!                    and is included because it is formally
+      !!                    published (and different from the above)
+      !!
+      !! AXY (25/05/17): add extra "corrected" Anderson scheme
+      !!
+      !!                 5. As Anderson et al. (2001) but modified to
+      !!                    more accurately reflect nutrient limitation
+      !!                    status of phytoplankton community
+      !!
+      !! AXY (08/07/15): amend to remove Julien's original calculation
+      !!                 as this is now superfluous; the four schemes 
+      !!                 are calculated and one is chosen to be passed
+      !!                 to the atmosphere in trc_bio_medusa
+      !!
+!=======================================================================
+
+      IMPLICIT NONE
+!
+      REAL(wp), INTENT( in )    :: chn                  !! non-diatom chlorophyll    (mg/m3)
+      REAL(wp), INTENT( in )    :: chd                  !! diatom chlorophyll        (mg/m3)
+      REAL(wp), INTENT( in )    :: mld                  !! mix layer depth           (m)
+      REAL(wp), INTENT( in )    :: xqsr                 !! surface irradiance        (W/m2)
+      REAL(wp), INTENT( in )    :: xdin                 !! surface DIN               (mmol N/m3)
+      REAL(wp), INTENT( in )    :: xlim                 !! surface DIN limitation    (mmol N/m3)
+      REAL(wp), INTENT( inout ) :: dms_andr             !! DMS surface concentration (nmol/L) 
+      REAL(wp), INTENT( inout ) :: dms_simo             !! DMS surface concentration (nmol/L) 
+      REAL(wp), INTENT( inout ) :: dms_aran             !! DMS surface concentration (nmol/L) 
+      REAL(wp), INTENT( inout ) :: dms_hall             !! DMS surface concentration (nmol/L) 
+      REAL(wp), INTENT( inout ) :: dms_andm             !! DMS surface concentration (nmol/L) 
+!
+      REAL(wp) :: CHL, cmr, sw_dms
+      REAL(wp) :: Jterm, Qterm
+      !! temporary variables
+      REAL(wp) ::    fq1,fq2,fq3
+! 
+!=======================================================================
+!
+! AXY (13/03/15): per remarks above, the following calculations estimate
+!                 DMS using all of the schemes examined for UKESM1
+!
+      CHL = 0.0
+      CHL = chn+chd                                 !! mg/m3 
+      cmr = CHL / mld
+!
+! AXY (13/03/15): Anderson et al. (2001)
+        Jterm = xqsr + 1.0e-6
+        !! this next line makes a hard-coded assumption about the 
+        !! half-saturation constant of MEDUSA (which should be
+        !! done properly; perhaps even scaled with the proportion
+        !! of diatoms and non-diatoms)
+        Qterm = xdin / (xdin + 0.5)
+        fq1 = log10(CHL * Jterm * Qterm)
+        if (fq1 > 1.72) then
+           dms_andr = (8.24 * (fq1 - 1.72)) + 2.29
+        else
+           dms_andr = 2.29
+        endif
+!
+! AXY (13/03/15): Simo & Dachs (2002)
+        fq1 = (-1.0 * log(mld)) + 5.7
+        fq2 = (55.8 * cmr) + 0.6
+        if (cmr < 0.02) then
+           dms_simo = fq1
+        else
+           dms_simo = fq2
+        endif
+!           
+! AXY (13/03/15): Aranami & Tsunogai (2004)
+        fq1 = 60.0 / mld
+        fq2 = (55.8 * cmr) + 0.6
+        if (cmr < 0.02) then
+           dms_aran = fq1
+        else
+           dms_aran = fq2
+        endif
+!        
+! AXY (13/03/15): Halloran et al. (2010)
+        fq1 = (-1.0 * log(mld)) + 5.7
+        fq2 = (55.8 * cmr) + 0.6
+        fq3 = (90.0 / mld)
+        if (cmr < 0.02) then
+           dms_hall = fq1
+        else
+           dms_hall = fq2
+        endif
+        if (mld > 182.5) then
+           dms_hall = fq3
+        endif
+!
+! AXY (25/05/17): modified Anderson et al. (2001)
+        Jterm = xqsr + 1.0e-6
+        !! this version fixes the hard-coded assumption above
+        Qterm = xlim
+        fq1 = log10(CHL * Jterm * Qterm)
+        if (fq1 > 1.72) then
+           dms_andm = (8.24 * (fq1 - 1.72)) + 2.29
+        else
+           dms_andm = 2.29
+        endif
+
+  END SUBROUTINE trc_dms_medusa
+
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+
+CONTAINS
+
+!=======================================================================
+!
+   SUBROUTINE trc_dms_medusa( kt )                                        !! EMPTY Routine
+!      
+!
+      INTEGER, INTENT( in ) ::   kt
+!
+
+      WRITE(*,*) 'trc_dms_medusa: You should not have seen this print! error?'
+
+   END SUBROUTINE trc_dms_medusa
+#endif
+
+   !!======================================================================
+END MODULE  trcdms_medusa
+
+
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcini_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcini_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcini_medusa.F90	(revision 9987)
@@ -0,0 +1,492 @@
+MODULE trcini_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcini_medusa  ***
+   !! TOP :   initialisation of the MEDUSA tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!              -   !  2011-04  (A. Yool) updated for ROAM project
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                         MEDUSA tracers
+   !!----------------------------------------------------------------------
+   !! trc_ini_medusa   : MEDUSA model initialisation
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc
+   USE trc
+   USE in_out_manager
+   !! AXY (04/11/13): add this in for initialisation stuff
+   USE iom
+   USE par_medusa
+   !! AXY (13/01/12): add this in for sediment variables
+   USE sms_medusa
+   !! AXY (04/11/13): add this in for initialisation stuff
+   USE trcsed_medusa
+   USE sbc_oce, ONLY: lk_oasis
+   USE oce,     ONLY: CO2Flux_out_cpl, DMS_out_cpl, chloro_out_cpl  !! Coupling variable
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_medusa   ! called by trcini.F90 module
+
+   !! AXY (25/02/10)
+   LOGICAL, PUBLIC ::                  &
+      bocalccd = .TRUE.
+   !! JPALM (14/09/15)
+   LOGICAL, PUBLIC ::                  &
+      ln_ccd = .TRUE.
+
+   INTEGER ::                          &
+      numccd
+
+   !! AXY (25/02/10)
+   INTEGER ::                          &
+      numriv
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_ini_medusa
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_medusa  ***  
+      !!
+      !! ** Purpose :   initialization for MEDUSA model
+      !!
+      !! ** Method  : - Read the namcfc namelist and check the parameter values
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+
+      !! vertical array index
+      INTEGER  ::    jk, ierr
+      !! AXY (19/07/12): added jk2 to set up friver_dep array
+      INTEGER            :: jk2
+      !! AXY (19/07/12): added tfthk to set up friver_dep array
+      REAL(wp)           :: fthk, tfthk
+      !! AXY (04/11/13): add in temporary variables for checks
+      REAL(wp)           :: fq0, fq1, fq2
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: initialisation of MEDUSA model'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+# if defined key_debug_medusa
+            CALL flush(numout)
+# endif
+
+                                           ! Allocate MEDUSA arrays
+      ierr =         sms_medusa_alloc()
+# if defined key_debug_medusa
+            IF (lwp) write (numout,*) '------------------------------'
+            IF (lwp) write (numout,*) 'Jpalm - debug'
+            IF (lwp) write (numout,*) 'in trc_ini_medusa, just after array allocate'
+            IF (lwp) write (numout,*) ' '
+            CALL flush(numout)
+# endif
+
+!!
+!! AXY (19/07/12): setup array to control distribution of river nutrients
+      friver_dep(:,:) = 0.
+      DO jk = 1,jpk
+         tfthk = 0.
+         DO jk2 = 1,jriver_dep
+            fthk  = e3t_1d(jk2)
+            if (jk2 .le. jk) then
+               tfthk = tfthk + fthk
+               friver_dep(jk2,jk) = fthk
+            endif
+         ENDDO
+         DO jk2 = 1,jriver_dep
+            friver_dep(jk2,jk) = friver_dep(jk2,jk) / tfthk
+         ENDDO
+      ENDDO
+!!
+!! Have a look at the result of this for a single depth (jriver_dep + 1)
+      IF(lwp) THEN
+          WRITE(numout,*) '=== River nutrient fraction by depth (for a water column of jpk depth)'
+          DO jk = 1,jpk
+             WRITE(numout,*)     &
+             &   ' cell = ', jk, ', friver_dep value = ', friver_dep(jk,jpk)
+          ENDDO
+          IF(lwp) CALL flush(numout)
+       ENDIF
+
+#if defined key_roam
+!! ROAM 3D and 2D carbonate system fields (calculated on first time
+!! step, then monthly)
+      f3_pH(:,:,:)    = 0.
+      f3_h2co3(:,:,:) = 0.
+      f3_hco3(:,:,:)  = 0.
+      f3_co3(:,:,:)   = 0.
+      f3_omcal(:,:,:) = 0.
+      f3_omarg(:,:,:) = 0.
+!!
+      f2_ccd_cal(:,:) = 0.
+      f2_ccd_arg(:,:) = 0.
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: carbonate fields initialised to zero'
+#endif
+      IF(lwp) CALL flush(numout)
+
+      !!----------------------------------------------------------------------
+      !! State variable initial conditions (all mmol / m3)
+      !!----------------------------------------------------------------------
+      !!     
+      !! biological and detrital components are initialised to nominal
+      !! values above 100 m depth and zero below; the latter condition
+      !! is applied since non-linear loss processes allow significant
+      !! concentrations of these components to persist at depth
+      !!
+      trn(:,:,:,jpchn) = 0.
+      trn(:,:,:,jpchd) = 0.
+      trn(:,:,:,jpphn) = 0.
+      trn(:,:,:,jpphd) = 0.
+      trn(:,:,:,jppds) = 0.
+      trn(:,:,:,jpzmi) = 0.
+      trn(:,:,:,jpzme) = 0.
+      trn(:,:,:,jpdet) = 0.
+      !!
+      DO jk = 1,13
+         !! non-diatom chlorophyll         (nominal)
+         trn(:,:,jk,jpchn) = 0.01
+         !!
+         !! diatom chlorophyll             (nominal)
+         trn(:,:,jk,jpchd) = 0.01
+         !!
+         !! non-diatom                     (nominal)
+         trn(:,:,jk,jpphn) = 0.01
+         !!
+         !! diatom                         (nominal)
+         trn(:,:,jk,jpphd) = 0.01
+         !!
+         !! diatom silicon                 (nominal)
+         trn(:,:,jk,jppds) = 0.01
+         !!
+         !! microzooplankton               (nominal)
+         trn(:,:,jk,jpzmi) = 0.01
+         !!
+         !! mesozooplankton                (nominal)
+         trn(:,:,jk,jpzme) = 0.01
+         !!
+         !! detrital nitrogen              (nominal)
+         trn(:,:,jk,jpdet) = 0.01
+      ENDDO
+      !!
+      !! dissolved inorganic nitrogen     (nominal average value; typically initialised from climatology)
+      trn(:,:,:,jpdin) = 30.
+      !!
+      !! dissolved silicic acid           (nominal average value; typically initialised from climatology)
+      trn(:,:,:,jpsil) = 90.
+      !!
+      !! dissolved "total" iron           (nominal; typically initialised from model-derived climatology)
+      trn(:,:,:,jpfer) = 1.0e-4           !! = 0.1 umol Fe / m3
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: MEDUSA-1 fields initialised to defaults'
+# if defined key_roam
+      !!
+      !! detrital carbon                  (nominal)
+      trn(:,:,:,jpdtc) = 0.
+      DO jk = 1,13
+         trn(:,:,jk,jpdtc) = 0.06625
+      ENDDO
+      !!
+      !! dissolved inorganic carbon (DIC) (nominal average value; typically initialised from climatology)
+      trn(:,:,:,jpdic) = 2330.
+      !!
+      !! total alkalinity                 (nominal average value; typically initialised from climatology)
+      trn(:,:,:,jpalk) = 2450.
+      !!
+      !! dissolved oxygen                 (nominal average value; typically initialised from climatology)
+      trn(:,:,:,jpoxy) = 175.
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: MEDUSA-2 fields initialised to defaults'
+# endif
+      IF(lwp) CALL flush(numout)
+
+      !!----------------------------------------------------------------------
+      !! Sediment pools initial conditions (all mmol / m2)
+      !!----------------------------------------------------------------------
+      !!     
+      !! these pools store biogenic material that has sunk to the seabed,
+      !! and act as a temporary reservoir
+      zb_sed_n(:,:)  = 0.0  !! organic N
+      zn_sed_n(:,:)  = 0.0
+      za_sed_n(:,:)  = 0.0
+      zb_sed_fe(:,:) = 0.0  !! organic Fe
+      zn_sed_fe(:,:) = 0.0
+      za_sed_fe(:,:) = 0.0
+      zb_sed_si(:,:) = 0.0  !! inorganic Si
+      zn_sed_si(:,:) = 0.0
+      za_sed_si(:,:) = 0.0
+      zb_sed_c(:,:)  = 0.0  !! organic C
+      zn_sed_c(:,:)  = 0.0
+      za_sed_c(:,:)  = 0.0
+      zb_sed_ca(:,:) = 0.0  !! inorganic C
+      zn_sed_ca(:,:) = 0.0
+      za_sed_ca(:,:) = 0.0
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: benthic fields initialised to zero'
+      IF(lwp) CALL flush(numout)
+     
+      !!----------------------------------------------------------------------
+      !! Averaged properties for DMS calculations (various units)
+      !!----------------------------------------------------------------------
+      !!     
+      !! these store temporally averaged properties for DMS calculations (AXY, 07/07/15)
+      zb_dms_chn(:,:)  = 0.0  !! CHN
+      zn_dms_chn(:,:)  = 0.0
+      za_dms_chn(:,:)  = 0.0
+      zb_dms_chd(:,:)  = 0.0  !! CHD
+      zn_dms_chd(:,:)  = 0.0
+      za_dms_chd(:,:)  = 0.0
+      zb_dms_mld(:,:)  = 0.0  !! MLD
+      zn_dms_mld(:,:)  = 0.0
+      za_dms_mld(:,:)  = 0.0
+      zb_dms_qsr(:,:)  = 0.0  !! QSR
+      zn_dms_qsr(:,:)  = 0.0
+      za_dms_qsr(:,:)  = 0.0
+      zb_dms_din(:,:)  = 0.0  !! DIN
+      zn_dms_din(:,:)  = 0.0
+      za_dms_din(:,:)  = 0.0
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: average fields for DMS initialised to zero'
+      IF(lwp) CALL flush(numout)
+      !!
+      !!---------------------------------------------------------------------
+      !!JPALM (14-06-2016): init dms and co2 flux for coupling with atm (UKESM)
+      !!---------------------------------------------------------------------
+      !!
+      zb_co2_flx(:,:)  = 0.0  !! CO2 flx
+      zn_co2_flx(:,:)  = 0.0
+      za_co2_flx(:,:)  = 0.0
+      zb_dms_srf(:,:)  = 0.0  !! DMS srf
+      zn_dms_srf(:,:)  = 0.0
+      za_dms_srf(:,:)  = 0.0
+      zn_chl_srf(:,:)  = 2.0E-8 !! Chl srf
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: DMS and CO2 flux (UKESM) initialised to zero'
+      IF(lwp) CALL flush(numout)
+      IF (lk_oasis) THEN
+         CO2Flux_out_cpl(:,:) =  zn_co2_flx(:,:)   !! Coupling variable
+         DMS_out_cpl(:,:)     =  zn_dms_srf(:,:)   !! Coupling variable
+         chloro_out_cpl(:,:)  =  zn_chl_srf(:,:)   !! Coupling variable
+      END IF
+      !!
+      !!----------------------------------------------------------------------
+      !! AXY (04/11/13): initialise fields previously done by trc_sed_medusa
+      !!----------------------------------------------------------------------
+      !!     
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: initialising dust deposition fields'
+      CALL trc_sed_medusa_sbc( nit000 )
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: initialising ocean CCD array'
+      CALL trc_ini_medusa_ccd( nit000 )
+      fq0 = MINVAL(ocal_ccd(:,:))
+      fq1 = MAXVAL(ocal_ccd(:,:))
+      if (lwp) write (numout,'(a,f10.3,a,f10.3)') & 
+         & 'CCD: min ', fq0, ' max ', fq1
+      !!
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: initialising riverine nutrient arrays'
+      riv_n(:,:)   = 0.0
+      riv_si(:,:)  = 0.0
+      riv_c(:,:)   = 0.0
+      riv_alk(:,:) = 0.0 
+      !!
+      CALL trc_ini_medusa_river( nit000 )
+      fq0 = MINVAL(riv_n(:,:))
+      fq1 = MAXVAL(riv_n(:,:))
+      if (lwp) write (numout,'(a,f10.3,a,f10.3)') & 
+         & 'RIV_N:   min ', fq0, ' max ', fq1
+      fq0 = MINVAL(riv_si(:,:))
+      fq1 = MAXVAL(riv_si(:,:))
+      if (lwp) write (numout,'(a,f10.3,a,f10.3)') & 
+         & 'RIV_SI:  min ', fq0, ' max ', fq1
+      fq0 = MINVAL(riv_c(:,:))
+      fq1 = MAXVAL(riv_c(:,:))
+      if (lwp) write (numout,'(a,f10.3,a,f10.3)') & 
+         & 'RIV_C:   min ', fq0, ' max ', fq1
+      fq0 = MINVAL(riv_alk(:,:))
+      fq1 = MAXVAL(riv_alk(:,:))
+      if (lwp) write (numout,'(a,f10.3,a,f10.3)') & 
+         & 'RIV_ALK: min ', fq0, ' max ', fq1
+      IF(lwp) CALL flush(numout)
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_medusa: MEDUSA initialised'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      IF(lwp) CALL flush(numout)
+
+   END SUBROUTINE trc_ini_medusa
+
+   !! ======================================================================
+   !! ======================================================================
+   !! ======================================================================
+
+   !! AXY (25/02/10)
+   SUBROUTINE trc_ini_medusa_ccd(kt)
+
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_ini_medusa_ccd  ***
+      !!
+      !! ** Purpose :   Read CCD field
+      !!
+      !! ** Method  :   Read the file
+      !!
+      !! ** input   :   external netcdf files
+      !!
+      !!----------------------------------------------------------------------
+      !! * arguments
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+
+      !!---------------------------------------------------------------------
+
+      !! Open the file
+      !! -------------
+      !!
+      !!!! JPALM -- 14-09-2015 -- 
+      !!!!       -- to test on ORCA2 with Christian, no file available, so initiate to 0 
+      IF (ln_ccd) THEN
+         IF(lwp) WRITE(numout,*) ' '
+         IF(lwp) WRITE(numout,*) ' **** Routine trc_ini_medusa_ccd'
+         CALL iom_open ( 'ccd_ocal_nemo.nc', numccd )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_ccd: ccd_ocal_nemo.nc opened'
+
+      !! Read the data
+      !! -------------
+      !!
+         CALL iom_get ( numccd, jpdom_data, 'OCAL_CCD', ocal_ccd )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_ccd: data read'
+
+      !! Close the file
+      !! --------------
+      !!
+         CALL iom_close ( numccd )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_ccd: ccd_ocal_nemo.nc closed'
+         IF(lwp) CALL flush(numout)
+      ELSE
+         IF(lwp) WRITE(numout,*) ' '
+         IF(lwp) WRITE(numout,*) ' **** Routine trc_ini_medusa_ccd'
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_ccd: do not read ccd_ocal_nemo.nc'
+         IF(lwp) WRITE(numout,*) ' **** ln_ccd = FALSE and ocal_ccd = 0.0 ---'
+         ocal_ccd(:,:) = 0.0  
+      ENDIF
+ 
+   END SUBROUTINE trc_ini_medusa_ccd
+
+   !! ======================================================================
+   !! ======================================================================
+   !! ======================================================================
+
+   !! AXY (26/01/12)
+   SUBROUTINE trc_ini_medusa_river(kt)
+
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_ini_medusa_river  ***
+      !!
+      !! ** Purpose :   Read riverine nutrient fields
+      !!
+      !! ** Method  :   Read the file
+      !!
+      !! ** input   :   external netcdf files
+      !!
+      !!----------------------------------------------------------------------
+      !! * arguments
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+
+      !!---------------------------------------------------------------------
+
+      IF(lwp) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' **** Routine trc_ini_medusa_river'
+         WRITE(numout,*) ' '
+      ENDIF
+
+      !! Open and read the files
+      !! -----------------------
+      !!
+      if (jriver_n.gt.0) then
+         if (jriver_n.eq.1) CALL iom_open ( 'river_N_conc_orca100.nc', numriv )
+         if (jriver_n.eq.2) CALL iom_open ( 'river_N_flux_orca100.nc', numriv )
+         CALL iom_get  ( numriv, jpdom_data, 'RIV_N', riv_n )
+         IF(lwp) THEN
+            if (jriver_n.eq.1) WRITE(numout,*) ' **** trc_ini_medusa_river: N CONC data read'
+            if (jriver_n.eq.2) WRITE(numout,*) ' **** trc_ini_medusa_river: N FLUX data read'
+         ENDIF
+         CALL iom_close ( numriv )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_river: river N file closed'
+      else
+         IF(lwp) THEN
+            WRITE(numout,*) ' **** trc_ini_medusa_river: N data NOT read'
+         ENDIF
+      endif
+      !!
+      if (jriver_si.gt.0) then
+         if (jriver_si.eq.1) CALL iom_open ( 'river_Si_conc_orca100.nc', numriv )
+         if (jriver_si.eq.2) CALL iom_open ( 'river_Si_flux_orca100.nc', numriv )
+         CALL iom_get  ( numriv, jpdom_data, 'RIV_SI', riv_si )
+         IF(lwp) THEN
+            if (jriver_si.eq.1) WRITE(numout,*) ' **** trc_ini_medusa_river: Si CONC data read'
+            if (jriver_si.eq.2) WRITE(numout,*) ' **** trc_ini_medusa_river: Si FLUX data read'
+         ENDIF
+         CALL iom_close ( numriv )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_river: river Si file closed'
+      else
+         IF(lwp) THEN
+            WRITE(numout,*) ' **** trc_ini_medusa_river: Si data NOT read'
+         ENDIF
+      endif
+      !!
+      if (jriver_c.gt.0) then
+         if (jriver_c.eq.1) CALL iom_open ( 'river_C_conc_orca100.nc', numriv )
+         if (jriver_c.eq.2) CALL iom_open ( 'river_C_flux_orca100.nc', numriv )
+         CALL iom_get  ( numriv, jpdom_data, 'RIV_C', riv_c )
+         IF(lwp) THEN
+            if (jriver_c.eq.1) WRITE(numout,*) ' **** trc_ini_medusa_river: C CONC data read'
+            if (jriver_c.eq.2) WRITE(numout,*) ' **** trc_ini_medusa_river: C FLUX data read'
+         ENDIF
+         CALL iom_close ( numriv )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_river: river C file closed'
+      else
+         IF(lwp) THEN
+            WRITE(numout,*) ' **** trc_ini_medusa_river: C data NOT read'
+         ENDIF
+      endif
+      !!
+      if (jriver_alk.gt.0) then
+         if (jriver_alk.eq.1) CALL iom_open ( 'river_alk_conc_orca100.nc', numriv )
+         if (jriver_alk.eq.2) CALL iom_open ( 'river_alk_flux_orca100.nc', numriv )
+         CALL iom_get  ( numriv, jpdom_data, 'RIV_ALK', riv_alk )
+         IF(lwp) THEN
+            if (jriver_alk.eq.1) WRITE(numout,*) ' **** trc_ini_medusa_river: alkalinity CONC data read'
+            if (jriver_alk.eq.2) WRITE(numout,*) ' **** trc_ini_medusa_river: alkalinity FLUX data read'
+         ENDIF
+         CALL iom_close ( numriv )
+         IF(lwp) WRITE(numout,*) ' **** trc_ini_medusa_river: river alkalinity file closed'
+      else
+         IF(lwp) THEN
+            WRITE(numout,*) ' **** trc_ini_medusa_river: alkalinity data NOT read'
+         ENDIF
+      endif
+      IF(lwp) CALL flush(numout)
+
+   END SUBROUTINE trc_ini_medusa_river
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                        No MEDUSA model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ini_medusa             ! Empty routine
+   END SUBROUTINE trc_ini_medusa
+#endif
+
+   !!======================================================================
+END MODULE trcini_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcnam_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcnam_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcnam_medusa.F90	(revision 9987)
@@ -0,0 +1,2352 @@
+MODULE trcnam_medusa
+   !!======================================================================
+   !!                      ***  MODULE trcnam_medusa  ***
+   !! TOP :   initialisation of some run parameters for MEDUSA bio-model
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!              -   !  2011-04  (A. Yool) updated for ROAM project
+   !!              -   !  2013-05  (A. Yool) renamed (from trclsm) for v3.5
+   !!              -   !  2015-11  (J. Palmieri) added iom_use for diags
+   !!              -   !  2016-11  (A. Yool) updated diags for CMIP6
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'   :                                       MEDUSA model
+   !!----------------------------------------------------------------------
+   !! trc_nam_medusa      : MEDUSA model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE par_trc         ! TOP parameters
+   USE trc             ! TOP variables
+   USE sms_medusa      ! sms trends
+   USE iom             ! I/O manager
+   !!USE trc_nam_dia     ! JPALM 13-11-2015 -- if iom_use for diag
+
+   !! AXY (04/02/14): necessary to find NaNs on HECTOR
+   USE, INTRINSIC :: ieee_arithmetic 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nam_medusa       ! called by trcnam.F90 module
+   PUBLIC   trc_nam_iom_medusa   ! called by trcnam.F90 module
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_nam_medusa
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_nam_medusa  ***  
+      !!
+      !! ** Purpose :   read MEDUSA namelist
+      !!
+      !! ** input   :   file 'namelist.trc.sms' containing the following
+      !!             namelist: natbio, natopt, and natdbi ("key_trc_diabio")
+      !!
+      !! ekp: namelist nabio contains ALL parameters of the ecosystem 
+      !!      point sourses and sinks PLUS sediment exchange
+      !!      dia_bio - used by Lobster to output all point terms 
+      !!                (sourses and sinks of bio)
+      !!      dia_add - additional diagnostics for biology such as 
+      !!                primary production (2d depth integrated field or 3d)
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER            :: ji,jj,jk
+      REAL(wp)           :: fthk, fdep, fdep1
+      REAL(wp)           :: q1, q2, q3
+      !
+      NAMELIST/natbio/ xxi,xaln,xald,jphy,xvpn,xvpd,          &
+      &    xsin0,xnsi0,xuif,jliebig, jq10,                    &
+      &    xthetam,xthetamd,xnln,xnld,xsld,xfln,xfld,         &
+      &  xgmi,xgme,xkmi,xkme,xphi,xbetan,xbetac,xkc,          &
+      &    xpmipn,xpmid,xpmepn,xpmepd,xpmezmi,xpmed,          &
+      &  xmetapn,xmetapd,xmetazmi,xmetazme,                   &
+      &  jmpn,xmpn,xkphn,jmpd,xmpd,xkphd,jmzmi,xmzmi,xkzmi,   &
+      &    jmzme,xmzme,xkzme,jmd,jsfd,xmd,xmdc,               &
+      &  xthetapn,xthetapd,xthetazmi,xthetazme,xthetad,       &
+      &    xrfn,xrsn,vsed,xhr,                                &
+      &  jiron,xfe_mass,xfe_sol,xfe_sed,xLgT,xk_FeL,xk_sc_Fe, &
+      &  jexport,jfdfate,jrratio,jocalccd,xridg_r0,           &
+      &    xfdfrac1,xfdfrac2,xfdfrac3,                        &
+      &    xcaco3a,xcaco3b,xmassc,xmassca,xmasssi,xprotca,    &
+      &    xprotsi,xfastc,xfastca,xfastsi,                    &
+      &  jorgben,jinorgben,xsedn,xsedfe,xsedsi,xsedc,xsedca,  &
+      &    xburial,                                           &
+      &  jriver_n,jriver_si,jriver_c,jriver_alk,jriver_dep,   &
+      &  xsdiss,                                              &
+      &  sedlam,sedlostpoc,jpkb,jdms,jdms_input,jdms_model
+#if defined key_roam
+      NAMELIST/natroam/ xthetaphy,xthetazoo,xthetanit,        &
+      &    xthetarem,xo2min 
+#endif
+      NAMELIST/natopt/xkg0,xkr0,xkgp,xkrp,xlg,xlr,rpig
+      INTEGER :: jl, jn
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      CHARACTER(LEN=32)   ::   clname
+      !!
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      clname = 'namelist_medusa'
+      IF(lwp) WRITE(numout,*) ' trc_nam_medusa: read MEDUSA namelist'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+# if defined key_debug_medusa
+      CALL flush(numout)
+# endif
+
+
+      CALL ctl_opn( numnatp_ref, TRIM( clname )//'_ref', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      CALL ctl_opn( numnatp_cfg, TRIM( clname )//'_cfg', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      IF(lwm) CALL ctl_opn( numonp     , 'output.namelist.pis' , 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+
+# if defined key_debug_medusa
+      CALL flush(numout)
+      IF (lwp) write (numout,*) '------------------------------'
+      IF (lwp) write (numout,*) 'Jpalm - debug'
+      IF (lwp) write (numout,*) 'open namelist_medusa -- OK'
+      IF (lwp) write (numout,*) 'Now, read namilists inside :'
+      IF (lwp) write (numout,*) ' '
+# endif
+      !
+# if defined key_debug_medusa
+      CALL flush(numout)
+# endif
+
+      ! 1.4 namelist natbio : biological parameters
+      ! -------------------------------------------
+      
+      xxi         = 0.
+      xaln        = 0.
+      xald        = 0.
+      jphy        = 0
+      xvpn        = 0.
+      xvpd        = 0.
+      xthetam     = 0.
+      xthetamd    = 0.
+!!
+      xsin0       = 0.
+      xnsi0       = 0.
+      xuif        = 0.
+!!
+      jliebig     = 0
+      jq10        = 0.
+      xnln        = 0.
+      xnld        = 0.
+      xsld        = 0.
+      xfln        = 0.
+      xfld        = 0.
+!!
+      xgmi        = 0.
+      xgme        = 0.
+      xkmi        = 0.
+      xkme        = 0.
+      xphi	  = 0.
+      xbetan      = 0.
+      xbetac      = 0.
+      xkc         = 0.
+      xpmipn      = 0.
+      xpmid       = 0.
+      xpmepn      = 0.
+      xpmepd      = 0.
+      xpmezmi     = 0.
+      xpmed       = 0.
+!!
+      xmetapn     = 0.
+      xmetapd     = 0.
+      xmetazmi    = 0.
+      xmetazme    = 0.
+!!
+      jmpn        = 0
+      xmpn        = 0.
+      xkphn       = 0.
+      jmpd        = 0
+      xmpd        = 0.
+      xkphd       = 0.
+      jmzmi       = 0
+      xmzmi       = 0.
+      xkzmi       = 0.
+      jmzme       = 0
+      xmzme       = 0.
+      xkzme       = 0.
+!!
+      jmd         = 0
+      jsfd        = 0
+      xmd         = 0.
+      xmdc        = 0.
+!!
+      xthetapn    = 0.
+      xthetapd    = 0.
+      xthetazmi   = 0.
+      xthetazme   = 0.
+      xthetad     = 0.
+      xrfn        = 0.
+      xrsn        = 0.  !: (NOT USED HERE; RETAINED FOR LOBSTER)
+!!
+      jiron       = 0
+      xfe_mass    = 0.
+      xfe_sol     = 0.
+      xfe_sed     = 0.
+      xLgT        = 0.
+      xk_FeL	  = 0.
+      xk_sc_Fe    = 0.
+!!
+      jexport     = 0
+      jfdfate     = 0
+      jrratio     = 0
+      jocalccd    = 0
+      xridg_r0    = 0.
+      xfdfrac1	  = 0.
+      xfdfrac2	  = 0.
+      xfdfrac3	  = 0.
+      xcaco3a	  = 0.
+      xcaco3b	  = 0.
+      xmassc	  = 0.
+      xmassca	  = 0.
+      xmasssi	  = 0.
+      xprotca	  = 0.
+      xprotsi	  = 0.
+      xfastc	  = 0.
+      xfastca	  = 0.
+      xfastsi	  = 0.
+!!
+      jorgben     = 0
+      jinorgben   = 0
+      xsedn       = 0.
+      xsedfe      = 0.
+      xsedsi      = 0.
+      xsedc       = 0.
+      xsedca      = 0.
+      xburial     = 0.
+!!
+      jriver_n    = 0
+      jriver_si   = 0
+      jriver_c    = 0
+      jriver_alk  = 0
+      jriver_dep  = 1
+!!
+      xsdiss	  = 0.
+!!
+      vsed        = 0.
+      xhr         = 0.
+!!
+      sedlam	  = 0.
+      sedlostpoc  = 0.
+      jpkb	  = 0.
+      jdms        = 0
+      jdms_input  = 0
+      jdms_model  = 0
+            
+      !REWIND(numnatm)
+      !READ(numnatm,natbio)
+         ! Namelist natbio
+         ! -------------------
+         REWIND( numnatp_ref )              ! Namelist natbio in reference namelist : MEDUSA diagnostics
+         READ  ( numnatp_ref, natbio, IOSTAT = ios, ERR = 903)
+903      IF( ios /= 0 ) CALL ctl_nam ( ios , 'natbio in reference namelist', lwp )
+
+         REWIND( numnatp_cfg )              ! Namelist natbio in configuration namelist : MEDUSA diagnostics
+         READ  ( numnatp_cfg, natbio, IOSTAT = ios, ERR = 904 )
+904      IF( ios /= 0 ) CALL ctl_nam ( ios , 'natbio in configuration namelist', lwp )
+         IF(lwm) WRITE ( numonp, natbio )
+
+!! Primary production and chl related quantities
+!!       xxi         :  conversion factor from gC to mmolN 
+!!       xaln        :  Chl-a specific initial slope of P-I curve for non-diatoms 
+!!       xald        :  Chl-a specific initial slope of P-I curve for diatoms
+!!       jphy        :  phytoplankton T-dependent growth switch
+!!       xvpn        :  maximum growth rate for non-diatoms
+!!       xvpd        :  maximum growth rate for diatoms
+!!       xthetam     :  maximum Chl to C ratio for non-diatoms      
+!!       xthetamd    :  maximum Chl to C ratio for diatoms      
+!!
+!! Diatom silicon parameters
+!!       xsin0       :  minimum diatom Si:N ratio
+!!       xnsi0       :  minimum diatom N:Si ratio
+!!       xuif        :  hypothetical growth ratio at infinite Si:N ratio
+!!
+!! Nutrient limitation
+!!       jliebig     :  Liebig nutrient uptake switch
+!!       xnln        :  half-sat constant for DIN uptake by non-diatoms 
+!!       xnld        :  half-sat constant for DIN uptake by diatoms 
+!!       xsl         :  half-sat constant for Si uptake by diatoms 
+!!       xfld        :  half-sat constant for Fe uptake by diatoms  
+!!       xfln        :  half-sat constant for Fe uptake by non-datoms 
+!!
+!! Grazing
+!!       xgmi        :  microzoo maximum growth rate 
+!!       xgme        :  mesozoo maximum growth rate 
+!!       xkmi        :  microzoo grazing half-sat parameter
+!!       xkme        :  mesozoo grazing half-sat parameter
+!!       xphi        :  micro/mesozoo grazing inefficiency
+!!       xbetan      :  micro/mesozoo N assimilation efficiency
+!!       xbetac      :  micro/mesozoo C assimilation efficiency
+!!       xkc         :  micro/mesozoo net C growth efficiency
+!!       xpmipn      :  grazing preference of microzoo for non-diatoms
+!!       xpmid       :  grazing preference of microzoo for diatoms
+!!       xpmepn      :  grazing preference of mesozoo for non-diatoms 
+!!       xpmepd      :  grazing preference of mesozoo for diatoms
+!!       xpmezmi     :  grazing preference of mesozoo for microzoo
+!!       xpmed       :  grazing preference of mesozoo for detritus
+!!
+!! Metabolic losses
+!!       xmetapn     :  non-diatom metabolic loss rate
+!!       xmetapd     :  diatom     metabolic loss rate
+!!       xmetazmi    :  microzoo   metabolic loss rate
+!!       xmetazme    :  mesozoo    metabolic loss rate
+!!
+!! Mortality/Remineralisation
+!!       jmpn        :  non-diatom mortality functional form
+!!       xmpn        :  non-diatom mortality rate
+!!       xkphn       :  non-diatom mortality half-sat constant
+!!       jmpd        :  diatom     mortality functional form
+!!       xmpd        :  diatom mortality rate
+!!       xkphd       :  diatom mortality half-sat constant
+!!       jmzmi       :  microzoo   mortality functional form
+!!       xmzmi       :  microzoo mortality rate
+!!       xkzmi       :  microzoo mortality half-sat constant
+!!       jmzme       :  mesozoo    mortality functional form
+!!       xmzme       :  mesozoo mortality rate
+!!       xkzme       :  mesozoo mortality half-sat constant
+!!
+!! Remineralisation
+!!       jmd         :  detritus T-dependent remineralisation switch
+!!       jsfd        :  accelerate seafloor detritus remin. switch
+!!       xmd         :  detrital nitrogen remineralisation rate 
+!!       xmdc        :  detrital carbon remineralisation rate 
+!!
+!! Stochiometric ratios
+!!       xthetapn    :  non-diatom C:N ratio
+!!       xthetapd    :  diatom C:N ratio
+!!       xthetazmi   :  microzoo C:N ratio
+!!       xthetazme   :  mesozoo C:N ratio
+!!       xthetad     :  detritus C:N ratio
+!!       xrfn        :  phytoplankton Fe:N ratio
+!!	 xrsn        :  diatom Si:N ratio (*NOT* used)
+!!
+!! Iron parameters
+!!       jiron       :  iron scavenging submodel switch
+!!       xfe_mass    :  iron atomic mass
+!!	 xfe_sol     :  aeolian iron solubility
+!!	 xfe_sed     :  sediment iron input
+!!	 xLgT	     :  total ligand concentration (umol/m3)
+!!	 xk_FeL	     :  dissociation constant for (Fe + L)
+!!	 xk_sc_Fe    :  scavenging rate of "free" iron
+!!	 
+!! Fast-sinking detritus parameters
+!!       jexport     :  fast detritus remineralisation switch
+!!       jfdfate     :  fate of fast detritus at seafloor switch
+!!       jrratio     :  rain ratio switch
+!!       jocalccd    :  CCD switch
+!!       xridg_r0    :  Ridgwell rain ratio coefficient
+!!       xfdfrac1    :  fast-sinking fraction of diatom nat. mort. losses
+!!       xfdfrac2    :  fast-sinking fraction of meszooplankton mort. losses
+!!       xfdfrac3    :  fast-sinking fraction of diatom silicon grazing losses
+!!       xcaco3a     :  polar (high latitude) CaCO3 fraction
+!!       xcaco3b     :  equatorial (low latitude) CaCO3 fraction
+!!       xmassc      :  organic C mass:mole ratio, C106 H175 O40 N16 P1
+!!       xmassca     :  calcium carbonate mass:mole ratio, CaCO3
+!!       xmasssi     :  biogenic silicon mass:mole ratio, (H2SiO3)n
+!!       xprotca     :  calcium carbonate protection ratio
+!!       xprotsi     :  biogenic silicon protection ratio
+!!       xfastc      :  organic C remineralisation length scale
+!!       xfastca     :  calcium carbonate dissolution length scale
+!!       xfastsi     :  biogenic silicon dissolution length scale
+!!
+!! Benthic 
+!!       jorgben     :  does   organic detritus go to the benthos?
+!!       jinorgben   :  does inorganic detritus go to the benthos?
+!!       xsedn       :  organic   nitrogen sediment remineralisation rate 
+!!       xsedfe      :  organic   iron     sediment remineralisation rate 
+!!       xsedsi      :  inorganic silicon  sediment dissolution      rate 
+!!       xsedc       :  organic   carbon   sediment remineralisation rate 
+!!       xsedca      :  inorganic carbon   sediment dissolution      rate 
+!!       xburial     :  burial rate of seafloor detritus
+!!
+!! Riverine inputs
+!!       jriver_n    :  riverine N          input?
+!!       jriver_si   :  riverine Si         input?
+!!       jriver_c    :  riverine C          input?
+!!       jriver_alk  :  riverine alkalinity input?
+!!       jriver_dep  :  depth of riverine   input?
+!!
+!! Miscellaneous
+!!       xsdiss      :  diatom frustule dissolution rate
+!!
+!! Gravitational sinking      
+!!       vsed        :  detritus gravitational sinking rate 
+!!       xhr         :  coeff for Martin's remineralisation profile
+!!
+!! Additional parameters
+!!       sedlam      :  time coeff of POC in sediments
+!!      sedlostpoc   :  sediment geol loss for POC
+!!       jpkb        :  vertical layer for diagnostic of the vertical flux 
+!!                      NOTE that in LOBSTER it is a first vertical layers where 
+!!                      biology is active  
+!!
+!! UKESM1 - new diagnostics  !! Jpalm
+!!       jdms        :  include dms diagnostics
+!!	 jdms_input  :  use instant (0) or diel-avg (1) inputs
+!!       jdms_model  :  choice of DMS model passed to atmosphere
+!!                      1 = ANDR, 2 = SIMO, 3 = ARAN, 4 = HALL, 5 = ANDM
+!!
+      IF(lwp) THEN
+!!
+!! AXY (08/11/13): compilation key notification
+         WRITE(numout,*) '=== Compilation keys'
+#if defined key_roam
+         WRITE(numout,*)     &
+         &   ' key_roam                                                               = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_roam                                                               = INACTIVE'
+#endif        
+#if defined key_axy_carbchem
+         WRITE(numout,*)     &
+         &   ' key_axy_carbchem                                                       = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_axy_carbchem                                                       = INACTIVE'
+#endif        
+#if defined key_mocsy
+         WRITE(numout,*)     &
+         &   ' key_mocsy                                                              = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_mocsy                                                              = INACTIVE'
+#endif        
+#if defined key_avgqsr_medusa
+         WRITE(numout,*)     &
+         &   ' key_avgqsr_medusa                                                      = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_avgqsr_medusa                                                      = INACTIVE'
+#endif        
+#if defined key_bs_axy_zforce
+         WRITE(numout,*)     &
+         &   ' key_bs_axy_zforce                                                      = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_bs_axy_zforce                                                      = INACTIVE'
+#endif        
+#if defined key_bs_axy_yrlen
+         WRITE(numout,*)     &
+         &   ' key_bs_axy_yrlen                                                       = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_bs_axy_yrlen                                                       = INACTIVE'
+#endif        
+#if defined key_deep_fe_fix
+         WRITE(numout,*)     &
+         &   ' key_deep_fe_fix                                                        = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_deep_fe_fix                                                        = INACTIVE'
+#endif        
+#if defined key_axy_nancheck
+         WRITE(numout,*)     &
+         &   ' key_axy_nancheck                                                       = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_axy_nancheck                                                       = INACTIVE'
+#endif        
+# if defined key_axy_pi_co2
+         WRITE(numout,*)     &
+         &   ' key_axy_pi_co2                                                         = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_axy_pi_co2                                                         = INACTIVE'
+# endif
+# if defined key_debug_medusa
+         WRITE(numout,*)     &
+         &   ' key_debug_medusa                                                       = ACTIVE'
+#else
+         WRITE(numout,*)     &
+         &   ' key_debug_medusa                                                       = INACTIVE'
+# endif
+         WRITE(numout,*) ' '
+
+         WRITE(numout,*) 'natbio'
+         WRITE(numout,*) ' '
+!!
+!! Primary production and chl related quantities
+         WRITE(numout,*) '=== Primary production'
+         WRITE(numout,*)     &
+         &   ' conversion factor from gC to mmolN,                        xxi         =', xxi
+         WRITE(numout,*)     &
+         &   ' Chl-a specific initial slope of P-I curve for non-diatoms, xaln        = ', xaln
+         WRITE(numout,*)     &
+         &   ' Chl-a specific initial slope of P-I curve for diatoms,     xald        = ', xald
+         if (jphy.eq.1) then
+            WRITE(numout,*) &
+            &   ' phytoplankton growth is *temperature-dependent*            jphy        = ', jphy
+         elseif (jphy.eq.2) then
+            WRITE(numout,*) &
+            &   ' phytoplankton growth is *temperature-dependent(Q10)*       jphy        = ', jphy
+         elseif (jphy.eq.0) then
+            WRITE(numout,*) &
+            &   ' phytoplankton growth is *temperature-independent*          jphy        = ', jphy
+         endif
+         WRITE(numout,*)     &
+         &   ' maximum growth rate for non-diatoms,                       xvpn        = ', xvpn
+         WRITE(numout,*)     &
+         &   ' maximum growth rate for diatoms,                           xvpn        = ', xvpd
+         WRITE(numout,*)     &
+         &   ' maximum Chl to C ratio for non-diatoms,                    xthetam     = ', xthetam
+         WRITE(numout,*)     &
+         &   ' maximum Chl to C ratio for diatoms,                        xthetamd    = ', xthetamd
+         WRITE(numout,*)     &
+         &   ' specific Q10 value (jphy==2),                                  jq10    = ', jq10
+!!
+!! Diatom silicon parameters
+         WRITE(numout,*) '=== Diatom silicon parameters'
+         WRITE(numout,*)     &
+         &   ' minimum diatom Si:N ratio,                                 xsin0       = ', xsin0
+         WRITE(numout,*)     &
+         &   ' minimum diatom N:Si ratio,                                 xnsi0       = ', xnsi0
+         WRITE(numout,*)     &
+         &   ' hypothetical growth ratio at infinite Si:N ratio,          xuif        = ', xuif
+!!
+!! Nutrient limitation
+         WRITE(numout,*) '=== Nutrient limitation'
+         if (jliebig.eq.1) then
+            WRITE(numout,*) &
+            &   ' nutrient uptake is a Liebig Law (= most limiting) function jliebig     = ', jliebig
+         elseif (jliebig.eq.0) then
+            WRITE(numout,*) &
+            &   ' nutrient uptake is a multiplicative function               jliebig     = ', jliebig
+         endif
+         WRITE(numout,*)     &
+         &   ' half-sat constant for DIN uptake by non-diatoms,           xnln        = ', xnln
+         WRITE(numout,*)     &
+         &   ' half-sat constant for DIN uptake by diatoms,               xnld        = ', xnld
+         WRITE(numout,*)     &
+         &   ' half-sat constant for Si uptake by diatoms,                xsld        = ', xsld
+         WRITE(numout,*)     &
+         &   ' half-sat constant for Fe uptake by non-diatoms,            xfln        = ', xfln
+         WRITE(numout,*)     &
+         &   ' half-sat constant for Fe uptake by diatoms,                xfld        = ', xfld
+!!
+!! Grazing
+         WRITE(numout,*) '=== Zooplankton grazing'
+         WRITE(numout,*)     &
+         &   ' microzoo maximum growth rate,                              xgmi        = ', xgmi
+         WRITE(numout,*)     &
+         &   ' mesozoo maximum growth rate,                               xgme        = ', xgme
+         WRITE(numout,*)     &
+         &   ' microzoo grazing half-sat parameter,                       xkmi        = ', xkmi
+         WRITE(numout,*)     &
+         &   ' mesozoo grazing half-sat parameter,                        xkme        = ', xkme
+         WRITE(numout,*)     &
+         &   ' micro/mesozoo grazing inefficiency,                        xphi        = ', xphi
+         WRITE(numout,*)     &
+         &   ' micro/mesozoo N assimilation efficiency,                   xbetan      = ', xbetan
+         WRITE(numout,*)     &
+         &   ' micro/mesozoo C assimilation efficiency,                   xbetac      = ', xbetan
+         WRITE(numout,*)     &
+         &   ' micro/mesozoo net C growth efficiency,                     xkc         = ', xkc
+         WRITE(numout,*)     &
+         &   ' grazing preference of microzoo for non-diatoms,            xpmipn      = ', xpmipn
+         WRITE(numout,*)     &
+         &   ' grazing preference of microzoo for detritus,               xpmid       = ', xpmid
+         WRITE(numout,*)     &
+         &   ' grazing preference of mesozoo for non-diatoms,             xpmepn      = ', xpmepn
+         WRITE(numout,*)     &
+         &   ' grazing preference of mesozoo for diatoms,                 xpmepd      = ', xpmepd
+         WRITE(numout,*)     &
+         &   ' grazing preference of mesozoo for microzoo,                xpmezmi     = ', xpmezmi
+         WRITE(numout,*)     &
+         &   ' grazing preference of mesozoo for detritus,                xpmed       = ', xpmed
+!!
+!! Metabolic losses
+         WRITE(numout,*) '=== Metabolic losses'
+         WRITE(numout,*)     &
+         &   ' non-diatom metabolic loss rate,                            xmetapn     = ', xmetapn
+         WRITE(numout,*)     &
+         &   ' diatom     metabolic loss rate,                            xmetapd     = ', xmetapd
+         WRITE(numout,*)     &
+         &   ' microzoo   metabolic loss rate,                            xmetazmi    = ', xmetazmi
+         WRITE(numout,*)     &
+         &   ' mesozoo    metabolic loss rate,                            xmetazme    = ', xmetazme
+!!
+!! Mortality losses
+         WRITE(numout,*) '=== Mortality losses'
+         if (jmpn.eq.1) then
+            WRITE(numout,*)     &
+            &   ' non-diatom mortality functional form,            LINEAR    jmpn        = ', jmpn
+         elseif (jmpn.eq.2) then
+            WRITE(numout,*)     &
+            &   ' non-diatom mortality functional form,         QUADRATIC    jmpn        = ', jmpn
+         elseif (jmpn.eq.3) then
+            WRITE(numout,*)     &
+            &   ' non-diatom mortality functional form,        HYPERBOLIC    jmpn        = ', jmpn
+         elseif (jmpn.eq.4) then
+            WRITE(numout,*)     &
+            &   ' non-diatom mortality functional form,           SIGMOID    jmpn        = ', jmpn
+         endif
+         WRITE(numout,*)     &
+         &   ' non-diatom mortality rate,                                 xmpn        = ', xmpn
+         WRITE(numout,*)     &
+         &   ' non-diatom mortality half-sat constant                     xkphn       = ', xkphn
+         if (jmpd.eq.1) then
+            WRITE(numout,*)     &
+            &   ' diatom mortality functional form,                LINEAR    jmpd        = ', jmpd
+         elseif (jmpd.eq.2) then
+            WRITE(numout,*)     &
+            &   ' diatom mortality functional form,             QUADRATIC    jmpd        = ', jmpd
+         elseif (jmpd.eq.3) then
+            WRITE(numout,*)     &
+            &   ' diatom mortality functional form,            HYPERBOLIC    jmpd        = ', jmpd
+         elseif (jmpd.eq.4) then
+            WRITE(numout,*)     &
+            &   ' diatom mortality functional form,               SIGMOID    jmpd        = ', jmpd
+         endif
+         WRITE(numout,*)     &
+         &   ' diatom mortality rate,                                     xmpd        = ', xmpd
+         WRITE(numout,*)     &
+         &   ' diatom mortality half-sat constant                         xkphd       = ', xkphd
+         if (jmzmi.eq.1) then
+            WRITE(numout,*)     &
+            &   ' microzoo mortality functional form,              LINEAR    jmzmi       = ', jmzmi
+         elseif (jmzmi.eq.2) then
+            WRITE(numout,*)     &
+            &   ' microzoo mortality functional form,           QUADRATIC    jmzmi       = ', jmzmi
+         elseif (jmzmi.eq.3) then
+            WRITE(numout,*)     &
+            &   ' microzoo mortality functional form,          HYPERBOLIC    jmzmi       = ', jmzmi
+         elseif (jmzmi.eq.4) then
+            WRITE(numout,*)     &
+            &   ' microzoo mortality functional form,             SIGMOID    jmzmi       = ', jmzmi
+         endif
+         WRITE(numout,*)     &
+         &   ' microzoo mortality rate,                                   xmzmi       = ', xmzmi
+         WRITE(numout,*)     &
+         &   ' mesozoo mortality half-sat constant,                       xkzmi       = ', xkzmi
+         if (jmzme.eq.1) then
+            WRITE(numout,*)     &
+            &   ' mesozoo mortality functional form,               LINEAR    jmzme       = ', jmzme
+         elseif (jmzme.eq.2) then
+            WRITE(numout,*)     &
+            &   ' mesozoo mortality functional form,            QUADRATIC    jmzme       = ', jmzme
+         elseif (jmzme.eq.3) then
+            WRITE(numout,*)     &
+            &   ' mesozoo mortality functional form,           HYPERBOLIC    jmzme       = ', jmzme
+         elseif (jmzme.eq.4) then
+            WRITE(numout,*)     &
+            &   ' mesozoo mortality functional form,              SIGMOID    jmzme       = ', jmzme
+         endif
+         WRITE(numout,*)     &
+         &   ' mesozoo mortality rate,                                    xmzme       = ', xmzme
+         WRITE(numout,*)     &
+         &   ' mesozoo mortality half-sat constant,                       xkzme       = ', xkzme
+!!
+!! Remineralisation
+         WRITE(numout,*) '=== Remineralisation'
+         if (jmd.eq.1) then
+            WRITE(numout,*) &
+            &   ' detritus remineralisation is *temperature-dependent*       jmd         = ', jmd
+         elseif (jmd.eq.2) then
+            WRITE(numout,*) &
+            &   ' detritus remineralisation is *temperature-dependent(Q10)*  jmd         = ', jmd
+         elseif (jmd.eq.0) then
+            WRITE(numout,*) &
+            &   ' detritus remineralisation is *temperature-independent*     jmd         = ', jmd
+         endif
+         if (jsfd.eq.1) then
+            WRITE(numout,*) &
+            &   ' detritus seafloor remineralisation is *accelerated*        jsfd        = ', jsfd
+         else
+            WRITE(numout,*) &
+            &   ' detritus seafloor remineralisation occurs at same rate     jsfd        = ', jsfd
+         endif
+         WRITE(numout,*)     &
+         &   ' detrital nitrogen remineralisation rate,                   xmd         = ', xmd
+         WRITE(numout,*)     &
+         &   ' detrital carbon remineralisation rate,                     xmdc        = ', xmdc
+!!
+!! Stochiometric ratios
+         WRITE(numout,*) '=== Stoichiometric ratios'
+         WRITE(numout,*)     &
+         &   ' non-diatom C:N ratio,                                      xthetapn    = ', xthetapn
+         WRITE(numout,*)     &
+         &   ' diatom C:N ratio,                                          xthetapd    = ', xthetapd
+         WRITE(numout,*)     &
+         &   ' microzoo C:N ratio,                                        xthetazmi   = ', xthetazmi
+         WRITE(numout,*)     &
+         &   ' mesozoo C:N ratio,                                         xthetazme   = ', xthetazme
+         WRITE(numout,*)     &
+         &   ' detritus C:N ratio,                                        xthetad     = ', xthetad
+         WRITE(numout,*)     &
+         &   ' phytoplankton Fe:N ratio,                                  xrfn        = ', xrfn
+         WRITE(numout,*)     &
+         &   ' diatom Si:N ratio,                                         xrsn        = ', xrsn
+!!	  
+!! Iron parameters
+         WRITE(numout,*) '=== Iron parameters'
+         if (jiron.eq.1) then
+            WRITE(numout,*)     &
+            &   ' Dutkiewicz et al. (2005) iron scavenging                   jiron       = ', jiron
+         elseif (jiron.eq.2) then
+            WRITE(numout,*)     &
+            &   ' Moore et al. (2004) iron scavenging                        jiron       = ', jiron
+         elseif (jiron.eq.3) then
+            WRITE(numout,*)     &
+            &   ' Moore et al. (2008) iron scavenging                        jiron       = ', jiron
+         elseif (jiron.eq.4) then
+            WRITE(numout,*)     &
+            &   ' Galbraith et al. (2010) iron scavenging                    jiron       = ', jiron
+         else
+            WRITE(numout,*)     &
+            &   ' There is **no** iron scavenging                            jiron       = ', jiron
+         endif
+         WRITE(numout,*)     &
+         &   ' iron atomic mass,                                          xfe_mass    = ', xfe_mass
+         WRITE(numout,*)     &
+         &   ' aeolian iron solubility,                                   xfe_sol     = ', xfe_sol
+         WRITE(numout,*)     &
+         &   ' sediment iron input,                                       xfe_sed     = ', xfe_sed
+         WRITE(numout,*)     &
+         &   ' total ligand concentration (umol/m3),                      xLgT        = ', xLgT
+         WRITE(numout,*)     &
+         &   ' dissociation constant for (Fe + L),                        xk_FeL      = ', xk_FeL
+         WRITE(numout,*)     &
+         &   ' scavenging rate for free iron,                             xk_sc_Fe    = ', xk_sc_Fe
+!!
+!! Fast-sinking detritus parameters
+         WRITE(numout,*) '=== Fast-sinking detritus'
+         if (jexport.eq.1) then
+            WRITE(numout,*) &
+            &   ' fast-detritus remin. uses Dunne et al. (2007; ballast)     jexport     = ', jexport
+         elseif (jexport.eq.2) then
+            WRITE(numout,*) &
+            &   ' fast-detritus remin. uses Martin et al. (1987)             jexport     = ', jexport
+         elseif (jexport.eq.2) then
+            WRITE(numout,*) &
+            &   ' fast-detritus remin. uses Henson et al. (2011)             jexport     = ', jexport
+         endif
+         if (jfdfate.eq.1) then
+            WRITE(numout,*) &
+            &   ' fast-detritus reaching seafloor becomes slow-detritus      jfdfate     = ', jfdfate
+         elseif (jfdfate.eq.0) then
+            WRITE(numout,*) &
+            &   ' fast-detritus reaching seafloor instantly remineralised    jfdfate     = ', jfdfate
+         endif
+#if defined key_roam
+         if (jrratio.eq.0) then
+            WRITE(numout,*) &
+            &   ' Dunne et al. (2005) rain ratio submodel                    jrratio     = ', jrratio
+         elseif (jrratio.eq.1) then
+            WRITE(numout,*) &
+            &   ' Ridgwell et al. (2007) rain ratio submodel (surface omega) jrratio     = ', jrratio
+         elseif (jrratio.eq.2) then
+            WRITE(numout,*) &
+            &   ' Ridgwell et al. (2007) rain ratio submodel (3D omega)      jrratio     = ', jrratio
+         endif
+#else          
+         jrratio = 0
+         WRITE(numout,*) &
+         &   ' Dunne et al. (2005) rain ratio submodel                    jrratio     = ', jrratio
+#endif          
+#if defined key_roam
+         if (jocalccd.eq.0) then
+            WRITE(numout,*) &
+            &   ' Default, fixed CCD used                                    jocalccd    = ', jocalccd
+         elseif (jocalccd.eq.1) then
+            WRITE(numout,*) &
+            &   ' Calculated, dynamic CCD used                               jocalccd    = ', jocalccd
+         endif
+#else          
+         jocalccd = 0
+         WRITE(numout,*) &
+         &   ' Default, fixed CCD used                                    jocalccd    = ', jocalccd
+#endif
+         WRITE(numout,*)     &
+         &   ' Ridgwell rain ratio coefficient,                           xridg_r0    = ', xridg_r0
+         WRITE(numout,*)     &
+         &   ' fast-sinking fraction of diatom nat. mort. losses,         xfdfrac1    = ', xfdfrac1
+         WRITE(numout,*)     &
+         &   ' fast-sinking fraction of mesozooplankton mort. losses,     xfdfrac2    = ', xfdfrac2
+         WRITE(numout,*)     &
+         &   ' fast-sinking fraction of diatom silicon grazing losses,    xfdfrac3    = ', xfdfrac3
+         WRITE(numout,*)     &
+         &   ' polar (high latitude) CaCO3 fraction,                      xcaco3a     = ', xcaco3a
+         WRITE(numout,*)     &
+         &   ' equatorial (low latitude) CaCO3 fraction,                  xcaco3b     = ', xcaco3b
+         WRITE(numout,*)     &
+         &   ' organic C mass:mole ratio, C106 H175 O40 N16 P1,           xmassc      = ', xmassc
+         WRITE(numout,*)     &
+         &   ' calcium carbonate mass:mole ratio, CaCO3,                  xmassca     = ', xmassca
+         WRITE(numout,*)     &
+         &   ' biogenic silicon mass:mole ratio, (H2SiO3)n,               xmasssi     = ', xmasssi
+         WRITE(numout,*)     &
+         &   ' calcium carbonate protection ratio,                        xprotca     = ', xprotca
+         WRITE(numout,*)     &
+         &   ' biogenic silicon protection ratio,                         xprotsi     = ', xprotsi
+         WRITE(numout,*)     &
+         &   ' organic C remineralisation length scale,                   xfastc      = ', xfastc
+         WRITE(numout,*)     &
+         &   ' calcium carbonate dissolution length scale,                xfastca     = ', xfastca
+         WRITE(numout,*)     &
+         &   ' biogenic silicon dissolution length scale,                 xfastsi     = ', xfastsi
+!!
+!! Benthos parameters
+         WRITE(numout,*) '=== Benthos parameters'
+         WRITE(numout,*)     &
+         &   ' does   organic detritus go to the benthos?,                jorgben     = ', jorgben
+         WRITE(numout,*)     &
+         &   ' does inorganic detritus go to the benthos?,                jinorgben   = ', jinorgben
+!!
+!! Some checks on parameters related to benthos parameters
+         if (jorgben.eq.1 .and. jsfd.eq.1) then
+            !! slow detritus going to benthos at an accelerated rate
+            WRITE(numout,*) '  === WARNING! ==='
+            WRITE(numout,*) '  jsfd *and* jorgben are active - please check that you wish this'
+            WRITE(numout,*) '  === WARNING! ==='
+         endif
+         if (jorgben.eq.1 .and. jfdfate.eq.1) then
+            !! fast detritus going to benthos but via slow detritus
+            WRITE(numout,*) '  === WARNING! ==='
+            WRITE(numout,*) '  jfdfate *and* jorgben are active - please check that you wish this'
+            WRITE(numout,*) '  === WARNING! ==='
+         endif
+         if (jorgben.eq.0 .and. jinorgben.eq.1) then
+            !! inorganic fast detritus going to benthos but organic fast detritus is not
+            WRITE(numout,*) '  === WARNING! ==='
+            WRITE(numout,*) '  jinorgben is active but jorgben is not - please check that you wish this'
+            WRITE(numout,*) '  === WARNING! ==='
+         endif
+         WRITE(numout,*)     &
+         &   ' organic   nitrogen sediment remineralisation rate,         xsedn       = ', xsedn
+         WRITE(numout,*)     &
+         &   ' organic   iron     sediment remineralisation rate,         xsedfe      = ', xsedfe
+         WRITE(numout,*)     &
+         &   ' inorganic silicon  sediment remineralisation rate,         xsedsi      = ', xsedsi
+         WRITE(numout,*)     &
+         &   ' organic   carbon   sediment remineralisation rate,         xsedc       = ', xsedc
+         WRITE(numout,*)     &
+         &   ' inorganic carbon   sediment remineralisation rate,         xsedca      = ', xsedca
+         WRITE(numout,*)     &
+         &   ' burial rate of seafloor detritus,                          xburial     = ', xburial
+!!
+!! Riverine inputs
+         WRITE(numout,*) '=== Riverine inputs'
+         if (jriver_n.eq.0) then
+            WRITE(numout,*)     &
+            &   ' *no* riverine N input,                                     jriver_n    = ', jriver_n
+         elseif (jriver_n.eq.1) then
+            WRITE(numout,*)     &
+            &   ' riverine N concentrations specified,                       jriver_n    = ', jriver_n
+         elseif (jriver_n.eq.2) then
+            WRITE(numout,*)     &
+            &   ' riverine N inputs specified,                               jriver_n    = ', jriver_n
+         endif
+         if (jriver_si.eq.0) then
+            WRITE(numout,*)     &
+            &   ' *no* riverine Si input,                                    jriver_si   = ', jriver_si
+         elseif (jriver_si.eq.1) then
+            WRITE(numout,*)     &
+            &   ' riverine Si concentrations specified,                      jriver_si   = ', jriver_si
+         elseif (jriver_si.eq.2) then
+            WRITE(numout,*)     &
+            &   ' riverine Si inputs specified,                              jriver_si   = ', jriver_si
+         endif
+         if (jriver_c.eq.0) then
+            WRITE(numout,*)     &
+            &   ' *no* riverine C input,                                     jriver_c    = ', jriver_c
+         elseif (jriver_c.eq.1) then
+            WRITE(numout,*)     &
+            &   ' riverine C concentrations specified,                       jriver_c    = ', jriver_c
+         elseif (jriver_c.eq.2) then
+            WRITE(numout,*)     &
+            &   ' riverine C inputs specified,                               jriver_c    = ', jriver_c
+         endif
+         if (jriver_alk.eq.0) then
+            WRITE(numout,*)     &
+            &   ' *no* riverine alkalinity input,                            jriver_alk  = ', jriver_alk
+         elseif (jriver_alk.eq.1) then
+            WRITE(numout,*)     &
+            &   ' riverine alkalinity concentrations specified,              jriver_alk  = ', jriver_alk
+         elseif (jriver_alk.eq.2) then
+            WRITE(numout,*)     &
+            &   ' riverine alkalinity inputs specified,                      jriver_alk  = ', jriver_alk
+         endif
+         !! AXY (19/07/12): prevent (gross) stupidity on part of user
+         if (jriver_dep.lt.1.or.jriver_dep.ge.jpk) then
+            jriver_dep = 1
+         endif
+         WRITE(numout,*)     &
+         &   ' riverine input applied to down to depth k = ...            jriver_dep  = ', jriver_dep
+!!
+!! Miscellaneous
+         WRITE(numout,*) '=== Miscellaneous'
+         WRITE(numout,*)     &
+         &   ' diatom frustule dissolution rate,                          xsdiss      = ', xsdiss
+!!
+!! Gravitational sinking      
+         WRITE(numout,*) '=== Gravitational sinking'
+         WRITE(numout,*)     &
+         &   ' detritus gravitational sinking rate,                       vsed        = ', vsed
+         WRITE(numout,*)     & 
+         &   ' coefficient for Martin et al. (1987) remineralisation,     xhr         = ', xhr
+!!
+!! Non-Medusa parameters
+         WRITE(numout,*) '=== Non-Medusa parameters'
+         WRITE(numout,*)     & 
+         &   ' time coeff of POC in sediments,                            sedlam      = ', sedlam
+         WRITE(numout,*)     &
+         &   ' Sediment geol loss for POC,                                sedlostpoc  = ', sedlostpoc
+         WRITE(numout,*)     &
+         &   ' Vert layer for diagnostic of vertical flux,                jpkp        = ', jpkb
+!!
+!! UKESM1 - new diagnostics  !! Jpalm; AXY (08/07/15)
+         WRITE(numout,*) '=== UKESM1-related parameters'
+         WRITE(numout,*)     &
+         &   ' include DMS diagnostic?,                                   jdms        = ', jdms
+         if (jdms_input .eq. 0) then
+            WRITE(numout,*)     &
+            &   ' use instant (0) or diel-avg (1) inputs,                    jdms_input  = instantaneous'
+         else
+            WRITE(numout,*)     &
+            &   ' use instant (0) or diel-avg (1) inputs,                    jdms_input  = diel-average'
+         endif
+	 if (jdms_model .eq. 1) then
+            WRITE(numout,*)     &
+            &   ' choice of DMS model passed to atmosphere,                  jdms_model  = Anderson et al. (2001)'
+	 elseif (jdms_model .eq. 2) then
+            WRITE(numout,*)     &
+            &   ' choice of DMS model passed to atmosphere,                  jdms_model  = Simo & Dachs (2002)'
+	 elseif (jdms_model .eq. 3) then
+            WRITE(numout,*)     &
+            &   ' choice of DMS model passed to atmosphere,                  jdms_model  = Aranami & Tsunogai (2004)'
+	 elseif (jdms_model .eq. 4) then
+            WRITE(numout,*)     &
+            &   ' choice of DMS model passed to atmosphere,                  jdms_model  = Halloran et al. (2010)'
+	 elseif (jdms_model .eq. 5) then
+            WRITE(numout,*)     &
+            &   ' choice of DMS model passed to atmosphere,                  jdms_model  = Anderson et al. (2001; modified)'
+         endif
+!!
+      ENDIF
+!!
+!! Key depth positions (with thanks to Andrew Coward for bug-fixing this bit)
+      DO jk = 1,jpk
+         !! level thickness
+         fthk  = e3t_1d(jk)
+         !! level depth (top of level)
+         fdep  = gdepw_1d(jk)
+         !! level depth (bottom of level)
+         fdep1 = fdep + fthk
+         !!
+         if (fdep.lt.100.0.AND.fdep1.gt.100.0) then        !  100 m
+            i0100 = jk
+         elseif (fdep.lt.150.0.AND.fdep1.gt.150.0) then    !  150 m (for BASIN)
+            i0150 = jk
+         elseif (fdep.lt.200.0.AND.fdep1.gt.200.0) then    !  200 m
+            i0200 = jk
+         elseif (fdep.lt.500.0.AND.fdep1.gt.500.0) then    !  500 m
+            i0500 = jk
+         elseif (fdep.lt.1000.0.AND.fdep1.gt.1000.0) then  ! 1000 m
+            i1000 = jk
+         elseif (fdep1.lt.1100.0) then                     ! 1100 m (for Moore et al. sedimentary iron)
+            i1100 = jk
+         endif
+      enddo
+      !!
+      IF(lwp) THEN
+          WRITE(numout,*) '=== Position of key depths'
+          WRITE(numout,*)     & 
+          &   ' jk position of  100 m horizon                              i0100       = ', i0100
+          WRITE(numout,*)     &
+          &   ' jk position of  150 m horizon                              i0150       = ', i0150
+          WRITE(numout,*)     & 
+          &   ' jk position of  200 m horizon                              i0200       = ', i0200
+          WRITE(numout,*)     & 
+          &   ' jk position of  500 m horizon                              i0500       = ', i0500
+          WRITE(numout,*)     & 
+          &   ' jk position of 1000 m horizon                              i1000       = ', i1000
+          WRITE(numout,*)     & 
+          &   ' jk position of 1100 m horizon [*]                          i1100       = ', i1100
+          WRITE(numout,*) 'Got here ' , SIZE(friver_dep)
+          CALL flush(numout)
+      ENDIF
+
+#if defined key_roam
+
+      ! 1.4b namelist natroam : ROAM parameters
+      ! ---------------------------------------
+      
+      xthetaphy = 0.
+      xthetazoo = 0.
+      xthetanit = 0.
+      xthetarem = 0.
+      xo2min    = 0.
+
+      !READ(numnatm,natroam)
+         ! Namelist natroam
+         ! -------------------
+         REWIND( numnatp_ref )              ! Namelist natroam in reference namelist : MEDUSA diagnostics
+         READ  ( numnatp_ref, natroam, IOSTAT = ios, ERR = 905)
+905      IF( ios /= 0 ) CALL ctl_nam ( ios , 'natroam in reference namelist', lwp )
+
+         REWIND( numnatp_cfg )              ! Namelist natroam in configuration namelist : MEDUSA diagnostics
+         READ  ( numnatp_cfg, natroam, IOSTAT = ios, ERR = 906 )
+906      IF( ios /= 0 ) CALL ctl_nam ( ios , 'natroam in configuration namelist', lwp )
+         IF(lwm) WRITE ( numonp, natroam )
+
+!! ROAM carbon, alkalinity and oxygen cycle parameters
+!!       xthetaphy :  oxygen evolution/consumption by phytoplankton
+!!       xthetazoo :  oxygen consumption by zooplankton
+!!       xthetanit :  oxygen consumption by nitrogen remineralisation
+!!       xthetarem :  oxygen consumption by carbon remineralisation
+!!       xo2min    :  oxygen minimum concentration
+
+      IF(lwp) THEN
+          WRITE(numout,*) 'natroam'
+          WRITE(numout,*) ' '
+!!
+!! ROAM carbon, alkalinity and oxygen cycle parameters
+          WRITE(numout,*) '=== ROAM carbon, alkalinity and oxygen cycle parameters'
+          WRITE(numout,*)     &
+          &   ' oxygen evolution/consumption by phytoplankton              xthetaphy   = ', xthetaphy
+          WRITE(numout,*)     &
+          &   ' oxygen consumption by zooplankton                          xthetazoo   = ', xthetazoo
+          WRITE(numout,*)     &
+          &   ' oxygen consumption by nitrogen remineralisation            xthetanit   = ', xthetanit
+          WRITE(numout,*)     &
+          &   ' oxygen consumption by carbon remineralisation              xthetarem   = ', xthetarem
+          WRITE(numout,*)     &
+          &   ' oxygen minimum concentration                               xo2min      = ', xo2min
+       ENDIF
+
+#endif
+
+      CALL flush(numout)
+
+      ! 1.5 namelist natopt : parameters for optic
+      ! ------------------------------------------
+
+      xkg0  = 0.
+      xkr0  = 0.
+      xkgp  = 0.
+      xkrp  = 0.
+      xlg   = 0.
+      xlr   = 0.
+      rpig  = 0.
+
+      !READ(numnatm,natopt)
+         ! Namelist natopt
+         ! -------------------
+         REWIND( numnatp_ref )              ! Namelist natopt in reference namelist : MEDUSA diagnostics
+         READ  ( numnatp_ref, natopt, IOSTAT = ios, ERR = 907)
+907      IF( ios /= 0 ) CALL ctl_nam ( ios , 'natopt in reference namelist', lwp )
+
+         REWIND( numnatp_cfg )              ! Namelist natopt in configuration namelist : MEDUSA diagnostics
+         READ  ( numnatp_cfg, natopt, IOSTAT = ios, ERR = 908 )
+908      IF( ios /= 0 ) CALL ctl_nam ( ios , 'natopt in configuration namelist', lwp )
+         IF(lwm) WRITE ( numonp, natopt )
+
+      IF(lwp) THEN
+         WRITE(numout,*) 'natopt'
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' green   water absorption coeff  xkg0  = ',xkg0
+         WRITE(numout,*) ' red water absorption coeff      xkr0  = ',xkr0
+         WRITE(numout,*) ' pigment red absorption coeff    xkrp  = ',xkrp
+         WRITE(numout,*) ' pigment green absorption coeff  xkgp  = ',xkgp
+         WRITE(numout,*) ' green chl exposant              xlg   = ',xlg
+         WRITE(numout,*) ' red   chl exposant              xlr   = ',xlr
+         WRITE(numout,*) ' chla/chla+phea ratio            rpig  = ',rpig
+         WRITE(numout,*) ' '
+
+      ENDIF
+
+      IF(lwp) THEN
+         WRITE(numout,*) 'NaN check'
+         WRITE(numout,*) ' '
+         q1 = -1.
+         q2 = 0.
+         q3 = log(q1)
+         write (numout,*) 'q3 = ', q3
+         if ( ieee_is_nan( q3 ) ) then
+            write (numout,*) 'NaN detected'
+         else
+            write (numout,*) 'NaN not detected'
+         endif
+         WRITE(numout,*) ' '
+       ENDIF
+
+   END SUBROUTINE trc_nam_medusa
+   
+   SUBROUTINE trc_nam_iom_medusa
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_nam_iom_medusa  ***
+      !!
+      !! ** Purpose : read all diag requested in iodef file through iom_use
+      !!              So it is done only once 
+      !!            ** All diagnostic MEDUSA could asked are registered in
+      !!            the med_diag type with a boolean value
+      !!            So if required, one diagnostic will be true.
+      !!
+      !!---------------------------------------------------------------------
+      !!
+      !!
+      !!----------------------------------------------------------------------            
+      !! Variable conventions
+      !!----------------------------------------------------------------------
+      !!
+      IF (iom_use("INVTN")) THEN 
+          med_diag%INVTN%dgsave = .TRUE.
+      ELSE 
+          med_diag%INVTN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INVTSI")) THEN 
+          med_diag%INVTSI%dgsave = .TRUE.
+      ELSE 
+          med_diag%INVTSI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INVTFE")) THEN 
+          med_diag%INVTFE%dgsave = .TRUE.
+      ELSE 
+          med_diag%INVTFE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PRN")) THEN 
+          med_diag%PRN%dgsave = .TRUE.
+      ELSE 
+          med_diag%PRN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MPN")) THEN 
+          med_diag%MPN%dgsave = .TRUE.
+      ELSE 
+          med_diag%MPN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PRD")) THEN 
+          med_diag%PRD%dgsave = .TRUE.
+      ELSE 
+          med_diag%PRD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MPD")) THEN 
+          med_diag%MPD%dgsave = .TRUE.
+      ELSE 
+          med_diag%MPD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DSED")) THEN 
+          med_diag%DSED%dgsave = .TRUE.
+      ELSE 
+          med_diag%DSED%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OPAL")) THEN 
+          med_diag%OPAL%dgsave = .TRUE.
+      ELSE 
+          med_diag%OPAL%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OPALDISS")) THEN 
+          med_diag%OPALDISS%dgsave = .TRUE.
+      ELSE 
+          med_diag%OPALDISS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMIPn")) THEN 
+          med_diag%GMIPn%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMIPn%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMID")) THEN 
+          med_diag%GMID%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMID%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MZMI")) THEN 
+          med_diag%MZMI%dgsave = .TRUE.
+      ELSE 
+          med_diag%MZMI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMEPN")) THEN 
+          med_diag%GMEPN%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMEPN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMEPD")) THEN 
+          med_diag%GMEPD%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMEPD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMEZMI")) THEN 
+          med_diag%GMEZMI%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMEZMI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMED")) THEN 
+          med_diag%GMED%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMED%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MZME")) THEN 
+          med_diag%MZME%dgsave = .TRUE.
+      ELSE 
+          med_diag%MZME%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DEXP")) THEN 
+          med_diag%DEXP%dgsave = .TRUE.
+      ELSE 
+          med_diag%DEXP%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DETN")) THEN 
+          med_diag%DETN%dgsave = .TRUE.
+      ELSE 
+          med_diag%DETN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MDET")) THEN 
+          med_diag%MDET%dgsave = .TRUE.
+      ELSE 
+          med_diag%MDET%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("AEOLIAN")) THEN 
+          med_diag%AEOLIAN%dgsave = .TRUE.
+      ELSE 
+          med_diag%AEOLIAN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BENTHIC")) THEN 
+          med_diag%BENTHIC%dgsave = .TRUE.
+      ELSE 
+          med_diag%BENTHIC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SCAVENGE")) THEN 
+          med_diag%SCAVENGE%dgsave = .TRUE.
+      ELSE 
+          med_diag%SCAVENGE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PN_JLIM")) THEN 
+          med_diag%PN_JLIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PN_JLIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PN_NLIM")) THEN 
+          med_diag%PN_NLIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PN_NLIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PN_FELIM")) THEN 
+          med_diag%PN_FELIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PN_FELIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PD_JLIM")) THEN 
+          med_diag%PD_JLIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PD_JLIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PD_NLIM")) THEN 
+          med_diag%PD_NLIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PD_NLIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PD_FELIM")) THEN 
+          med_diag%PD_FELIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PD_FELIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PD_SILIM")) THEN 
+          med_diag%PD_SILIM%dgsave = .TRUE.
+      ELSE 
+          med_diag%PD_SILIM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PDSILIM2")) THEN 
+          med_diag%PDSILIM2%dgsave = .TRUE.
+      ELSE 
+          med_diag%PDSILIM2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDT__100")) THEN 
+          med_diag%SDT__100%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDT__100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDT__200")) THEN 
+          med_diag%SDT__200%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDT__200%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDT__500")) THEN 
+          med_diag%SDT__500%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDT__500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDT_1000")) THEN 
+          med_diag%SDT_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDT_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("TOTREG_N")) THEN 
+          med_diag%TOTREG_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%TOTREG_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("TOTRG_SI")) THEN 
+          med_diag%TOTRG_SI%dgsave = .TRUE.
+      ELSE 
+          med_diag%TOTRG_SI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REG__100")) THEN 
+          med_diag%REG__100%dgsave = .TRUE.
+      ELSE 
+          med_diag%REG__100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REG__200")) THEN 
+          med_diag%REG__200%dgsave = .TRUE.
+      ELSE 
+          med_diag%REG__200%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REG__500")) THEN 
+          med_diag%REG__500%dgsave = .TRUE.
+      ELSE 
+          med_diag%REG__500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REG_1000")) THEN 
+          med_diag%REG_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%REG_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FASTN")) THEN 
+          med_diag%FASTN%dgsave = .TRUE.
+      ELSE 
+          med_diag%FASTN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FASTSI")) THEN 
+          med_diag%FASTSI%dgsave = .TRUE.
+      ELSE 
+          med_diag%FASTSI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FASTFE")) THEN 
+          med_diag%FASTFE%dgsave = .TRUE.
+      ELSE 
+          med_diag%FASTFE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FASTC")) THEN 
+          med_diag%FASTC%dgsave = .TRUE.
+      ELSE 
+          med_diag%FASTC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FASTCA")) THEN 
+          med_diag%FASTCA%dgsave = .TRUE.
+      ELSE 
+          med_diag%FASTCA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDT__100")) THEN 
+          med_diag%FDT__100%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDT__100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDT__200")) THEN 
+          med_diag%FDT__200%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDT__200%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDT__500")) THEN 
+          med_diag%FDT__500%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDT__500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDT_1000")) THEN 
+          med_diag%FDT_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDT_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RG__100F")) THEN 
+          med_diag%RG__100F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RG__100F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RG__200F")) THEN 
+          med_diag%RG__200F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RG__200F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RG__500F")) THEN 
+          med_diag%RG__500F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RG__500F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RG_1000F")) THEN 
+          med_diag%RG_1000F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RG_1000F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDS__100")) THEN 
+          med_diag%FDS__100%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDS__100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDS__200")) THEN 
+          med_diag%FDS__200%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDS__200%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDS__500")) THEN 
+          med_diag%FDS__500%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDS__500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FDS_1000")) THEN 
+          med_diag%FDS_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%FDS_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RGS_100F")) THEN 
+          med_diag%RGS_100F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RGS_100F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RGS_200F")) THEN 
+          med_diag%RGS_200F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RGS_200F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RGS_500F")) THEN 
+          med_diag%RGS_500F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RGS_500F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RGS1000F")) THEN 
+          med_diag%RGS1000F%dgsave = .TRUE.
+      ELSE 
+          med_diag%RGS1000F%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMINN")) THEN 
+          med_diag%REMINN%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMINN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMINSI")) THEN 
+          med_diag%REMINSI%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMINSI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMINFE")) THEN 
+          med_diag%REMINFE%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMINFE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMINC")) THEN 
+          med_diag%REMINC%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMINC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMINCA")) THEN 
+          med_diag%REMINCA%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMINCA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SEAFLRN")) THEN 
+          med_diag%SEAFLRN%dgsave = .TRUE.
+      ELSE 
+          med_diag%SEAFLRN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SEAFLRSI")) THEN 
+          med_diag%SEAFLRSI%dgsave = .TRUE.
+      ELSE 
+          med_diag%SEAFLRSI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SEAFLRFE")) THEN 
+          med_diag%SEAFLRFE%dgsave = .TRUE.
+      ELSE 
+          med_diag%SEAFLRFE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SEAFLRC")) THEN 
+          med_diag%SEAFLRC%dgsave = .TRUE.
+      ELSE 
+          med_diag%SEAFLRC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SEAFLRCA")) THEN 
+          med_diag%SEAFLRCA%dgsave = .TRUE.
+      ELSE 
+          med_diag%SEAFLRCA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MED_QSR")) THEN 
+          med_diag%MED_QSR%dgsave = .TRUE.
+      ELSE 
+          med_diag%MED_QSR%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MED_XPAR")) THEN 
+          med_diag%MED_XPAR%dgsave = .TRUE.
+      ELSE 
+          med_diag%MED_XPAR%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTFLX_N")) THEN 
+          med_diag%INTFLX_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTFLX_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTFLX_SI")) THEN 
+          med_diag%INTFLX_SI%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTFLX_SI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTFLX_FE")) THEN 
+          med_diag%INTFLX_FE%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTFLX_FE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INT_PN")) THEN 
+          med_diag%INT_PN%dgsave = .TRUE.
+      ELSE 
+          med_diag%INT_PN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INT_PD")) THEN 
+          med_diag%INT_PD%dgsave = .TRUE.
+      ELSE 
+          med_diag%INT_PD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ML_PRN")) THEN 
+          med_diag%ML_PRN%dgsave = .TRUE.
+      ELSE 
+          med_diag%ML_PRN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ML_PRD")) THEN 
+          med_diag%ML_PRD%dgsave = .TRUE.
+      ELSE 
+          med_diag%ML_PRD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCAL_CCD")) THEN 
+          med_diag%OCAL_CCD%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCAL_CCD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCAL_LVL")) THEN 
+          med_diag%OCAL_LVL%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCAL_LVL%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FE_0000")) THEN 
+          med_diag%FE_0000%dgsave = .TRUE.
+      ELSE 
+          med_diag%FE_0000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FE_0100")) THEN 
+          med_diag%FE_0100%dgsave = .TRUE.
+      ELSE 
+          med_diag%FE_0100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FE_0200")) THEN 
+          med_diag%FE_0200%dgsave = .TRUE.
+      ELSE 
+          med_diag%FE_0200%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FE_0500")) THEN 
+          med_diag%FE_0500%dgsave = .TRUE.
+      ELSE 
+          med_diag%FE_0500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FE_1000")) THEN 
+          med_diag%FE_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%FE_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MED_XZE")) THEN 
+          med_diag%MED_XZE%dgsave = .TRUE.
+      ELSE 
+          med_diag%MED_XZE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("WIND")) THEN 
+          med_diag%WIND%dgsave = .TRUE.
+      ELSE 
+          med_diag%WIND%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ATM_PCO2")) THEN 
+          med_diag%ATM_PCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%ATM_PCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_PH")) THEN 
+          med_diag%OCN_PH%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_PH%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_PCO2")) THEN 
+          med_diag%OCN_PCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_PCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCNH2CO3")) THEN 
+          med_diag%OCNH2CO3%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCNH2CO3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_HCO3")) THEN 
+          med_diag%OCN_HCO3%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_HCO3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_CO3")) THEN 
+          med_diag%OCN_CO3%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_CO3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("CO2FLUX")) THEN 
+          med_diag%CO2FLUX%dgsave = .TRUE.
+      ELSE 
+          med_diag%CO2FLUX%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OM_CAL")) THEN 
+          med_diag%OM_CAL%dgsave = .TRUE.
+      ELSE 
+          med_diag%OM_CAL%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OM_ARG")) THEN 
+          med_diag%OM_ARG%dgsave = .TRUE.
+      ELSE 
+          med_diag%OM_ARG%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("TCO2")) THEN 
+          med_diag%TCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%TCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("TALK")) THEN 
+          med_diag%TALK%dgsave = .TRUE.
+      ELSE 
+          med_diag%TALK%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("KW660")) THEN 
+          med_diag%KW660%dgsave = .TRUE.
+      ELSE 
+          med_diag%KW660%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ATM_PP0")) THEN 
+          med_diag%ATM_PP0%dgsave = .TRUE.
+      ELSE 
+          med_diag%ATM_PP0%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2FLUX")) THEN 
+          med_diag%O2FLUX%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2FLUX%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2SAT")) THEN 
+          med_diag%O2SAT%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2SAT%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("CAL_CCD")) THEN 
+          med_diag%CAL_CCD%dgsave = .TRUE.
+      ELSE 
+          med_diag%CAL_CCD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ARG_CCD")) THEN 
+          med_diag%ARG_CCD%dgsave = .TRUE.
+      ELSE 
+          med_diag%ARG_CCD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SFR_OCAL")) THEN 
+          med_diag%SFR_OCAL%dgsave = .TRUE.
+      ELSE 
+          med_diag%SFR_OCAL%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SFR_OARG")) THEN 
+          med_diag%SFR_OARG%dgsave = .TRUE.
+      ELSE 
+          med_diag%SFR_OARG%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("N_PROD")) THEN 
+          med_diag%N_PROD%dgsave = .TRUE.
+      ELSE 
+          med_diag%N_PROD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("N_CONS")) THEN 
+          med_diag%N_CONS%dgsave = .TRUE.
+      ELSE 
+          med_diag%N_CONS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("C_PROD")) THEN 
+          med_diag%C_PROD%dgsave = .TRUE.
+      ELSE 
+          med_diag%C_PROD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("C_CONS")) THEN 
+          med_diag%C_CONS%dgsave = .TRUE.
+      ELSE 
+          med_diag%C_CONS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2_PROD")) THEN 
+          med_diag%O2_PROD%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2_PROD%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2_CONS")) THEN 
+          med_diag%O2_CONS%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2_CONS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2_ANOX")) THEN 
+          med_diag%O2_ANOX%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2_ANOX%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RR_0100")) THEN 
+          med_diag%RR_0100%dgsave = .TRUE.
+      ELSE 
+          med_diag%RR_0100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RR_0500")) THEN 
+          med_diag%RR_0500%dgsave = .TRUE.
+      ELSE 
+          med_diag%RR_0500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RR_1000")) THEN 
+          med_diag%RR_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%RR_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("IBEN_N")) THEN 
+          med_diag%IBEN_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%IBEN_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("IBEN_FE")) THEN 
+          med_diag%IBEN_FE%dgsave = .TRUE.
+      ELSE 
+          med_diag%IBEN_FE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("IBEN_C")) THEN 
+          med_diag%IBEN_C%dgsave = .TRUE.
+      ELSE 
+          med_diag%IBEN_C%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("IBEN_SI")) THEN 
+          med_diag%IBEN_SI%dgsave = .TRUE.
+      ELSE 
+          med_diag%IBEN_SI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("IBEN_CA")) THEN 
+          med_diag%IBEN_CA%dgsave = .TRUE.
+      ELSE 
+          med_diag%IBEN_CA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OBEN_N")) THEN 
+          med_diag%OBEN_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%OBEN_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OBEN_FE")) THEN 
+          med_diag%OBEN_FE%dgsave = .TRUE.
+      ELSE 
+          med_diag%OBEN_FE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OBEN_C")) THEN 
+          med_diag%OBEN_C%dgsave = .TRUE.
+      ELSE 
+          med_diag%OBEN_C%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OBEN_SI")) THEN 
+          med_diag%OBEN_SI%dgsave = .TRUE.
+      ELSE 
+          med_diag%OBEN_SI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OBEN_CA")) THEN 
+          med_diag%OBEN_CA%dgsave = .TRUE.
+      ELSE 
+          med_diag%OBEN_CA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BEN_N")) THEN 
+          med_diag%BEN_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%BEN_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BEN_FE")) THEN 
+          med_diag%BEN_FE%dgsave = .TRUE.
+      ELSE 
+          med_diag%BEN_FE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BEN_C")) THEN 
+          med_diag%BEN_C%dgsave = .TRUE.
+      ELSE 
+          med_diag%BEN_C%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BEN_SI")) THEN 
+          med_diag%BEN_SI%dgsave = .TRUE.
+      ELSE 
+          med_diag%BEN_SI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BEN_CA")) THEN 
+          med_diag%BEN_CA%dgsave = .TRUE.
+      ELSE 
+          med_diag%BEN_CA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RUNOFF")) THEN 
+          med_diag%RUNOFF%dgsave = .TRUE.
+      ELSE 
+          med_diag%RUNOFF%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RIV_N")) THEN 
+          med_diag%RIV_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%RIV_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RIV_SI")) THEN 
+          med_diag%RIV_SI%dgsave = .TRUE.
+      ELSE 
+          med_diag%RIV_SI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RIV_C")) THEN 
+          med_diag%RIV_C%dgsave = .TRUE.
+      ELSE 
+          med_diag%RIV_C%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("RIV_ALK")) THEN 
+          med_diag%RIV_ALK%dgsave = .TRUE.
+      ELSE 
+          med_diag%RIV_ALK%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DETC")) THEN 
+          med_diag%DETC%dgsave = .TRUE.
+      ELSE 
+          med_diag%DETC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDC__100")) THEN 
+          med_diag%SDC__100%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDC__100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDC__200")) THEN 
+          med_diag%SDC__200%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDC__200%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDC__500")) THEN 
+          med_diag%SDC__500%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDC__500%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("SDC_1000")) THEN 
+          med_diag%SDC_1000%dgsave = .TRUE.
+      ELSE 
+          med_diag%SDC_1000%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INVTC")) THEN 
+          med_diag%INVTC%dgsave = .TRUE.
+      ELSE 
+          med_diag%INVTC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INVTALK")) THEN 
+          med_diag%INVTALK%dgsave = .TRUE.
+      ELSE 
+          med_diag%INVTALK%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INVTO2")) THEN 
+          med_diag%INVTO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%INVTO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("LYSO_CA")) THEN 
+          med_diag%LYSO_CA%dgsave = .TRUE.
+      ELSE 
+          med_diag%LYSO_CA%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("COM_RESP")) THEN 
+          med_diag%COM_RESP%dgsave = .TRUE.
+      ELSE 
+          med_diag%COM_RESP%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PN_LLOSS")) THEN 
+          med_diag%PN_LLOSS%dgsave = .TRUE.
+      ELSE 
+          med_diag%PN_LLOSS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PD_LLOSS")) THEN 
+          med_diag%PD_LLOSS%dgsave = .TRUE.
+      ELSE 
+          med_diag%PD_LLOSS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_LLOSS")) THEN 
+          med_diag%ZI_LLOSS%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_LLOSS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_LLOSS")) THEN 
+          med_diag%ZE_LLOSS%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_LLOSS%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_MES_N")) THEN 
+          med_diag%ZI_MES_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_MES_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_MES_D")) THEN 
+          med_diag%ZI_MES_D%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_MES_D%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_MES_C")) THEN 
+          med_diag%ZI_MES_C%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_MES_C%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_MESDC")) THEN 
+          med_diag%ZI_MESDC%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_MESDC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_EXCR")) THEN 
+          med_diag%ZI_EXCR%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_EXCR%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_RESP")) THEN 
+          med_diag%ZI_RESP%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_RESP%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZI_GROW")) THEN 
+          med_diag%ZI_GROW%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZI_GROW%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_MES_N")) THEN 
+          med_diag%ZE_MES_N%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_MES_N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_MES_D")) THEN 
+          med_diag%ZE_MES_D%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_MES_D%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_MES_C")) THEN 
+          med_diag%ZE_MES_C%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_MES_C%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_MESDC")) THEN 
+          med_diag%ZE_MESDC%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_MESDC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_EXCR")) THEN 
+          med_diag%ZE_EXCR%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_EXCR%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_RESP")) THEN 
+          med_diag%ZE_RESP%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_RESP%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZE_GROW")) THEN 
+          med_diag%ZE_GROW%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZE_GROW%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MDETC")) THEN 
+          med_diag%MDETC%dgsave = .TRUE.
+      ELSE 
+          med_diag%MDETC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMIDC")) THEN 
+          med_diag%GMIDC%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMIDC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("GMEDC")) THEN 
+          med_diag%GMEDC%dgsave = .TRUE.
+      ELSE 
+          med_diag%GMEDC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INT_ZMI")) THEN 
+          med_diag%INT_ZMI%dgsave = .TRUE.
+      ELSE 
+          med_diag%INT_ZMI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INT_ZME")) THEN 
+          med_diag%INT_ZME%dgsave = .TRUE.
+      ELSE 
+          med_diag%INT_ZME%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INT_DET")) THEN 
+          med_diag%INT_DET%dgsave = .TRUE.
+      ELSE 
+          med_diag%INT_DET%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INT_DTC")) THEN 
+          med_diag%INT_DTC%dgsave = .TRUE.
+      ELSE 
+          med_diag%INT_DTC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DMS_SURF")) THEN 
+          med_diag%DMS_SURF%dgsave = .TRUE.
+      ELSE 
+          med_diag%DMS_SURF%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DMS_ANDR")) THEN 
+          med_diag%DMS_ANDR%dgsave = .TRUE.
+      ELSE 
+          med_diag%DMS_ANDR%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DMS_SIMO")) THEN 
+          med_diag%DMS_SIMO%dgsave = .TRUE.
+      ELSE 
+          med_diag%DMS_SIMO%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DMS_ARAN")) THEN 
+          med_diag%DMS_ARAN%dgsave = .TRUE.
+      ELSE 
+          med_diag%DMS_ARAN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DMS_HALL")) THEN 
+          med_diag%DMS_HALL%dgsave = .TRUE.
+      ELSE 
+          med_diag%DMS_HALL%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DMS_ANDM")) THEN 
+          med_diag%DMS_ANDM%dgsave = .TRUE.
+      ELSE 
+          med_diag%DMS_ANDM%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ATM_XCO2")) THEN 
+          med_diag%ATM_XCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%ATM_XCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_FCO2")) THEN 
+          med_diag%OCN_FCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_FCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ATM_FCO2")) THEN 
+          med_diag%ATM_FCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%ATM_FCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_RHOSW")) THEN 
+          med_diag%OCN_RHOSW%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_RHOSW%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_SCHCO2")) THEN 
+          med_diag%OCN_SCHCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_SCHCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_KWCO2")) THEN 
+          med_diag%OCN_KWCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_KWCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_K0")) THEN 
+          med_diag%OCN_K0%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_K0%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("CO2STARAIR")) THEN 
+          med_diag%CO2STARAIR%dgsave = .TRUE.
+      ELSE 
+          med_diag%CO2STARAIR%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OCN_DPCO2")) THEN 
+          med_diag%OCN_DPCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%OCN_DPCO2%dgsave = .FALSE.
+      ENDIF
+      !!
+      IF  (iom_use("TPP3")) THEN 
+          med_diag%TPP3%dgsave = .TRUE.
+      ELSE 
+          med_diag%TPP3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DETFLUX3")) THEN 
+          med_diag%DETFLUX3%dgsave = .TRUE.
+      ELSE 
+          med_diag%DETFLUX3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMIN3N")) THEN 
+          med_diag%REMIN3N%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMIN3N%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PH3")) THEN 
+          med_diag%PH3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PH3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("OM_CAL3")) THEN 
+          med_diag%OM_CAL3%dgsave = .TRUE.
+      ELSE 
+          med_diag%OM_CAL3%dgsave = .FALSE.
+      ENDIF
+      !!
+      !!----------------------------------------------------------------------
+      !! AXY (03/11/16): add in additional CMIP6 diagnostics
+      !!----------------------------------------------------------------------
+      !!
+      !! 2D fields
+      IF  (iom_use("epC100")) THEN 
+          med_diag%epC100%dgsave = .TRUE.
+      ELSE 
+          med_diag%epC100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("epCALC100")) THEN 
+          med_diag%epCALC100%dgsave = .TRUE.
+      ELSE 
+          med_diag%epCALC100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("epN100")) THEN 
+          med_diag%epN100%dgsave = .TRUE.
+      ELSE 
+          med_diag%epN100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("epSI100")) THEN 
+          med_diag%epSI100%dgsave = .TRUE.
+      ELSE 
+          med_diag%epSI100%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FGCO2")) THEN 
+          med_diag%FGCO2%dgsave = .TRUE.
+      ELSE 
+          med_diag%FGCO2%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTDISSIC")) THEN 
+          med_diag%INTDISSIC%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTDISSIC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTDISSIN")) THEN 
+          med_diag%INTDISSIN%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTDISSIN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTDISSISI")) THEN 
+          med_diag%INTDISSISI%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTDISSISI%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("INTTALK")) THEN 
+          med_diag%INTTALK%dgsave = .TRUE.
+      ELSE 
+          med_diag%INTTALK%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2min")) THEN 
+          med_diag%O2min%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2min%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("ZO2min")) THEN 
+          med_diag%ZO2min%dgsave = .TRUE.
+      ELSE 
+          med_diag%ZO2min%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FBDDTALK")) THEN 
+          med_diag%FBDDTALK%dgsave = .TRUE.
+      ELSE 
+          med_diag%FBDDTALK%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FBDDTDIC")) THEN 
+          med_diag%FBDDTDIC%dgsave = .TRUE.
+      ELSE 
+          med_diag%FBDDTDIC%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FBDDTDIFE")) THEN 
+          med_diag%FBDDTDIFE%dgsave = .TRUE.
+      ELSE 
+          med_diag%FBDDTDIFE%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FBDDTDIN")) THEN 
+          med_diag%FBDDTDIN%dgsave = .TRUE.
+      ELSE 
+          med_diag%FBDDTDIN%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FBDDTDISI")) THEN 
+          med_diag%FBDDTDISI%dgsave = .TRUE.
+      ELSE 
+          med_diag%FBDDTDISI%dgsave = .FALSE.
+      ENDIF
+      !!
+      !! 3D
+      IF  (iom_use("TPPD3")) THEN 
+          med_diag%TPPD3%dgsave = .TRUE.
+      ELSE 
+          med_diag%TPPD3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BDDTALK3")) THEN 
+          med_diag%BDDTALK3%dgsave = .TRUE.
+      ELSE 
+          med_diag%BDDTALK3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BDDTDIC3")) THEN 
+          med_diag%BDDTDIC3%dgsave = .TRUE.
+      ELSE 
+          med_diag%BDDTDIC3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BDDTDIFE3")) THEN 
+          med_diag%BDDTDIFE3%dgsave = .TRUE.
+      ELSE 
+          med_diag%BDDTDIFE3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BDDTDIN3")) THEN 
+          med_diag%BDDTDIN3%dgsave = .TRUE.
+      ELSE 
+          med_diag%BDDTDIN3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("BDDTDISI3")) THEN 
+          med_diag%BDDTDISI3%dgsave = .TRUE.
+      ELSE 
+          med_diag%BDDTDISI3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FD_NIT3")) THEN 
+          med_diag%FD_NIT3%dgsave = .TRUE.
+      ELSE 
+          med_diag%FD_NIT3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FD_SIL3")) THEN 
+          med_diag%FD_SIL3%dgsave = .TRUE.
+      ELSE 
+          med_diag%FD_SIL3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FD_CAR3")) THEN 
+          med_diag%FD_CAR3%dgsave = .TRUE.
+      ELSE 
+          med_diag%FD_CAR3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FD_CAL3")) THEN 
+          med_diag%FD_CAL3%dgsave = .TRUE.
+      ELSE 
+          med_diag%FD_CAL3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("CO33")) THEN 
+          med_diag%CO33%dgsave = .TRUE.
+      ELSE 
+          med_diag%CO33%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("CO3SATARAG3")) THEN 
+          med_diag%CO3SATARAG3%dgsave = .TRUE.
+      ELSE 
+          med_diag%CO3SATARAG3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("CO3SATCALC3")) THEN 
+          med_diag%CO3SATCALC3%dgsave = .TRUE.
+      ELSE 
+          med_diag%CO3SATCALC3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("DCALC3")) THEN 
+          med_diag%DCALC3%dgsave = .TRUE.
+      ELSE 
+          med_diag%DCALC3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("EXPC3")) THEN 
+          med_diag%EXPC3%dgsave = .TRUE.
+      ELSE 
+          med_diag%EXPC3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("EXPN3")) THEN 
+          med_diag%EXPN3%dgsave = .TRUE.
+      ELSE 
+          med_diag%EXPN3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FEDISS3")) THEN 
+          med_diag%FEDISS3%dgsave = .TRUE.
+      ELSE 
+          med_diag%FEDISS3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("FESCAV3")) THEN 
+          med_diag%FESCAV3%dgsave = .TRUE.
+      ELSE 
+          med_diag%FESCAV3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MIGRAZP3")) THEN 
+          med_diag%MIGRAZP3%dgsave = .TRUE.
+      ELSE 
+          med_diag%MIGRAZP3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MIGRAZD3")) THEN 
+          med_diag%MIGRAZD3%dgsave = .TRUE.
+      ELSE 
+          med_diag%MIGRAZD3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MEGRAZP3")) THEN 
+          med_diag%MEGRAZP3%dgsave = .TRUE.
+      ELSE 
+          med_diag%MEGRAZP3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MEGRAZD3")) THEN 
+          med_diag%MEGRAZD3%dgsave = .TRUE.
+      ELSE 
+          med_diag%MEGRAZD3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("MEGRAZZ3")) THEN 
+          med_diag%MEGRAZZ3%dgsave = .TRUE.
+      ELSE 
+          med_diag%MEGRAZZ3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("O2SAT3")) THEN 
+          med_diag%O2SAT3%dgsave = .TRUE.
+      ELSE 
+          med_diag%O2SAT3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PBSI3")) THEN 
+          med_diag%PBSI3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PBSI3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PCAL3")) THEN 
+          med_diag%PCAL3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PCAL3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("REMOC3")) THEN 
+          med_diag%REMOC3%dgsave = .TRUE.
+      ELSE 
+          med_diag%REMOC3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PNLIMJ3")) THEN 
+          med_diag%PNLIMJ3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PNLIMJ3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PNLIMN3")) THEN 
+          med_diag%PNLIMN3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PNLIMN3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PNLIMFE3")) THEN 
+          med_diag%PNLIMFE3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PNLIMFE3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PDLIMJ3")) THEN 
+          med_diag%PDLIMJ3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PDLIMJ3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PDLIMN3")) THEN 
+          med_diag%PDLIMN3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PDLIMN3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PDLIMFE3")) THEN 
+          med_diag%PDLIMFE3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PDLIMFE3%dgsave = .FALSE.
+      ENDIF
+      IF  (iom_use("PDLIMSI3")) THEN 
+          med_diag%PDLIMSI3%dgsave = .TRUE.
+      ELSE 
+          med_diag%PDLIMSI3%dgsave = .FALSE.
+      ENDIF
+
+   END SUBROUTINE   trc_nam_iom_medusa
+   
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                             No MEDUSA
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_nam_medusa                      ! Empty routine
+   END  SUBROUTINE  trc_nam_medusa
+#endif  
+
+   !!======================================================================
+END MODULE trcnam_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcopt_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcopt_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcopt_medusa.F90	(revision 9987)
@@ -0,0 +1,187 @@
+MODULE trcopt_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcopt_medusa  ***
+   !! TOP :   MEDUSA Compute the light availability in the water column
+   !!======================================================================
+   !! History :    -   !  1995-05  (M. Levy) Original code
+   !!              -   !  1999-09  (J.-M. Andre, M. Levy) 
+   !!              -   !  1999-11  (C. Menkes, M.-A. Foujols) itabe initial
+   !!              -   !  2000-02  (M.A. Foujols) change x**y par exp(y*log(x))
+   !!             2.0  !  2007-12  (C. Deltel, G. Madec)  F90
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                      MEDUSA bio-model
+   !!----------------------------------------------------------------------
+   !!   trc_opt_medusa        :   Compute the light availability in the water column
+   !!----------------------------------------------------------------------
+   USE oce_trc         !
+   USE trc
+   USE prtctl_trc      ! Print control for debbuging
+   USE sms_medusa
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_opt_medusa   ! called in trcprg.F90
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_opt_medusa( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_opt_medusa  ***
+      !!
+      !! ** Purpose :   computes the light propagation in the water column
+      !!              and the euphotic layer depth
+      !!
+      !! ** Method  :   local par is computed in w layers using light propagation
+      !!              mean par in t layers are computed by integration
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! index of the time stepping
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zpig                                    ! total pigment
+      REAL(wp) ::   zkr                                     ! total absorption coefficient in red
+      REAL(wp) ::   zkg                                     ! total absorption coefficient in green
+      REAL(wp) ::   totchl                                  ! total Chl concentreation
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zpar100         ! irradiance at euphotic layer depth
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zpar0m          ! irradiance just below the surface
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zparr, zparg    ! red and green compound of par
+
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+
+      !! AXY (20/11/14): alter this to report on first MEDUSA call
+      !! IF( kt == nit000 ) THEN
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_opt_medusa: MEDUSA optic-model'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+	 IF(lwp) WRITE(numout,*) ' kt =',kt
+      ENDIF
+
+      ! determination of surface irradiance
+      ! -----------------------------------
+      ! AXY (23/07/15): the inclusion of empirical DMS calculations requires
+      !                 daily averages of a series of properties that are
+      !                 used as inputs; these include surface irradiance; 
+      !                 here, this is taken advantage of to allow MEDUSA to
+      !                 base its submarine light field on daily average
+      !                 rather than "instantaneous" irradiance; largely
+      !                 because MEDUSA was originally formulated to work
+      !                 with diel average irradiance rather than a diel
+      !                 cycle; using key_avgqsr_medusa activates this
+      !                 functionality, while its absence gives default
+      !                 MEDUSA (which is whatever is supplied by NEMO)
+# if defined key_avgqsr_medusa
+      ! surface irradiance input is rolling average irradiance
+      zpar0m (:,:)   = zn_dms_qsr(:,:) * 0.43
+# else      
+      ! surface irradiance input is   instantaneous irradiance
+      zpar0m (:,:)   =        qsr(:,:) * 0.43
+# endif
+      ! AXY (22/08/14): when zpar0m = 0, zpar100 is also zero and calculating 
+      !                 euphotic depth is not possible (cf. the Arctic Octopus); 
+      !                 a "solution" to this is to set zpar0m to some minimal
+      !                 value such that zpar100 also has a non-zero value and
+      !                 euphotic depth can be calculated properly; note that,
+      !                 in older, non-diurnal versions of NEMO, this was much
+      !                 less of a problem; note also that, if pushed, I will
+      !                 claim that my minimal value of zpar0m refers to light
+      !                 from stars
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( zpar0m(ji,jj) <= 0.0 ) zpar0m(ji,jj) = 0.001  ! = 1 mW/m2
+         ENDDO
+      ENDDO
+      zpar100(:,:)   = zpar0m(:,:) * 0.01
+      xpar   (:,:,1) = zpar0m(:,:)
+      zparr  (:,:,1) = 0.5 * zpar0m(:,:)
+      zparg  (:,:,1) = 0.5 * zpar0m(:,:)
+
+      ! determination of xpar
+      ! ---------------------
+
+      DO jk = 2, jpk                     ! determination of local par in w levels
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               totchl =trn(ji,jj,jk-1,jpchn)+trn(ji,jj,jk-1,jpchd)
+               zpig = MAX( TINY(0.), totchl/rpig) 
+               zkr  = xkr0 + xkrp * EXP( xlr * LOG( zpig ) )
+               zkg  = xkg0 + xkgp * EXP( xlg * LOG( zpig ) )
+               zparr(ji,jj,jk) = zparr(ji,jj,jk-1) * EXP( -zkr * fse3t(ji,jj,jk-1) )
+               zparg(ji,jj,jk) = zparg(ji,jj,jk-1) * EXP( -zkg * fse3t(ji,jj,jk-1) )
+            END DO
+        END DO
+      END DO
+
+      DO jk = 1, jpkm1                   ! mean par in t levels
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               totchl =trn(ji,jj,jk  ,jpchn)+trn(ji,jj,jk  ,jpchd)
+               zpig = MAX( TINY(0.), totchl/rpig) 
+               zkr  = xkr0 + xkrp * EXP( xlr * LOG( zpig ) )
+               zkg  = xkg0 + xkgp * EXP( xlg * LOG( zpig ) )
+               zparr(ji,jj,jk)    = zparr(ji,jj,jk) / zkr / fse3t(ji,jj,jk) * ( 1 - EXP( -zkr*fse3t(ji,jj,jk) ) )
+               zparg(ji,jj,jk)    = zparg(ji,jj,jk) / zkg / fse3t(ji,jj,jk) * ( 1 - EXP( -zkg*fse3t(ji,jj,jk) ) )
+               xpar (ji,jj,jk) = MAX( zparr(ji,jj,jk) + zparg(ji,jj,jk), 1.e-15 )
+            END DO
+         END DO
+      END DO
+
+      ! 3. Determination of euphotic layer depth
+      ! ----------------------------------------
+
+      ! Euphotic layer bottom level
+      neln(:,:) = 1                                           ! initialisation of EL level
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+           DO ji = 1, jpi
+              IF( xpar(ji,jj,jk) >= zpar100(ji,jj) )   neln(ji,jj) = jk+1 ! 1rst T-level strictly below EL bottom
+              !                                                  ! nb. this is to ensure compatibility with
+              !                                                  ! nmld_trc definition in trd_mld_trc_zint
+           END DO
+         END DO
+      ENDDO
+
+      ! Euphotic layer depth
+      !! Jpalm -- 06-03-2017 -- add init xze, to avoid halo problems within the
+      !!                        writing process
+      xze(:,:) = 0.0
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            xze(ji,jj) = fsdepw( ji, jj, neln(ji,jj) )            ! exact EL depth
+         END DO
+      ENDDO 
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('opt')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc( tab4d=trn, mask=tmask, clinfo=ctrcnm )
+      ENDIF
+
+   END SUBROUTINE trc_opt_medusa
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE trc_opt_medusa( kt )                   ! Empty routine
+      INTEGER, INTENT( in ) ::   kt
+      WRITE(*,*) 'trc_opt_medusa: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_opt_medusa
+#endif 
+
+   !!======================================================================
+END MODULE  trcopt_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcoxy_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcoxy_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcoxy_medusa.F90	(revision 9987)
@@ -0,0 +1,280 @@
+MODULE trcoxy_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcoxy_medusa  ***
+   !! TOP :   MEDUSA
+   !!======================================================================
+   !! History :
+   !!  -   !  2011-07  (A. Yool)             added for ROAM project
+   !!----------------------------------------------------------------------
+#if defined key_medusa && defined key_roam
+   !!----------------------------------------------------------------------
+   !!                                        MEDUSA oxygen cycle
+   !!----------------------------------------------------------------------
+   !!   trc_oxy_medusa        :  
+   !!----------------------------------------------------------------------
+      USE oce_trc
+      USE trc
+      USE sms_medusa
+      USE lbclnk
+      USE prtctl_trc      ! Print control for debugging
+
+      IMPLICIT NONE
+      PRIVATE
+      
+      PUBLIC   trc_oxy_medusa    ! called in trc_bio_medusa
+      PUBLIC   oxy_sato          ! called in trc_bio_medusa
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+! The following is a map of the subroutines contained within this module
+! - trc_oxy_medusa
+!      - CALLS oxy_schmidt
+!      - CALLS oxy_sato
+
+CONTAINS
+
+!=======================================================================
+!
+   SUBROUTINE trc_oxy_medusa( pt, ps, kw660, pp0, o2,  &  !! inputs
+      kwo2, o2flux, o2sat )                               !! outputs
+!      
+!=======================================================================
+      !!
+      !! Title  : Calculates O2 change due to air-sea gas exchange
+      !! Author : Andrew Yool
+      !! Date   : 15/10/04 (revised 08/07/11)
+      !!
+      !! This subroutine calculates oxygen air-sea gas exchange in the
+      !! surface layer of the ocean.  The formulation is taken from one 
+      !! written by Ray Najjar for the OCMIP-2 project.  The routine
+      !! calls two other subroutines, oxy_schmidt.f (calculates Schmidt 
+      !! number of oxygen) and oxy_sato.f (calculates oxygen saturation 
+      !! concentration at 1 atm).
+      !!
+      !! AXY (23/06/15): revised to allow common gas transfer velocity
+      !!                 to be used for CO2 and O2; outputs of this
+      !!                 routine amended to mmol/m3 from mol/m3
+      !! 
+      !! Function inputs are (in order) : 
+      !!     pt      temperature                     (degrees C)
+      !!     ps      salinity                        (PSU)
+      !!     kw660   gas transfer velocity           (m/s)
+      !!     pp0     surface pressure                (divided by 1 atm)
+      !!     o2      surface O2 concentration        (mmol/m3)
+      !! (+) kwo2    gas transfer velocity for O2    (m/s)
+      !! (*) o2flux  exchange rate of oxygen         (mmol/m2/s)
+      !! (+) o2sat   oxygen saturation concentration (mmol/m3)
+      !! 
+      !! Where (*) is the function output (note its units).  
+      !!
+!=======================================================================
+
+      implicit none
+!
+      REAL(wp), INTENT( in )    :: pt
+      REAL(wp), INTENT( in )    :: ps
+      REAL(wp), INTENT( in )    :: kw660
+      REAL(wp), INTENT( in )    :: pp0
+      REAL(wp), INTENT( in )    :: o2
+      REAL(wp), INTENT( out )   :: kwo2, o2flux, o2sat
+!
+      REAL(wp) :: o2schmidt, o2sato, mol_o2
+!
+! Oxygen to mol / m3
+!
+      mol_o2 = o2 / 1000.
+!
+! Calculate oxygen Schmidt number
+! 
+      call oxy_schmidt(pt, o2schmidt)
+!
+! Calculate the transfer velocity for O2 (m/s)
+!
+      kwo2 = kw660 * (660 / o2schmidt)**0.5
+!
+! Calculate the saturation concentration for oxygen (mol/m3)
+!
+      call oxy_sato(pt, ps, o2sato)
+      o2sat = o2sato * pp0
+!
+! Calculate time rate of change of O2 due to gas exchange (mol/m3/s)
+!
+      o2flux = kwo2 * (o2sat - mol_o2)
+!
+! Oxygen flux and saturation to mmol / m3
+!
+      o2sat  =  o2sat * 1000.
+      o2flux = o2flux * 1000.
+!
+      END SUBROUTINE trc_oxy_medusa
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+   SUBROUTINE oxy_schmidt( pt, &  !! input
+      o2_schmidt )                !! output
+!      
+!=======================================================================
+      !!
+      !! Title  : Calculates Schmidt number for ocean uptake of O2
+      !! Author : Andrew Yool
+      !! Date   : 14/10/04 (revised 08/07/11)
+      !! 
+      !! This subroutine calculates the Schmidt number for O2 using sea 
+      !! surface temperature.  The code is based upon that developed as 
+      !! part of the OCMIP-2 project (1998-2000).  The coefficients used 
+      !! are taken from Keeling et al. (1998, GBC, 12, 141-163).
+      !! 
+      !! AXY (23/06/2015)
+      !! UPDATED: revised formulation from Wanninkhof (2014) for
+      !! consistency with MOCSY
+      !!
+      !! Winninkhof, R. (2014). Relationship between wind speed and gas
+      !! exchange over the ocean revisited. LIMNOLOGY AND OCEANOGRAPHY-METHODS
+      !! 12, 351-362, doi:10.4319/lom.2014.12.351
+      !!
+      !! Function inputs are (in order) : 
+      !!     t           temperature (degrees C)
+      !! (*) o2_schmidt  oxygen Schmidt number
+      !! 
+      !! Where (*) is the function output.
+      !!
+!=======================================================================
+
+      implicit none
+!
+      REAL(wp) :: pt, o2_schmidt
+      REAL(wp) :: a0, a1, a2, a3, a4
+!
+! AXY (23/06/15): OCMIP-2 coefficients
+!     data a0 /    1638.0 /
+!     data a1 /    -81.83 /
+!     data a2 /     1.483 /
+!     data a3 / -0.008004 /
+!
+! AXY (23/06/15): Wanninkhof (2014) coefficients
+      data a0 /     1920.4 /
+      data a1 /     -135.6 /
+      data a2 /     5.2121 /
+      data a3 /   -0.10939 /
+      data a4 / 0.00093777 /
+!
+!     o2_schmidt = a0 + pt*(a1 + pt*(a2 + pt*a3))
+      o2_schmidt = a0 + pt*(a1 + pt*(a2 + pt*(a3 + pt*a4)))
+!
+      END SUBROUTINE oxy_schmidt
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+!=======================================================================
+!
+   SUBROUTINE oxy_sato( pt, ps, &  !! inputs 
+      o2_sato )                    !! output
+!      
+!=======================================================================
+      !!
+      !! Title  : Calculates O2 saturation at 1 atm pressure
+      !! Author : Andrew Yool
+      !! Date   : 14/10/04 (revised 08/07/11)
+      !! 
+      !! This subroutine calculates the oxygen saturation concentration
+      !! at 1 atmosphere pressure in mol/m3 given ambient temperature
+      !! and salinity.  This formulation is (ostensibly) taken from 
+      !! Garcia & Gordon (1992, L&O, 1307-1312).  The function works
+      !! in the range -1.9 <= T <= 40, 0 <= S <= 42.
+      !!
+      !! Function inputs are (in order) : 
+      !!     pt       temperature (degrees C)
+      !!     ps       salinity (PSU)
+      !! (*) o2_sato  oxygen saturation (mol/m3)
+      !!
+      !! Where (*) is the function output (note its units).  
+      !!
+      !! Check value : T = 10, S = 35, oxy_sato = 0.282015 mol/m3
+      !!
+!=======================================================================
+
+      implicit none
+!
+      REAL(wp) :: pt, ps, o2_sato
+!
+      REAL(wp) :: a0, a1, a2, a3, a4, a5
+      REAL(wp) :: b0, b1, b2, b3
+      REAL(wp) :: c0
+!
+      REAL(wp) :: tt, tk, ts, ts2, ts3, ts4, ts5
+      REAL(wp) :: ans1, ans2
+!
+      data a0 /  2.00907    /
+      data a1 /  3.22014    /
+      data a2 /  4.05010    /
+      data a3 /  4.94457    /
+      data a4 / -2.56847E-1 /
+      data a5 /  3.88767    /
+!
+      data b0 / -6.24523E-3 /
+      data b1 / -7.37614E-3 /
+      data b2 / -1.03410E-2 /
+      data b3 / -8.17083E-3 /
+!
+      data c0 / -4.88682E-7 /
+!     
+      tt   = 298.15 - pt
+      tk   = 273.15 + pt
+      ts   = log(tt / tk)
+      ts2  = ts**2
+      ts3  = ts**3
+      ts4  = ts**4
+      ts5  = ts**5
+      ans1 = a0 + a1*ts + a2*ts2 + a3*ts3 + a4*ts4 + a5*ts5  &
+           + ps*(b0 + b1*ts + b2*ts2 + b3*ts3)               &
+           + c0*(ps*ps)
+      ans2 = exp(ans1)
+!
+!  Convert from ml/l to mol/m3
+!
+      o2_sato = (ans2 / 22391.6) * 1000.0
+!
+      END SUBROUTINE oxy_sato
+
+!=======================================================================
+!=======================================================================
+!=======================================================================
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+
+CONTAINS
+
+   SUBROUTINE trc_oxy_medusa( pt, ps, kw660, pp0, o2,  &  !! inputs
+      o2flux, o2sat )                                     !! outputs
+      USE par_kind
+
+      REAL(wp), INTENT( in )    :: pt
+      REAL(wp), INTENT( in )    :: ps
+      REAL(wp), INTENT( in )    :: kw660
+      REAL(wp), INTENT( in )    :: pp0
+      REAL(wp), INTENT( in )    :: o2
+      REAL(wp), INTENT( inout ) :: o2flux, o2sat
+
+      WRITE(*,*) 'trc_oxy_medusa: You should not have seen this print! error?', kt
+
+   END SUBROUTINE trc_oxy_medusa
+#endif
+
+   !!======================================================================
+END MODULE  trcoxy_medusa
+  
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcsed_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcsed_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcsed_medusa.F90	(revision 9987)
@@ -0,0 +1,423 @@
+MODULE trcsed_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcsed_medusa  ***
+   !! TOP :   MEDUSA Compute loss of organic matter in the sediments
+   !!======================================================================
+   !! History :    -   !  1995-06 (M. Levy)  original code
+   !!              -   !  2000-12 (E. Kestenare)  clean up
+   !!             2.0  !  2007-12  (C. Deltel, G. Madec)  F90 + simplifications
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!              -   !  2011-04  (A. Yool) updated for ROAM project
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                      MEDUSA bio-model
+   !!----------------------------------------------------------------------
+   !!   trc_sed_medusa        :  Compute loss of organic matter in the sediments
+   !!----------------------------------------------------------------------
+   USE oce_trc         !
+   USE trc
+   USE sms_medusa
+   !! AXY (10/02/09)
+   USE iom
+   !! USE trc_nam_dia                   ! JPALM 13-11-2015 -- if iom_use for diag
+   !! USE trc_nam_iom_medusa            ! JPALM 13-11-2015 -- if iom_use for diag
+   USE fldread                          !  time interpolation
+   USE lbclnk
+   USE prtctl_trc                       ! Print control for debbuging
+   !! JPALM (27-06-2016): add lk_oasis for CO2 and DMS coupling with atm
+   USE sbc_oce, ONLY: lk_oasis
+   USE oce,     ONLY: Dust_in_cpl
+   !! Check Dust dep
+# if defined key_debug_medusa   
+   !! USE trcrst, ONLY: trc_rst_dia_stat   !! variable stat
+# endif
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sed_medusa     ! called in ???
+   PUBLIC   trc_sed_medusa_sbc     
+   PUBLIC   trc_sed_medusa_dust 
+
+   !! * Module variables
+   !! INTEGER ::                   &
+     !! ryyss,                     &  !: number of seconds per year
+     !! rmtss                         !: number of seconds per month
+
+   !! AXY (10/02/09)
+   LOGICAL, PUBLIC  ::   bdustfer  !: boolean for dust input from the atmosphere
+   REAL(wp), PUBLIC ::                 &
+      sedfeinput = 1.e-9_wp  ,         &
+      dustsolub  = 0.014_wp
+   REAL(wp), PARAMETER :: Fe_dust_mratio = 0.035   !! Fe:dust mass ratio = 0.035
+   INTEGER , PARAMETER ::        nbtimes = 365     !: maximum number of times record in a file
+   INTEGER  :: ntimes_dust                         ! number of time steps in a file
+
+   INTEGER ::                          &
+      numdust,                         &
+      nflx1,  nflx2,                   &
+      nflx11, nflx12
+   
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_dust      ! structure of input dust
+
+   
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_sed_medusa( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sed_medusa  ***
+      !!
+      !! ** Purpose :   compute the now trend due to the vertical sedimentation of
+      !!              detritus and add it to the general trend of detritus equations
+      !!
+      !! ** Method  :   this ROUTINE compute not exactly the advection but the
+      !!              transport term, i.e.  dz(wt) and dz(ws)., dz(wtr)
+      !!              using an upstream scheme
+      !!              the now vertical advection of tracers is given by:
+      !!                      dz(trn wn) = 1/bt dk+1( e1t e2t vsed (trn) )
+      !!              add this trend now to the general trend of tracer (ta,sa,tra):
+      !!                             tra = tra + dz(trn wn)
+      !!        
+      !!              IF 'key_trc_diabio' is defined, the now vertical advection
+      !!              trend of passive tracers is saved for futher diagnostics.
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !! AXY (10/02/09)
+      INTEGER  ::   jnt
+      !!
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   ztra
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwork
+
+      !! AXY (10/02/09)
+      REAL(wp) ::   rfact2
+
+      CHARACTER (len=25) :: charout
+      
+      !! JPALM - 26-11-2015 -add iom_use for diagnostic
+       REAL(wp), POINTER, DIMENSION(:,:  ) :: zw2d
+      !!---------------------------------------------------------------------
+      !!
+      IF( lk_iomput) THEN  
+           IF( med_diag%DSED%dgsave ) THEN
+               CALL wrk_alloc( jpi, jpj,      zw2d )
+                zw2d(:,:)      = 0.0      !!
+           ENDIF
+      ENDIF
+      
+      !! AXY (10/02/09)
+      jnt = 1
+      rfact2 = 1.0
+
+      ! Number of seconds per year and per month
+      !! ryyss = nyear_len(1) * rday
+      !! rmtss = ryyss / raamo
+
+      !! AXY (20/11/14): alter this to report on first MEDUSA call
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_sed_medusa: MEDUSA sedimentation'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+	 IF(lwp) WRITE(numout,*) ' kt =',kt
+      ENDIF
+
+      ! sedimentation of detrital nitrogen : upstream scheme
+      ! ----------------------------------------------------
+      !
+      zwork(:,:,:) = 0.e0        ! initialisation of sinking variable
+      ! for detrital nitrogen sedimentation only - jpdet
+      zwork(:,:,1  ) = 0.e0      ! surface value set to zero
+      !!    DO ji = 1, jpi
+      !!       zirondep(ji,jj,1) = (dustsolub * dust(ji,jj) / (55.85 * rmtss) + 3.e-10 / ryyss) &
+      !!       & * rfact2 / fse3t(ji,jj,1)
+      !!       zsidep  (ji,jj)   = 8.8 * 0.075 * dust(ji,jj) * rfact2 / &
+      !!       & (fse3t(ji,jj,1) * 28.1 * rmtss)
+      !!    END DO
+      !! END DO
+
+      ! sedimentation of detrital nitrogen : upstream scheme
+      ! ----------------------------------------------------
+      !
+      zwork(:,:,:) = 0.e0        ! initialisation of sinking variable
+      ! for detrital nitrogen sedimentation only - jpdet
+      zwork(:,:,1  ) = 0.e0      ! surface value set to zero
+      zwork(:,:,jpk) = 0.e0      ! bottom value  set to zero
+      !
+      ! tracer flux at w-point: we use -vsed (downward flux)  with simplification : no e1*e2
+      DO jk = 2, jpk
+         ! AXY (17/07/14): change "0.d0" to "0."
+         ! zwork(:,:,jk) = -vsed * max(trn(:,:,jk-1,jpdet),0.d0) * tmask(:,:,jk-1)
+         zwork(:,:,jk) = -vsed * max(trn(:,:,jk-1,jpdet),0.) * tmask(:,:,jk-1)
+         !
+         ! AXY (16/01/14): stop sinking in upper 10m to reduce model instability 
+         !                 in shallower grid cells
+         ! if ( jk .lt. 9 ) zwork(:,:,jk) = 0.e0
+      END DO
+      !
+      ! tracer flux divergence at t-point added to the general trend
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1,jpi
+               ztra  = - ( zwork(ji,jj,jk) - zwork(ji,jj,jk+1) ) / fse3t(ji,jj,jk)
+               tra(ji,jj,jk,jpdet) = tra(ji,jj,jk,jpdet) + ztra
+               IF( med_diag%DSED%dgsave ) THEN
+                   zw2d(ji,jj) = zw2d(ji,jj) + ztra * fse3t(ji,jj,jk) * 86400.
+               ENDIF   
+                
+            END DO
+         END DO
+      END DO
+      !
+      IF( med_diag%DSED%dgsave ) THEN
+           CALL iom_put( "DSED"  ,  zw2d)
+           CALL wrk_dealloc( jpi, jpj,    zw2d  )
+      ENDIF
+      !!
+# if defined key_roam
+
+      ! sedimentation of detrital carbon : upstream scheme
+      ! --------------------------------------------------
+      !
+      zwork(:,:,:) = 0.e0        ! initialisation of sinking variable
+      ! for detrital carbon sedimentation only - jpdtc
+      zwork(:,:,1  ) = 0.e0      ! surface value set to zero
+      zwork(:,:,jpk) = 0.e0      ! bottom value  set to zero
+      !
+      ! tracer flux at w-point: we use -vsed (downward flux)  with simplification : no e1*e2
+      DO jk = 2, jpk
+         ! AXY (17/07/14): change "0.d0" to "0."
+         ! zwork(:,:,jk) = -vsed * max(trn(:,:,jk-1,jpdtc),0.d0) * tmask(:,:,jk-1)
+         zwork(:,:,jk) = -vsed * max(trn(:,:,jk-1,jpdtc),0.) * tmask(:,:,jk-1)
+         !
+         ! AXY (16/01/14): stop sinking in upper 10m to reduce model instability 
+         !                 in shallower grid cells
+         ! if ( jk .lt. 9 ) zwork(:,:,jk) = 0.e0
+      END DO
+      !
+      ! tracer flux divergence at t-point added to the general trend
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1,jpi
+               ztra  = - ( zwork(ji,jj,jk) - zwork(ji,jj,jk+1) ) / fse3t(ji,jj,jk)
+               tra(ji,jj,jk,jpdtc) = tra(ji,jj,jk,jpdtc) + ztra
+            END DO
+         END DO
+      END DO
+      !
+
+# endif
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('sed')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+
+   END SUBROUTINE trc_sed_medusa
+
+   !! ======================================================================
+   !! ======================================================================
+   !! ======================================================================
+
+   !! AXY (10/02/09)
+   !! JPALM -- 31-03-2016 -- Completely change trc_sed_medusa_sbc.
+   !!                     -- We now need to read dust file through a namelist.
+   !!                     To be able to use time varying dust depositions from
+   !!                     -- copy and adapt the PISCES p4z_sbc_ini subroutine
+   !!                     -- Only use the dust related part.      
+   SUBROUTINE trc_sed_medusa_sbc(kt)
+
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_sed_medusa_sbc  ***
+      !!
+      !! ** Purpose :   Read and dust namelist and files.
+      !!                The interpolation is done in trc_sed through 
+      !!                "CALL fld_read( kt, 1, sf_dust )"
+      !!
+      !! ** Method  :   Read the sbc namelist, and the adapted dust file, if required
+      !!                called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   -- namelist sbc ref and cfg
+      !!                -- external netcdf files
+      !!
+      !!----------------------------------------------------------------------
+      !! * arguments
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+      INTEGER  :: ji, jj, jk, jm, ifpr
+      INTEGER  :: ii0, ii1, ij0, ij1
+      INTEGER  :: numdust
+      INTEGER  :: ierr 
+      INTEGER  :: jfld                ! dummy loop arguments
+      INTEGER  :: ios                 ! Local integer output status for namelist read
+      INTEGER  :: isrow               ! index for ORCA1 starting row
+      REAL(wp) :: ztimes_dust
+      REAL(wp), DIMENSION(nbtimes) :: zsteps                 ! times records
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: zdust
+      !
+      CHARACTER(len=100)         ::  cn_dir       ! Root directory for location of ssr files
+      TYPE(FLD_N), DIMENSION(1)  ::   slf_d       ! array of namelist informations on the fields to read
+      TYPE(FLD_N)                ::   sn_dust     ! informations about the fields to be read
+      !
+      NAMELIST/nammedsbc/cn_dir, sn_dust, bdustfer 
+
+      !!---------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('trc_sed_medusa_sbc')
+      !
+      !                            !* set file information
+      REWIND( numnatp_ref )        ! Namelist nammedsbc in reference namelist : MEDUSA external sources of Dust
+      READ  ( numnatp_ref, nammedsbc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nammedsbc in reference namelist', lwp )
+
+      REWIND( numnatp_cfg )        ! Namelist nammedsbc in configuration namelist : MEDUSA external sources of Dust
+      READ  ( numnatp_cfg, nammedsbc, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nammedsbc in configuration namelist', lwp )
+      IF(lwm) WRITE ( numonp, nammedsbc )
+
+      IF(lwp) THEN
+          WRITE(numout,*) ' '
+          WRITE(numout,*) ' namelist : nammedsbc '
+          WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~ '
+          WRITE(numout,*) '    dust input from the atmosphere bdustfer     = ', bdustfer
+      END IF
+
+      ! dust input from the atmosphere
+      ! ------------------------------
+      IF( bdustfer ) THEN
+         !
+         IF(lwp) WRITE(numout,*) '    initialize dust input from atmosphere '
+         IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ '
+         !
+         !! already allocated in sms_medusa
+         !!ALLOCATE( dust(jpi,jpj) )    ! allocation
+         !
+         slf_d(1) = sn_dust                          ! store namelist information in an array
+         !
+         ALLOCATE( sf_dust(1), STAT=ierr )           !* allocate and fill sf_sst (forcing structure) with sn_sst
+         IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'trc_sed_medusa_sbc: unable to allocate sf_dust structure' )
+         ALLOCATE( sf_dust(1)%fnow(jpi,jpj,1))
+         IF( slf_d(1)%ln_tint )     ALLOCATE( sf_dust(1)%fdta(jpi,jpj,1,2) )
+         !
+         CALL fld_fill( sf_dust, slf_d, cn_dir, 'trc_sed_medusa_sbc', 'Atmospheric dust deposition', 'nammedsed' )
+         !
+         CALL fld_read( kt, 1, sf_dust )
+         dust(:,:) = sf_dust(1)%fnow(:,:,1)
+         !
+      ELSEIF (lk_oasis) THEN
+         dust = Dust_in_cpl
+      ELSE
+         dust(:,:) = 0.0
+      END IF
+      !
+      zirondep(:,:) = 0.e0     !! Initialisation of deposition variables
+      zirondep(:,:) = dust(:,:) * Fe_dust_mratio / xfe_mass * 1.e6 * 86400.      !! mmol-Fe/m2/d
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('trc_sed_medusa_sbc')
+      !
+   END SUBROUTINE trc_sed_medusa_sbc
+
+   !! ======================================================================
+   !! ======================================================================
+   !! ======================================================================
+
+   !! AXY & JPALM (28/02/17)
+
+   SUBROUTINE trc_sed_medusa_dust( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sed_medusa_dust  ***
+      !!
+      !! ** Purpose : compute current dust *before* trc_bio_medusa call
+      !!
+      !! ** Method  : does what it says on the tin
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+
+      !! AXY (20/11/14): alter this to report on first MEDUSA call
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_sed_medusa_dust: MEDUSA dust timestep'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+	 IF(lwp) WRITE(numout,*) ' kt =',kt
+      ENDIF
+
+      !! AXY (04/11/13): replace this with a call in trc_ini_medusa
+      !! AXY (25/02/10)
+      !! call routine for populating CCD array if this is the first time-step
+      !! IF( kt == nittrc000 ) CALL medusa_ccd( kt )
+
+      !! AXY (04/11/13): replace this with a call in trc_ini_medusa
+      !! AXY (26/01/12)
+      !! call routine for populating river arrays if this is the first time-step
+      !! IF( kt == nittrc000 ) CALL medusa_river( kt )
+
+      !! AXY (10/02/09)
+      !! IF( (jnt == 1) .and. (bdustfer) )  CALL trc_sed_medusa_sbc( kt )
+
+      !! JPALM -- 31-03-2016 -- rewrite trc_sed_medusa_sbc.
+      !! IF (kt == nittrc000 ) CALL trc_sed_medusa_sbc 
+
+      !! JPALM -- 20-07-2016 -- adapt dust forcing fields reading and conversion
+      !!                     To read dust dep in kg-dust/m2/s instead of g-Fe/m2/month 
+      !!                     So all forcings and coupling dust dep are in the same SI units
+      !!                     and then convert in mmol-Fe/m2/day
+
+      IF( bdustfer ) THEN
+            CALL fld_read( kt, 1, sf_dust )
+            dust(:,:) = sf_dust(1)%fnow(:,:,1)
+      ELSEIF (lk_oasis) THEN
+         dust = Dust_in_cpl
+      ELSE
+         dust(:,:) = 0.0
+      ENDIF
+      !!
+      zirondep(:,:) = 0.e0     !! Initialisation of deposition variables
+      zirondep(:,:) = dust(:,:) * Fe_dust_mratio / xfe_mass * 1.e6 * 86400.  !! mmol-Fe/m2/d
+      
+      !! JPALM -- 20-07-2016 -- Zirondep and zsidep are not used.
+      !!                     So comment out the following lines. but keep them
+      !!                     as we may want to used them later on
+      !!================================================     
+      !!
+      !! zirondep(:,:,:) = 0.e0     !! Initialisation of deposition variables
+      !! zsidep  (:,:)   = 0.e0
+      !!
+      !! Iron and Si deposition at the surface
+      !! -------------------------------------
+      !!
+      !! DO jj = 1, jpj
+      !!    DO ji = 1, jpi
+      !!       zirondep(ji,jj,1) = (dustsolub * dust(ji,jj) / (55.85 * rmtss) + 3.e-10 / ryyss) &
+      !!       & * rfact2 / fse3t(ji,jj,1)
+      !!       zsidep  (ji,jj)   = 8.8 * 0.075 * dust(ji,jj) * rfact2 / &
+      !!       & (fse3t(ji,jj,1) * 28.1 * rmtss)
+      !!    END DO
+      !! END DO
+
+   END SUBROUTINE trc_sed_medusa_dust
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE trc_sed_medusa( kt )                   ! Empty routine
+      INTEGER, INTENT( in ) ::   kt
+      WRITE(*,*) 'trc_sed_medusa: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sed_medusa
+#endif 
+
+   !!======================================================================
+END MODULE  trcsed_medusa
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcsms_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcsms_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcsms_medusa.F90	(revision 9987)
@@ -0,0 +1,112 @@
+MODULE trcsms_medusa
+   !!======================================================================
+   !!                         ***  MODULE trcsms_medusa  ***
+   !! TOP :   Main module of the MEDUSA tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!              -   !  2008-08  (K. Popova) adaptation for MEDUSA
+   !!              -   !  2008-11  (A. Yool) continuing adaptation for MEDUSA
+   !!              -   !  2010-03  (A. Yool) updated for branch inclusion
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                       bio tracers
+   !!----------------------------------------------------------------------
+   !! trc_sms_medusa   : MEDUSA_TRC model main routine 
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc
+   USE trc
+   USE trcbio_medusa
+   USE trcopt_medusa
+   USE trcsed_medusa
+   USE trcavg_medusa
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_medusa   ! called by trcsms.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_sms_medusa( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_sms_medusa  ***  
+      !!
+      !! ** Purpose :   main routine of MEDUSA_TRC model
+      !!
+      !! ** Method  : - 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt   ! ocean time-step index
+
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) ' MEDUSA inside trc_sms_medusa'
+         CALL flush(numout)
+# endif
+
+      IF( kt == nittrc000 ) THEN
+       IF(lwp) WRITE(numout,*)
+       IF(lwp) WRITE(numout,*) ' trc_sms_medusa:  MEDUSA model'
+       IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      ENDIF
+
+      CALL trc_avg_medusa( kt ) ! rolling average module
+# if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) ' MEDUSA done trc_avg_medusa'
+      CALL flush(numout)
+# endif
+      
+      CALL trc_opt_medusa( kt ) ! optical model
+# if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) ' MEDUSA done trc_opt_medusa'
+      CALL flush(numout)
+# endif
+
+      !! AXY & JPALM (28/02/17): call dust before trc_bio_medusa (because of coupling)
+      CALL trc_sed_medusa_dust( kt ) ! dust submodel
+# if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) ' MEDUSA done trc_sed_medusa_dust'
+      CALL flush(numout)
+# endif
+
+# if defined key_kill_medusa
+      !! MEDUSA skipped
+      IF(lwp) WRITE(numout,*) ' MEDUSA killed at kt =', kt
+      CALL flush(numout)
+# else
+      CALL trc_bio_medusa( kt ) ! biological model
+#  if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) ' MEDUSA done trc_bio_medusa'
+      CALL flush(numout)
+#  endif
+      
+      CALL trc_sed_medusa( kt ) ! sedimentation model
+#  if defined key_debug_medusa
+      IF(lwp) WRITE(numout,*) ' MEDUSA done trc_sed_medusa'
+      CALL flush(numout)
+#  endif
+# endif
+
+   END SUBROUTINE trc_sms_medusa
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                        No MEDUSA model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_sms_medusa( kt )             ! Empty routine
+      INTEGER, INTENT( in ) ::   kt
+      WRITE(*,*) 'trc_sms_medusa: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sms_medusa
+#endif
+
+   !!======================================================================
+END MODULE trcsms_medusa
+
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcwri_medusa.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcwri_medusa.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/trcwri_medusa.F90	(revision 9987)
@@ -0,0 +1,60 @@
+MODULE trcwri_medusa
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    MEDUSA :   Output of MEDUSA tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!             1.1  !  2013-05 (A. Yool)  converted for MEDUSA
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_iomput && defined key_medusa
+   !!----------------------------------------------------------------------
+   !!   'key_medusa'                                           MEDUSA model
+   !!----------------------------------------------------------------------
+   !! trc_wri_medusa   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   USE trc         ! passive tracers common variables 
+   USE sms_medusa  ! MEDUSA variables
+   USE iom         ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_medusa 
+
+CONTAINS
+
+   SUBROUTINE trc_wri_medusa
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra
+      INTEGER              :: jn
+      !!---------------------------------------------------------------------
+ 
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      DO jn = jp_msa0, jp_msa1
+         cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
+         CALL iom_put( cltra, trn(:,:,:,jn) )
+      END DO
+      !
+   END SUBROUTINE trc_wri_medusa
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_medusa
+CONTAINS
+   SUBROUTINE trc_wri_medusa                     ! Empty routine  
+   END SUBROUTINE trc_wri_medusa
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!======================================================================
+END MODULE trcwri_medusa
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/zooplankton.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/zooplankton.F90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/MEDUSA/zooplankton.F90	(revision 9987)
@@ -0,0 +1,318 @@
+MODULE zooplankton_mod
+   !!======================================================================
+   !!                         ***  MODULE zooplankton_mod  ***
+   !! Calculates the zooplankton grazing
+   !!======================================================================
+   !! History :
+   !!   -   ! 2017-04 (M. Stringer)        Code taken from trcbio_medusa.F90
+   !!----------------------------------------------------------------------
+#if defined key_medusa
+   !!----------------------------------------------------------------------
+   !!                                                   MEDUSA bio-model
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+      
+   PUBLIC   zooplankton        ! Called in plankton.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 2.0 , LOCEAN-IPSL (2007) 
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE zooplankton( jk )
+      !!------------------------------------------------------------------
+      !!                     ***  ROUTINE zooplankton  ***
+      !! This called from PLANKTON and calculates the zooplankton 
+      !! grazing
+      !!------------------------------------------------------------------
+      USE bio_medusa_mod,    ONLY: fgmed, fgmedc, fgmepd, fgmepds,       &
+                                   fgmepn, fgmezmi,                      & 
+                                   fgmid, fgmidc, fgmipn,                &
+                                   ficme, ficmi, finme, finmi,           &
+                                   fmeexcr, fmegrow, fmeresp,            &
+                                   fmiexcr, fmigrow, fmiresp,            & 
+                                   fsin,                                 &
+                                   fzme_i, fzme_o, fzmi_i, fzmi_o,       &
+                                   idf, idfval,                          &
+                                   zdet, zdtc, zphd, zphn, zzme, zzmi
+      USE dom_oce,           ONLY: e3t_0, e3t_n, tmask
+      USE par_kind,          ONLY: wp
+      USE in_out_manager,    ONLY: lwp, numout
+      USE par_oce,           ONLY: jpim1, jpjm1
+      USE phycst,            ONLY: rsmall
+      USE sms_medusa,        ONLY: xbetac, xbetan, xgme, xgmi,           &
+                                   xkc, xkme, xkmi, xphi,                &
+                                   xpmed, xpmepd, xpmepn, xpmezmi,       &
+                                   xpmid, xpmipn,                        &
+                                   xthetapd, xthetapn,                   &
+                                   xthetazme, xthetazmi
+
+   !!* Substitution
+#  include "domzgr_substitute.h90"
+
+      !! Level
+      INTEGER, INTENT( in ) :: jk
+
+      INTEGER :: ji, jj
+
+      !! Microzooplankton grazing
+      REAL(wp) :: fmi1, fmi
+      REAL(wp) :: fstarmi, fmith
+      !!
+      !! Mesozooplankton grazing
+      REAL(wp) :: fme1, fme
+      REAL(wp) :: fstarme, fmeth
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            !! OPEN wet point IF..THEN loop
+            if (tmask(ji,jj,jk) == 1) then
+
+               !!----------------------------------------------------------
+               !! Zooplankton Grazing 
+               !! this code supplements the base grazing model with one that
+               !! considers the C:N ratio of grazed food and balances this
+               !! against the requirements of zooplankton growth; this model 
+               !! is derived from that of Anderson & Pondaven (2003)
+               !!
+               !! The current version of the code assumes a fixed C:N ratio 
+               !! for detritus (in contrast to Anderson & Pondaven, 2003), 
+               !! though the full equations are retained for future extension
+               !!----------------------------------------------------------
+               !!
+               !!----------------------------------------------------------
+               !! Microzooplankton first
+               !!----------------------------------------------------------
+               !!
+               fmi1           = (xkmi * xkmi) + (xpmipn * zphn(ji,jj) *      &
+                                                 zphn(ji,jj)) +              &
+                                (xpmid * zdet(ji,jj) * zdet(ji,jj))
+               fmi            = xgmi * zzmi(ji,jj) / fmi1
+               !! grazing on non-diatoms
+               fgmipn(ji,jj)  = fmi * xpmipn * zphn(ji,jj) * zphn(ji,jj)
+               !! grazing on detrital nitrogen
+               fgmid(ji,jj)   = fmi * xpmid  * zdet(ji,jj) * zdet(ji,jj)
+# if defined key_roam   
+               ! acc            
+               fgmidc(ji,jj)  = rsmall
+               !! grazing on detrital carbon
+               IF ( zdet(ji,jj) .GT. rsmall ) fgmidc(ji,jj)  =               &
+                  (zdtc(ji,jj) / (zdet(ji,jj) + tiny(zdet(ji,jj)))) *        &
+                  fgmid(ji,jj)
+# else
+               !! AXY (26/11/08): implicit detrital carbon change
+               !! grazing on detrital carbon
+               fgmidc(ji,jj)  = xthetad * fgmid(ji,jj)
+# endif
+# if defined key_debug_medusa
+               !! report microzooplankton grazing
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fmi1(',jk,')    = ', fmi1
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! which translates to these incoming N and C fluxes
+               finmi(ji,jj)   = (1.0 - xphi) * (fgmipn(ji,jj) + fgmid(ji,jj))
+               ficmi(ji,jj)   = (1.0 - xphi) * ((xthetapn * fgmipn(ji,jj)) + &
+                                                fgmidc(ji,jj))
+               !!
+               !! the ideal food C:N ratio for microzooplankton
+               !! xbetan = 0.77; xthetaz = 5.625; xbetac = 0.64; xkc = 0.80
+               fstarmi = (xbetan * xthetazmi) / (xbetac * xkc)
+               !!
+               !! process these to determine proportioning of grazed N and C
+               !! (since there is no explicit consideration of respiration,
+               !! only growth and excretion are calculated here)
+               fmith = (ficmi(ji,jj) / (finmi(ji,jj) + tiny(finmi(ji,jj))))
+               if (fmith.ge.fstarmi) then
+                  fmigrow(ji,jj) = xbetan * finmi(ji,jj)
+                  fmiexcr(ji,jj) = 0.0
+               else
+                  fmigrow(ji,jj) = (xbetac * xkc * ficmi(ji,jj)) / xthetazmi
+                  fmiexcr(ji,jj) = ficmi(ji,jj) *                            &
+                                   ((xbetan / (fmith + tiny(fmith))) -       &
+                                    ((xbetac * xkc) / xthetazmi))
+               endif
+# if defined key_roam
+               fmiresp(ji,jj) = (xbetac * ficmi(ji,jj)) -                    &
+                                (xthetazmi * fmigrow(ji,jj))
+# endif
+
+# if defined key_debug_medusa
+               !! report microzooplankton grazing
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fgmipn(',jk,')  = ', fgmipn(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmid(',jk,')   = ', fgmid(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmidc(',jk,')  = ', fgmidc(ji,jj)
+                  IF (lwp) write (numout,*) 'finmi(',jk,')   = ', finmi(ji,jj)
+                  IF (lwp) write (numout,*) 'ficmi(',jk,')   = ', ficmi(ji,jj)
+                  IF (lwp) write (numout,*) 'fstarmi(',jk,') = ', fstarmi
+                  IF (lwp) write (numout,*) 'fmith(',jk,')   = ', fmith
+                  IF (lwp) write (numout,*) 'fmigrow(',jk,') = ', fmigrow(ji,jj)
+                  IF (lwp) write (numout,*) 'fmiexcr(',jk,') = ', fmiexcr(ji,jj)
+#  if defined key_roam
+                  IF (lwp) write (numout,*) 'fmiresp(',jk,') = ', fmiresp(ji,jj)
+#  endif
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!----------------------------------------------------------
+               !! Mesozooplankton second
+               !!----------------------------------------------------------
+               !!
+               fme1           = (xkme * xkme) + (xpmepn * zphn(ji,jj) *       &
+                                                 zphn(ji,jj)) +               &
+                                (xpmepd * zphd(ji,jj) * zphd(ji,jj)) +        & 
+                                (xpmezmi * zzmi(ji,jj) * zzmi(ji,jj)) +       &
+                                (xpmed * zdet(ji,jj) * zdet(ji,jj))
+               fme            = xgme * zzme(ji,jj) / fme1
+               !! grazing on non-diatoms
+               fgmepn(ji,jj)  = fme * xpmepn  * zphn(ji,jj) * zphn(ji,jj)
+               !! grazing on diatoms
+               fgmepd(ji,jj)  = fme * xpmepd  * zphd(ji,jj) * zphd(ji,jj)
+               !! grazing on diatom silicon
+               fgmepds(ji,jj) = fsin(ji,jj) * fgmepd(ji,jj)
+               !! grazing on microzooplankton
+               fgmezmi(ji,jj) = fme * xpmezmi * zzmi(ji,jj) * zzmi(ji,jj)
+               !! grazing on detrital nitrogen
+               fgmed(ji,jj)   = fme * xpmed   * zdet(ji,jj) * zdet(ji,jj)
+# if defined key_roam
+               !! acc
+               fgmedc(ji,jj)  = rsmall
+               !! grazing on detrital carbon
+               IF ( zdet(ji,jj) .GT. rsmall ) fgmedc(ji,jj)  = (zdtc(ji,jj) / &
+                  (zdet(ji,jj) + tiny(zdet(ji,jj)))) * fgmed(ji,jj)
+# else
+               !! AXY (26/11/08): implicit detrital carbon change
+               !! grazing on detrital carbon
+               fgmedc(ji,jj)  = xthetad * fgmed(ji,jj)
+# endif
+               !!
+               !! which translates to these incoming N and C fluxes
+               finme(ji,jj)   = (1.0 - xphi) *                               &
+                                (fgmepn(ji,jj) + fgmepd(ji,jj) +             &
+                                 fgmezmi(ji,jj) + fgmed(ji,jj))
+               ficme(ji,jj)   = (1.0 - xphi) *                               &
+                                ((xthetapn * fgmepn(ji,jj)) +                &
+                                (xthetapd * fgmepd(ji,jj)) +                 &
+                                (xthetazmi * fgmezmi(ji,jj)) + fgmedc(ji,jj))
+# if defined key_debug_medusa
+               !! report mesozooplankton grazing
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fme1(',jk,')    = ', fme1
+                  IF (lwp) write (numout,*) 'fme(',jk,')     = ', fme
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               !!
+               !! the ideal food C:N ratio for mesozooplankton
+               !! xbetan = 0.77; xthetaz = 5.625; xbetac = 0.64; xkc = 0.80
+               fstarme        = (xbetan * xthetazme) / (xbetac * xkc)
+               !!
+               !! process these to determine proportioning of grazed N and C
+               !! (since there is no explicit consideration of respiration,
+               !! only growth and excretion are calculated here)
+               fmeth   = (ficme(ji,jj) / (finme(ji,jj) + tiny(finme(ji,jj))))
+               if (fmeth.ge.fstarme) then
+                  fmegrow(ji,jj) = xbetan * finme(ji,jj)
+                  fmeexcr(ji,jj) = 0.0
+               else
+                  fmegrow(ji,jj) = (xbetac * xkc * ficme(ji,jj)) / xthetazme
+                  fmeexcr(ji,jj) = ficme(ji,jj) *                            &
+                                   ((xbetan / (fmeth + tiny(fmeth))) -       &
+                                    ((xbetac * xkc) / xthetazme))
+               endif
+# if defined key_roam
+               fmeresp(ji,jj) = (xbetac * ficme(ji,jj)) - (xthetazme *       &
+                                                           fmegrow(ji,jj))
+# endif
+
+# if defined key_debug_medusa
+               !! report mesozooplankton grazing
+               if (idf.eq.1.AND.idfval.eq.1) then
+                  IF (lwp) write (numout,*) '------------------------------'
+                  IF (lwp) write (numout,*) 'fgmepn(',jk,')  = ', fgmepn(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmepd(',jk,')  = ', fgmepd(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmepds(',jk,') = ', fgmepds(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmezmi(',jk,') = ', fgmezmi(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmed(',jk,')   = ', fgmed(ji,jj)
+                  IF (lwp) write (numout,*) 'fgmedc(',jk,')  = ', fgmedc(ji,jj)
+                  IF (lwp) write (numout,*) 'finme(',jk,')   = ', finme(ji,jj)
+                  IF (lwp) write (numout,*) 'ficme(',jk,')   = ', ficme(ji,jj)
+                  IF (lwp) write (numout,*) 'fstarme(',jk,') = ', fstarme
+                  IF (lwp) write (numout,*) 'fmeth(',jk,')   = ', fmeth
+                  IF (lwp) write (numout,*) 'fmegrow(',jk,') = ', fmegrow(ji,jj)
+                  IF (lwp) write (numout,*) 'fmeexcr(',jk,') = ', fmeexcr(ji,jj)
+#  if defined key_roam
+                  IF (lwp) write (numout,*) 'fmeresp(',jk,') = ', fmeresp(ji,jj)
+#  endif
+               endif
+# endif
+            ENDIF
+         ENDDO
+      ENDDO
+
+      DO jj = 2,jpjm1
+         DO ji = 2,jpim1
+            if (tmask(ji,jj,jk) == 1) then
+               fzmi_i(ji,jj)  = fzmi_i(ji,jj)  + fse3t(ji,jj,jk) *          &
+                                ( fgmipn(ji,jj) + fgmid(ji,jj) )
+               fzmi_o(ji,jj)  = fzmi_o(ji,jj)  + fse3t(ji,jj,jk) *          &
+                                ( fmigrow(ji,jj) +                          &
+                                  (xphi * (fgmipn(ji,jj) + fgmid(ji,jj))) + &
+                                  fmiexcr(ji,jj) + ((1.0 - xbetan) *        &
+                                                    finmi(ji,jj)) )
+               fzme_i(ji,jj)  = fzme_i(ji,jj)  + fse3t(ji,jj,jk) *          &
+                                ( fgmepn(ji,jj) + fgmepd(ji,jj) +           &
+                                  fgmezmi(ji,jj) + fgmed(ji,jj) )
+               fzme_o(ji,jj)  = fzme_o(ji,jj)  + fse3t(ji,jj,jk) *          &
+                                ( fmegrow(ji,jj) +                          &
+                                  (xphi * (fgmepn(ji,jj) + fgmepd(ji,jj) +  &
+                                  fgmezmi(ji,jj) + fgmed(ji,jj))) +         &
+                                  fmeexcr(ji,jj) + ((1.0 - xbetan) *        &
+                                                    finme(ji,jj)) )
+            ENDIF
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE zooplankton
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                   No MEDUSA bio-model
+   !!======================================================================
+CONTAINS
+   SUBROUTINE zooplankton( )                    ! Empty routine
+      WRITE(*,*) 'zooplankton: You should not have seen this print! error?'
+   END SUBROUTINE zooplankton
+#endif 
+
+   !!======================================================================
+END MODULE zooplankton_mod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zbio.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zbio.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zbio.F90	(revision 9987)
@@ -599,3 +599,3 @@
 
    !!======================================================================
-END MODULE  p2zbio
+END MODULE p2zbio
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsms.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsms.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsms.F90	(revision 9987)
@@ -84,3 +84,3 @@
 
    !!======================================================================
-END MODULE  p2zsms
+END MODULE p2zsms
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zbio.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zbio.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zbio.F90	(revision 9987)
@@ -109,4 +109,3 @@
 
    !!======================================================================
-END MODULE  p4zbio
-
+END MODULE p4zbio
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zche.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zche.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zche.F90	(revision 9987)
@@ -32,5 +32,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   fekeq    ! chemistry of Fe
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   chemc    ! Solubilities of O2 and CO2
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   chemo2    ! Solubilities of O2 and CO2
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   chemo2   ! Solubilities of O2 and CO2
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tempis   ! In situ temperature
 
    REAL(wp), PUBLIC ::   atcox  = 0.20946         ! units atm
@@ -39,15 +40,5 @@
    REAL(wp) ::   o2atm  = 1. / ( 1000. * 0.20946 )  
 
-   REAL(wp) ::   akcc1  = -171.9065       ! coeff. for apparent solubility equilibrium
-   REAL(wp) ::   akcc2  =   -0.077993     ! Millero et al. 1995 from Mucci 1983
-   REAL(wp) ::   akcc3  = 2839.319        
-   REAL(wp) ::   akcc4  =   71.595        
-   REAL(wp) ::   akcc5  =   -0.77712      
-   REAL(wp) ::   akcc6  =    0.00284263   
-   REAL(wp) ::   akcc7  =  178.34        
-   REAL(wp) ::   akcc8  =   -0.07711     
-   REAL(wp) ::   akcc9  =    0.0041249   
-
-   REAL(wp) ::   rgas   = 83.143         ! universal gas constants
+   REAL(wp) ::   rgas   = 83.14472       ! universal gas constants
    REAL(wp) ::   oxyco  = 1. / 22.4144   ! converts from liters of an ideal gas to moles
 
@@ -55,67 +46,9 @@
    REAL(wp) ::   bor2   = 1. / 10.82
 
-   REAL(wp) ::   ca0    = -162.8301      ! WEISS & PRICE 1980, units mol/(kg atm)
-   REAL(wp) ::   ca1    =  218.2968
-   REAL(wp) ::   ca2    =   90.9241
-   REAL(wp) ::   ca3    =   -1.47696
-   REAL(wp) ::   ca4    =    0.025695
-   REAL(wp) ::   ca5    =   -0.025225
-   REAL(wp) ::   ca6    =    0.0049867
-
-   REAL(wp) ::   c10    = -3670.7        ! Coeff. for 1. dissoc. of carbonic acid (Edmond and Gieskes, 1970)   
-   REAL(wp) ::   c11    =    62.008     
-   REAL(wp) ::   c12    =    -9.7944    
-   REAL(wp) ::   c13    =     0.0118     
-   REAL(wp) ::   c14    =    -0.000116
-
-   REAL(wp) ::   c20    = -1394.7       ! coeff. for 2. dissoc. of carbonic acid (Millero, 1995)   
-   REAL(wp) ::   c21    =    -4.777   
-   REAL(wp) ::   c22    =     0.0184   
-   REAL(wp) ::   c23    =    -0.000118
-
    REAL(wp) ::   st1    =      0.14     ! constants for calculate concentrations for sulfate
    REAL(wp) ::   st2    =  1./96.062    !  (Morris & Riley 1966)
-   REAL(wp) ::   ks0    =    141.328 
-   REAL(wp) ::   ks1    =  -4276.1  
-   REAL(wp) ::   ks2    =    -23.093
-   REAL(wp) ::   ks3    = -13856.  
-   REAL(wp) ::   ks4    =   324.57 
-   REAL(wp) ::   ks5    =   -47.986
-   REAL(wp) ::   ks6    =  35474. 
-   REAL(wp) ::   ks7    =   -771.54
-   REAL(wp) ::   ks8    =    114.723
-   REAL(wp) ::   ks9    =  -2698.  
-   REAL(wp) ::   ks10   =   1776. 
-   REAL(wp) ::   ks11   =      1.
-   REAL(wp) ::   ks12   =     -0.001005 
 
    REAL(wp) ::   ft1    =    0.000067   ! constants for calculate concentrations for fluorides
    REAL(wp) ::   ft2    = 1./18.9984    ! (Dickson & Riley 1979 )
-   REAL(wp) ::   kf0    =  -12.641    
-   REAL(wp) ::   kf1    = 1590.2    
-   REAL(wp) ::   kf2    =    1.525    
-   REAL(wp) ::   kf3    =    1.0     
-   REAL(wp) ::   kf4    =   -0.001005
-
-   REAL(wp) ::   cb0    = -8966.90      ! Coeff. for 1. dissoc. of boric acid 
-   REAL(wp) ::   cb1    = -2890.53      ! (Dickson and Goyet, 1994)
-   REAL(wp) ::   cb2    =   -77.942
-   REAL(wp) ::   cb3    =     1.728
-   REAL(wp) ::   cb4    =    -0.0996
-   REAL(wp) ::   cb5    =   148.0248
-   REAL(wp) ::   cb6    =   137.1942
-   REAL(wp) ::   cb7    =     1.62142
-   REAL(wp) ::   cb8    =   -24.4344
-   REAL(wp) ::   cb9    =   -25.085
-   REAL(wp) ::   cb10   =    -0.2474 
-   REAL(wp) ::   cb11   =     0.053105
-
-   REAL(wp) ::   cw0    = -13847.26     ! Coeff. for dissoc. of water (Dickson and Riley, 1979 )
-   REAL(wp) ::   cw1    =    148.9652  
-   REAL(wp) ::   cw2    =    -23.6521
-   REAL(wp) ::   cw3    =    118.67 
-   REAL(wp) ::   cw4    =     -5.977 
-   REAL(wp) ::   cw5    =      1.0495  
-   REAL(wp) ::   cw6    =     -0.01615
 
    !                                    ! volumetric solubility constants for o2 in ml/L  
@@ -185,6 +118,6 @@
       REAL(wp) ::   ztgg , ztgg2, ztgg3 , ztgg4 , ztgg5
       REAL(wp) ::   zpres, ztc  , zcl   , zcpexp, zoxy  , zcpexp2
-      REAL(wp) ::   zsqrt, ztr  , zlogt , zcek1
-      REAL(wp) ::   zis  , zis2 , zsal15, zisqrt
+      REAL(wp) ::   zsqrt, ztr  , zlogt , zcek1, zc1, zplat
+      REAL(wp) ::   zis  , zis2 , zsal15, zisqrt, za1  , za2
       REAL(wp) ::   zckb , zck1 , zck2  , zckw  , zak1 , zak2  , zakb , zaksp0, zakw
       REAL(wp) ::   zst  , zft  , zcks  , zckf  , zaksp1
@@ -193,4 +126,20 @@
       IF( nn_timing == 1 )  CALL timing_start('p4z_che')
       !
+      ! Computations of chemical constants require in situ temperature
+      ! Here a quite simple formulation is used to convert 
+      ! potential temperature to in situ temperature. The errors is less than 
+      ! 0.04°C relative to an exact computation
+      ! ---------------------------------------------------------------------
+      DO jk = 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zpres = fsdept(ji,jj,jk) / 1000.
+               za1 = 0.04 * ( 1.0 + 0.185 * tsn(ji,jj,jk,jp_tem) + 0.035 * (tsn(ji,jj,jk,jp_sal) - 35.0) )
+               za2 = 0.0075 * ( 1.0 - tsn(ji,jj,jk,jp_tem) / 30.0 )
+               tempis(ji,jj,jk) = tsn(ji,jj,jk,jp_tem) - za1 * zpres + za2 * zpres**2
+            END DO
+         END DO
+      END DO
+      !
       ! CHEMICAL CONSTANTS - SURFACE LAYER
       ! ----------------------------------
@@ -200,5 +149,5 @@
          DO ji = 1, jpi
             !                             ! SET ABSOLUTE TEMPERATURE
-            ztkel = tsn(ji,jj,1,jp_tem) + 273.16
+            ztkel = tempis(ji,jj,1) + 273.15
             zt    = ztkel * 0.01
             zt2   = zt * zt
@@ -208,17 +157,10 @@
             !                             ! LN(K0) OF SOLUBILITY OF CO2 (EQ. 12, WEISS, 1980)
             !                             !     AND FOR THE ATMOSPHERE FOR NON IDEAL GAS
-            zcek1 = ca0 + ca1 / zt + ca2 * zlogt + ca3 * zt2 + zsal * ( ca4 + ca5 * zt + ca6 * zt2 )
-            !                             ! LN(K0) OF SOLUBILITY OF O2 and N2 in ml/L (EQ. 8, GARCIA AND GORDON, 1992)
-            ztgg  = LOG( ( 298.15 - tsn(ji,jj,1,jp_tem) ) / ztkel )  ! Set the GORDON & GARCIA scaled temperature
-            ztgg2 = ztgg  * ztgg
-            ztgg3 = ztgg2 * ztgg
-            ztgg4 = ztgg3 * ztgg
-            ztgg5 = ztgg4 * ztgg
-            zoxy  = ox0 + ox1 * ztgg + ox2 * ztgg2 + ox3 * ztgg3 + ox4 * ztgg4 + ox5 * ztgg5   &
-                   + zsal * ( ox6 + ox7 * ztgg + ox8 * ztgg2 + ox9 * ztgg3 ) +  ox10 * zsal2
-
+            zcek1 = 9345.17/ztkel - 60.2409 + 23.3585 * LOG(zt) + zsal*(0.023517 - 0.00023656*ztkel    &
+            &       + 0.0047036e-4*ztkel**2)
             !                             ! SET SOLUBILITIES OF O2 AND CO2 
-            chemc(ji,jj,1) = EXP( zcek1 ) * 1.e-6 * rhop(ji,jj,1) / 1000.  ! mol/(L uatm)
-            chemc(ji,jj,2) = ( EXP( zoxy  ) * o2atm ) * oxyco              ! mol/(L atm)
+            chemc(ji,jj,1) = EXP( zcek1 ) * 1.e-6 * rhop(ji,jj,1) / 1000. ! mol/(kg uatm)
+            chemc(ji,jj,2) = -1636.75 + 12.0408*ztkel - 0.0327957*ztkel**2 + 0.0000316528*ztkel**3
+            chemc(ji,jj,3) = 57.7 - 0.118*ztkel
             !
          END DO
@@ -233,8 +175,8 @@
 !CDIR NOVERRCHK
             DO ji = 1, jpi
-              ztkel = tsn(ji,jj,jk,jp_tem) + 273.16
+              ztkel = tempis(ji,jj,jk) + 273.15
               zsal  = tsn(ji,jj,jk,jp_sal) + ( 1.- tmask(ji,jj,jk) ) * 35.
               zsal2 = zsal * zsal
-              ztgg  = LOG( ( 298.15 - tsn(ji,jj,jk,jp_tem) ) / ztkel )  ! Set the GORDON & GARCIA scaled temperature
+              ztgg  = LOG( ( 298.15 - tempis(ji,jj,jk) ) / ztkel )  ! Set the GORDON & GARCIA scaled temperature
               ztgg2 = ztgg  * ztgg
               ztgg3 = ztgg2 * ztgg
@@ -259,9 +201,12 @@
             DO ji = 1, jpi
 
-               ! SET PRESSION
-               zpres   = 1.025e-1 * fsdept(ji,jj,jk)
+               ! SET PRESSION ACCORDING TO SAUNDER (1980)
+               zplat   = SIN ( ABS(gphit(ji,jj)*3.141592654/180.) )
+               zc1 = 5.92E-3 + zplat**2 * 5.25E-3
+               zpres = ((1-zc1)-SQRT(((1-zc1)**2)-(8.84E-6*fsdept(ji,jj,jk)))) / 4.42E-6
+               zpres = zpres / 10.0
 
                ! SET ABSOLUTE TEMPERATURE
-               ztkel   = tsn(ji,jj,jk,jp_tem) + 273.16
+               ztkel   = tempis(ji,jj,jk) + 273.15
                zsal    = tsn(ji,jj,jk,jp_sal) + ( 1.-tmask(ji,jj,jk) ) * 35.
                zsqrt  = SQRT( zsal )
@@ -272,5 +217,5 @@
                zis2   = zis * zis
                zisqrt = SQRT( zis )
-               ztc     = tsn(ji,jj,jk,jp_tem) + ( 1.- tmask(ji,jj,jk) ) * 20.
+               ztc     = tempis(ji,jj,jk) + ( 1.- tmask(ji,jj,jk) ) * 20.
 
                ! CHLORINITY (WOOSTER ET AL., 1969)
@@ -284,29 +229,42 @@
 
                ! DISSOCIATION CONSTANT FOR SULFATES on free H scale (Dickson 1990)
-               zcks    = EXP(  ks1 * ztr + ks0 + ks2 * zlogt                           &
-                  &                     + ( ks3 * ztr + ks4 + ks5 * zlogt ) * zisqrt   &
-                  &                     + ( ks6 * ztr + ks7 + ks8 * zlogt ) * zis      &
-                  &                     + ks9 * ztr * zis * zisqrt + ks10 * ztr *zis2 + LOG( ks11 + ks12 *zsal )  )
+               zcks    = EXP(-4276.1 * ztr + 141.328 - 23.093 * zlogt         &
+               &         + (-13856. * ztr + 324.57 - 47.986 * zlogt) * zisqrt &
+               &         + (35474. * ztr - 771.54 + 114.723 * zlogt) * zis    &
+               &         - 2698. * ztr * zis**1.5 + 1776.* ztr * zis2         &
+               &         + LOG(1.0 - 0.001005 * zsal))
+               !
+               aphscale(ji,jj,jk) = ( 1. + zst / zcks )
 
                ! DISSOCIATION CONSTANT FOR FLUORIDES on free H scale (Dickson and Riley 79)
-               zckf    = EXP(  kf1 * ztr + kf0 + kf2 * zisqrt + LOG( kf3 + kf4 * zsal )  )
+               zckf    = EXP( 1590.2*ztr - 12.641 + 1.525*zisqrt   &
+               &         + LOG(1.0d0 - 0.001005d0*zsal)            &
+               &         + LOG(1.0d0 + zst/zcks))
 
                ! DISSOCIATION CONSTANT FOR CARBONATE AND BORATE
-               zckb    = ( cb0 + cb1 * zsqrt + cb2  * zsal + cb3 * zsal15 + cb4 * zsal * zsal ) * ztr   &
-                  &    + ( cb5 + cb6 * zsqrt + cb7  * zsal )                                            &
-                  &    + ( cb8 + cb9 * zsqrt + cb10 * zsal ) * zlogt + cb11 * zsqrt * ztkel             &
-                  &    + LOG(  ( 1.+ zst / zcks + zft / zckf ) / ( 1.+ zst / zcks )  )
-
-               zck1    = c10 * ztr + c11 + c12 * zlogt + c13 * zsal + c14 * zsal * zsal
-               zck2    = c20 * ztr + c21 + c22 * zsal   + c23 * zsal**2
+               zckb=  (-8966.90 - 2890.53*zsqrt - 77.942*zsal        &
+               &      + 1.728*zsal15 - 0.0996*zsal*zsal)*ztr         &
+               &      + (148.0248 + 137.1942*zsqrt + 1.62142*zsal)   &
+               &      + (-24.4344 - 25.085*zsqrt - 0.2474*zsal)      & 
+               &      * zlogt + 0.053105*zsqrt*ztkel
+
+
+               ! DISSOCIATION COEFFICIENT FOR CARBONATE ACCORDING TO 
+               ! MEHRBACH (1973) REFIT BY MILLERO (1995), seawater scale
+               zck1    = -1.0*(3633.86*ztr - 61.2172 + 9.6777*zlogt  &
+                  - 0.011555*zsal + 0.0001152*zsal*zsal)
+               zck2    = -1.0*(471.78*ztr + 25.9290 - 3.16967*zlogt      &
+                  - 0.01781*zsal + 0.0001122*zsal*zsal)
 
                ! PKW (H2O) (DICKSON AND RILEY, 1979)
-               zckw    = cw0 * ztr + cw1 + cw2 * zlogt + ( cw3 * ztr + cw4 + cw5 * zlogt ) * zsqrt + cw6 * zsal
-
+               zckw = -13847.26*ztr + 148.9652 - 23.6521 * zlogt    & 
+               &     + (118.67*ztr - 5.977 + 1.0495 * zlogt)        &
+               &     * zsqrt - 0.01615 * zsal
 
                ! APPARENT SOLUBILITY PRODUCT K'SP OF CALCITE IN SEAWATER
                !       (S=27-43, T=2-25 DEG C) at pres =0 (atmos. pressure) (MUCCI 1983)
-               zaksp0  = akcc1 + akcc2 * ztkel + akcc3 * ztr + akcc4 * LOG10( ztkel )   &
-                  &   + ( akcc5 + akcc6 * ztkel + akcc7 * ztr ) * zsqrt + akcc8 * zsal + akcc9 * zsal15
+               zaksp0  = -171.9065 -0.077993*ztkel + 2839.319*ztr + 71.595*LOG10( ztkel )   &
+                  &      + (-0.77712 + 0.00284263*ztkel + 178.34*ztr) * zsqrt  &
+                  &      - 0.07711*zsal + 0.0041249*zsal15
 
                ! K1, K2 OF CARBONIC ACID, KB OF BORIC ACID, KW (H2O) (LIT.?)
@@ -378,5 +336,6 @@
       !!                     ***  ROUTINE p4z_che_alloc  ***
       !!----------------------------------------------------------------------
-      ALLOCATE( sio3eq(jpi,jpj,jpk), fekeq(jpi,jpj,jpk), chemc(jpi,jpj,2), chemo2(jpi,jpj,jpk), STAT=p4z_che_alloc )
+      ALLOCATE( sio3eq(jpi,jpj,jpk), fekeq(jpi,jpj,jpk), chemc(jpi,jpj,3), chemo2(jpi,jpj,jpk),   &
+      &         tempis(jpi,jpj,jpk), STAT=p4z_che_alloc )
       !
       IF( p4z_che_alloc /= 0 )   CALL ctl_warn('p4z_che_alloc : failed to allocate arrays.')
@@ -396,3 +355,3 @@
 
    !!======================================================================
-END MODULE  p4zche
+END MODULE p4zche
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zflx.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zflx.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zflx.F90	(revision 9987)
@@ -84,15 +84,16 @@
       !
       INTEGER  ::   ji, jj, jm, iind, iindm1
-      REAL(wp) ::   ztc, ztc2, ztc3, zws, zkgwan
+      REAL(wp) ::   ztc, ztc2, ztc3, ztc4, zws, zkgwan
       REAL(wp) ::   zfld, zflu, zfld16, zflu16, zfact
+      REAL(wp) ::   zvapsw, zsal, zfco2, zxc2, xCO2approx, ztkel, zfugcoeff
       REAL(wp) ::   zph, zah2, zbot, zdic, zalk, zsch_o2, zalka, zsch_co2
       REAL(wp) ::   zyr_dec, zdco2dt
       CHARACTER (len=25) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:) :: zkgco2, zkgo2, zh2co3, zoflx, zw2d 
+      REAL(wp), POINTER, DIMENSION(:,:) :: zkgco2, zkgo2, zh2co3, zoflx, zw2d, zpco2atm 
       !!---------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('p4z_flx')
       !
-      CALL wrk_alloc( jpi, jpj, zkgco2, zkgo2, zh2co3, zoflx )
+      CALL wrk_alloc( jpi, jpj, zkgco2, zkgo2, zh2co3, zoflx, zpco2atm )
       !
 
@@ -135,5 +136,6 @@
 
                ! CALCULATE [ALK]([CO3--], [HCO3-])
-               zalk  = zalka - (  akw3(ji,jj,1) / zph - zph + zbot / ( 1.+ zph / akb3(ji,jj,1) )  )
+               zalk  = zalka - (  akw3(ji,jj,1) / zph - zph / aphscale(ji,jj,1)    &
+               &       + zbot / ( 1.+ zph / akb3(ji,jj,1) )  )
 
                ! CALCULATE [H+] AND [H2CO3]
@@ -162,11 +164,12 @@
             ztc2 = ztc * ztc
             ztc3 = ztc * ztc2 
+            ztc4 = ztc2 * ztc2 
             ! Compute the schmidt Number both O2 and CO2
-            zsch_co2 = 2073.1 - 125.62 * ztc + 3.6276 * ztc2 - 0.043126 * ztc3
-            zsch_o2  = 1953.4 - 128.0  * ztc + 3.9918 * ztc2 - 0.050091 * ztc3
+            zsch_co2 = 2116.8 - 136.25 * ztc + 4.7353 * ztc2 - 0.092307 * ztc3 + 0.0007555 * ztc4
+            zsch_o2  = 1920.4 - 135.6  * ztc + 5.2122 * ztc2 - 0.109390 * ztc3 + 0.0009377 * ztc4
             !  wind speed 
             zws  = wndm(ji,jj) * wndm(ji,jj)
             ! Compute the piston velocity for O2 and CO2
-            zkgwan = 0.3 * zws  + 2.5 * ( 0.5246 + 0.016256 * ztc + 0.00049946  * ztc2 )
+            zkgwan = 0.251 * zws
             zkgwan = zkgwan * xconv * ( 1.- fr_i(ji,jj) ) * tmask(ji,jj,1)
 # if defined key_degrad
@@ -181,15 +184,24 @@
       DO jj = 1, jpj
          DO ji = 1, jpi
+            ztkel  = tsn(ji,jj,1,jp_tem) + 273.15
+            zsal   = tsn(ji,jj,1,jp_sal) + ( 1.- tmask(ji,jj,1) ) * 35.
+            zvapsw = EXP(24.4543 - 67.4509*(100.0/ztkel) - 4.8489*LOG(ztkel/100) - 0.000544*zsal)
+            zpco2atm(ji,jj) = satmco2(ji,jj) * ( patm(ji,jj) - zvapsw )
+            zxc2 = (1.0 - zpco2atm(ji,jj) * 1E-6 )**2
+            zfugcoeff = EXP(patm(ji,jj) * (chemc(ji,jj,2) + 2.0 * zxc2 * chemc(ji,jj,3) )   &
+            &           / (82.05736 * ztkel))
+            zfco2 = zpco2atm(ji,jj) * zfugcoeff
+
             ! Compute CO2 flux for the sea and air
-            zfld = satmco2(ji,jj) * patm(ji,jj) * tmask(ji,jj,1) * chemc(ji,jj,1) * zkgco2(ji,jj)   ! (mol/L) * (m/s)
-            zflu = zh2co3(ji,jj) * tmask(ji,jj,1) * zkgco2(ji,jj)                                   ! (mol/L) (m/s) ?
+            zfld = zfco2 * chemc(ji,jj,1) * zkgco2(ji,jj)  ! (mol/L) * (m/s)
+            zflu = zh2co3(ji,jj) * zkgco2(ji,jj)                                   ! (mol/L) (m/s) ?
             oce_co2(ji,jj) = ( zfld - zflu ) * rfact2 * e1e2t(ji,jj) * tmask(ji,jj,1) * 1000.
             ! compute the trend
-            tra(ji,jj,1,jpdic) = tra(ji,jj,1,jpdic) + ( zfld - zflu ) * rfact2 / fse3t(ji,jj,1)
+            tra(ji,jj,1,jpdic) = tra(ji,jj,1,jpdic) + ( zfld - zflu ) * rfact2 / fse3t(ji,jj,1) * tmask(ji,jj,1)
 
             ! Compute O2 flux 
-            zfld16 = atcox * patm(ji,jj) * chemc(ji,jj,2) * tmask(ji,jj,1) * zkgo2(ji,jj)          ! (mol/L) * (m/s)
-            zflu16 = trb(ji,jj,1,jpoxy) * tmask(ji,jj,1) * zkgo2(ji,jj)
-            zoflx(ji,jj) = zfld16 - zflu16
+            zfld16 = patm(ji,jj) * chemo2(ji,jj,1) * zkgo2(ji,jj)          ! (mol/L) * (m/s)
+            zflu16 = trb(ji,jj,1,jpoxy) * zkgo2(ji,jj)
+            zoflx(ji,jj) = ( zfld16 - zflu16 ) * tmask(ji,jj,1)
             tra(ji,jj,1,jpoxy) = tra(ji,jj,1,jpoxy) + zoflx(ji,jj) * rfact2 / fse3t(ji,jj,1)
          END DO
@@ -222,9 +234,9 @@
          ENDIF
          IF( iom_use( "Dpco2" ) ) THEN
-           zw2d(:,:) = ( satmco2(:,:) * patm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1)
+           zw2d(:,:) = ( zpco2atm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1)
            CALL iom_put( "Dpco2" ,  zw2d )
          ENDIF
          IF( iom_use( "Dpo2" ) )  THEN
-           zw2d(:,:) = ( atcox * patm(:,:) - trb(:,:,1,jpoxy) / ( chemc(:,:,2) + rtrn ) ) * tmask(:,:,1)
+           zw2d(:,:) = ( atcox * patm(:,:) - atcox * trn(:,:,1,jpoxy) / ( chemo2(:,:,1) + rtrn ) ) * tmask(:,:,1)
            CALL iom_put( "Dpo2"  , zw2d )
          ENDIF
@@ -238,9 +250,9 @@
             trc2d(:,:,jp_pcs0_2d + 1) = zoflx(:,:) * 1000 * tmask(:,:,1) 
             trc2d(:,:,jp_pcs0_2d + 2) = zkgco2(:,:) * tmask(:,:,1) 
-            trc2d(:,:,jp_pcs0_2d + 3) = ( satmco2(:,:) * patm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1) 
-         ENDIF
-      ENDIF
-      !
-      CALL wrk_dealloc( jpi, jpj, zkgco2, zkgo2, zh2co3, zoflx )
+            trc2d(:,:,jp_pcs0_2d + 3) = ( zpco2atm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1)
+         ENDIF
+      ENDIF
+      !
+      CALL wrk_dealloc( jpi, jpj, zkgco2, zkgo2, zh2co3, zoflx, zpco2atm )
       !
       IF( nn_timing == 1 )  CALL timing_stop('p4z_flx')
@@ -400,3 +412,3 @@
 
    !!======================================================================
-END MODULE  p4zflx
+END MODULE p4zflx
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zint.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zint.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zint.F90	(revision 9987)
@@ -81,3 +81,3 @@
 
    !!======================================================================
-END MODULE  p4zint
+END MODULE p4zint
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlim.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlim.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlim.F90	(revision 9987)
@@ -44,4 +44,5 @@
    REAL(wp), PUBLIC ::  xkdoc       !:  2nd half-sat. of DOC remineralization  
    REAL(wp), PUBLIC ::  concbfe     !:  Fe half saturation for bacteria 
+   REAL(wp), PUBLIC ::  oxymin      !:  half saturation constant for anoxia
    REAL(wp), PUBLIC ::  qnfelim     !:  optimal Fe quota for nanophyto
    REAL(wp), PUBLIC ::  qdfelim     !:  optimal Fe quota for diatoms
@@ -121,5 +122,5 @@
                zlim1    = xnanono3(ji,jj,jk) + xnanonh4(ji,jj,jk)
                zlim2    = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + concbnh4 )
-               zlim3    = trb(ji,jj,jk,jpfer) / ( concbfe + trb(ji,jj,jk,jpfer) )
+               zlim3    = biron(ji,jj,jk)     / ( concbfe + biron(ji,jj,jk) )
                zlim4    = trb(ji,jj,jk,jpdoc) / ( xkdoc   + trb(ji,jj,jk,jpdoc) )
                xlimbacl(ji,jj,jk) = MIN( zlim1, zlim2, zlim3 )
@@ -187,4 +188,14 @@
       END DO
       !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! denitrification factor computed from O2 levels
+               nitrfac(ji,jj,jk) = MAX(  0.e0, 0.4 * ( 6.e-6  - trb(ji,jj,jk,jpoxy) )    &
+                  &                                / ( oxymin + trb(ji,jj,jk,jpoxy) )  )
+               nitrfac(ji,jj,jk) = MIN( 1., nitrfac(ji,jj,jk) )
+            END DO
+         END DO
+      END DO
       !
       IF( lk_iomput .AND. knt == nrdttrc ) THEN        ! save output diagnostics
@@ -216,5 +227,5 @@
       NAMELIST/nampislim/ concnno3, concdno3, concnnh4, concdnh4, concnfer, concdfer, concbfe,   &
          &                concbno3, concbnh4, xsizedia, xsizephy, xsizern, xsizerd,          & 
-         &                xksi1, xksi2, xkdoc, qnfelim, qdfelim, caco3r
+         &                xksi1, xksi2, xkdoc, qnfelim, qdfelim, caco3r, oxymin
       INTEGER :: ios                 ! Local integer output status for namelist read
 
@@ -249,8 +260,11 @@
          WRITE(numout,*) '    Minimum size criteria for nanophyto      xsizephy  = ', xsizephy
          WRITE(numout,*) '    Fe half saturation for bacteria          concbfe   = ', concbfe
+         WRITE(numout,*) '    halk saturation constant for anoxia       oxymin   =' , oxymin
          WRITE(numout,*) '    optimal Fe quota for nano.               qnfelim   = ', qnfelim
          WRITE(numout,*) '    Optimal Fe quota for diatoms             qdfelim   = ', qdfelim
       ENDIF
-
+      !
+      nitrfac (:,:,:) = 0._wp
+      !
    END SUBROUTINE p4z_lim_init
 
@@ -265,3 +279,3 @@
 
    !!======================================================================
-END MODULE  p4zlim
+END MODULE p4zlim
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlys.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlys.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlys.F90	(revision 9987)
@@ -65,10 +65,10 @@
       REAL(wp) ::   zomegaca, zexcess, zexcess0
       CHARACTER (len=25) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zco3, zcaldiss   
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zco3, zco3sat, zcaldiss   
       !!---------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('p4z_lys')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zco3, zcaldiss )
+      CALL wrk_alloc( jpi, jpj, jpk, zco3, zco3sat, zcaldiss )
       !
       zco3    (:,:,:) = 0.
@@ -91,5 +91,6 @@
                   zalka = trb(ji,jj,jk,jptal) / zfact
                   ! CALCULATE [ALK]([CO3--], [HCO3-])
-                  zalk  = zalka - ( akw3(ji,jj,jk) / zph - zph + borat(ji,jj,jk) / ( 1. + zph / akb3(ji,jj,jk) ) )
+                  zalk  = zalka - ( akw3(ji,jj,jk) / zph - zph / ( aphscale(ji,jj,jk) + rtrn )  &
+                  &       + borat(ji,jj,jk) / ( 1. + zph / akb3(ji,jj,jk) ) )
                   ! CALCULATE [H+] and [CO3--]
                   zaldi = zdic - zalk
@@ -119,5 +120,6 @@
                zcalcon  = calcon * ( tsn(ji,jj,jk,jp_sal) / 35._wp )
                zfact    = rhop(ji,jj,jk) / 1000._wp
-               zomegaca = ( zcalcon * zco3(ji,jj,jk) * zfact ) / aksp(ji,jj,jk) 
+               zomegaca = ( zcalcon * zco3(ji,jj,jk) ) / ( aksp(ji,jj,jk) * zfact + rtrn )
+               zco3sat(ji,jj,jk) = aksp(ji,jj,jk) * zfact / ( zcalcon + rtrn )
 
                ! SET DEGREE OF UNDER-/SUPERSATURATION
@@ -148,11 +150,13 @@
       IF( lk_iomput .AND. knt == nrdttrc ) THEN
          IF( iom_use( "PH"     ) ) CALL iom_put( "PH"    , -1. * LOG10( hi(:,:,:) )          * tmask(:,:,:) )
-         IF( iom_use( "CO3"    ) ) CALL iom_put( "CO3"   , zco3(:,:,:) * 1.e+3               * tmask(:,:,:) )
-         IF( iom_use( "CO3sat" ) ) CALL iom_put( "CO3sat", aksp(:,:,:) * 1.e+3 / calcon      * tmask(:,:,:) )
-         IF( iom_use( "DCAL"   ) ) CALL iom_put( "DCAL"  , zcaldiss(:,:,:) * 1.e+3 * rfact2r   * tmask(:,:,:) )
+         IF( iom_use( "CO3"    ) ) CALL iom_put( "CO3"   , zco3(:,:,:)    * 1.e+3            * tmask(:,:,:) )
+         IF( iom_use( "CO3sat" ) ) CALL iom_put( "CO3sat", zco3sat(:,:,:) * 1.e+3            * tmask(:,:,:) )
+         IF( iom_use( "DCAL"   ) ) CALL iom_put( "DCAL"  , zcaldiss(:,:,:) * 1.e+3 * rfact2r * tmask(:,:,:) )
       ELSE
-         trc3d(:,:,:,jp_pcs0_3d    ) = -1. * LOG10( hi(:,:,:) ) * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 1) = zco3(:,:,:)              * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 2) = aksp(:,:,:) / calcon     * tmask(:,:,:)
+         IF( ln_diatrc ) THEN
+            trc3d(:,:,:,jp_pcs0_3d    ) = -1. * LOG10( hi(:,:,:) ) * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 1) = zco3(:,:,:)              * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 2) = zco3sat(:,:,:)           * tmask(:,:,:)
+         ENDIF
       ENDIF
       !
@@ -163,5 +167,5 @@
       ENDIF
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zco3, zcaldiss )
+      CALL wrk_dealloc( jpi, jpj, jpk, zco3, zco3sat, zcaldiss )
       !
       IF( nn_timing == 1 )  CALL timing_stop('p4z_lys')
@@ -223,3 +227,3 @@
 #endif 
    !!======================================================================
-END MODULE  p4zlys
+END MODULE p4zlys
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmeso.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmeso.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmeso.F90	(revision 9987)
@@ -340,3 +340,3 @@
 
    !!======================================================================
-END MODULE  p4zmeso
+END MODULE p4zmeso
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmicro.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmicro.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmicro.F90	(revision 9987)
@@ -273,3 +273,3 @@
 
    !!======================================================================
-END MODULE  p4zmicro
+END MODULE p4zmicro
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmort.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmort.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmort.F90	(revision 9987)
@@ -277,3 +277,3 @@
 
    !!======================================================================
-END MODULE  p4zmort
+END MODULE p4zmort
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zopt.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zopt.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zopt.F90	(revision 9987)
@@ -76,5 +76,6 @@
       REAL(wp) ::   zchl
       REAL(wp) ::   zc0 , zc1 , zc2, zc3, z1_dep
-      REAL(wp), POINTER, DIMENSION(:,:  ) :: zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4, zqsr100
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zqsr100, zqsr_corr
       REAL(wp), POINTER, DIMENSION(:,:,:) :: zpar, ze0, ze1, ze2, ze3
       !!---------------------------------------------------------------------
@@ -83,5 +84,6 @@
       !
       ! Allocate temporary workspace
-      CALL wrk_alloc( jpi, jpj,      zqsr100, zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4 )
+      CALL wrk_alloc( jpi, jpj,      zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4 )
+      CALL wrk_alloc( jpi, jpj,      zqsr100, zqsr_corr )
       CALL wrk_alloc( jpi, jpj, jpk, zpar, ze0, ze1, ze2, ze3 )
 
@@ -112,8 +114,8 @@
       !                                        !  --------------------------------------
       IF( l_trcdm2dc ) THEN                     !  diurnal cycle
-         ! 1% of qsr to compute euphotic layer
-         zqsr100(:,:) = 0.01 * qsr_mean(:,:)     !  daily mean qsr
-         !
-         CALL p4z_opt_par( kt, qsr_mean, ze1, ze2, ze3 ) 
+         !
+         zqsr_corr(:,:) = qsr_mean(:,:) / ( 1. - fr_i(:,:) + rtrn )
+         !
+         CALL p4z_opt_par( kt, zqsr_corr, ze1, ze2, ze3, pqsr100 = zqsr100 ) 
          !
          DO jk = 1, nksrp      
@@ -123,5 +125,7 @@
          END DO
          !
-         CALL p4z_opt_par( kt, qsr, ze1, ze2, ze3 ) 
+         zqsr_corr(:,:) = qsr(:,:) / ( 1. - fr_i(:,:) + rtrn )
+         !
+         CALL p4z_opt_par( kt, zqsr_corr, ze1, ze2, ze3 ) 
          !
          DO jk = 1, nksrp      
@@ -130,8 +134,8 @@
          !
       ELSE
-         ! 1% of qsr to compute euphotic layer
-         zqsr100(:,:) = 0.01 * qsr(:,:)
-         !
-         CALL p4z_opt_par( kt, qsr, ze1, ze2, ze3 ) 
+         !
+         zqsr_corr(:,:) = qsr(:,:) / ( 1. - fr_i(:,:) + rtrn )
+         !
+         CALL p4z_opt_par( kt, zqsr_corr, ze1, ze2, ze3, pqsr100 = zqsr100 ) 
          !
          DO jk = 1, nksrp      
@@ -161,5 +165,5 @@
          DO jj = 1, jpj
            DO ji = 1, jpi
-              IF( etot_ndcy(ji,jj,jk) * tmask(ji,jj,jk) >= 0.43 * zqsr100(ji,jj) )  THEN
+              IF( etot_ndcy(ji,jj,jk) * tmask(ji,jj,jk) >= zqsr100(ji,jj) )  THEN
                  neln(ji,jj) = jk+1                    ! Euphotic level : 1rst T-level strictly below Euphotic layer
                  !                                     ! nb: ensure the compatibility with nmld_trc definition in trd_mld_trc_zint
@@ -226,5 +230,6 @@
       ENDIF
       !
-      CALL wrk_dealloc( jpi, jpj,      zqsr100, zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4 )
+      CALL wrk_dealloc( jpi, jpj,      zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4 )
+      CALL wrk_dealloc( jpi, jpj,      zqsr100, zqsr_corr )
       CALL wrk_dealloc( jpi, jpj, jpk, zpar,  ze0, ze1, ze2, ze3 )
       !
@@ -233,5 +238,5 @@
    END SUBROUTINE p4z_opt
 
-   SUBROUTINE p4z_opt_par( kt, pqsr, pe1, pe2, pe3, pe0 ) 
+   SUBROUTINE p4z_opt_par( kt, pqsr, pe1, pe2, pe3, pe0, pqsr100 ) 
       !!----------------------------------------------------------------------
       !!                  ***  routine p4z_opt_par  ***
@@ -242,8 +247,9 @@
       !!----------------------------------------------------------------------
       !! * arguments
-      INTEGER, INTENT(in)                                       ::  kt            !   ocean time-step
-      REAL(wp), DIMENSION(jpi,jpj)    , INTENT(in)              ::  pqsr          !   shortwave
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout)           ::  pe1 , pe2 , pe3   !  PAR ( R-G-B)
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout), OPTIONAL ::  pe0  
+      INTEGER, INTENT(in)                                        ::  kt            !   ocean time-step
+      REAL(wp), DIMENSION(jpi,jpj)    , INTENT(in)               ::  pqsr          !   shortwave
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout)            ::  pe1 , pe2 , pe3   !  PAR ( R-G-B)
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout), OPTIONAL  ::  pe0 
+      REAL(wp), DIMENSION(jpi,jpj)    , INTENT(out)  , OPTIONAL  ::  pqsr100  
       !! * local variables
       INTEGER    ::   ji, jj, jk     ! dummy loop indices
@@ -255,4 +261,7 @@
       ELSE                  ;  zqsr(:,:) = xparsw         * pqsr(:,:)
       ENDIF
+
+      !  Light at the euphotic depth 
+      IF( PRESENT( pqsr100 ) )  pqsr100(:,:) = 0.01 * 3. * zqsr(:,:)
       !
       IF( PRESENT( pe0 ) ) THEN     !  W-level
@@ -439,3 +448,3 @@
 
    !!======================================================================
-END MODULE  p4zopt
+END MODULE p4zopt
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zprod.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zprod.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zprod.F90	(revision 9987)
@@ -202,17 +202,13 @@
                       zdiattot    = ediat(ji,jj,jk) * zstrn(ji,jj)
                       !
-                      zpislopead (ji,jj,jk) = pislope  * ( 1.+ zadap  * EXP( -znanotot ) )
-                      zpislopead2(ji,jj,jk) = (pislope * zconctemp2 + pislope2 * zconctemp)  / ( trb(ji,jj,jk,jpdia) + rtrn )
-
-                      zpislopen =  zpislopead(ji,jj,jk) * trb(ji,jj,jk,jpnch)                &
-                        &          / ( trb(ji,jj,jk,jpphy) * 12.                  + rtrn )   &
-                        &          / ( prmax(ji,jj,jk) * rday * xlimphy(ji,jj,jk) + rtrn )
-
-                      zpislope2n = zpislopead2(ji,jj,jk) * trb(ji,jj,jk,jpdch)                &
-                        &          / ( trb(ji,jj,jk,jpdia) * 12.                  + rtrn )   &
-                        &          / ( prmax(ji,jj,jk) * rday * xlimdia(ji,jj,jk) + rtrn )
+                      zpislopead (ji,jj,jk) = pislope  * ( 1.+ zadap  * EXP( -znanotot ) )           &
+                         &                   * trb(ji,jj,jk,jpnch) /( trb(ji,jj,jk,jpphy) * 12. + rtrn)
+                      zpislopead2(ji,jj,jk) = (pislope * zconctemp2 + pislope2 * zconctemp)  / ( trb(ji,jj,jk,jpdia) + rtrn )   &
+                         &                   * trb(ji,jj,jk,jpdch) /( trb(ji,jj,jk,jpdia) * 12. + rtrn)
 
                       ! Computation of production function for Carbon
                       !  ---------------------------------------------
+                      zpislopen  =  zpislopead(ji,jj,jk)  / ( prmax(ji,jj,jk) * rday * xlimphy(ji,jj,jk) + rtrn )
+                      zpislope2n =  zpislopead2(ji,jj,jk) / ( prmax(ji,jj,jk) * rday * xlimdia(ji,jj,jk) + rtrn )
                       zprbio(ji,jj,jk) = zprbio(ji,jj,jk) * ( 1.- EXP( -zpislopen  * znanotot ) )
                       zprdia(ji,jj,jk) = zprdia(ji,jj,jk) * ( 1.- EXP( -zpislope2n * zdiattot ) )
@@ -220,6 +216,6 @@
                       !  Computation of production function for Chlorophyll
                       !--------------------------------------------------
-                      zprnch(ji,jj,jk) = prmax(ji,jj,jk) * ( 1.- EXP( -zpislopen  * enano(ji,jj,jk) ) )
-                      zprdch(ji,jj,jk) = prmax(ji,jj,jk) * ( 1.- EXP( -zpislope2n * ediat(ji,jj,jk) ) )
+                      zprnch(ji,jj,jk) = prmax(ji,jj,jk) * ( 1.- EXP( -zpislopen  * znanotot ) )
+                      zprdch(ji,jj,jk) = prmax(ji,jj,jk) * ( 1.- EXP( -zpislope2n * zdiattot ) )
                   ENDIF
                END DO
@@ -227,6 +223,5 @@
          END DO
       ENDIF
-
-
+      
       !  Computation of a proxy of the N/C ratio
       !  ---------------------------------------
@@ -278,10 +273,12 @@
             zmxltst = MAX( 0.e0, hmld(ji,jj) - heup(ji,jj) )
             zmxlday = zmxltst * zmxltst * r1_rday
-            zmixnano(ji,jj) = 1. - zmxlday / ( 2. + zmxlday )
-            zmixdiat(ji,jj) = 1. - zmxlday / ( 4. + zmxlday )
+            zmixnano(ji,jj) = 1. - zmxlday / ( 1. + zmxlday )
+            zmixdiat(ji,jj) = 1. - zmxlday / ( 2. + zmxlday )
          END DO
       END DO
  
-      !  Mixed-layer effect on production                                                                               
+      !  Mixed-layer effect on production 
+      !  Sea-ice effect on production
+
       DO jk = 1, jpkm1
          DO jj = 1, jpj
@@ -291,4 +288,6 @@
                   zprdia(ji,jj,jk) = zprdia(ji,jj,jk) * zmixdiat(ji,jj)
                ENDIF
+                  zprbio(ji,jj,jk) = zprbio(ji,jj,jk) * ( 1. - fr_i(ji,jj) )
+                  zprdia(ji,jj,jk) = zprdia(ji,jj,jk) * ( 1. - fr_i(ji,jj) )
             END DO
          END DO
@@ -330,57 +329,31 @@
       END DO
 
-      IF( ln_newprod ) THEN
-!CDIR NOVERRCHK
-         DO jk = 1, jpkm1
-!CDIR NOVERRCHK
-            DO jj = 1, jpj
-!CDIR NOVERRCHK
-               DO ji = 1, jpi
-                  IF( fsdepw(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
-                     zprnch(ji,jj,jk) = zprnch(ji,jj,jk) * zmixnano(ji,jj)
-                     zprdch(ji,jj,jk) = zprdch(ji,jj,jk) * zmixdiat(ji,jj)
-                  ENDIF
-                  IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
-                     !  production terms for nanophyto. ( chlorophyll )
-                     znanotot = enano(ji,jj,jk) * zstrn(ji,jj)
-                     zprod    = rday * zprorca(ji,jj,jk) * zprnch(ji,jj,jk) * xlimphy(ji,jj,jk)
-                     zprochln(ji,jj,jk) = chlcmin * 12. * zprorca (ji,jj,jk)
-                     zprochln(ji,jj,jk) = zprochln(ji,jj,jk) + (chlcnm-chlcmin) * 12. * zprod / &
-                                        & (  zpislopead(ji,jj,jk) * znanotot +rtrn)
-                     !  production terms for diatomees ( chlorophyll )
-                     zdiattot = ediat(ji,jj,jk) * zstrn(ji,jj)
-                     zprod = rday * zprorcad(ji,jj,jk) * zprdch(ji,jj,jk) * xlimdia(ji,jj,jk)
-                     zprochld(ji,jj,jk) = chlcmin * 12. * zprorcad(ji,jj,jk)
-                     zprochld(ji,jj,jk) = zprochld(ji,jj,jk) + (chlcdm-chlcmin) * 12. * zprod / &
-                                        & ( zpislopead2(ji,jj,jk) * zdiattot +rtrn )
-                  ENDIF
-               END DO
-            END DO
-         END DO
-      ELSE
-!CDIR NOVERRCHK
-         DO jk = 1, jpkm1
-!CDIR NOVERRCHK
-            DO jj = 1, jpj
-!CDIR NOVERRCHK
-               DO ji = 1, jpi
-                  IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
-                     !  production terms for nanophyto. ( chlorophyll )
-                     znanotot = enano(ji,jj,jk)
-                     zprod = rday * zprorca(ji,jj,jk) * zprnch(ji,jj,jk) * trb(ji,jj,jk,jpphy) * xlimphy(ji,jj,jk)
-                     zprochln(ji,jj,jk) = chlcmin * 12. * zprorca (ji,jj,jk)
-                     zprochln(ji,jj,jk) = zprochln(ji,jj,jk) + (chlcnm-chlcmin) * 144. * zprod            &
-                     &                    / ( zpislopead(ji,jj,jk) * trb(ji,jj,jk,jpnch) * znanotot +rtrn )
-                     !  production terms for diatomees ( chlorophyll )
-                     zdiattot = ediat(ji,jj,jk)
-                     zprod = rday * zprorcad(ji,jj,jk) * zprdch(ji,jj,jk) * trb(ji,jj,jk,jpdia) * xlimdia(ji,jj,jk)
-                     zprochld(ji,jj,jk) = chlcmin * 12. * zprorcad(ji,jj,jk)
-                     zprochld(ji,jj,jk) = zprochld(ji,jj,jk) + (chlcdm-chlcmin) * 144. * zprod             &
-                     &                    / ( zpislopead2(ji,jj,jk) * trb(ji,jj,jk,jpdch) * zdiattot +rtrn )
-                  ENDIF
-               END DO
-            END DO
-         END DO
-      ENDIF
+!CDIR NOVERRCHK
+      DO jk = 1, jpkm1
+!CDIR NOVERRCHK
+         DO jj = 1, jpj
+!CDIR NOVERRCHK
+            DO ji = 1, jpi
+               IF( fsdepw(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
+                  zprnch(ji,jj,jk) = zprnch(ji,jj,jk) * zmixnano(ji,jj)
+                  zprdch(ji,jj,jk) = zprdch(ji,jj,jk) * zmixdiat(ji,jj)
+               ENDIF
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !  production terms for nanophyto. ( chlorophyll )
+                  znanotot = enano(ji,jj,jk) * zstrn(ji,jj)
+                  zprod    = rday * zprorca(ji,jj,jk) * zprnch(ji,jj,jk) * xlimphy(ji,jj,jk)
+                  zprochln(ji,jj,jk) = chlcmin * 12. * zprorca (ji,jj,jk)
+                  zprochln(ji,jj,jk) = zprochln(ji,jj,jk) + (chlcnm-chlcmin) * 12. * zprod / &
+                                     & (  zpislopead(ji,jj,jk) * znanotot +rtrn)
+                  !  production terms for diatomees ( chlorophyll )
+                  zdiattot = ediat(ji,jj,jk) * zstrn(ji,jj)
+                  zprod = rday * zprorcad(ji,jj,jk) * zprdch(ji,jj,jk) * xlimdia(ji,jj,jk)
+                  zprochld(ji,jj,jk) = chlcmin * 12. * zprorcad(ji,jj,jk)
+                  zprochld(ji,jj,jk) = zprochld(ji,jj,jk) + (chlcdm-chlcmin) * 12. * zprod / &
+                                     & ( zpislopead2(ji,jj,jk) * zdiattot +rtrn )
+               ENDIF
+            END DO
+         END DO
+      END DO
 
       !   Update the arrays TRA which contain the biological sources and sinks
@@ -629,3 +602,3 @@
 
    !!======================================================================
-END MODULE  p4zprod
+END MODULE p4zprod
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zrem.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zrem.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zrem.F90	(revision 9987)
@@ -44,6 +44,4 @@
    REAL(wp), PUBLIC ::  xsiremlab  !: fast remineralisation rate of POC 
    REAL(wp), PUBLIC ::  xsilab     !: fraction of labile biogenic silica 
-   REAL(wp), PUBLIC ::  oxymin     !: halk saturation constant for anoxia 
-
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   denitr     !: denitrification array
@@ -111,15 +109,4 @@
                   zdepprod(ji,jj,jk) = zdepmin**0.273
                ENDIF
-            END DO
-         END DO
-      END DO
-
-      DO jk = 1, jpkm1
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               ! denitrification factor computed from O2 levels
-               nitrfac(ji,jj,jk) = MAX(  0.e0, 0.4 * ( 6.e-6  - trb(ji,jj,jk,jpoxy) )    &
-                  &                                / ( oxymin + trb(ji,jj,jk,jpoxy) )  )
-               nitrfac(ji,jj,jk) = MIN( 1., nitrfac(ji,jj,jk) )
             END DO
          END DO
@@ -357,6 +344,5 @@
       !!
       !!----------------------------------------------------------------------
-      NAMELIST/nampisrem/ xremik, xremip, nitrif, xsirem, xsiremlab, xsilab,   &
-      &                   oxymin
+      NAMELIST/nampisrem/ xremik, xremip, nitrif, xsirem, xsiremlab, xsilab
       INTEGER :: ios                 ! Local integer output status for namelist read
 
@@ -380,8 +366,6 @@
          WRITE(numout,*) '    fraction of labile biogenic silica        xsilab    =', xsilab
          WRITE(numout,*) '    NH4 nitrification rate                    nitrif    =', nitrif
-         WRITE(numout,*) '    halk saturation constant for anoxia       oxymin    =', oxymin
       ENDIF
       !
-      nitrfac (:,:,:) = 0._wp
       denitr  (:,:,:) = 0._wp
       denitnh4(:,:,:) = 0._wp
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsbc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsbc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsbc.F90	(revision 9987)
@@ -159,10 +159,11 @@
       IF( ln_ndepo ) THEN
          IF( kt == nit000 .OR. ( kt /= nit000 .AND. ntimes_ndep > 1 ) ) THEN
-            CALL fld_read( kt, 1, sf_ndepo )
-            DO jj = 1, jpj
-               DO ji = 1, jpi
-                  nitdep(ji,jj) = sf_ndepo(1)%fnow(ji,jj,1) / rno3 / ( 14E6 * ryyss * fse3t(ji,jj,1) + rtrn )
-               END DO
-            END DO
+             zcoef = rno3 * 14E6 * ryyss
+             CALL fld_read( kt, 1, sf_ndepo )
+             nitdep(:,:) = sf_ndepo(1)%fnow(:,:,1) / zcoef / fse3t(:,:,1) 
+         ENDIF
+         IF( lk_vvl ) THEN
+           zcoef = rno3 * 14E6 * ryyss
+           nitdep(:,:) = sf_ndepo(1)%fnow(:,:,1) / zcoef / fse3t(:,:,1) 
          ENDIF
       ENDIF
@@ -455,5 +456,5 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zexpide   = MIN( 8.,( fsdept(ji,jj,jk) / 500. )**(-1.5) )
+                  zexpide   = MIN( 8.,( gdept_0(ji,jj,jk) / 500. )**(-1.5) )
                   zdenitide = -0.9543 + 0.7662 * LOG( zexpide ) - 0.235 * LOG( zexpide )**2
                   zcmask(ji,jj,jk) = zcmask(ji,jj,jk) * MIN( 1., EXP( zdenitide ) / 0.5 )
@@ -465,5 +466,5 @@
          ironsed(:,:,jpk) = 0._wp
          DO jk = 1, jpkm1
-            ironsed(:,:,jk) = sedfeinput * zcmask(:,:,jk) / ( fse3t(:,:,jk) * rday )
+            ironsed(:,:,jk) = sedfeinput * zcmask(:,:,jk) / ( e3t_0(:,:,jk) * rday )
          END DO
          DEALLOCATE( zcmask)
@@ -483,5 +484,7 @@
          CALL iom_close( numhydro )
          !
-         hydrofe(:,:,:) = ( hydrofe(:,:,:) * hratio ) / ( cvol(:,:,:) * ryyss + rtrn ) / 1000._wp
+         DO jk = 1, jpk
+            hydrofe(:,:,jk) = ( hydrofe(:,:,jk) * hratio ) / ( e1e2t(:,:) * e3t_0(:,:,jk) * ryyss + rtrn ) / 1000._wp
+         ENDDO
          !
       ENDIF
@@ -519,3 +522,3 @@
 
    !!======================================================================
-END MODULE  p4zsbc
+END MODULE p4zsbc
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsed.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsed.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsed.F90	(revision 9987)
@@ -72,4 +72,5 @@
       CHARACTER (len=25) :: charout
       REAL(wp), POINTER, DIMENSION(:,:  ) :: zpdep, zsidep, zwork1, zwork2, zwork3
+      REAL(wp), POINTER, DIMENSION(:,:)   :: zsedcal, zsedsi, zsedc
       REAL(wp), POINTER, DIMENSION(:,:  ) :: zdenit2d, zironice, zbureff
       REAL(wp), POINTER, DIMENSION(:,:  ) :: zwsbio3, zwsbio4, zwscal
@@ -83,4 +84,5 @@
       ! Allocate temporary workspace
       CALL wrk_alloc( jpi, jpj, zdenit2d, zwork1, zwork2, zwork3, zbureff )
+      CALL wrk_alloc( jpi, jpj, zsedcal,  zsedsi, zsedc )
       CALL wrk_alloc( jpi, jpj, zwsbio3, zwsbio4, zwscal )
       CALL wrk_alloc( jpi, jpj, jpk, zsoufer )
@@ -91,4 +93,7 @@
       zwork2  (:,:) = 0.e0
       zwork3  (:,:) = 0.e0
+      zsedsi   (:,:) = 0.e0
+      zsedcal  (:,:) = 0.e0
+      zsedc    (:,:) = 0.e0
 
       ! Iron input/uptake due to sea ice : Crude parameterization based on Lancelot et al.
@@ -298,4 +303,6 @@
             tra(ji,jj,ikt,jptal) =  tra(ji,jj,ikt,jptal) + zcaloss * zrivalk * 2.0
             tra(ji,jj,ikt,jpdic) =  tra(ji,jj,ikt,jpdic) + zcaloss * zrivalk
+            zsedcal(ji,jj) = (1.0 - zrivalk) * zcaloss / zdep
+            zsedsi (ji,jj) = (1.0 - zrivsil) * zsiloss / zdep
 #endif
          END DO
@@ -336,5 +343,6 @@
             tra(ji,jj,ikt,jptal) = tra(ji,jj,ikt,jptal) + rno3 * (zolimit + (1.+rdenit) * (zpdenit + zdenitt) )
             tra(ji,jj,ikt,jpdic) = tra(ji,jj,ikt,jpdic) + zpdenit + zolimit + zdenitt
-            sdenit(ji,jj) = rdenit * zpdenit * fse3t(ji,jj,ikt)
+            sdenit(ji,jj) = rdenit * zpdenit / zdep
+            zsedc(ji,jj)   = (1. - zrivno3) * zwstpoc / zdep
 #endif
          END DO
@@ -392,4 +400,8 @@
                CALL iom_put( "INTNFIX" , zwork1 ) 
             ENDIF
+            IF( iom_use("SedCal" ) ) CALL iom_put( "SedCal", zsedcal(:,:) * 1.e+3 )
+            IF( iom_use("SedSi" ) )  CALL iom_put( "SedSi",  zsedsi (:,:) * 1.e+3 )
+            IF( iom_use("SedC" ) )   CALL iom_put( "SedC",   zsedc  (:,:) * 1.e+3 )
+            IF( iom_use("Sdenit" ) ) CALL iom_put( "Sdenit", sdenit (:,:) * 1.e+3 * rno3 )
          ENDIF
       ELSE
@@ -405,4 +417,5 @@
       !
       CALL wrk_dealloc( jpi, jpj, zdenit2d, zwork1, zwork2, zwork3, zbureff )
+      CALL wrk_dealloc( jpi, jpj, zsedcal , zsedsi, zsedc )
       CALL wrk_dealloc( jpi, jpj, zwsbio3, zwsbio4, zwscal )
       CALL wrk_dealloc( jpi, jpj, jpk, zsoufer )
@@ -436,3 +449,3 @@
 
    !!======================================================================
-END MODULE  p4zsed
+END MODULE p4zsed
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsink.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsink.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsink.F90	(revision 9987)
@@ -913,3 +913,3 @@
 
    !!======================================================================
-END MODULE  p4zsink
+END MODULE p4zsink
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsms.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsms.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsms.F90	(revision 9987)
@@ -38,5 +38,5 @@
 
    REAL(wp) :: alkbudget, no3budget, silbudget, ferbudget, po4budget
-   REAL(wp) :: xfact1, xfact2
+   REAL(wp) :: xfact1, xfact2, xfact3
    INTEGER ::  numco2, numnut, numnit  !: logical unit for co2 budget
 
@@ -133,6 +133,6 @@
          !
          CALL p4z_bio( kt, jnt )   ! Biology
-         CALL p4z_sed( kt, jnt )   ! Sedimentation
          CALL p4z_lys( kt, jnt )   ! Compute CaCO3 saturation
+         CALL p4z_sed( kt, jnt )   ! Surface and Bottom boundary conditions
          CALL p4z_flx( kt, jnt )   ! Compute surface fluxes
          !
@@ -474,7 +474,6 @@
       !!---------------------------------------------------------------------
       !
-      INTEGER , INTENT( in ) ::   kt      ! ocean time-step index      
-      REAL(wp)               ::  zfact       
-      REAL(wp) ::  zrdenittot, zsdenittot, znitrpottot
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      REAL(wp)             ::  zrdenittot, zsdenittot, znitrpottot
       CHARACTER(LEN=100)   ::   cltxt
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zvol
@@ -492,4 +491,5 @@
             xfact1 = rfact2r * 12. / 1.e15 * ryyss    ! conversion molC/kt --> PgC/yr
             xfact2 = 1.e+3 * rno3 * 14. / 1.e12 * ryyss   ! conversion molC/l/s ----> TgN/m3/yr
+            xfact3 = 1.e+3 * rfact2r * rno3   ! conversion molC/l/kt ----> molN/m3/s
             cltxt='time-step   Alkalinity        Nitrate        Phosphorus         Silicate           Iron'
             IF( lwp ) WRITE(numnut,*)  TRIM(cltxt)
@@ -574,5 +574,5 @@
       IF( iom_use( "Sdenit" ) .OR.  ( ln_check_mass .AND. kt == nitend )  ) THEN
          zsdenittot   = glob_sum ( sdenit(:,:) * e1e2t(:,:) )
-         CALL iom_put( "Sdenit", sdenit(:,:) * zfact * tmask(:,:,1) )  ! Nitrate reduction in the sediments
+         CALL iom_put( "Sdenit", sdenit(:,:) * xfact3 * tmask(:,:,1) )  ! Nitrate reduction in the sediments
       ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/sms_pisces.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/sms_pisces.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/sms_pisces.F90	(revision 9987)
@@ -101,4 +101,6 @@
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hi         !: ???
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   excess     !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   aphscale   !: 
+
 
    !!* Temperature dependancy of SMS terms
@@ -154,5 +156,6 @@
          &      ak23(jpi,jpj,jpk)    , aksp  (jpi,jpj,jpk) ,       &
          &      akw3(jpi,jpj,jpk)    , borat (jpi,jpj,jpk) ,       &
-         &      hi  (jpi,jpj,jpk)    , excess(jpi,jpj,jpk) ,     STAT=ierr(4) )
+         &      hi  (jpi,jpj,jpk)    , excess(jpi,jpj,jpk) ,       &
+         &      aphscale(jpi,jpj,jpk),                           STAT=ierr(4) )
          !
       !* Temperature dependancy of SMS terms
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/trcice_pisces.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/trcice_pisces.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/trcice_pisces.F90	(revision 9987)
@@ -29,7 +29,24 @@
 CONTAINS
 
+
    SUBROUTINE trc_ice_ini_pisces
       !!----------------------------------------------------------------------
-      !!                   ***  ROUTINE trc_ice_ini_pisces ***
+      !!                   ***  ROUTINE trc_ini_pisces ***
+      !!
+      !! ** Purpose :   Initialisation of the PISCES biochemical model
+      !!----------------------------------------------------------------------
+
+      IF( lk_p4z ) THEN  ;   CALL p4z_ice_ini   !  PISCES
+      ELSE               ;   CALL p2z_ice_ini   !  LOBSTER
+      ENDIF
+
+   END SUBROUTINE trc_ice_ini_pisces
+
+
+   SUBROUTINE p4z_ice_ini
+
+#if defined key_pisces 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE p4z_ice_ini ***
       !!
       !! ** Purpose :   PISCES fake sea ice model setting
@@ -58,6 +75,8 @@
 
                                         !--- Dummy variables
-      REAL(wp), DIMENSION(jptra,2) &
-               ::  zratio            ! effective ice-ocean tracer cc ratio
+      REAL(wp), DIMENSION(jp_pisces,2)  :: zratio  ! effective ice-ocean tracer cc ratio
+      REAL(wp), DIMENSION(jp_pisces,4)  :: zpisc   ! prescribes concentration 
+      !                                            !  1:global, 2:Arctic, 3:Antarctic, 4:Baltic
+
       REAL(wp), DIMENSION(2) :: zrs  ! ice-ocean salinity ratio, 1 - global, 2- Baltic
       REAL(wp) :: zsice_bal          ! prescribed ice salinity in the Baltic
@@ -80,128 +99,139 @@
       ! fluxes
 
-      !--- Global case 
-      IF ( cn_trc_o(jpdic) == 'GL ' ) trc_o(:,:,jpdic) =  1.99e-3_wp 
-      IF ( cn_trc_o(jpdoc) == 'GL ' ) trc_o(:,:,jpdoc) =  2.04e-5_wp 
-      IF ( cn_trc_o(jptal) == 'GL ' ) trc_o(:,:,jptal) =  2.31e-3_wp 
-      IF ( cn_trc_o(jpoxy) == 'GL ' ) trc_o(:,:,jpoxy) =  2.47e-4_wp
-      IF ( cn_trc_o(jpcal) == 'GL ' ) trc_o(:,:,jpcal) =  1.04e-8_wp
-      IF ( cn_trc_o(jppo4) == 'GL ' ) trc_o(:,:,jppo4) =  5.77e-7_wp / po4r 
-      IF ( cn_trc_o(jppoc) == 'GL ' ) trc_o(:,:,jppoc) =  1.27e-6_wp  
+      !--- Global values
+      zpisc(jpdic,1) =  1.99e-3_wp 
+      zpisc(jpdoc,1) =  2.04e-5_wp 
+      zpisc(jptal,1) =  2.31e-3_wp 
+      zpisc(jpoxy,1) =  2.47e-4_wp
+      zpisc(jpcal,1) =  1.04e-8_wp
+      zpisc(jppo4,1) =  5.77e-7_wp / po4r 
+      zpisc(jppoc,1) =  1.27e-6_wp  
 #  if ! defined key_kriest
-      IF ( cn_trc_o(jpgoc) == 'GL ' ) trc_o(:,:,jpgoc) =  5.23e-8_wp  
-      IF ( cn_trc_o(jpbfe) == 'GL ' ) trc_o(:,:,jpbfe) =  9.84e-13_wp 
+      zpisc(jpgoc,1) =  5.23e-8_wp  
+      zpisc(jpbfe,1) =  9.84e-13_wp 
 #  else
-      IF ( cn_trc_o(jpnum) == 'GL ' ) trc_o(:,:,jpnum) = 0. ! could not get this value since did not use it
+      zpisc(jpnum,1) = 0. ! could not get this value since did not use it
 #  endif
-      IF ( cn_trc_o(jpsil) == 'GL ' ) trc_o(:,:,jpsil) =  7.36e-6_wp  
-      IF ( cn_trc_o(jpdsi) == 'GL ' ) trc_o(:,:,jpdsi) =  1.07e-7_wp 
-      IF ( cn_trc_o(jpgsi) == 'GL ' ) trc_o(:,:,jpgsi) =  1.53e-8_wp
-      IF ( cn_trc_o(jpphy) == 'GL ' ) trc_o(:,:,jpphy) =  9.57e-8_wp
-      IF ( cn_trc_o(jpdia) == 'GL ' ) trc_o(:,:,jpdia) =  4.24e-7_wp
-      IF ( cn_trc_o(jpzoo) == 'GL ' ) trc_o(:,:,jpzoo) =  6.07e-7_wp
-      IF ( cn_trc_o(jpmes) == 'GL ' ) trc_o(:,:,jpmes) =  3.44e-7_wp
-      IF ( cn_trc_o(jpfer) == 'GL ' ) trc_o(:,:,jpfer) =  4.06e-10_wp
-      IF ( cn_trc_o(jpsfe) == 'GL ' ) trc_o(:,:,jpsfe) =  2.51e-11_wp
-      IF ( cn_trc_o(jpdfe) == 'GL ' ) trc_o(:,:,jpdfe) =  6.57e-12_wp
-      IF ( cn_trc_o(jpnfe) == 'GL ' ) trc_o(:,:,jpnfe) =  1.76e-11_wp
-      IF ( cn_trc_o(jpnch) == 'GL ' ) trc_o(:,:,jpnch) =  1.67e-7_wp
-      IF ( cn_trc_o(jpdch) == 'GL ' ) trc_o(:,:,jpdch) =  1.02e-7_wp
-      IF ( cn_trc_o(jpno3) == 'GL ' ) trc_o(:,:,jpno3) =  5.79e-6_wp / rno3 
-      IF ( cn_trc_o(jpnh4) == 'GL ' ) trc_o(:,:,jpnh4) =  3.22e-7_wp / rno3
+      zpisc(jpsil,1) =  7.36e-6_wp  
+      zpisc(jpdsi,1) =  1.07e-7_wp 
+      zpisc(jpgsi,1) =  1.53e-8_wp
+      zpisc(jpphy,1) =  9.57e-8_wp
+      zpisc(jpdia,1) =  4.24e-7_wp
+      zpisc(jpzoo,1) =  6.07e-7_wp
+      zpisc(jpmes,1) =  3.44e-7_wp
+      zpisc(jpfer,1) =  4.06e-10_wp
+      zpisc(jpsfe,1) =  2.51e-11_wp
+      zpisc(jpdfe,1) =  6.57e-12_wp
+      zpisc(jpnfe,1) =  1.76e-11_wp
+      zpisc(jpnch,1) =  1.67e-7_wp
+      zpisc(jpdch,1) =  1.02e-7_wp
+      zpisc(jpno3,1) =  5.79e-6_wp / rno3 
+      zpisc(jpnh4,1) =  3.22e-7_wp / rno3
 
       !--- Arctic specificities (dissolved inorganic & DOM)
-      IF ( cn_trc_o(jpdic) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpdic) =  1.98e-3_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdoc) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpdoc) =  6.00e-6_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jptal) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jptal) =  2.13e-3_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpoxy) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpoxy) =  3.65e-4_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpcal) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpcal) =  1.50e-9_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jppo4) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jppo4) =  4.09e-7_wp / po4r ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jppoc) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jppoc) =  4.05e-7_wp  ; END WHERE ; ENDIF
+      zpisc(jpdic,2) =  1.98e-3_wp 
+      zpisc(jpdoc,2) =  6.00e-6_wp 
+      zpisc(jptal,2) =  2.13e-3_wp 
+      zpisc(jpoxy,2) =  3.65e-4_wp  
+      zpisc(jpcal,2) =  1.50e-9_wp  
+      zpisc(jppo4,2) =  4.09e-7_wp / po4r 
+      zpisc(jppoc,2) =  4.05e-7_wp  
 #  if ! defined key_kriest
-      IF ( cn_trc_o(jpgoc) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpgoc) =  2.84e-8_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpbfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpbfe) =  7.03e-13_wp ; END WHERE ; ENDIF
+      zpisc(jpgoc,2) =  2.84e-8_wp  
+      zpisc(jpbfe,2) =  7.03e-13_wp 
 #  else
-      IF ( cn_trc_o(jpnum) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpnum) =  0.00e-00_wp ; END WHERE ; ENDIF
+      zpisc(jpnum,2) =  0.00e-00_wp 
 #  endif
-      IF ( cn_trc_o(jpsil) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpsil) =  6.87e-6_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdsi) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpdsi) =  1.73e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpgsi) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpgsi) =  7.93e-9_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpphy) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpphy) =  5.25e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdia) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpdia) =  7.75e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpzoo) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpzoo) =  3.34e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpmes) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpmes) =  2.49e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpfer) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpfer) =  1.43e-9_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpsfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpsfe) =  2.21e-11_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpdfe) =  2.04e-11_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpnfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpnfe) =  1.75e-11_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpnch) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpnch) =  1.46e-07_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdch) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpdch) =  2.36e-07_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpno3) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpno3) =  3.51e-06_wp / rno3 ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpnh4) == 'AA ' ) THEN ; WHERE( gphit(:,:) >= 00._wp ) ; trc_o(:,:,jpnh4) =  6.15e-08_wp / rno3 ; END WHERE ; ENDIF
+      zpisc(jpsil,2) =  6.87e-6_wp  
+      zpisc(jpdsi,2) =  1.73e-7_wp 
+      zpisc(jpgsi,2) =  7.93e-9_wp
+      zpisc(jpphy,2) =  5.25e-7_wp  
+      zpisc(jpdia,2) =  7.75e-7_wp 
+      zpisc(jpzoo,2) =  3.34e-7_wp
+      zpisc(jpmes,2) =  2.49e-7_wp  
+      zpisc(jpfer,2) =  1.43e-9_wp 
+      zpisc(jpsfe,2) =  2.21e-11_wp 
+      zpisc(jpdfe,2) =  2.04e-11_wp 
+      zpisc(jpnfe,2) =  1.75e-11_wp 
+      zpisc(jpnch,2) =  1.46e-07_wp 
+      zpisc(jpdch,2) =  2.36e-07_wp 
+      zpisc(jpno3,2) =  3.51e-06_wp / rno3 
+      zpisc(jpnh4,2) =  6.15e-08_wp / rno3 
 
       !--- Antarctic specificities (dissolved inorganic & DOM)
-      IF ( cn_trc_o(jpdic) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpdic) =  2.20e-3_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdoc) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpdoc) =  7.02e-6_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jptal) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jptal) =  2.37e-3_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpoxy) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpoxy) =  3.42e-4_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpcal) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpcal) =  3.17e-9_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jppo4) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jppo4) =  1.88e-6_wp / po4r  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jppoc) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jppoc) =  1.13e-6_wp  ; END WHERE ; ENDIF
+      zpisc(jpdic,3) =  2.20e-3_wp  
+      zpisc(jpdoc,3) =  7.02e-6_wp  
+      zpisc(jptal,3) =  2.37e-3_wp  
+      zpisc(jpoxy,3) =  3.42e-4_wp  
+      zpisc(jpcal,3) =  3.17e-9_wp  
+      zpisc(jppo4,3) =  1.88e-6_wp / po4r  
+      zpisc(jppoc,3) =  1.13e-6_wp  
 #  if ! defined key_kriest
-      IF ( cn_trc_o(jpgoc) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpgoc) =  2.89e-8_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpbfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpbfe) =  5.63e-13_wp ; END WHERE ; ENDIF
+      zpisc(jpgoc,3) =  2.89e-8_wp  
+      zpisc(jpbfe,3) =  5.63e-13_wp 
 #  else
-      IF ( cn_trc_o(jpnum) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpnum) =  0.00e-00_wp ; END WHERE ; ENDIF
+      zpisc(jpnum,3) =  0.00e-00_wp 
 #  endif
-      IF ( cn_trc_o(jpsil) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpsil) =  4.96e-5_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdsi) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpdsi) =  5.63e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpgsi) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpgsi) =  5.35e-8_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpphy) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpphy) =  8.10e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdia) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpdia) =  5.77e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpzoo) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpzoo) =  6.68e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpmes) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpmes) =  3.55e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpfer) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpfer) =  1.62e-10_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpsfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpsfe) =  2.29e-11_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpdfe) =  8.75e-12_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpnfe) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpnfe) =  1.48e-11_wp ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpnch) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpnch) =  2.02e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpdch) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpdch) =  1.60e-7_wp  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpno3) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpno3) =  2.64e-5_wp / rno3  ; END WHERE ; ENDIF
-      IF ( cn_trc_o(jpnh4) == 'AA ' ) THEN ; WHERE( gphit(:,:) <  00._wp ) ; trc_o(:,:,jpnh4) =  3.39e-7_wp / rno3  ; END WHERE ; ENDIF
+      zpisc(jpsil,3) =  4.96e-5_wp  
+      zpisc(jpdsi,3) =  5.63e-7_wp 
+      zpisc(jpgsi,3) =  5.35e-8_wp
+      zpisc(jpphy,3) =  8.10e-7_wp  
+      zpisc(jpdia,3) =  5.77e-7_wp 
+      zpisc(jpzoo,3) =  6.68e-7_wp
+      zpisc(jpmes,3) =  3.55e-7_wp  
+      zpisc(jpfer,3) =  1.62e-10_wp
+      zpisc(jpsfe,3) =  2.29e-11_wp 
+      zpisc(jpdfe,3) =  8.75e-12_wp
+      zpisc(jpnfe,3) =  1.48e-11_wp 
+      zpisc(jpnch,3) =  2.02e-7_wp  
+      zpisc(jpdch,3) =  1.60e-7_wp  
+      zpisc(jpno3,3) =  2.64e-5_wp / rno3  
+      zpisc(jpnh4,3) =  3.39e-7_wp / rno3  
 
       !--- Baltic Sea particular case for ORCA configurations
-      IF( cp_cfg == "orca" ) THEN            ! Baltic mask
-         WHERE( 14._wp <= glamt(:,:) .AND. glamt(:,:) <= 32._wp .AND.    &
-                54._wp <= gphit(:,:) .AND. gphit(:,:) <= 66._wp )
-         trc_o(:,:,jpdic) = 1.14e-3_wp
-         trc_o(:,:,jpdoc) = 1.06e-5_wp
-         trc_o(:,:,jptal) = 1.16e-3_wp
-         trc_o(:,:,jpoxy) = 3.71e-4_wp
-         trc_o(:,:,jpcal) = 1.51e-9_wp
-         trc_o(:,:,jppo4) = 2.85e-9_wp / po4r
-         trc_o(:,:,jppoc) = 4.84e-7_wp
+      zpisc(jpdic,4) = 1.14e-3_wp
+      zpisc(jpdoc,4) = 1.06e-5_wp
+      zpisc(jptal,4) = 1.16e-3_wp
+      zpisc(jpoxy,4) = 3.71e-4_wp
+      zpisc(jpcal,4) = 1.51e-9_wp
+      zpisc(jppo4,4) = 2.85e-9_wp / po4r
+      zpisc(jppoc,4) = 4.84e-7_wp
 #  if ! defined key_kriest
-         trc_o(:,:,jpgoc) = 1.05e-8_wp
-         trc_o(:,:,jpbfe) = 4.97e-13_wp
+      zpisc(jpgoc,4) = 1.05e-8_wp
+      zpisc(jpbfe,4) = 4.97e-13_wp
 #  else
-         trc_o(:,:,jpnum) = 0. ! could not get this value
+      zpisc(jpnum,4) = 0. ! could not get this value
 #  endif
-         trc_o(:,:,jpsil) = 4.91e-5_wp
-         trc_o(:,:,jpdsi) = 3.25e-7_wp
-         trc_o(:,:,jpgsi) = 1.93e-8_wp
-         trc_o(:,:,jpphy) = 6.64e-7_wp
-         trc_o(:,:,jpdia) = 3.41e-7_wp
-         trc_o(:,:,jpzoo) = 3.83e-7_wp
-         trc_o(:,:,jpmes) = 0.225e-6_wp
-         trc_o(:,:,jpfer) = 2.45e-9_wp
-         trc_o(:,:,jpsfe) = 3.89e-11_wp
-         trc_o(:,:,jpdfe) = 1.33e-11_wp
-         trc_o(:,:,jpnfe) = 2.62e-11_wp
-         trc_o(:,:,jpnch) = 1.17e-7_wp
-         trc_o(:,:,jpdch) = 9.69e-8_wp
-         trc_o(:,:,jpno3) = 5.36e-5_wp / rno3
-         trc_o(:,:,jpnh4) = 7.18e-7_wp / rno3
-         END WHERE
-      ENDIF ! cfg
+      zpisc(jpsil,4) = 4.91e-5_wp
+      zpisc(jpdsi,4) = 3.25e-7_wp
+      zpisc(jpgsi,4) = 1.93e-8_wp
+      zpisc(jpphy,4) = 6.64e-7_wp
+      zpisc(jpdia,4) = 3.41e-7_wp
+      zpisc(jpzoo,4) = 3.83e-7_wp
+      zpisc(jpmes,4) = 0.225e-6_wp
+      zpisc(jpfer,4) = 2.45e-9_wp
+      zpisc(jpsfe,4) = 3.89e-11_wp
+      zpisc(jpdfe,4) = 1.33e-11_wp
+      zpisc(jpnfe,4) = 2.62e-11_wp
+      zpisc(jpnch,4) = 1.17e-7_wp
+      zpisc(jpdch,4) = 9.69e-8_wp
+      zpisc(jpno3,4) = 5.36e-5_wp / rno3
+      zpisc(jpnh4,4) = 7.18e-7_wp / rno3
+ 
+      DO jn = jp_pcs0, jp_pcs1
+         IF( cn_trc_o(jn) == 'GL ' ) trc_o(:,:,jn) = zpisc(jn,1)  ! Global case
+         IF( cn_trc_o(jn) == 'AA ' ) THEN 
+            WHERE( gphit(:,:) >= 0._wp ) ; trc_o(:,:,jn) = zpisc(jn,2) ; END WHERE ! Arctic 
+            WHERE( gphit(:,:) <  0._wp ) ; trc_o(:,:,jn) = zpisc(jn,3) ; END WHERE ! Antarctic 
+         ENDIF
+         IF( cp_cfg == "orca" ) THEN     !  Baltic Sea particular case for ORCA configurations
+             WHERE( 14._wp <= glamt(:,:) .AND. glamt(:,:) <= 32._wp .AND.    &
+                    54._wp <= gphit(:,:) .AND. gphit(:,:) <= 66._wp )
+                    trc_o(:,:,jn) = zpisc(jn,4)
+            END WHERE
+         ENDIF 
+      ENDDO
+
+
 
       !-----------------------------
@@ -217,7 +247,7 @@
 
       DO jn = jp_pcs0, jp_pcs1
-         IF ( trc_ice_ratio(jn) >= 0._wp )  zratio(jn,:) = trc_ice_ratio(jn)
-         IF ( trc_ice_ratio(jn) == -1._wp ) zratio(jn,:) = zrs(:)
-         IF ( trc_ice_ratio(jn) == -2._wp ) zratio(jn,:) = -9999.99_wp
+         IF( trc_ice_ratio(jn) >= 0._wp )  zratio(jn,:) = trc_ice_ratio(jn)
+         IF( trc_ice_ratio(jn) == -1._wp ) zratio(jn,:) = zrs(:)
+         IF( trc_ice_ratio(jn) == -2._wp ) zratio(jn,:) = -9999.99_wp
       END DO
 
@@ -227,20 +257,18 @@
       DO jn = jp_pcs0, jp_pcs1
          !-- Everywhere but in the Baltic
-         IF ( trc_ice_ratio(jn) >= -1._wp ) THEN !! no prescribed concentration
-                                              !! (typically everything but iron) 
+         IF ( trc_ice_ratio(jn) >= -1._wp ) THEN ! no prescribed conc. ; typically everything but iron) 
             trc_i(:,:,jn) = zratio(jn,1) * trc_o(:,:,jn) 
-         ELSE                                 !! prescribed concentration
+         ELSE                                    ! prescribed concentration
             trc_i(:,:,jn) = trc_ice_prescr(jn)
          ENDIF
        
          !-- Baltic
-         IF( cp_cfg == "orca" ) THEN !! Baltic treated seperately for ORCA configs
-            IF ( trc_ice_ratio(jn) >= - 1._wp ) THEN !! no prescribed concentration
-                                                 !! (typically everything but iron) 
+         IF( cp_cfg == "orca" ) THEN  ! Baltic treated seperately for ORCA configs
+            IF ( trc_ice_ratio(jn) >= - 1._wp ) THEN ! no prescribed conc. ; typically everything but iron) 
                WHERE( 14._wp <= glamt(:,:) .AND. glamt(:,:) <= 32._wp .AND.    &
                       54._wp <= gphit(:,:) .AND. gphit(:,:) <= 66._wp )
                      trc_i(:,:,jn) = zratio(jn,2) * trc_o(:,:,jn) 
                END WHERE
-            ELSE                                 !! prescribed tracer concentration in ice
+            ELSE                                 ! prescribed tracer concentration in ice
                WHERE( 14._wp <= glamt(:,:) .AND. glamt(:,:) <= 32._wp .AND.    &
                    54._wp <= gphit(:,:) .AND. gphit(:,:) <= 66._wp )
@@ -251,6 +279,18 @@
       !
       END DO ! jn
-
-   END SUBROUTINE trc_ice_ini_pisces
+#endif
+
+   END SUBROUTINE p4z_ice_ini
+
+   SUBROUTINE p2z_ice_ini
+#if defined key_pisces_reduced 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE p2z_ice_ini ***
+      !!
+      !! ** Purpose :   Initialisation of the LOBSTER biochemical model
+      !!----------------------------------------------------------------------
+#endif
+   END SUBROUTINE p2z_ice_ini
+
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/trcini_pisces.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/trcini_pisces.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/PISCES/trcini_pisces.F90	(revision 9987)
@@ -115,7 +115,8 @@
       po4r    =   1._wp / 122._wp
       o2nit   =  32._wp / 122._wp
-      rdenit  = 105._wp /  16._wp
+      o2ut    = 133._wp / 122._wp
+      rdenit  =  ( ( o2ut + o2nit ) * 0.80 - rno3 - rno3 * 0.60 ) / rno3
       rdenita =   3._wp /  5._wp
-      o2ut    = 133._wp / 122._wp
+
 
       ! Initialization of tracer concentration in case of  no restart 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcadv.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcadv.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcadv.F90	(revision 9987)
@@ -26,4 +26,6 @@
    USE traadv_mle      ! ML eddy induced velocity  (tra_adv_mle    routine)
    USE ldftra_oce      ! lateral diffusion coefficient on tracers
+   USE trd_oce
+   USE trdtra
    USE prtctl_trc      ! Print control
 
@@ -71,7 +73,8 @@
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       !
-      INTEGER ::   jk 
+      INTEGER ::   jk, jn 
       CHARACTER (len=22) ::   charout
       REAL(wp), POINTER, DIMENSION(:,:,:) :: zun, zvn, zwn  ! effective velocity
+      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   ztrtrd
       !!----------------------------------------------------------------------
       !
@@ -111,4 +114,9 @@
       IF( ln_mle    )   CALL tra_adv_mle( kt, nittrc000, zun, zvn, zwn, 'TRC' )    ! add the mle transport (if necessary)
       !
+      IF( l_trdtrc )  THEN
+         CALL wrk_alloc( jpi, jpj, jpk, jptra, ztrtrd )
+         ztrtrd(:,:,:,:)  = tra(:,:,:,:)
+      ENDIF
+      !
       SELECT CASE ( nadv )                            !==  compute advection trend and add it to general trend  ==!
       CASE ( 1 )   ;    CALL tra_adv_cen2  ( kt, nittrc000, 'TRC',       zun, zvn, zwn, trb, trn, tra, jptra )   !  2nd order centered
@@ -140,4 +148,12 @@
          !
       END SELECT
+      !
+      IF( l_trdtrc )   THEN                      ! save the advective trends for further diagnostics
+        DO jn = 1, jptra
+           ztrtrd(:,:,:,jn) = tra(:,:,:,jn) - ztrtrd(:,:,:,jn)
+           CALL trd_tra( kt, 'TRC', jn, jptra_totad, ztrtrd(:,:,:,jn) )
+        END DO
+        CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztrtrd )
+      ENDIF
 
       !                                              ! print mean trends (used for debugging)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcbbl.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcbbl.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcbbl.F90	(revision 9987)
@@ -53,5 +53,5 @@
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step 
       CHARACTER (len=22) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   ztrtrd
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   ztrtrd
       !!----------------------------------------------------------------------
       !
@@ -64,5 +64,5 @@
 
       IF( l_trdtrc )  THEN
-         CALL wrk_alloc( jpi, jpj, jpk, jptra, ztrtrd ) ! temporary save of trends
+         ALLOCATE(ztrtrd( 1:jpi, 1:jpj, 1:jpk, 1:jptra )) ! temporary save of trends
          ztrtrd(:,:,:,:)  = tra(:,:,:,:)
       ENDIF
@@ -95,5 +95,5 @@
            CALL trd_tra( kt, 'TRC', jn, jptra_bbl, ztrtrd(:,:,:,jn) )
         END DO
-        CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztrtrd ) ! temporary save of trends
+        DEALLOCATE(ztrtrd ) ! temporary save of trends
       ENDIF
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcdmp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcdmp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcdmp.F90	(revision 9987)
@@ -35,5 +35,5 @@
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   restotr   ! restoring coeff. on tracers (s-1)
 
-   INTEGER, PARAMETER           ::   npncts   = 5        ! number of closed sea
+   INTEGER, PARAMETER           ::   npncts   = 8        ! number of closed sea
    INTEGER, DIMENSION(npncts)   ::   nctsi1, nctsj1      ! south-west closed sea limits (i,j)
    INTEGER, DIMENSION(npncts)   ::   nctsi2, nctsj2      ! north-east closed sea limits (i,j)
@@ -107,6 +107,5 @@
                
                jl = n_trc_index(jn) 
-               CALL trc_dta( kt, sf_trcdta(jl),rf_trfac(jl) )   ! read tracer data at nit000
-               ztrcdta(:,:,:) = sf_trcdta(jl)%fnow(:,:,:)
+               CALL trc_dta( kt, sf_trcdta(jl), rf_trfac(jl), ztrcdta )   ! read tracer data at nit000
 
                SELECT CASE ( nn_zdmp_tr )
@@ -208,6 +207,27 @@
             !
                                                         ! Caspian Sea
-            nctsi1(1)   = 332  ; nctsj1(1)   = 243 - isrow
-            nctsi2(1)   = 344  ; nctsj2(1)   = 275 - isrow
+            nctsi1(1)   = 333  ; nctsj1(1)   = 243 - isrow
+            nctsi2(1)   = 342  ; nctsj2(1)   = 274 - isrow
+            !                                           ! Lake Superior
+            nctsi1(2)   = 198  ; nctsj1(2)   = 258 - isrow
+            nctsi2(2)   = 204  ; nctsj2(2)   = 262 - isrow
+            !                                           ! Lake Michigan
+            nctsi1(3)   = 201  ; nctsj1(3)   = 250 - isrow
+            nctsi2(3)   = 203  ; nctsj2(3)   = 256 - isrow
+            !                                           ! Lake Huron
+            nctsi1(4)   = 204  ; nctsj1(4)   = 252 - isrow
+            nctsi2(4)   = 209  ; nctsj2(4)   = 256 - isrow
+            !                                           ! Lake Erie
+            nctsi1(5)   = 206  ; nctsj1(5)   = 249 - isrow
+            nctsi2(5)   = 209  ; nctsj2(5)   = 251 - isrow
+            !                                           ! Lake Ontario
+            nctsi1(6)   = 210  ; nctsj1(6)   = 252 - isrow
+            nctsi2(6)   = 212  ; nctsj2(6)   = 252 - isrow
+            !                                           ! Victoria Lake
+            nctsi1(7)   = 321  ; nctsj1(7)   = 180 - isrow
+            nctsi2(7)   = 322  ; nctsj2(7)   = 189 - isrow
+            !                                           ! Baltic Sea
+            nctsi1(8)   = 297  ; nctsj1(8)   = 270 - isrow
+            nctsi2(8)   = 308  ; nctsj2(8)   = 293 - isrow
             !                                        
             !                                           ! =======================
@@ -283,11 +303,10 @@
             IF( ln_trc_ini(jn) ) THEN      ! update passive tracers arrays with input data read from file
                 jl = n_trc_index(jn)
-                CALL trc_dta( kt, sf_trcdta(jl),rf_trfac(jl) )   ! read tracer data at nit000
-                ztrcdta(:,:,:) = sf_trcdta(jl)%fnow(:,:,:)
+                CALL trc_dta( kt, sf_trcdta(jl), rf_trfac(jl), ztrcdta )   ! read tracer data at nit000
                 DO jc = 1, npncts
                    DO jk = 1, jpkm1
                       DO jj = nctsj1(jc), nctsj2(jc)
                          DO ji = nctsi1(jc), nctsi2(jc)
-                            trn(ji,jj,jk,jn) = ztrcdta(ji,jj,jk) * tmask(ji,jj,jk)
+                            trn(ji,jj,jk,jn) = ztrcdta(ji,jj,jk)
                             trb(ji,jj,jk,jn) = trn(ji,jj,jk,jn)
                          ENDDO
@@ -317,4 +336,6 @@
       IF( nn_timing == 1 )  CALL timing_start('trc_dmp_init')
       !
+      !Allocate arrays
+      IF( trc_dmp_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_dmp_init: unable to allocate arrays' )
 
       IF( lzoom )   nn_zdmp_tr = 0           ! restoring to climatology at closed north or south boundaries
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcldf.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcldf.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcldf.F90	(revision 9987)
@@ -56,7 +56,8 @@
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
       !!
-      INTEGER            :: jn
+      INTEGER            :: ji, jj, jk, jn
+      REAL(wp)           :: zdep
       CHARACTER (len=22) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   ztrtrd
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   ztrtrd
       !!----------------------------------------------------------------------
       !
@@ -66,7 +67,19 @@
 
       rldf = rldf_rat
-
+      !
+      r_fact_lap(:,:,:) = 1.
+      DO jk= 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( fsdept(ji,jj,jk) > 200. .AND. gphit(ji,jj) < 5. .AND. gphit(ji,jj) > -5. ) THEN
+                  zdep = MAX( fsdept(ji,jj,jk) - 1000., 0. ) / 1000.
+                  r_fact_lap(ji,jj,jk) = MAX( 1., rn_fact_lap * EXP( -zdep ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
       IF( l_trdtrc )  THEN
-         CALL wrk_alloc( jpi, jpj, jpk, jptra, ztrtrd )
+         ALLOCATE( ztrtrd ( 1:jpi, 1:jpj, 1:jpk, 1:jptra) )
          ztrtrd(:,:,:,:)  = tra(:,:,:,:)
       ENDIF
@@ -107,5 +120,5 @@
            CALL trd_tra( kt, 'TRC', jn, jptra_ldf, ztrtrd(:,:,:,jn) )
         END DO
-        CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztrtrd )
+        DEALLOCATE( ztrtrd )
       ENDIF
       !                                          ! print mean trends (used for debugging)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcnam_trp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcnam_trp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcnam_trp.F90	(revision 9987)
@@ -40,4 +40,5 @@
    REAL(wp), PUBLIC ::   rn_ahtrc_0          !: diffusivity coefficient for passive tracer (m2/s)
    REAL(wp), PUBLIC ::   rn_ahtrb_0          !: background diffusivity coefficient for passive tracer (m2/s)
+   REAL(wp), PUBLIC ::   rn_fact_lap         !: Enhanced zonal diffusivity coefficent in the equatorial domain
 
    !                                        !!: ** Treatment of Negative concentrations ( nam_trcrad )
@@ -74,5 +75,7 @@
       NAMELIST/namtrc_ldf/ ln_trcldf_lap  ,     &
          &                 ln_trcldf_bilap, ln_trcldf_level,     &
-         &                 ln_trcldf_hor  , ln_trcldf_iso  , rn_ahtrc_0, rn_ahtrb_0
+         &                 ln_trcldf_hor  , ln_trcldf_iso  , rn_ahtrc_0, rn_ahtrb_0,   &
+         &                 rn_fact_lap
+
       NAMELIST/namtrc_zdf/ ln_trczdf_exp  , nn_trczdf_exp
       NAMELIST/namtrc_rad/ ln_trcrad
@@ -127,4 +130,5 @@
          WRITE(numout,*) '      diffusivity coefficient                                 rn_ahtrc_0 = ', rn_ahtrc_0
          WRITE(numout,*) '      background hor. diffusivity                             rn_ahtrb_0 = ', rn_ahtrb_0
+         WRITE(numout,*) '      enhanced zonal diffusivity                             rn_fact_lap = ', rn_fact_lap
       ENDIF
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcnxt.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcnxt.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcnxt.F90	(revision 9987)
@@ -102,4 +102,7 @@
       ENDIF
 
+#if defined key_agrif
+      CALL Agrif_trc                   ! AGRIF zoom boundaries
+#endif
       ! Update after tracer on domain lateral boundaries
       DO jn = 1, jptra
@@ -110,7 +113,4 @@
 #if defined key_bdy
 !!      CALL bdy_trc( kt )               ! BDY open boundaries
-#endif
-#if defined key_agrif
-      CALL Agrif_trc                   ! AGRIF zoom boundaries
 #endif
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcsbc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcsbc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trcsbc.F90	(revision 9987)
@@ -102,15 +102,18 @@
          IF(lwp) WRITE(numout,*) '~~~~~~~ '
 
-         IF( ln_rsttr .AND.    &                     ! Restart: read in restart  file
-            iom_varid( numrtr, 'sbc_'//TRIM(ctrcnm(1))//'_b', ldstop = .FALSE. ) > 0 ) THEN
-            IF(lwp) WRITE(numout,*) '          nittrc000-nn_dttrc surface tracer content forcing fields red in the restart file'
-            zfact = 0.5_wp
-            DO jn = 1, jptra
-               CALL iom_get( numrtr, jpdom_autoglo, 'sbc_'//TRIM(ctrcnm(jn))//'_b', sbc_trc_b(:,:,jn) )   ! before tracer content sbc
-            END DO
-         ELSE                                         ! No restart or restart not found: Euler forward time stepping
+         !! JPALM -- 12-01-2016 -- problem after restart, maybe because of this...
+         !!                     -- set sbc_trc_b to 0 after restart, first, to check.
+         !!------------------------------------------------------------------------------
+        ! IF( ln_rsttr .AND. .NOT.ln_top_euler .AND.   &                     ! Restart: read in restart  file
+        !    iom_varid( numrtr, 'sbc_'//TRIM(ctrcnm(1))//'_b', ldstop = .FALSE. ) > 0 ) THEN
+        !    IF(lwp) WRITE(numout,*) '          nittrc000-nn_dttrc surface tracer content forcing fields red in the restart file'
+        !    zfact = 0.5_wp
+        !    DO jn = 1, jptra
+        !       CALL iom_get( numrtr, jpdom_autoglo, 'sbc_'//TRIM(ctrcnm(jn))//'_b', sbc_trc_b(:,:,jn) )   ! before tracer content sbc
+        !    END DO
+        ! ELSE                                         ! No restart or restart not found: Euler forward time stepping
            zfact = 1._wp
            sbc_trc_b(:,:,:) = 0._wp
-         ENDIF
+        ! ENDIF
       ELSE                                         ! Swap of forcing fields
          IF( ln_top_euler ) THEN
@@ -170,4 +173,6 @@
             END DO
          ENDIF
+         !
+         CALL lbc_lnk( sbc_trc(:,:,jn), 'T', 1. )
          !                                       Concentration dilution effect on tracers due to evaporation & precipitation 
          DO jj = 2, jpj
@@ -188,5 +193,5 @@
       !                                           Write in the tracer restar  file
       !                                          *******************************
-      IF( lrst_trc ) THEN
+      IF( lrst_trc .AND. .NOT.ln_top_euler ) THEN
          IF(lwp) WRITE(numout,*)
          IF(lwp) WRITE(numout,*) 'sbc : ocean surface tracer content forcing fields written in tracer restart file ',   &
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trctrp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trctrp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/TRP/trctrp.F90	(revision 9987)
@@ -27,4 +27,8 @@
    USE trcsbc          ! surface boundary condition          (trc_sbc routine)
    USE zpshde          ! partial step: hor. derivative       (zps_hde routine)
+# if defined key_debug_medusa
+   USE trcrst
+# endif
+
 
 #if defined key_agrif
@@ -65,8 +69,17 @@
          !
                                 CALL trc_sbc( kstp )            ! surface boundary condition
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) ' MEDUSA trc_trp after trc_sbc at kt =', kstp
+         CALL trc_rst_tra_stat
+         CALL flush(numout)
+# endif
          IF( lk_trabbl )        CALL trc_bbl( kstp )            ! advective (and/or diffusive) bottom boundary layer scheme
          IF( ln_trcdmp )        CALL trc_dmp( kstp )            ! internal damping trends
-         IF( ln_trcdmp_clo )    CALL trc_dmp_clo( kstp )        ! internal damping trends on closed seas only
                                 CALL trc_adv( kstp )            ! horizontal & vertical advection 
+         IF( ln_zps ) THEN
+           IF( ln_isfcav ) THEN ; CALL zps_hde_isf( kstp, jptra, trb, pgtu=gtru, pgtv=gtrv, pgtui=gtrui, pgtvi=gtrvi )  ! both top & bottom
+           ELSE                 ; CALL zps_hde    ( kstp, jptra, trb, gtru, gtrv )                                      !  only bottom
+           ENDIF
+         ENDIF
                                 CALL trc_ldf( kstp )            ! lateral mixing
          IF( .NOT. lk_offline .AND. lk_zdfkpp )    &
@@ -77,5 +90,11 @@
                                 CALL trc_zdf( kstp )            ! vertical mixing and after tracer fields
                                 CALL trc_nxt( kstp )            ! tracer fields at next time step     
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) ' MEDUSA trc_trp after trc_nxt at kt =', kstp
+         CALL trc_rst_tra_stat
+         CALL flush(numout)
+# endif
          IF( ln_trcrad )        CALL trc_rad( kstp )            ! Correct artificial negative concentrations
+         IF( ln_trcdmp_clo )    CALL trc_dmp_clo( kstp )        ! internal damping trends on closed seas only
 
 #if defined key_agrif
@@ -83,10 +102,4 @@
 #endif
 
-         IF( ln_zps  .AND. .NOT. ln_isfcav)        &
-            &            CALL zps_hde    ( kstp, jptra, trn, gtru, gtrv )   ! Partial steps: now horizontal gradient of passive
-         IF( ln_zps .AND.        ln_isfcav)        &
-            &            CALL zps_hde_isf( kstp, jptra, trn, pgtu=gtru, pgtv=gtrv, pgtui=gtrui, pgtvi=gtrvi )  ! Partial steps: now horizontal gradient of passive
-                                                                ! tracers at the bottom ocean level
-         !
       ELSE                                               ! 1D vertical configuration
                                 CALL trc_sbc( kstp )            ! surface boundary condition
@@ -100,4 +113,6 @@
       !
       IF( nn_timing == 1 )   CALL timing_stop('trc_trp')
+      !
+9400  FORMAT(a25,i4,D23.16)
       !
    END SUBROUTINE trc_trp
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/oce_trc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/oce_trc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/oce_trc.F90	(revision 9987)
@@ -116,4 +116,5 @@
    USE ldftra_oce , ONLY :  aeiw     =>   aeiw        !: eddy induced velocity coef. at w-points (m2/s) 
    USE ldftra_oce , ONLY :  lk_traldf_eiv  =>  lk_traldf_eiv     !: eddy induced velocity flag
+   USE ldftra_oce , ONLY :  r_fact_lap     =>  r_fact_lap        !: enhanced zonal diffusivity coefficient
 
    !* vertical diffusion *
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/par_trc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/par_trc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/par_trc.F90	(revision 9987)
@@ -8,4 +8,5 @@
    !!             1.0  !  2004-03  (C. Ethe) Free form and module
    !!             2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!              -   !  2014-06  (A. Yool, J. Palmieri) adding MEDUSA-2
    !!----------------------------------------------------------------------
    USE par_kind          ! kind parameters
@@ -14,5 +15,8 @@
    USE par_c14b      ! C14 bomb tracer
    USE par_cfc       ! CFC 11 and 12 tracers
+   USE par_age       ! AGE  tracer
    USE par_my_trc    ! user defined passive tracers
+   USE par_idtra     ! Idealize tracer
+   USE par_medusa    ! MEDUSA model
 
    IMPLICIT NONE
@@ -24,9 +28,9 @@
    ! Passive tracers : Total size
    ! ---------------               ! total number of passive tracers, of 2d and 3d output and trend arrays
-   INTEGER, PUBLIC,  PARAMETER ::   jptra    =  jp_pisces     + jp_cfc     + jp_c14b    + jp_my_trc
-   INTEGER, PUBLIC,  PARAMETER ::   jpdia2d  =  jp_pisces_2d  + jp_cfc_2d  + jp_c14b_2d + jp_my_trc_2d
-   INTEGER, PUBLIC,  PARAMETER ::   jpdia3d  =  jp_pisces_3d  + jp_cfc_3d  + jp_c14b_3d + jp_my_trc_3d
+   INTEGER, PUBLIC,  PARAMETER ::   jptra    =  jp_pisces     + jp_cfc     + jp_c14b    + jp_age    + jp_my_trc    + jp_idtra     + jp_medusa   
+   INTEGER, PUBLIC,  PARAMETER ::   jpdia2d  =  jp_pisces_2d  + jp_cfc_2d  + jp_c14b_2d + jp_age_2d + jp_my_trc_2d + jp_idtra_2d  + jp_medusa_2d
+   INTEGER, PUBLIC,  PARAMETER ::   jpdia3d  =  jp_pisces_3d  + jp_cfc_3d  + jp_c14b_3d + jp_age_3d + jp_my_trc_3d + jp_idtra_3d  + jp_medusa_3d
    !                     ! total number of sms diagnostic arrays
-   INTEGER, PUBLIC,  PARAMETER ::   jpdiabio =  jp_pisces_trd + jp_cfc_trd + jp_c14b_trd + jp_my_trc_trd
+   INTEGER, PUBLIC,  PARAMETER ::   jpdiabio =  jp_pisces_trd + jp_cfc_trd + jp_c14b_trd + jp_age_trd + jp_my_trc_trd + jp_idtra_trd + jp_medusa_trd 
    
    !  1D configuration ("key_c1d")
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trc.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trc.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trc.F90	(revision 9987)
@@ -7,4 +7,5 @@
    !!              -   !  2000-04  (O. Aumont, M.A. Foujols)  HAMOCC3 and P3ZD
    !!   NEMO      1.0  !  2004-03  (C. Ethe)  Free form and module
+   !!             3.6  !  2016-11  (A. Yool)  Updated diags for CMIP6
    !!----------------------------------------------------------------------
 #if defined key_top
@@ -25,5 +26,5 @@
    INTEGER, PUBLIC                                                 ::   numnat_cfg = -1   !: logical unit for the reference passive tracer namelist_top_cfg
    INTEGER, PUBLIC                                                 ::   numont     = -1   !: logical unit for the reference passive tracer namelist output output.namelist.top
-   INTEGER, PUBLIC                                                 ::   numstr        !: logical unit for tracer statistics
+   INTEGER, PUBLIC                                                 ::   numstr     = -1   !: logical unit for tracer statistics
    INTEGER, PUBLIC                                                 ::   numrtr        !: logical unit for trc restart (read )
    INTEGER, PUBLIC                                                 ::   numrtw        !: logical unit for trc restart ( write )
@@ -104,4 +105,54 @@
    END TYPE DIAG
 
+#if defined key_medusa && defined key_iomput
+   TYPE, PUBLIC :: BDIAG
+      LOGICAL              :: dgsave
+   END TYPE BDIAG
+   
+   TYPE, PUBLIC :: DIAG_IOM
+      TYPE(BDIAG) INVTN, INVTSI, INVTFE, PRN, MPN, PRD, MPD, DSED, OPAL, OPALDISS, GMIPn,            &
+                  GMID, MZMI, GMEPN, GMEPD, GMEZMI, GMED, MZME, DEXP, DETN, MDET, AEOLIAN, BENTHIC,  &
+                  SCAVENGE, PN_JLIM, PN_NLIM, PN_FELIM, PD_JLIM, PD_NLIM, PD_FELIM, PD_SILIM,        &
+                  PDSILIM2, SDT__100, SDT__200, SDT__500, SDT_1000, TOTREG_N, TOTRG_SI, REG__100,    &
+                  REG__200, REG__500, REG_1000, FASTN, FASTSI, FASTFE, FASTC, FASTCA, FDT__100,      &
+                  FDT__200, FDT__500, FDT_1000, RG__100F, RG__200F, RG__500F, RG_1000F, FDS__100,    &
+                  FDS__200, FDS__500, FDS_1000, RGS_100F, RGS_200F, RGS_500F, RGS1000F, REMINN,      &
+                  REMINSI, REMINFE, REMINC, REMINCA, SEAFLRN, SEAFLRSI, SEAFLRFE, SEAFLRC, SEAFLRCA, &
+                  MED_QSR, MED_XPAR, INTFLX_N, INTFLX_SI, INTFLX_FE, INT_PN, INT_PD, ML_PRN, ML_PRD, &
+                  OCAL_CCD, OCAL_LVL, FE_0000, FE_0100, FE_0200, FE_0500, FE_1000, MED_XZE, WIND,    &
+                  ATM_PCO2, OCN_PH, OCN_PCO2, OCNH2CO3, OCN_HCO3, OCN_CO3, CO2FLUX, OM_CAL, OM_ARG,  &
+                  TCO2, TALK, KW660, ATM_PP0, O2FLUX, O2SAT, CAL_CCD, ARG_CCD, SFR_OCAL, SFR_OARG,   &
+                  N_PROD, N_CONS, C_PROD, C_CONS, O2_PROD, O2_CONS, O2_ANOX, RR_0100, RR_0500,       &
+                  RR_1000, IBEN_N, IBEN_FE, IBEN_C, IBEN_SI, IBEN_CA, OBEN_N, OBEN_FE, OBEN_C,       &
+                  OBEN_SI, OBEN_CA, BEN_N, BEN_FE, BEN_C, BEN_SI, BEN_CA, RUNOFF, RIV_N, RIV_SI,     &
+                  RIV_C, RIV_ALK, DETC, SDC__100, SDC__200, SDC__500, SDC_1000, INVTC, INVTALK,      &
+                  INVTO2, LYSO_CA, COM_RESP, PN_LLOSS, PD_LLOSS, ZI_LLOSS, ZE_LLOSS, ZI_MES_N,       &
+                  ZI_MES_D, ZI_MES_C, ZI_MESDC, ZI_EXCR, ZI_RESP, ZI_GROW, ZE_MES_N, ZE_MES_D,       &
+                  ZE_MES_C, ZE_MESDC, ZE_EXCR, ZE_RESP, ZE_GROW, MDETC, GMIDC, GMEDC,                &
+                  INT_ZMI, INT_ZME, INT_DET, INT_DTC, DMS_SURF, DMS_ANDR, DMS_SIMO, DMS_ARAN,        &
+                  DMS_HALL, DMS_ANDM, ATM_XCO2, OCN_FCO2, ATM_FCO2, OCN_RHOSW, OCN_SCHCO2,           &
+                  OCN_KWCO2, OCN_K0, CO2STARAIR, OCN_DPCO2,                                          & ! end of regular 2D
+                  TPP3, DETFLUX3, REMIN3N, PH3, OM_CAL3,                                             & ! end of regular 3D
+! AXY (11/11/16): additional CMIP6 2D diagnostics
+                  epC100, epCALC100, epN100, epSI100,                                                &
+                  FGCO2, INTDISSIC, INTDISSIN, INTDISSISI, INTTALK, O2min, ZO2min,                   &
+                  FBDDTALK, FBDDTDIC, FBDDTDIFE, FBDDTDIN, FBDDTDISI,                                & 
+! AXY (11/11/16): additional CMIP6 3D diagnostics
+                  TPPD3,                                                                             &
+                  BDDTALK3, BDDTDIC3, BDDTDIFE3, BDDTDIN3, BDDTDISI3,                                & 
+                  FD_NIT3, FD_SIL3, FD_CAR3, FD_CAL3,                                                & 
+                  CO33, CO3SATARAG3, CO3SATCALC3, DCALC3,                                            &
+                  EXPC3, EXPN3, EXPCALC3, EXPSI3,                                                    &
+                  FEDISS3, FESCAV3,                                                                  &
+                  MIGRAZP3, MIGRAZD3, MEGRAZP3, MEGRAZD3, MEGRAZZ3,                                  &
+                  O2SAT3, PBSI3, PCAL3, REMOC3,                                                      &
+                  PNLIMJ3, PNLIMN3, PNLIMFE3, PDLIMJ3, PDLIMN3, PDLIMFE3, PDLIMSI3       
+                  !!
+                  !! list of all MEDUSA diagnostics that could be called by iom_use
+   END TYPE DIAG_IOM  
+   !!
+   TYPE(DIAG_IOM), PUBLIC :: med_diag  ! define which diagnostics are asked in outputs
+# endif                   
+
    !! information for inputs
    !! --------------------------------------------------
@@ -216,4 +267,8 @@
 
       IF( trc_alloc /= 0 )   CALL ctl_warn('trc_alloc: failed to allocate arrays')
+
+      ! It is known that not intialising SBC_TRC can introduce NaNs
+      sbc_trc(:,:,:) = 0.0
+
       !
    END FUNCTION trc_alloc
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcdta.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcdta.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcdta.F90	(revision 9987)
@@ -77,5 +77,5 @@
       ALLOCATE( n_trc_index(ntrc), slf_i(ntrc), STAT=ierr0 )
       IF( ierr0 > 0 ) THEN
-         CALL ctl_stop( 'trc_nam: unable to allocate n_trc_index' )   ;   RETURN
+         CALL ctl_stop( 'trc_dta_init: unable to allocate n_trc_index' )   ;   RETURN
       ENDIF
       nb_trcdta      = 0
@@ -91,4 +91,6 @@
       IF(lwp) THEN
          WRITE(numout,*) ' '
+         WRITE(numout,*) 'trc_dta_init : Passive tracers Initial Conditions '
+         WRITE(numout,*) '~~~~~~~~~~~~~~ '
          WRITE(numout,*) ' number of passive tracers to be initialize by data :', ntra
          WRITE(numout,*) ' '
@@ -107,14 +109,18 @@
          DO jn = 1, ntrc
             IF( ln_trc_ini(jn) )  THEN    ! open input file only if ln_trc_ini(jn) is true
-               clndta = TRIM( sn_trcdta(jn)%clvar ) 
-               clntrc = TRIM( ctrcnm   (jn)       ) 
+               clndta = TRIM( sn_trcdta(jn)%clvar )
+               if (jn > jptra) then
+                  clntrc='Dummy' ! By pass weird formats in ocean.output if ntrc > jptra
+               else
+                  clntrc = TRIM( ctrcnm   (jn)       )
+               endif
                zfact  = rn_trfac(jn)
-               IF( clndta /=  clntrc ) THEN 
-                  CALL ctl_warn( 'trc_dta_init: passive tracer data initialisation :  ',   &
-                  &              'the variable name in the data file : '//clndta//   & 
-                  &              '  must be the same than the name of the passive tracer : '//clntrc//' ')
+               IF( clndta /=  clntrc ) THEN
+                  CALL ctl_warn( 'trc_dta_init: passive tracer data initialisation    ',   &
+                  &              'Input name of data file : '//TRIM(clndta)//   &
+                  &              ' differs from that of tracer : '//TRIM(clntrc)//' ')
                ENDIF
-               WRITE(numout,*) ' read an initial file for passive tracer number :', jn, ' name : ', clndta, & 
-               &               ' multiplicative factor : ', zfact
+               WRITE(numout,'(a, i4,3a,e11.3)') ' Read IC file for tracer number :', &
+               &            jn, ', name : ', TRIM(clndta), ', Multiplicative Scaling factor : ', zfact
             ENDIF
          END DO
@@ -124,5 +130,5 @@
          ALLOCATE( sf_trcdta(nb_trcdta), rf_trfac(nb_trcdta), STAT=ierr1 )
          IF( ierr1 > 0 ) THEN
-            CALL ctl_stop( 'trc_dta_ini: unable to allocate  sf_trcdta structure' )   ;   RETURN
+            CALL ctl_stop( 'trc_dta_init: unable to allocate  sf_trcdta structure' )   ;   RETURN
          ENDIF
          !
@@ -135,5 +141,5 @@
                IF( sn_trcdta(jn)%ln_tint )  ALLOCATE( sf_trcdta(jl)%fdta(jpi,jpj,jpk,2) , STAT=ierr3 )
                IF( ierr2 + ierr3 > 0 ) THEN
-                 CALL ctl_stop( 'trc_dta : unable to allocate passive tracer data arrays' )   ;   RETURN
+                 CALL ctl_stop( 'trc_dta_init : unable to allocate passive tracer data arrays' )   ;   RETURN
                ENDIF
             ENDIF
@@ -141,5 +147,5 @@
          ENDDO
          !                         ! fill sf_trcdta with slf_i and control print
-         CALL fld_fill( sf_trcdta, slf_i, cn_dir, 'trc_dta', 'Passive tracer data', 'namtrc' )
+         CALL fld_fill( sf_trcdta, slf_i, cn_dir, 'trc_dta_init', 'Passive tracer data', 'namtrc' )
          !
       ENDIF
@@ -151,5 +157,5 @@
 
 
-   SUBROUTINE trc_dta( kt, sf_dta, zrf_trfac )
+   SUBROUTINE trc_dta( kt, sf_dta, ptrfac, ptrc)
       !!----------------------------------------------------------------------
       !!                   ***  ROUTINE trc_dta  ***
@@ -164,10 +170,12 @@
       !!----------------------------------------------------------------------
       INTEGER                     , INTENT(in   ) ::   kt     ! ocean time-step
-      TYPE(FLD), DIMENSION(1)   , INTENT(inout) ::   sf_dta     ! array of information on the field to read
-      REAL(wp)                  , INTENT(in   ) ::   zrf_trfac  ! multiplication factor
+      TYPE(FLD), DIMENSION(1)     , INTENT(inout) ::   sf_dta     ! array of information on the field to read
+      REAL(wp)                    , INTENT(in   ) ::   ptrfac  ! multiplication factor
+      REAL(wp), DIMENSION(jpi,jpj,jpk), OPTIONAL  , INTENT(out  ) ::   ptrc
       !
       INTEGER ::   ji, jj, jk, jl, jkk, ik    ! dummy loop indices
       REAL(wp)::   zl, zi
       REAL(wp), DIMENSION(jpk) ::  ztp                ! 1D workspace
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrcdta   ! 3D  workspace
       CHARACTER(len=100) :: clndta
       !!----------------------------------------------------------------------
@@ -177,5 +185,8 @@
       IF( nb_trcdta > 0 ) THEN
          !
+         CALL wrk_alloc( jpi, jpj, jpk, ztrcdta )    ! Memory allocation
+         !
          CALL fld_read( kt, 1, sf_dta )      !==   read data at kt time step   ==!
+         ztrcdta(:,:,:) = sf_dta(1)%fnow(:,:,:) * tmask(:,:,:)    ! Mask
          !
          IF( ln_sco ) THEN                   !==   s- or mixed s-zps-coordinate   ==!
@@ -186,53 +197,58 @@
             ENDIF
             !
-               DO jj = 1, jpj                         ! vertical interpolation of T & S
+            DO jj = 1, jpj                         ! vertical interpolation of T & S
+               DO ji = 1, jpi
+                  DO jk = 1, jpk                        ! determines the intepolated T-S profiles at each (i,j) points
+                     zl = fsdept_n(ji,jj,jk)
+                     IF(     zl < gdept_1d(1  ) ) THEN         ! above the first level of data
+                        ztp(jk) = ztrcdta(ji,jj,1)
+                     ELSEIF( zl > gdept_1d(jpk) ) THEN         ! below the last level of data
+                        ztp(jk) =  ztrcdta(ji,jj,jpkm1)
+                     ELSE                                      ! inbetween : vertical interpolation between jkk & jkk+1
+                        DO jkk = 1, jpkm1                                  ! when  gdept(jkk) < zl < gdept(jkk+1)
+                           IF( (zl-gdept_1d(jkk)) * (zl-gdept_1d(jkk+1)) <= 0._wp ) THEN
+                              zi = ( zl - gdept_1d(jkk) ) / (gdept_1d(jkk+1)-gdept_1d(jkk))
+                              ztp(jk) = ztrcdta(ji,jj,jkk) + ( ztrcdta(ji,jj,jkk+1) - &
+                                        ztrcdta(ji,jj,jkk) ) * zi 
+                           ENDIF
+                        END DO
+                     ENDIF
+                  END DO
+                  DO jk = 1, jpkm1
+                    ztrcdta(ji,jj,jk) = ztp(jk) * tmask(ji,jj,jk)     ! mask required for mixed zps-s-coord
+                  END DO
+                  ztrcdta(ji,jj,jpk) = 0._wp
+                END DO
+            END DO
+            ! 
+         ELSE                                !==   z- or zps- coordinate   ==!
+            !
+            IF( ln_zps ) THEN                      ! zps-coordinate (partial steps) interpolation at the last ocean level
+               DO jj = 1, jpj
                   DO ji = 1, jpi
-                     DO jk = 1, jpk                        ! determines the intepolated T-S profiles at each (i,j) points
-                        zl = fsdept_n(ji,jj,jk)
-                        IF(     zl < gdept_1d(1  ) ) THEN         ! above the first level of data
-                           ztp(jk) =  sf_dta(1)%fnow(ji,jj,1)
-                        ELSEIF( zl > gdept_1d(jpk) ) THEN         ! below the last level of data
-                           ztp(jk) =  sf_dta(1)%fnow(ji,jj,jpkm1)
-                        ELSE                                      ! inbetween : vertical interpolation between jkk & jkk+1
-                           DO jkk = 1, jpkm1                                  ! when  gdept(jkk) < zl < gdept(jkk+1)
-                              IF( (zl-gdept_1d(jkk)) * (zl-gdept_1d(jkk+1)) <= 0._wp ) THEN
-                                 zi = ( zl - gdept_1d(jkk) ) / (gdept_1d(jkk+1)-gdept_1d(jkk))
-                                 ztp(jk) = sf_dta(1)%fnow(ji,jj,jkk) + ( sf_dta(1)%fnow(ji,jj,jkk+1) - &
-                                           sf_dta(1)%fnow(ji,jj,jkk) ) * zi 
-                              ENDIF
-                           END DO
-                        ENDIF
-                     END DO
-                     DO jk = 1, jpkm1
-                        sf_dta(1)%fnow(ji,jj,jk) = ztp(jk) * tmask(ji,jj,jk)     ! mask required for mixed zps-s-coord
-                     END DO
-                     sf_dta(1)%fnow(ji,jj,jpk) = 0._wp
+                     ik = mbkt(ji,jj) 
+                     IF( ik > 1 ) THEN
+                        zl = ( gdept_1d(ik) - fsdept_n(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
+                        ztrcdta(ji,jj,ik) = (1.-zl) * ztrcdta(ji,jj,ik) + zl * ztrcdta(ji,jj,ik-1)
+                     ENDIF
+                     ik = mikt(ji,jj)
+                     IF( ik > 1 ) THEN
+                        zl = ( fsdept_n(ji,jj,ik) - gdept_1d(ik) ) / ( gdept_1d(ik+1) - gdept_1d(ik) )
+                        ztrcdta(ji,jj,ik) = (1.-zl) * ztrcdta(ji,jj,ik) + zl * ztrcdta(ji,jj,ik+1)
+                     ENDIF
                   END DO
                END DO
-            ! 
-         ELSE                                !==   z- or zps- coordinate   ==!
-            !                             
-               sf_dta(1)%fnow(:,:,:) = sf_dta(1)%fnow(:,:,:) * tmask(:,:,:)    ! Mask
-               !
-               IF( ln_zps ) THEN                      ! zps-coordinate (partial steps) interpolation at the last ocean level
-                  DO jj = 1, jpj
-                     DO ji = 1, jpi
-                        ik = mbkt(ji,jj) 
-                        IF( ik > 1 ) THEN
-                           zl = ( gdept_1d(ik) - fsdept_n(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
-                           sf_dta(1)%fnow(ji,jj,ik) = (1.-zl) * sf_dta(1)%fnow(ji,jj,ik) + zl * sf_dta(1)%fnow(ji,jj,ik-1)
-                        ENDIF
-                        ik = mikt(ji,jj)
-                        IF( ik > 1 ) THEN
-                           zl = ( gdept_0(ji,jj,ik) - gdept_1d(ik) ) / ( gdept_1d(ik+1) - gdept_1d(ik) )
-                           sf_dta(1)%fnow(ji,jj,ik) = (1.-zl) * sf_dta(1)%fnow(ji,jj,ik) + zl * sf_dta(1)%fnow(ji,jj,ik+1)
-                        ENDIF
-                     END DO
-                  END DO
-               ENDIF
-            !
-         ENDIF
-         !
-         sf_dta(1)%fnow(:,:,:) = sf_dta(1)%fnow(:,:,:) * zrf_trfac   !  multiplicative factor
+            ENDIF
+            !
+         ENDIF
+         !
+         ! Add multiplicative factor
+         ztrcdta(:,:,:) = ztrcdta(:,:,:) * ptrfac
+         !
+         ! Data structure for trc_ini (and BFMv5.1 coupling)
+         IF( .NOT. PRESENT(ptrc) ) sf_dta(1)%fnow(:,:,:) = ztrcdta(:,:,:)
+         !
+         ! Data structure for trc_dmp
+         IF( PRESENT(ptrc) )  ptrc(:,:,:) = ztrcdta(:,:,:)
          !
          IF( lwp .AND. kt == nit000 ) THEN
@@ -241,11 +257,14 @@
                WRITE(numout,*)
                WRITE(numout,*)'  level = 1'
-               CALL prihre( sf_dta(1)%fnow(:,:,1), jpi, jpj, 1, jpi, 20, 1, jpj, 20, 1., numout )
+               CALL prihre( ztrcdta(:,:,1), jpi, jpj, 1, jpi, 20, 1, jpj, 20, 1., numout )
                WRITE(numout,*)'  level = ', jpk/2
-               CALL prihre( sf_dta(1)%fnow(:,:,jpk/2), jpi, jpj, 1, jpi, 20, 1, jpj, 20, 1., numout )
+               CALL prihre( ztrcdta(:,:,jpk/2), jpi, jpj, 1, jpi, 20, 1, jpj, 20, 1., numout )
                WRITE(numout,*)'  level = ', jpkm1
-               CALL prihre( sf_dta(1)%fnow(:,:,jpkm1), jpi, jpj, 1, jpi, 20, 1, jpj, 20, 1., numout )
+               CALL prihre( ztrcdta(:,:,jpkm1), jpi, jpj, 1, jpi, 20, 1, jpj, 20, 1., numout )
                WRITE(numout,*)
          ENDIF
+         !
+         CALL wrk_dealloc( jpi, jpj, jpk, ztrcdta )
+         !
       ENDIF
       !
@@ -258,5 +277,5 @@
    !!----------------------------------------------------------------------
 CONTAINS
-   SUBROUTINE trc_dta( kt, sf_dta, zrf_trfac )        ! Empty routine
+   SUBROUTINE trc_dta( kt, sf_dta, ptrfac, ptrc)        ! Empty routine
       WRITE(*,*) 'trc_dta: You should not have seen this print! error?', kt
    END SUBROUTINE trc_dta
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcini.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcini.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcini.F90	(revision 9987)
@@ -8,4 +8,5 @@
    !!            2.0  ! 2005-10 (C. Ethe, G. Madec) revised architecture
    !!            4.0  ! 2011-01 (A. R. Porter, STFC Daresbury) dynamical allocation
+   !!             -   ! 2014-06 (A. Yool, J. Palmieri) adding MEDUSA-2
    !!----------------------------------------------------------------------
 #if defined key_top
@@ -23,8 +24,10 @@
    USE trcini_pisces   ! PISCES   initialisation
    USE trcini_c14b     ! C14 bomb initialisation
+   USE trcini_age      ! AGE      initialisation
    USE trcini_my_trc   ! MY_TRC   initialisation
+   USE trcini_idtra    ! idealize tracer initialisation
+   USE trcini_medusa   ! MEDUSA   initialisation
    USE trcdta          ! initialisation from files
    USE daymod          ! calendar manager
-   USE zpshde          ! partial step: hor. derivative   (zps_hde routine)
    USE prtctl_trc      ! Print control passive tracers (prt_ctl_trc_init routine)
    USE trcsub          ! variables to substep passive tracers
@@ -61,5 +64,4 @@
       INTEGER ::   jk, jn, jl    ! dummy loop indices
       CHARACTER (len=25) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrcdta   ! 4D  workspace
       !!---------------------------------------------------------------------
       !
@@ -100,16 +102,26 @@
       IF( lk_cfc     )       CALL trc_ini_cfc          ! CFC     tracers
       IF( lk_c14b    )       CALL trc_ini_c14b         ! C14 bomb  tracer
+      IF( lk_age     )       CALL trc_ini_age          ! AGE       tracer
       IF( lk_my_trc  )       CALL trc_ini_my_trc       ! MY_TRC  tracers
+      IF( lk_idtra   )       CALL trc_ini_idtra        ! Idealize tracers
+      IF( lk_medusa  )       CALL trc_ini_medusa       ! MEDUSA  tracers
 
       CALL trc_ice_ini                                 ! Tracers in sea ice
 
-      IF( lwp ) THEN
+      IF( ln_ctl ) THEN
          !
-         CALL ctl_opn( numstr, 'tracer.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp , narea )
+         IF (narea == 1) THEN  
+            ! The tracer.stat file only contains global tracer sum values, if 
+            ! it contains anything at all. Hence it only needs to be opened 
+            ! and written to on the master PE, not on all PEs.  
+            CALL ctl_opn( numstr, 'tracer.stat', 'REPLACE','FORMATTED',  & 
+                          'SEQUENTIAL', -1, numout, lwp , narea ) 
+         ENDIF  
          !
       ENDIF
 
-      IF( ln_trcdta )      CALL trc_dta_init(jptra)
-
+      IF( ln_trcdta ) THEN
+         CALL trc_dta_init(jptra)
+      ENDIF
 
       IF( ln_rsttr ) THEN
@@ -120,13 +132,10 @@
         !
         IF( ln_trcdta .AND. nb_trcdta > 0 ) THEN  ! Initialisation of tracer from a file that may also be used for damping
-            !
-            CALL wrk_alloc( jpi, jpj, jpk, ztrcdta )    ! Memory allocation
             !
             DO jn = 1, jptra
                IF( ln_trc_ini(jn) ) THEN      ! update passive tracers arrays with input data read from file
                   jl = n_trc_index(jn) 
-                  CALL trc_dta( nit000, sf_trcdta(jl),rf_trfac(jl) )   ! read tracer data at nit000
-                  ztrcdta(:,:,:) = sf_trcdta(jl)%fnow(:,:,:)
-                  trn(:,:,:,jn) = ztrcdta(:,:,:) * tmask(:,:,:)  
+                  CALL trc_dta( nit000, sf_trcdta(jl), rf_trfac(jl) )   ! read tracer data at nit000
+                  trn(:,:,:,jn) = sf_trcdta(jl)%fnow(:,:,:) 
                   IF( .NOT.ln_trcdmp .AND. .NOT.ln_trcdmp_clo ) THEN      !== deallocate data structure   ==!
                      !                                                    (data used only for initialisation)
@@ -138,5 +147,5 @@
                ENDIF
             ENDDO
-            CALL wrk_dealloc( jpi, jpj, jpk, ztrcdta )
+            !
         ENDIF
         !
@@ -146,10 +155,4 @@
  
       tra(:,:,:,:) = 0._wp
-      IF( ln_zps .AND. .NOT. lk_c1d .AND. .NOT. ln_isfcav )   &              ! Partial steps: before horizontal gradient of passive
-        &    CALL zps_hde    ( nit000, jptra, trn, gtru, gtrv  )  ! Partial steps: before horizontal gradient
-      IF( ln_zps .AND. .NOT. lk_c1d .AND.       ln_isfcav )   &
-        &    CALL zps_hde_isf( nit000, jptra, trn, pgtu=gtru, pgtv=gtrv, pgtui=gtrui, pgtvi=gtrvi )       ! tracers at the bottom ocean level
-
-
       !
       IF( nn_dttrc /= 1 )        CALL trc_sub_ini      ! Initialize variables for substepping passive tracers
@@ -168,4 +171,12 @@
          WRITE(numout,*) '          *** Total inital content of all tracers '
          WRITE(numout,*)
+# if defined key_debug_medusa
+         CALL flush(numout)
+# endif
+         !
+# if defined key_debug_medusa
+         WRITE(numout,*) ' litle check :  ', ctrcnm(1)
+         CALL flush(numout)
+# endif
          DO jn = 1, jptra
             WRITE(numout,9000) jn, TRIM( ctrcnm(jn) ), trai(jn)
@@ -180,4 +191,14 @@
          CALL prt_ctl_trc( tab4d=trn, mask=tmask, clinfo=ctrcnm )
       ENDIF
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_init : passive tracer set up completed'
+      IF(lwp) WRITE(numout,*) '~~~~~~~'
+      IF(lwp) CALL flush(numout)
+# if defined key_debug_medusa
+         CALL trc_rst_stat
+         CALL flush(numout)
+# endif
+
 9000  FORMAT(' tracer nb : ',i2,'      name :',a10,'      initial content :',e18.10)
       !
@@ -201,4 +222,8 @@
       USE trdmxl_trc    , ONLY:   trd_mxl_trc_alloc
 #endif
+# if defined key_medusa
+      USE bio_medusa_mod, ONLY:   bio_medusa_alloc
+# endif
+
       !
       INTEGER :: ierr
@@ -213,4 +238,7 @@
       ierr = ierr + trd_mxl_trc_alloc()
 #endif
+#if defined key_medusa
+      ierr = ierr + bio_medusa_alloc()
+#endif
       !
       IF( lk_mpp    )   CALL mpp_sum( ierr )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcnam.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcnam.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcnam.F90	(revision 9987)
@@ -11,4 +11,5 @@
    !!              -   !  2001-01 (E Kestenare) suppress ndttrc=1 for CEN2 and TVD schemes
    !!             1.0  !  2005-03 (O. Aumont, A. El Moussaoui) F90
+   !!              -   !  2014-06  (A. Yool, J. Palmieri) adding MEDUSA-2
    !!----------------------------------------------------------------------
 #if defined key_top
@@ -24,5 +25,8 @@
    USE trcnam_cfc        ! CFC SMS namelist
    USE trcnam_c14b       ! C14 SMS namelist
+   USE trcnam_age        ! AGE SMS namelist
    USE trcnam_my_trc     ! MY_TRC SMS namelist
+   USE trcnam_idtra      ! Idealise tracer namelist
+   USE trcnam_medusa     ! MEDUSA namelist
    USE trd_oce       
    USE trdtrc_oce
@@ -54,7 +58,7 @@
       !! ** Method  : - read passive tracer namelist 
       !!              - read namelist of each defined SMS model
-      !!                ( (PISCES, CFC, MY_TRC )
-      !!---------------------------------------------------------------------
-      INTEGER  ::   jn                  ! dummy loop indice
+      !!                ( (PISCES, CFC, MY_TRC, MEDUSA, IDTRA, Age )
+      !!---------------------------------------------------------------------
+      INTEGER  ::   jn, jk                     ! dummy loop indice
       !                                        !   Parameters of the run 
       IF( .NOT. lk_offline ) CALL trc_nam_run
@@ -109,4 +113,10 @@
       ENDIF
 
+# if defined key_debug_medusa
+       DO jk = 1, jpk
+          WRITE(numout,*) '  level number: ', jk, 'rdttrc: ',rdttrc(jk),'rdttra: ', rdttra(jk),'nn_dttrc: ', nn_dttrc
+       END DO
+      CALL flush(numout)
+# endif
       
       rdttrc(:) = rdttra(:) * FLOAT( nn_dttrc )   ! vertical profile of passive tracer time-step
@@ -165,6 +175,18 @@
       ENDIF
 
+      IF( lk_age     ) THEN  ;   CALL trc_nam_age         ! AGE     tracer
+      ELSE                   ;   IF(lwp) WRITE(numout,*) '          AGE not used'
+      ENDIF
+
       IF( lk_my_trc  ) THEN   ;   CALL trc_nam_my_trc      ! MY_TRC  tracers
       ELSE                    ;   IF(lwp) WRITE(numout,*) '          MY_TRC not used'
+      ENDIF
+
+      IF( lk_idtra   ) THEN   ;   CALL trc_nam_idtra       ! Idealize tracers
+      ELSE                    ;   IF(lwp) WRITE(numout,*) '          Idealize tracers not used'
+      ENDIF
+
+      IF( lk_medusa  ) THEN   ;   CALL trc_nam_medusa      ! MEDUSA  tracers
+      ELSE                    ;   IF(lwp) WRITE(numout,*) '          MEDUSA not used'
       ENDIF
       !
@@ -216,4 +238,5 @@
          WRITE(numout,*) '   Use euler integration for TRC (y/n)          ln_top_euler  = ', ln_top_euler
          WRITE(numout,*) ' '
+        CALL flush(numout)
       ENDIF
       !
@@ -357,7 +380,8 @@
          WRITE(numout,*) '    frequency of outputs for biological trends  nn_writebio = ', nn_writebio
          WRITE(numout,*) ' '
-      ENDIF
-
-      IF( ln_diatrc .AND. .NOT. lk_iomput ) THEN 
+         CALL flush(numout)
+      ENDIF
+
+      IF( ( ln_diatrc .AND. .NOT. lk_iomput ) .OR. ( ln_diatrc .AND. lk_medusa ) ) THEN 
          ALLOCATE( trc2d(jpi,jpj,jpdia2d), trc3d(jpi,jpj,jpk,jpdia3d),  &
            &       ctrc2d(jpdia2d), ctrc2l(jpdia2d), ctrc2u(jpdia2d) ,  & 
@@ -397,3 +421,3 @@
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
    !!======================================================================
-END MODULE  trcnam
+END MODULE trcnam
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcrst.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcrst.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcrst.F90	(revision 9987)
@@ -27,5 +27,21 @@
    USE trcnam_trp
    USE iom
+   USE ioipsl, ONLY : ju2ymds    ! for calendar
    USE daymod
+   !! AXY (05/11/13): need these for MEDUSA to input/output benthic reservoirs
+   USE sms_medusa
+   USE trcsms_medusa
+   !!
+#if defined key_idtra
+   USE trcsms_idtra
+#endif
+   !!
+#if defined key_cfc
+   USE trcsms_cfc
+#endif
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE sbc_oce, ONLY: lk_oasis 
+   USE oce,     ONLY: CO2Flux_out_cpl, DMS_out_cpl, chloro_out_cpl  !! Coupling variable
+
    IMPLICIT NONE
    PRIVATE
@@ -35,4 +51,7 @@
    PUBLIC   trc_rst_wri       ! called by ???
    PUBLIC   trc_rst_cal
+   PUBLIC   trc_rst_stat
+   PUBLIC   trc_rst_dia_stat
+   PUBLIC   trc_rst_tra_stat
 
    !! * Substitutions
@@ -48,4 +67,7 @@
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt       ! number of iteration
+      INTEGER             ::   iyear, imonth, iday
+      REAL (wp)           ::   zsec
+      REAL (wp)           ::   zfjulday
       !
       CHARACTER(LEN=20)   ::   clkt     ! ocean time-step define as a character
@@ -78,7 +100,26 @@
       ! except if we write tracer restart files every tracer time step or if a tracer restart file was writen at nitend - 2*nn_dttrc + 1
       IF( kt == nitrst - 2*nn_dttrc .OR. nstock == nn_dttrc .OR. ( kt == nitend - nn_dttrc .AND. .NOT. lrst_trc ) ) THEN
-         ! beware of the format used to write kt (default is i8.8, that should be large enough)
-         IF( nitrst > 1.0e9 ) THEN   ;   WRITE(clkt,*       ) nitrst
-         ELSE                        ;   WRITE(clkt,'(i8.8)') nitrst
+         IF ( ln_rstdate ) THEN
+            !! JPALM -- 22-12-2015 -- modif to get the good date on restart trc file name
+            !!                     -- the condition to open the rst file is not the same than for the dynamic rst.
+            !!                     -- here it - for an obscure reason - is open 2 time-step before the restart writing process
+            !!                     instead of 1.
+            !!                     -- i am not sure if someone forgot +1 in the if loop condition as
+            !!                     it is writen in all comments nitrst -2*nn_dttrc + 1 and the condition is 
+            !!                     nitrst - 2*nn_dttrc
+            !!                     -- nevertheless we didn't wanted to broke something already working 
+            !!                     and just adapted the part we added.
+            !!                     -- So instead of calling ju2ymds( fjulday + (rdttra(1)) 
+            !!                     we call ju2ymds( fjulday + (2*rdttra(1)) 
+            !!--------------------------------------------------------------------      
+            zfjulday = fjulday + (2*rdttra(1)) / rday
+            IF( ABS(zfjulday - REAL(NINT(zfjulday),wp)) < 0.1 / rday )   zfjulday = REAL(NINT(zfjulday),wp)   ! avoid truncation error
+            CALL ju2ymds( zfjulday + (2*rdttra(1)) / rday, iyear, imonth, iday, zsec )
+            WRITE(clkt, '(i4.4,2i2.2)') iyear, imonth, iday
+         ELSE
+            ! beware of the format used to write kt (default is i8.8, that should be large enough)
+            IF( nitrst > 1.0e9 ) THEN   ;   WRITE(clkt,*       ) nitrst
+            ELSE                        ;   WRITE(clkt,'(i8.8)') nitrst
+            ENDIF
          ENDIF
          ! create the file
@@ -101,5 +142,7 @@
       !! ** purpose  :   read passive tracer fields in restart files
       !!----------------------------------------------------------------------
-      INTEGER  ::  jn     
+      INTEGER  ::  jn, jl     
+      !! AXY (05/11/13): temporary variables
+      REAL(wp) ::    fq0,fq1,fq2
 
       !!----------------------------------------------------------------------
@@ -112,10 +155,227 @@
       DO jn = 1, jptra
          CALL iom_get( numrtr, jpdom_autoglo, 'TRN'//ctrcnm(jn), trn(:,:,:,jn) )
+         trn(:,:,:,jn) = trn(:,:,:,jn) * tmask(:,:,:)
       END DO
 
       DO jn = 1, jptra
          CALL iom_get( numrtr, jpdom_autoglo, 'TRB'//ctrcnm(jn), trb(:,:,:,jn) )
+         trb(:,:,:,jn) = trb(:,:,:,jn) * tmask(:,:,:)
       END DO
       !
+      !! AXY (09/06/14): the ARCHER version of MEDUSA-2 does not include an equivalent
+      !!                 call to MEDUSA-2 at this point; this suggests that the FCM
+      !!                 version of NEMO date significantly earlier than the current
+      !!                 version
+
+#if defined key_medusa
+      !! AXY (13/01/12): check if the restart contains sediment fields;
+      !!                 this is only relevant for simulations that include
+      !!                 biogeochemistry and are restarted from earlier runs
+      !!                 in which there was no sediment component
+      !!
+      IF( iom_varid( numrtr, 'B_SED_N', ldstop = .FALSE. ) > 0 ) THEN
+         !! YES; in which case read them
+         !!
+         IF(lwp) WRITE(numout,*) ' MEDUSA sediment fields present - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_SED_N',  zb_sed_n(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_SED_N',  zn_sed_n(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_SED_FE', zb_sed_fe(:,:) )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_SED_FE', zn_sed_fe(:,:) )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_SED_SI', zb_sed_si(:,:) )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_SED_SI', zn_sed_si(:,:) )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_SED_C',  zb_sed_c(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_SED_C',  zn_sed_c(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_SED_CA', zb_sed_ca(:,:) )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_SED_CA', zn_sed_ca(:,:) )
+      ELSE
+         !! NO; in which case set them to zero
+         !!
+         IF(lwp) WRITE(numout,*) ' MEDUSA sediment fields absent - setting to zero ...'
+         zb_sed_n(:,:)  = 0.0   !! organic N
+         zn_sed_n(:,:)  = 0.0
+         zb_sed_fe(:,:) = 0.0   !! organic Fe
+         zn_sed_fe(:,:) = 0.0
+         zb_sed_si(:,:) = 0.0   !! inorganic Si
+         zn_sed_si(:,:) = 0.0
+         zb_sed_c(:,:)  = 0.0   !! organic C
+         zn_sed_c(:,:)  = 0.0
+         zb_sed_ca(:,:) = 0.0   !! inorganic C
+         zn_sed_ca(:,:) = 0.0
+      ENDIF
+      !!
+      !! calculate stats on these fields
+      IF(lwp) WRITE(numout,*) ' MEDUSA sediment field stats (min, max, sum) ...'
+      call trc_rst_dia_stat(zn_sed_n(:,:), 'Sediment  N')
+      call trc_rst_dia_stat(zn_sed_fe(:,:), 'Sediment Fe')
+      call trc_rst_dia_stat(zn_sed_si(:,:), 'Sediment Si')
+      call trc_rst_dia_stat(zn_sed_c(:,:), 'Sediment C')
+      call trc_rst_dia_stat(zn_sed_ca(:,:), 'Sediment Ca')
+      !!
+      !! AXY (07/07/15): read in temporally averaged fields for DMS
+      !!                 calculations
+      !!
+      IF( iom_varid( numrtr, 'B_DMS_CHN', ldstop = .FALSE. ) > 0 ) THEN
+         !! YES; in which case read them
+         !!
+         IF(lwp) WRITE(numout,*) ' MEDUSA averaged properties for DMS present - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_DMS_CHN',  zb_dms_chn(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_DMS_CHN',  zn_dms_chn(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_DMS_CHD',  zb_dms_chd(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_DMS_CHD',  zn_dms_chd(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_DMS_MLD',  zb_dms_mld(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_DMS_MLD',  zn_dms_mld(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_DMS_QSR',  zb_dms_qsr(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_DMS_QSR',  zn_dms_qsr(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_DMS_DIN',  zb_dms_din(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_DMS_DIN',  zn_dms_din(:,:)  )
+      ELSE
+         !! NO; in which case set them to zero
+         !!
+         IF(lwp) WRITE(numout,*) ' MEDUSA averaged properties for DMS absent - setting to zero ...'
+         zb_dms_chn(:,:)  = 0.0   !! CHN
+         zn_dms_chn(:,:)  = 0.0
+         zb_dms_chd(:,:)  = 0.0   !! CHD
+         zn_dms_chd(:,:)  = 0.0
+         zb_dms_mld(:,:)  = 0.0   !! MLD
+         zn_dms_mld(:,:)  = 0.0
+         zb_dms_qsr(:,:)  = 0.0   !! QSR
+         zn_dms_qsr(:,:)  = 0.0
+         zb_dms_din(:,:)  = 0.0   !! DIN
+         zn_dms_din(:,:)  = 0.0
+      ENDIF
+      !!  
+      !! JPALM 14-06-2016 -- add CO2 flux and DMS surf through the restart
+      !!                  -- needed for the coupling with atm
+      IF( iom_varid( numrtr, 'N_DMS_srf', ldstop = .FALSE. ) > 0 ) THEN
+         IF(lwp) WRITE(numout,*) 'DMS surf concentration - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_DMS_srf',  zb_dms_srf(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_DMS_srf',  zn_dms_srf(:,:)  )
+      ELSE
+         IF(lwp) WRITE(numout,*) 'DMS surf concentration - setting to zero ...'
+         zb_dms_srf(:,:)  = 0.0   !! DMS
+         zn_dms_srf(:,:)  = 0.0
+      ENDIF
+      IF (lk_oasis) THEN
+         DMS_out_cpl(:,:) = zn_dms_srf(:,:)        !! Coupling variable
+      END IF
+      !!
+      IF( iom_varid( numrtr, 'B_CO2_flx', ldstop = .FALSE. ) > 0 ) THEN
+         IF(lwp) WRITE(numout,*) 'CO2 air-sea flux - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'B_CO2_flx',  zb_co2_flx(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_CO2_flx',  zn_co2_flx(:,:)  )
+      ELSE
+         IF(lwp) WRITE(numout,*) 'CO2 air-sea flux - setting to zero ...'
+         zb_co2_flx(:,:)  = 0.0   !! CO2 flx
+         zn_co2_flx(:,:)  = 0.0
+      ENDIF
+      IF (lk_oasis) THEN
+         CO2Flux_out_cpl(:,:) =  zn_co2_flx(:,:)   !! Coupling variable
+      END IF
+      !!
+      !! JPALM 02-06-2017 -- in complement to DMS surf 
+      !!                  -- the atm model needs surf Chl 
+      !!                     as proxy of org matter from the ocean
+      !!                  -- needed for the coupling with atm
+      IF( iom_varid( numrtr, 'N_CHL_srf', ldstop = .FALSE. ) > 0 ) THEN
+         IF(lwp) WRITE(numout,*) 'Chl surf concentration - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'N_CHL_srf',  zn_chl_srf(:,:)  )
+      ELSE
+         IF(lwp) WRITE(numout,*) 'Chl surf concentration - setting to zero ...'
+         zn_chl_srf(:,:)  = (trn(:,:,1,jpchn) + trn(:,:,1,jpchd)) * 1.E-6
+      ENDIF
+      IF (lk_oasis) THEN
+         chloro_out_cpl(:,:) = zn_chl_srf(:,:)        !! Coupling variable
+      END IF
+      !!
+      !! calculate stats on these fields
+      IF(lwp) WRITE(numout,*) ' MEDUSA averaged properties for DMS stats (min, max, sum) ...'
+      call trc_rst_dia_stat(zn_dms_chn(:,:), 'DMS, CHN')
+      call trc_rst_dia_stat(zn_dms_chd(:,:), 'DMS, CHD')
+      call trc_rst_dia_stat(zn_dms_mld(:,:), 'DMS, MLD')
+      call trc_rst_dia_stat(zn_dms_qsr(:,:), 'DMS, QSR')
+      call trc_rst_dia_stat(zn_dms_din(:,:), 'DMS, DIN')
+      call trc_rst_dia_stat(zn_dms_srf(:,:), 'DMS surf')
+      call trc_rst_dia_stat(zn_co2_flx(:,:), 'CO2 flux')
+      call trc_rst_dia_stat(zn_chl_srf(:,:), 'CHL surf')
+      !!  
+      !! JPALM 14-06-2016 -- add Carbonate chenistry variables through the restart
+      !!                  -- needed for monthly call of carb-chem routine and better reproducibility
+# if defined key_roam
+      IF( iom_varid( numrtr, 'pH_3D', ldstop = .FALSE. ) > 0 ) THEN
+         IF(lwp) WRITE(numout,*) 'Carbonate chem variable - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'pH_3D'   ,  f3_pH(:,:,:)     )
+         CALL iom_get( numrtr, jpdom_autoglo, 'h2CO3_3D',  f3_h2co3(:,:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'hCO3_3D' ,  f3_hco3(:,:,:)   )
+         CALL iom_get( numrtr, jpdom_autoglo, 'CO3_3D'  ,  f3_co3(:,:,:)    )
+         CALL iom_get( numrtr, jpdom_autoglo, 'omcal_3D',  f3_omcal(:,:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'omarg_3D',  f3_omarg(:,:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'CCD_CAL' ,  f2_ccd_cal(:,:)  )
+         CALL iom_get( numrtr, jpdom_autoglo, 'CCD_ARG' ,  f2_ccd_arg(:,:)  )
+         !!
+         IF(lwp) WRITE(numout,*) ' MEDUSA averaged Carb-chem stats (min, max, sum) ...'
+      call trc_rst_dia_stat( f3_pH(:,:,1)   ,'pH 3D surf')
+      call trc_rst_dia_stat( f3_h2co3(:,:,1),'h2CO3 3D surf')
+      call trc_rst_dia_stat( f3_hco3(:,:,1) ,'hCO3 3D surf' )
+      call trc_rst_dia_stat( f3_co3(:,:,1)  ,'CO3 3D surf' )
+      call trc_rst_dia_stat( f3_omcal(:,:,1),'omcal 3D surf')
+      call trc_rst_dia_stat( f3_omarg(:,:,1),'omarg 3D surf')
+      call trc_rst_dia_stat( f2_ccd_cal(:,:),'CCD_CAL')
+      call trc_rst_dia_stat( f2_ccd_arg(:,:),'CCD_ARG')
+
+      ELSE
+         IF(lwp) WRITE(numout,*) 'WARNING : No Carbonate-chem variable in the restart.... '
+         IF(lwp) WRITE(numout,*) 'Is not a problem if start a month, but may be very problematic if not '
+         IF(lwp) WRITE(numout,*) 'Check if   mod(kt*rdt,2592000) == rdt' 
+         IF(lwp) WRITE(numout,*) 'Or don t start from uncomplete restart...' 
+      ENDIF
+# endif
+
+
+#endif
+      !
+#if defined key_idtra
+      !! JPALM -- 05-01-2016 -- mv idtra and CFC restart reading and 
+      !!                        writting here undre their key.
+      !!                        problems in CFC restart, maybe because of this...
+      !!                        and pb in idtra diag or diad-restart writing.
+      !!----------------------------------------------------------------------
+      IF( iom_varid( numrtr, 'qint_IDTRA', ldstop = .FALSE. ) > 0 ) THEN
+         !! YES; in which case read them
+         !!
+         IF(lwp) WRITE(numout,*) ' IDTRA averaged properties present - reading in ...'
+         CALL iom_get( numrtr, jpdom_autoglo, 'qint_IDTRA',  qint_idtra(:,:,1)  )
+      ELSE
+         !! NO; in which case set them to zero
+         !!
+         IF(lwp) WRITE(numout,*) ' IDTRA averaged properties absent - setting to zero ...'
+         qint_idtra(:,:,1)  = 0.0   !! CHN
+      ENDIF
+      !!
+      !! calculate stats on these fields
+      IF(lwp) WRITE(numout,*) ' IDTRA averaged properties stats (min, max, sum) ...'
+      call trc_rst_dia_stat(qint_idtra(:,:,1), 'qint_IDTRA')
+#endif
+      !
+#if defined key_cfc
+      DO jl = 1, jp_cfc
+         jn = jp_cfc0 + jl - 1
+         IF( iom_varid( numrtr, 'qint_'//ctrcnm(jn), ldstop = .FALSE. ) > 0 ) THEN
+            !! YES; in which case read them
+            !!
+            IF(lwp) WRITE(numout,*) ' CFC averaged properties present - reading in ...'
+            CALL iom_get( numrtr, jpdom_autoglo, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jl) )
+         ELSE
+            !! NO; in which case set them to zero
+            !!
+            IF(lwp) WRITE(numout,*) ' CFC averaged properties absent - setting to zero ...'
+            qint_cfc(:,:,jn)  = 0.0   !! CHN
+         ENDIF
+         !!
+         !! calculate stats on these fields
+         IF(lwp) WRITE(numout,*) ' CFC averaged properties stats (min, max, sum) ...'
+         call trc_rst_dia_stat(qint_cfc(:,:,jl), 'qint_'//ctrcnm(jn))
+      END DO
+#endif
+      !
    END SUBROUTINE trc_rst_read
 
@@ -128,6 +388,8 @@
       INTEGER, INTENT( in ) ::   kt    ! ocean time-step index
       !!
-      INTEGER  :: jn
+      INTEGER  :: jn, jl
       REAL(wp) :: zarak0
+      !! AXY (05/11/13): temporary variables
+      REAL(wp) ::    fq0,fq1,fq2
       !!----------------------------------------------------------------------
       !
@@ -142,5 +404,129 @@
          CALL iom_rstput( kt, nitrst, numrtw, 'TRB'//ctrcnm(jn), trb(:,:,:,jn) )
       END DO
-      !
+
+      !! AXY (09/06/14): the ARCHER version of MEDUSA-2 does not include an equivalent
+      !!                 call to MEDUSA-2 at this point; this suggests that the FCM
+      !!                 version of NEMO date significantly earlier than the current
+      !!                 version
+
+#if defined key_medusa
+      !! AXY (13/01/12): write out "before" and "now" state of seafloor
+      !!                 sediment pools into restart; this happens
+      !!                 whether or not the pools are to be used by
+      !!                 MEDUSA (which is controlled by a switch in the
+      !!                 namelist_top file)
+      !!
+      IF(lwp) WRITE(numout,*) ' MEDUSA sediment fields - writing out ...'
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_SED_N',  zb_sed_n(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_SED_N',  zn_sed_n(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_SED_FE', zb_sed_fe(:,:) )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_SED_FE', zn_sed_fe(:,:) )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_SED_SI', zb_sed_si(:,:) )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_SED_SI', zn_sed_si(:,:) )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_SED_C',  zb_sed_c(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_SED_C',  zn_sed_c(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_SED_CA', zb_sed_ca(:,:) )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_SED_CA', zn_sed_ca(:,:) )
+      !!
+      !! calculate stats on these fields
+      IF(lwp) WRITE(numout,*) ' MEDUSA sediment field stats (min, max, sum) ...'
+      call trc_rst_dia_stat(zn_sed_n(:,:), 'Sediment  N')
+      call trc_rst_dia_stat(zn_sed_fe(:,:), 'Sediment Fe')
+      call trc_rst_dia_stat(zn_sed_si(:,:), 'Sediment Si')
+      call trc_rst_dia_stat(zn_sed_c(:,:), 'Sediment C')
+      call trc_rst_dia_stat(zn_sed_ca(:,:), 'Sediment Ca')
+      !!
+      !! AXY (07/07/15): write out temporally averaged fields for DMS
+      !!                 calculations
+      !!
+      IF(lwp) WRITE(numout,*) ' MEDUSA averaged properties for DMS - writing out ...'
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_DMS_CHN',  zb_dms_chn(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_DMS_CHN',  zn_dms_chn(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_DMS_CHD',  zb_dms_chd(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_DMS_CHD',  zn_dms_chd(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_DMS_MLD',  zb_dms_mld(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_DMS_MLD',  zn_dms_mld(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_DMS_QSR',  zb_dms_qsr(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_DMS_QSR',  zn_dms_qsr(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_DMS_DIN',  zb_dms_din(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_DMS_DIN',  zn_dms_din(:,:)  )
+         !! JPALM 14-06-2016 -- add CO2 flux and DMS surf through the restart
+         !!                  -- needed for the coupling with atm
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_DMS_srf',  zb_dms_srf(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_DMS_srf',  zn_dms_srf(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'B_CO2_flx',  zb_co2_flx(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_CO2_flx',  zn_co2_flx(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'N_CHL_srf',  zn_chl_srf(:,:)  )
+      !!
+      !! calculate stats on these fields
+      IF(lwp) WRITE(numout,*) ' MEDUSA averaged properties for DMS stats (min, max, sum) ...'
+      call trc_rst_dia_stat(zn_dms_chn(:,:), 'DMS, CHN')
+      call trc_rst_dia_stat(zn_dms_chd(:,:), 'DMS, CHD')
+      call trc_rst_dia_stat(zn_dms_mld(:,:), 'DMS, MLD')
+      call trc_rst_dia_stat(zn_dms_qsr(:,:), 'DMS, QSR')
+      call trc_rst_dia_stat(zn_dms_din(:,:), 'DMS, DIN')
+      call trc_rst_dia_stat(zn_dms_srf(:,:), 'DMS surf')
+      call trc_rst_dia_stat(zn_co2_flx(:,:), 'CO2 flux')
+      call trc_rst_dia_stat(zn_chl_srf(:,:), 'CHL surf')
+      !!
+      IF(lwp) WRITE(numout,*) ' MEDUSA averaged prop. for dust and iron dep.'
+      call trc_rst_dia_stat(dust(:,:), 'Dust dep')
+      call trc_rst_dia_stat(zirondep(:,:), 'Iron dep')
+      !! 
+      !!  
+      !! JPALM 14-06-2016 -- add Carbonate chenistry variables through the restart
+      !!                  -- needed for monthly call of carb-chem routine and better reproducibility
+# if defined key_roam
+      IF(lwp) WRITE(numout,*) 'Carbonate chem variable - writing out ...'
+      CALL iom_rstput( kt, nitrst, numrtw, 'pH_3D'   ,  f3_pH(:,:,:)     )
+      CALL iom_rstput( kt, nitrst, numrtw, 'h2CO3_3D',  f3_h2co3(:,:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'hCO3_3D' ,  f3_hco3(:,:,:)   )
+      CALL iom_rstput( kt, nitrst, numrtw, 'CO3_3D'  ,  f3_co3(:,:,:)    )
+      CALL iom_rstput( kt, nitrst, numrtw, 'omcal_3D',  f3_omcal(:,:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'omarg_3D',  f3_omarg(:,:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'CCD_CAL' ,  f2_ccd_cal(:,:)  )
+      CALL iom_rstput( kt, nitrst, numrtw, 'CCD_ARG' ,  f2_ccd_arg(:,:)  )
+      !!
+      IF(lwp) WRITE(numout,*) ' MEDUSA averaged Carb-chem stats (min, max, sum) ...'
+      call trc_rst_dia_stat( f3_pH(:,:,1)   ,'pH 3D surf')
+      call trc_rst_dia_stat( f3_h2co3(:,:,1),'h2CO3 3D surf')
+      call trc_rst_dia_stat( f3_hco3(:,:,1) ,'hCO3 3D surf' )
+      call trc_rst_dia_stat( f3_co3(:,:,1)  ,'CO3 3D surf' )
+      call trc_rst_dia_stat( f3_omcal(:,:,1),'omcal 3D surf')
+      call trc_rst_dia_stat( f3_omarg(:,:,1),'omarg 3D surf')
+      call trc_rst_dia_stat( f2_ccd_cal(:,:),'CCD_CAL')
+      call trc_rst_dia_stat( f2_ccd_arg(:,:),'CCD_ARG')
+      !!
+# endif
+!!
+#endif
+      !
+#if defined key_idtra
+      !! JPALM -- 05-01-2016 -- mv idtra and CFC restart reading and 
+      !!                        writting here undre their key.
+      !!                        problems in CFC restart, maybe because of this...
+      !!                        and pb in idtra diag or diad-restart writing.
+      !!----------------------------------------------------------------------
+      IF(lwp) WRITE(numout,*) ' IDTRA averaged properties - writing out ...'
+      CALL iom_rstput( kt, nitrst, numrtw, 'qint_IDTRA',  qint_idtra(:,:,1) )
+      !!
+      !! calculate stats on these fields
+      IF(lwp) WRITE(numout,*) ' IDTRA averaged properties stats (min, max, sum) ...'
+      call trc_rst_dia_stat(qint_idtra(:,:,1), 'qint_IDTRA')
+#endif
+      !
+#if defined key_cfc
+      DO jl = 1, jp_cfc
+         jn = jp_cfc0 + jl - 1
+         IF(lwp) WRITE(numout,*) ' CFC averaged properties - writing out ...'
+         CALL iom_rstput( kt, nitrst, numrtw, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jl) )
+         !!
+         !! calculate stats on these fields
+         IF(lwp) WRITE(numout,*) ' CFC averaged properties stats (min, max, sum) ...'
+         call trc_rst_dia_stat(qint_cfc(:,:,jl), 'qint_'//ctrcnm(jn))
+      END DO
+#endif
+      !
+
       IF( kt == nitrst ) THEN
           CALL trc_rst_stat            ! statistics
@@ -304,9 +690,96 @@
          IF(lwp) WRITE(numout,9000) jn, TRIM( ctrcnm(jn) ), zmean, zmin, zmax, zdrift
       END DO
-      WRITE(numout,*) 
+      IF(lwp) WRITE(numout,*) 
 9000  FORMAT(' tracer nb :',i2,'    name :',a10,'    mean :',e18.10,'    min :',e18.10, &
       &      '    max :',e18.10,'    drift :',e18.10, ' %')
       !
    END SUBROUTINE trc_rst_stat
+
+
+   SUBROUTINE trc_rst_tra_stat
+      !!----------------------------------------------------------------------
+      !!                    ***  trc_rst_tra_stat  ***
+      !!
+      !! ** purpose  :   Compute tracers statistics - check where crazy values appears
+      !!----------------------------------------------------------------------
+      INTEGER  :: jk, jn
+      REAL(wp) :: ztraf, zmin, zmax, zmean, zdrift, areasf
+      REAL(wp), DIMENSION(jpi,jpj) :: zvol
+      !!----------------------------------------------------------------------
+
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '           ----SURFACE TRA STAT----             '
+         WRITE(numout,*)
+      ENDIF
+      !
+      zvol(:,:) = e1e2t(:,:) * fse3t_a(:,:,1) * tmask(:,:,1)
+      areasf = glob_sum(zvol(:,:))
+      DO jn = 1, jptra
+         ztraf = glob_sum( tra(:,:,1,jn) * zvol(:,:) )
+         zmin  = MINVAL( tra(:,:,1,jn), mask= ((tmask(:,:,1).NE.0.)) )
+         zmax  = MAXVAL( tra(:,:,1,jn), mask= ((tmask(:,:,1).NE.0.)) )
+         IF( lk_mpp ) THEN
+            CALL mpp_min( zmin )      ! min over the global domain
+            CALL mpp_max( zmax )      ! max over the global domain
+         END IF
+         zmean  = ztraf / areasf
+         IF(lwp) WRITE(numout,9001) jn, TRIM( ctrcnm(jn) ), zmean, zmin, zmax
+      END DO
+      IF(lwp) WRITE(numout,*)
+9001  FORMAT(' tracer nb :',i2,'    name :',a10,'    mean :',e18.10,'    min :',e18.10, &
+      &      '    max :',e18.10)
+      !
+   END SUBROUTINE trc_rst_tra_stat
+
+
+
+   SUBROUTINE trc_rst_dia_stat( dgtr, names)
+      !!----------------------------------------------------------------------
+      !!                    ***  trc_rst_dia_stat  ***
+      !!
+      !! ** purpose  :   Compute tracers statistics
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) , INTENT(in) ::   dgtr      ! 2D diag var
+      CHARACTER(len=*)             , INTENT(in) ::   names     ! 2D diag name
+      !!---------------------------------------------------------------------
+      INTEGER  :: jk, jn
+      CHARACTER (LEN=18) :: text_zmean
+      REAL(wp) :: ztraf, zmin, zmax, zmean, areasf
+      REAL(wp), DIMENSION(jpi,jpj) :: zvol
+      !!----------------------------------------------------------------------
+
+      IF( lwp )  WRITE(numout,*) 'STAT- ', names
+      
+      ! fse3t_a will be undefined at the start of a run, but this routine
+      ! may be called at any stage! Hence we MUST make sure it is 
+      ! initialised to zero when allocated to enable us to test for 
+      ! zero content here and avoid potentially dangerous and non-portable 
+      ! operations (e.g. divide by zero, global sums of junk values etc.)   
+      zvol(:,:) = e1e2t(:,:) * fse3t_a(:,:,1) * tmask(:,:,1)
+      ztraf = glob_sum( dgtr(:,:) * zvol(:,:) )
+      !! areasf = glob_sum(e1e2t(:,:) * tmask(:,:,1) )
+      areasf = glob_sum(zvol(:,:))
+      zmin  = MINVAL( dgtr(:,:), mask= ((tmask(:,:,1).NE.0.)) )
+      zmax  = MAXVAL( dgtr(:,:), mask= ((tmask(:,:,1).NE.0.)) )
+      IF( lk_mpp ) THEN
+         CALL mpp_min( zmin )      ! min over the global domain
+         CALL mpp_max( zmax )      ! max over the global domain
+      END IF
+
+      text_zmean = "N/A"
+      ! Avoid divide by zero. areasf must be positive.
+      IF  (areasf > 0.0) THEN 
+         zmean = ztraf / areasf
+         WRITE(text_zmean,'(e18.10)') zmean
+      ENDIF
+
+      IF(lwp) WRITE(numout,9002) TRIM( names ), text_zmean, zmin, zmax
+
+  9002  FORMAT(' tracer name :',A,'    mean :',A,'    min :',e18.10, &
+      &      '    max :',e18.10 )
+      !
+   END SUBROUTINE trc_rst_dia_stat
+
 
 #else
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcsms.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcsms.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcsms.F90	(revision 9987)
@@ -18,5 +18,8 @@
    USE trcsms_cfc         ! CFC 11 & 12
    USE trcsms_c14b        ! C14b tracer 
+   USE trcsms_age         ! AGE tracer 
    USE trcsms_my_trc      ! MY_TRC  tracers
+   USE trcsms_idtra       ! Idealize Tracer
+   USE trcsms_medusa      ! MEDUSA tracers
    USE prtctl_trc         ! Print control for debbuging
 
@@ -51,5 +54,8 @@
       IF( lk_cfc     )   CALL trc_sms_cfc    ( kt )    ! surface fluxes of CFC
       IF( lk_c14b    )   CALL trc_sms_c14b   ( kt )    ! surface fluxes of C14
+      IF( lk_age     )   CALL trc_sms_age    ( kt )    ! AGE tracer
       IF( lk_my_trc  )   CALL trc_sms_my_trc ( kt )    ! MY_TRC  tracers
+      IF( lk_idtra   )   CALL trc_sms_idtra  ( kt )    ! radioactive decay of Id. tracer
+      IF( lk_medusa  )   CALL trc_sms_medusa ( kt )    ! MEDUSA  tracers
 
       IF(ln_ctl) THEN      ! print mean trends (used for debugging)
@@ -75,3 +81,3 @@
 
    !!======================================================================
-END MODULE  trcsms
+END MODULE trcsms
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcstp.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcstp.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcstp.F90	(revision 9987)
@@ -32,5 +32,5 @@
    REAL(wp), DIMENSION(:,:,:), SAVE, ALLOCATABLE ::   qsr_arr ! save qsr during TOP time-step
    REAL(wp) :: rdt_sampl
-   INTEGER  :: nb_rec_per_days
+   INTEGER  :: nb_rec_per_day
    INTEGER  :: isecfst, iseclast
    LOGICAL  :: llnew
@@ -55,9 +55,11 @@
       !!              Update the passive tracers
       !!-------------------------------------------------------------------
+
+      USE dom_oce, ONLY: narea
+
       INTEGER, INTENT( in ) ::  kt      ! ocean time-step index
       INTEGER               ::  jk, jn  ! dummy loop indices
       REAL(wp)              ::  ztrai
       CHARACTER (len=25)    ::  charout 
-
       !!-------------------------------------------------------------------
       !
@@ -93,5 +95,17 @@
          ENDIF
                                    CALL trc_sms      ( kt )       ! tracers: sinks and sources
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) ' MEDUSA trc_stp SMS complete at kt =', kt
+         CALL trc_rst_stat
+         CALL trc_rst_tra_stat
+         CALL flush(numout)
+# endif
                                    CALL trc_trp      ( kt )       ! transport of passive tracers
+# if defined key_debug_medusa
+         IF(lwp) WRITE(numout,*) ' MEDUSA trc_stp transport complete at kt =', kt
+         CALL trc_rst_stat
+         CALL trc_rst_tra_stat
+         CALL flush(numout)
+# endif
          IF( kt == nittrc000 ) THEN
             CALL iom_close( numrtr )       ! close input tracer restart file
@@ -105,10 +119,21 @@
       ENDIF
       !
-      ztrai = 0._wp                                                   !  content of all tracers
-      DO jn = 1, jptra
-         ztrai = ztrai + glob_sum( trn(:,:,:,jn) * cvol(:,:,:)   )
-      END DO
-      IF( lwp ) WRITE(numstr,9300) kt,  ztrai / areatot
-9300  FORMAT(i10,e18.10)
+      IF (ln_ctl) THEN 
+         ! The following code is very expensive since it involves multiple 
+         ! reproducible global sums over all tracer fields and is potentially  
+         ! called on every timestep. The results it produces are purely for 
+         ! informational purposes and do not affect model evolution. 
+         ! Hence we restrict its use by protecting it with the ln_ctl RTL 
+         ! which should normally only be used under debugging conditions 
+         ! and not in operational runs. We also need to restrict output  
+         ! to the master PE since there's no point duplicating the same results 
+         ! on all processors.    
+         ztrai = 0._wp                                                   !  content of all tracers
+         DO jn = 1, jptra
+            ztrai = ztrai + glob_sum( trn(:,:,:,jn) * cvol(:,:,:)   )
+         END DO
+         IF( numstr /= -1 ) WRITE(numstr,9300) kt,  ztrai / areatot
+9300     FORMAT(i10,D23.16)
+      ENDIF
       !
       IF( nn_timing == 1 )   CALL timing_stop('trc_stp')
@@ -123,5 +148,5 @@
       !!               of diurnal cycle
       !!
-      !! ** Method  : store in TOP the qsr every hour ( or every time-step the latter 
+      !! ** Method  : store in TOP the qsr every hour ( or every time-step if the latter 
       !!              is greater than 1 hour ) and then, compute the  mean with 
       !!              a moving average over 24 hours. 
@@ -130,42 +155,84 @@
       INTEGER, INTENT(in) ::   kt
       INTEGER  :: jn
+      REAL(wp) :: zsecfst
+      CHARACTER(len=1)               ::   cl1                      ! 1 character
+      CHARACTER(len=2)               ::   cl2                      ! 2 characters
 
       IF( kt == nittrc000 ) THEN
          IF( ln_cpl )  THEN  
             rdt_sampl = 86400. / ncpl_qsr_freq
-            nb_rec_per_days = ncpl_qsr_freq
+            nb_rec_per_day = ncpl_qsr_freq
          ELSE  
             rdt_sampl = MAX( 3600., rdt * nn_dttrc )
-            nb_rec_per_days = INT( 86400 / rdt_sampl )
+            nb_rec_per_day = INT( 86400 / rdt_sampl )
          ENDIF
          !
          IF( lwp ) THEN
             WRITE(numout,*) 
-            WRITE(numout,*) ' Sampling frequency dt = ', rdt_sampl, 's','   Number of sampling per day  nrec = ', nb_rec_per_days
+            WRITE(numout,*) ' Sampling frequency dt = ', rdt_sampl, 's','   Number of sampling per day  nrec = ', nb_rec_per_day
             WRITE(numout,*) 
          ENDIF
          !
-         ALLOCATE( qsr_arr(jpi,jpj,nb_rec_per_days ) )
-         DO jn = 1, nb_rec_per_days
-            qsr_arr(:,:,jn) = qsr(:,:)
-         ENDDO
-         qsr_mean(:,:) = qsr(:,:)
-         !
-         isecfst  = nsec_year + nsec1jan000   !   number of seconds between Jan. 1st 00h of nit000 year and the middle of time step
-         iseclast = isecfst
+         ALLOCATE( qsr_arr(jpi,jpj,nb_rec_per_day ) )
+         !
+         !                                            !* Restart: read in restart file
+         IF( ln_rsttr .AND. iom_varid( numrtr, 'qsr_mean' , ldstop = .FALSE. ) > 0 .AND. &
+                            iom_varid( numrtr, 'qsr_arr_1', ldstop = .FALSE. ) > 0 .AND. &
+                            iom_varid( numrtr, 'zsecfst'  , ldstop = .FALSE. ) > 0 ) THEN 
+            IF(lwp) WRITE(numout,*) 'trc_qsr_mean:   qsr_mean read in the restart file'
+            CALL iom_get( numrtr, jpdom_autoglo, 'qsr_mean', qsr_mean )   !  A mean of qsr
+            CALL iom_get( numrtr, 'zsecfst', zsecfst )   !  A mean of qsr
+            isecfst = INT( zsecfst )
+            DO jn = 1, nb_rec_per_day 
+             IF( jn <= 9 )  THEN
+               WRITE(cl1,'(i1)') jn
+               CALL iom_get( numrtr, jpdom_autoglo, 'qsr_arr_'//cl1, qsr_arr(:,:,jn) )   !  A mean of qsr
+             ELSE
+               WRITE(cl2,'(i2.2)') jn
+               CALL iom_get( numrtr, jpdom_autoglo, 'qsr_arr_'//cl2, qsr_arr(:,:,jn) )   !  A mean of qsr
+             ENDIF
+           ENDDO
+         ELSE                                         !* no restart: set from nit000 values
+            IF(lwp) WRITE(numout,*) 'trc_qsr_mean:   qsr_mean set to nit000 values'
+            isecfst  = nsec_year + nsec1jan000   !   number of seconds between Jan. 1st 00h of nit000 year and the middle of time step
+            !
+            qsr_mean(:,:) = qsr(:,:)
+            DO jn = 1, nb_rec_per_day
+               qsr_arr(:,:,jn) = qsr_mean(:,:)
+            ENDDO
+         ENDIF
          !
       ENDIF
       !
       iseclast = nsec_year + nsec1jan000
+      !
       llnew   = ( iseclast - isecfst )  > INT( rdt_sampl )   !   new shortwave to store
-      IF( kt /= nittrc000 .AND. llnew ) THEN
+      IF( llnew ) THEN
           IF( lwp ) WRITE(numout,*) ' New shortwave to sample for TOP at time kt = ', kt, &
              &                      ' time = ', (iseclast+rdt*nn_dttrc/2.)/3600.,'hours '
           isecfst = iseclast
-          DO jn = 1, nb_rec_per_days - 1
+          DO jn = 1, nb_rec_per_day - 1
              qsr_arr(:,:,jn) = qsr_arr(:,:,jn+1)
           ENDDO
-          qsr_arr (:,:,nb_rec_per_days) = qsr(:,:)
-          qsr_mean(:,:                ) = SUM( qsr_arr(:,:,:), 3 ) / nb_rec_per_days
+          qsr_arr (:,:,nb_rec_per_day) = qsr(:,:)
+          qsr_mean(:,:                ) = SUM( qsr_arr(:,:,:), 3 ) / nb_rec_per_day
+      ENDIF
+      !
+      IF( lrst_trc ) THEN    !* Write the mean of qsr in restart file 
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_mean_qsr : write qsr_mean in restart file  kt =', kt
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+          DO jn = 1, nb_rec_per_day 
+             IF( jn <= 9 )  THEN
+               WRITE(cl1,'(i1)') jn
+               CALL iom_rstput( kt, nitrst, numrtw, 'qsr_arr_'//cl1, qsr_arr(:,:,jn) )
+             ELSE
+               WRITE(cl2,'(i2.2)') jn
+               CALL iom_rstput( kt, nitrst, numrtw, 'qsr_arr_'//cl2, qsr_arr(:,:,jn) )
+             ENDIF
+         ENDDO
+         CALL iom_rstput( kt, nitrst, numrtw, 'qsr_mean', qsr_mean(:,:) )
+         zsecfst = REAL( isecfst, wp )
+         CALL iom_rstput( kt, nitrst, numrtw, 'zsecfst', zsecfst )
       ENDIF
       !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcwri.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcwri.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/NEMO/TOP_SRC/trcwri.F90	(revision 9987)
@@ -5,4 +5,5 @@
    !!======================================================================
    !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!              -   !  2014-06 (A. Yool, J. Palmieri) adding MEDUSA-2
    !!----------------------------------------------------------------------
 #if defined key_top && defined key_iomput
@@ -20,5 +21,8 @@
    USE trcwri_cfc
    USE trcwri_c14b
+   USE trcwri_age
    USE trcwri_my_trc
+   USE trcwri_idtra
+   USE trcwri_medusa
 
    IMPLICIT NONE
@@ -59,5 +63,8 @@
       IF( lk_cfc     )   CALL trc_wri_cfc        ! surface fluxes of CFC
       IF( lk_c14b    )   CALL trc_wri_c14b       ! surface fluxes of C14
+      IF( lk_age     )   CALL trc_wri_age        ! AGE tracer
       IF( lk_my_trc  )   CALL trc_wri_my_trc     ! MY_TRC  tracers
+      IF( lk_idtra   )   CALL trc_wri_idtra       ! Idealize tracers
+      IF( lk_medusa  )   CALL trc_wri_medusa     ! MESDUSA
       !
       IF( nn_timing == 1 )  CALL timing_stop('trc_wri')
Index: anches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-athena-xios
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-athena-xios	(revision 9986)
+++ 	(revision )
@@ -1,80 +1,0 @@
-#!/bin/bash 
-#!
-#BSUB -q poe_short
-#BSUB -n NPROCS
-#BSUB -a poe
-#BSUB -J MPI_config
-#BSUB -o poe.stdout.%J
-#BSUB -e poe.stderr.%J
-
- 
-
-###############################################################
-# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
-# (via sed operating on this template job file). 
-#
-  OCEANCORES=NPROCS
-  export SETTE_DIR=DEF_SETTE_DIR
-
-###############################################################
-#
-# set up mpp computing environment
-#
-# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
-#
-
-# export MPIRUN="mpirun -n $OCEANCORES"
-
-export MPIRUN="mpirun.lsf"
-
-#
-# load sette functions (only post_test_tidyup needed)
-#
-  . ${SETTE_DIR}/all_functions.sh
-
-
-# Don't remove neither change the following line 
-# BODY
-
-#
-# These variables are needed by post_test_tidyup function in all_functions.sh
-#
-  export EXE_DIR=DEF_EXE_DIR
-  export INPUT_DIR=DEF_INPUT_DIR
-  export CONFIG_DIR=DEF_CONFIG_DIR
-  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
-  export NEW_CONF=DEF_NEW_CONF
-  export CMP_NAM=DEF_CMP_NAM
-  export TEST_NAME=DEF_TEST_NAME
-#
-# end of set up
-
-
-###############################################################
-#
-# change to the working directory 
-#
-cd ${EXE_DIR}
-
-#
-  echo Running on host `hostname`
-  echo Time is `date`
-  echo Directory is `pwd`
-# 
-#  Run the parallel MPI executable 
-#
-#  echo "Running time ${MPIRUN} " $OCEANCORES " ./opa"
-#
-
-  if [ MPI_FLAG == "yes" ]; then
-     time ${MPIRUN} ./opa
-  else
-     time ./opa
-  fi
-#
-  post_test_tidyup
-
-# END_BODY
-# Don't remove neither change the previous line 
-
-  exit
Index: anches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-gfortran_athena_xios
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-gfortran_athena_xios	(revision 9986)
+++ 	(revision )
@@ -1,127 +1,0 @@
-#!/bin/bash 
-#!
-#BSUB -q poe_short
-#BSUB -n TOTAL_NPROCS
-#BSUB -a poe
-#BSUB -J MPI_config
-#BSUB -o poe.stdout.%J
-#BSUB -e poe.stderr.%J
-
- 
-
-###############################################################
-# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
-# (via sed operating on this template job file). 
-#
-  OCEANCORES=NPROCS
-  XIOS_NUMPROCS=NXIOPROCS
-  export SETTE_DIR=DEF_SETTE_DIR
-
-###############################################################
-#
-# set up mpp computing environment
-#
-# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
-#
-
-# export MPIRUN="mpirun -n $OCEANCORES"
-
-export MPIRUN="mpirun.lsf"
-export LANG=en_US
-export NLSPATH=/opt/ibmhpc/pecurrent/base/msg/%L/%N:$NLSPATH
-export MP_LABELIO=yes
-export MP_STDOUTMODE=unordered
-export MP_EUILIB=us
-export MP_INFOLEVEL=0
-export MP_EUIDEVELOP=min
-export MP_INSTANCES=1
-export MP_SHARED_MEMORY=yes
-export MP_EAGER_LIMIT_LOCAL=2000000000
-export MP_EUIDEVICE=sn_single
-export MP_BULK_MIN_MSG_SIZE=16384
-export MP_POLLING_INTERVAL=1000000
-export MP_DEVTYPE=ib
-export MP_EAGER_LIMIT=262144
-export MP_TASK_AFFINITY=core
-export MP_BINDPROC=yes
-export MP_DEBUG_CHECK_PARAM=no
-export MP_MSG_API=mpi
-export MP_USE_BULK_XFER=yes
-export MP_WAIT_MODE=poll
-export LDR_CNTRL=TEXTPSIZE=64K@STACKPSIZE=64K@DATAPSIZE=64K
-export LD_LIBRARY_PATH=/users/home/ans040/local/lib:${LD_LIBRARY_PATH}
-
-XIOS_SERVER_PATHNAME="/users/home/ans040/SOFTWARE/XIOS/trunk/bin/xios_server.exe"
-
-
-#
-# load sette functions (only post_test_tidyup needed)
-#
-  . ${SETTE_DIR}/all_functions.sh
-
-
-# Don't remove neither change the following line 
-# BODY
-
-#
-# These variables are needed by post_test_tidyup function in all_functions.sh
-#
-  export EXE_DIR=DEF_EXE_DIR
-  export INPUT_DIR=DEF_INPUT_DIR
-  export CONFIG_DIR=DEF_CONFIG_DIR
-  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
-  export NEW_CONF=DEF_NEW_CONF
-  export CMP_NAM=DEF_CMP_NAM
-  export TEST_NAME=DEF_TEST_NAME
-#
-# end of set up
-
-
-###############################################################
-#
-# change to the working directory 
-#
-cd ${EXE_DIR}
-
-#
-  echo Running on host `hostname`
-  echo Time is `date`
-  echo Directory is `pwd`
-# 
-#  Run the parallel MPI executable 
-#
-#  echo "Running time ${MPIRUN} " $OCEANCORES " ./opa"
-#
-
-  if [ MPI_FLAG == "yes" ]; then
-     if [ $XIOS_NUMPROCS -eq 0 ]; then
-       time ${MPIRUN} ./opa
-     else
-
-       export MP_PGMMODEL=mpmd
-       export MP_CMDFILE=xioscmdfile
-       rm xioscmdfile &> /dev/null
-       touch xioscmdfile
-       k=0
-       while (( k < $OCEANCORES )) ; do
-          echo ./opa >> xioscmdfile
-          k=`expr $k + 1`
-       done
-       k=0
-       while (( k < $XIOS_NUMPROCS )) ; do
-          echo $XIOS_SERVER_PATHNAME >> xioscmdfile
-          k=`expr $k + 1`
-       done
-
-       time ${MPIRUN}
-     fi
-  else
-     time ./opa
-  fi
-#
-  post_test_tidyup
-
-# END_BODY
-# Don't remove neither change the previous line 
-
-  exit
Index: anches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_MERCATOR_CLUSTER
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_MERCATOR_CLUSTER	(revision 9986)
+++ 	(revision )
@@ -1,74 +1,0 @@
-#!/bin/bash 
-#!
-#PBS -N sette
-#PBS -e sette.$PBS_JOBID.err
-#PBS -o sette.$PBS_JOBID.out
-#PBS -l nodes=NODES:ppn=NPROC_NODE
-#PBS -q QUEUE
-#PBS -l walltime=03:00:00
-#PBS -l pvmem=5gb
-
-#
-# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
-# (via sed operating on this template job file). 
-#
-  OCEANCORES=NPROCS
-  export SETTE_DIR=DEF_SETTE_DIR
-
-###############################################################
-#
-# set up mpp computing environment
-#
-# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
-#
-#cbr export MPIRUN="mpiexec -n $OCEANCORES"
-export MPIRUN="mpirun -np $OCEANCORES"
-
-#
-# load sette functions (only post_test_tidyup needed)
-#
-  . ${SETTE_DIR}/all_functions.sh
-#
-
-# Don't remove neither change the following line
-# BODY
-
-#
-# These variables are needed by post_test_tidyup function in all_functions.sh
-#
-  export EXE_DIR=DEF_EXE_DIR
-  export INPUT_DIR=DEF_INPUT_DIR
-  export CONFIG_DIR=DEF_CONFIG_DIR
-  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
-  export NEW_CONF=DEF_NEW_CONF
-  export CMP_NAM=DEF_CMP_NAM
-  export TEST_NAME=DEF_TEST_NAME
-#
-# end of set up
-###############################################################
-#
-# change to the working directory 
-#
-cd ${EXE_DIR}
-  echo Running on host `hostname`
-  echo Time is `date`
-  echo Directory is `pwd`
-# 
-#  Run the parallel MPI executable 
-#
-  echo "Running time ${MPIRUN} ./opa"
-#
-  if [ MPI_FLAG == "yes" ]; then
-     mpirun -np $OCEANCORES ./opa
-  else
-     time ./opa
-  fi
-
-#
-  post_test_tidyup
-
-# END_BODY
-# Don't remove neither change the previous line
-
-
-  exit
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_athena
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_athena	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_athena	(revision 9987)
@@ -0,0 +1,80 @@
+#!/bin/bash 
+#!
+#BSUB -q poe_short
+#BSUB -n NPROCS
+#BSUB -a poe
+#BSUB -J MPI_config
+#BSUB -o poe.stdout.%J
+#BSUB -e poe.stderr.%J
+
+ 
+
+###############################################################
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). 
+#
+  OCEANCORES=NPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+
+###############################################################
+#
+# set up mpp computing environment
+#
+# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
+#
+
+# export MPIRUN="mpirun -n $OCEANCORES"
+
+export MPIRUN="mpirun.lsf"
+
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+
+
+# Don't remove neither change the following line 
+# BODY
+
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export EXE_DIR=DEF_EXE_DIR
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+#
+# end of set up
+
+
+###############################################################
+#
+# change to the working directory 
+#
+cd ${EXE_DIR}
+
+#
+  echo Running on host `hostname`
+  echo Time is `date`
+  echo Directory is `pwd`
+# 
+#  Run the parallel MPI executable 
+#
+#  echo "Running time ${MPIRUN} " $OCEANCORES " ./opa"
+#
+
+  if [ MPI_FLAG == "yes" ]; then
+     time ${MPIRUN} ./opa
+  else
+     time ./opa
+  fi
+#
+  post_test_tidyup
+
+# END_BODY
+# Don't remove neither change the previous line 
+
+  exit
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_athena_xios
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_athena_xios	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-ifort_athena_xios	(revision 9987)
@@ -0,0 +1,106 @@
+#!/bin/bash 
+#!
+#BSUB -q poe_short
+#BSUB -n TOTAL_NPROCS
+#BSUB -a poe
+#BSUB -J MPI_config
+#BSUB -o poe.stdout.%J
+#BSUB -e poe.stderr.%J
+
+ 
+
+###############################################################
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). 
+#
+  OCEANCORES=NPROCS
+  XIOS_NUMPROCS=NXIOPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+
+###############################################################
+#
+# set up mpp computing environment
+#
+# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
+#
+
+# export MPIRUN="mpirun -n $OCEANCORES"
+
+module load  INTEL/intel_xe_2013 NETCDF/netcdf-4.3_parallel NETCDF/parallel-netcdf-1.3.1 HDF5/hdf5-1.8.11_parallel
+export MPIRUN="mpirun.lsf"
+
+export LD_LIBRARY_PATH=${XIOS}/lib:${LD_LIBRARY_PATH}
+
+XIOS_SERVER_PATHNAME="${XIOS}/bin/xios_server.exe"
+
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+
+
+# Don't remove neither change the following line 
+# BODY
+
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export EXE_DIR=DEF_EXE_DIR
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+#
+# end of set up
+
+
+###############################################################
+#
+# change to the working directory 
+#
+cd ${EXE_DIR}
+
+#
+  echo Running on host `hostname`
+  echo Time is `date`
+  echo Directory is `pwd`
+# 
+#  Run the parallel MPI executable 
+#
+#  echo "Running time ${MPIRUN} " $OCEANCORES " ./opa"
+#
+
+  if [ MPI_FLAG == "yes" ]; then
+     if [ $XIOS_NUMPROCS -eq 0 ]; then
+       time ${MPIRUN} ./opa
+     else
+
+       export MP_PGMMODEL=mpmd
+       export MP_CMDFILE=xioscmdfile
+       rm xioscmdfile &> /dev/null
+       touch xioscmdfile
+       k=0
+       while (( k < $OCEANCORES )) ; do
+          echo ./opa >> xioscmdfile
+          k=`expr $k + 1`
+       done
+       k=0
+       while (( k < $XIOS_NUMPROCS )) ; do
+          echo $XIOS_SERVER_PATHNAME >> xioscmdfile
+          k=`expr $k + 1`
+       done
+
+       time ${MPIRUN}
+     fi
+  else
+     time ./opa
+  fi
+#
+  post_test_tidyup
+
+# END_BODY
+# Don't remove neither change the previous line 
+
+  exit
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-openmpi_NAVITI_MERCATOR
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-openmpi_NAVITI_MERCATOR	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-openmpi_NAVITI_MERCATOR	(revision 9987)
@@ -0,0 +1,74 @@
+#!/bin/bash 
+#!
+#PBS -N sette
+#PBS -e sette.$PBS_JOBID.err
+#PBS -o sette.$PBS_JOBID.out
+#PBS -l nodes=NODES:ppn=NPROC_NODE
+#PBS -q QUEUE
+#PBS -l walltime=03:00:00
+#PBS -l pmem=3gb
+
+#
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). 
+#
+  OCEANCORES=NPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+
+###############################################################
+#
+# set up mpp computing environment
+#
+# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
+#
+#cbr export MPIRUN="mpiexec -n $OCEANCORES"
+export MPIRUN="mpirun -np $OCEANCORES"
+
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+#
+
+# Don't remove neither change the following line
+# BODY
+
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export EXE_DIR=DEF_EXE_DIR
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+#
+# end of set up
+###############################################################
+#
+# change to the working directory 
+#
+cd ${EXE_DIR}
+  echo Running on host `hostname`
+  echo Time is `date`
+  echo Directory is `pwd`
+# 
+#  Run the parallel MPI executable 
+#
+  echo "Running time ${MPIRUN} ./opa"
+#
+  if [ MPI_FLAG == "yes" ]; then
+     mpirun -np $OCEANCORES ./opa
+  else
+     time ./opa
+  fi
+
+#
+  post_test_tidyup
+
+# END_BODY
+# Don't remove neither change the previous line
+
+
+  exit
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/all_functions.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/all_functions.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/all_functions.sh	(revision 9987)
@@ -286,22 +286,30 @@
         echo "################" >> ${SETTE_DIR}/output.sette
 
+        inxml=$1
         VAR_NAME=$( grep "^.*<.*file_definition.*type.*=" ${EXE_DIR}/$1 | sed -e "s% *\!.*%%" )
         if [ ${#VAR_NAME} -eq 0 ]
         then
+# This may have failed because the job is using XIOS_2.0 conventions and the file descriptions have moved to file_def.xml
+# Check again in case this is the case
+          VAR_NAME=$( grep "^.*<.*file_definition.*type.*=" ${EXE_DIR}/file_def.xml | sed -e "s% *\!.*%%" )
+          inxml="file_def.xml"
+          if [ ${#VAR_NAME} -eq 0 ]
+          then
                 echo "doing \"set_xio_file_type $@\". "
                 echo "xml_tag: file_definition with variable: type is empty"
-                echo "confirm that an appropriate file_definition is in \"${EXE_DIR}/$1\" "
+                echo "confirm that an appropriate file_definition is in \"${EXE_DIR}/$1\" or file_def.xml"
                 echo "exit"
                 echo "error in executing script : set_xio_file_type $@" >> ${SETTE_DIR}/output.sette
                 echo "....." >> ${SETTE_DIR}/output.sette
                 exit 1
+          fi
         fi
         if [ $2 == "one_file" ] 
         then
-           sed -e "s:multiple_file:one_file:" ${EXE_DIR}/$1 > ${EXE_DIR}/$1.tmp
+           sed -e "s:multiple_file:one_file:" ${EXE_DIR}/$inxml > ${EXE_DIR}/$inxml.tmp
         else
-           sed -e "s:one_file:multiple_file:" ${EXE_DIR}/$1 > ${EXE_DIR}/$1.tmp
-        fi
-        mv ${EXE_DIR}/$1.tmp ${EXE_DIR}/$1
+           sed -e "s:one_file:multiple_file:" ${EXE_DIR}/$inxml > ${EXE_DIR}/$inxml.tmp
+        fi
+        mv ${EXE_DIR}/$inxml.tmp ${EXE_DIR}/$inxml
 
         echo "finished script : set_xio_file_type $@" >> ${SETTE_DIR}/output.sette
@@ -336,6 +344,11 @@
         if [ ${#VAR_NAME} -eq 0 ]
         then
+# This may have failed because the iodef file is using XIOS_2.0 syntax where "boolean" has reduced to "bool"
+# Check again in case this is the case
+          VAR_NAME=$( grep "^.*<.*variable id.*=.*using_server.*=.*bool" ${EXE_DIR}/$1 | sed -e "s% *\!.*%%" )
+           if [ ${#VAR_NAME} -eq 0 ]
+           then
                 echo "doing \"set_xio_using_server $@\". "
-                echo "xml_tag: "variable id=using_server" with variable: boolean is empty"
+                echo "xml_tag: "variable id=using_server" with either variable: boolean or bool is empty"
                 echo "confirm that an appropriate variable id is in \"${EXE_DIR}/$1\" "
                 echo "exit"
@@ -343,4 +356,5 @@
                 echo "....." >> ${SETTE_DIR}/output.sette
                 exit 1
+           fi
         fi
         if [ $2 == "false" ]
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/prepare_exe_dir.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/prepare_exe_dir.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/prepare_exe_dir.sh	(revision 9987)
@@ -70,5 +70,5 @@
 export EXE_DIR=${CONFIG_DIR}/${NEW_CONF}/${TEST_NAME}
 
-cp -r ${CONFIG_DIR}/${NEW_CONF}/EXP00/* ${EXE_DIR}/.
-cp -r ${SETTE_DIR}/iodef_sette.xml ${EXE_DIR}/iodef.xml
+cp -rL ${CONFIG_DIR}/${NEW_CONF}/EXP00/* ${EXE_DIR}/.
+if [ ! -f ${EXE_DIR}/file_def.xml ]; then cp -r ${SETTE_DIR}/iodef_sette.xml ${EXE_DIR}/iodef.xml; fi
 cd ${EXE_DIR}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/prepare_job.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/prepare_job.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/prepare_job.sh	(revision 9987)
@@ -186,5 +186,5 @@
   #  if [ ${MPI_FLAG} == "no" ] ; then
 		case ${COMPILER} in 
-			X64_MOBILIS)
+			X64_MOBILIS*)
                                 NB_REM=$( echo $NB_PROC $NXIO_PROC | awk '{print ( $1 + $2 ) % 16}')
 		        	if [ ${NB_REM} == 0 ] ; then
@@ -280,5 +280,5 @@
                                 fi
                                 ;;
-                        ifort_MERCATOR_CLUSTER)
+                        openmpi_NAVITI_MERCATOR)
                                 echo NB_PROCS ${NB_PROC}
                                 echo NB_NODES ${NB_NODES}
@@ -289,12 +289,12 @@
                                    NB_PROC_NODE=${NB_PROC}
                                 else
-                                   if [ ${NB_PROC} -le 8 ] ; then
+                                   if [ ${NB_PROC} -le 16 ] ; then
                                       NB_NODES=1
                                       QUEUE=mono
                                       NB_PROC_NODE=${NB_PROC}
                                    else
-                                      NB_NODES=$( echo $NB_PROC | awk '{print $1 - $1 % 8}'  | awk '{print $1 / 8 }')
+                                      NB_NODES=$( echo $NB_PROC | awk '{print $1 - $1 % 16}'  | awk '{print $1 / 16 }')
                                       QUEUE=multi
-                                      NB_PROC_NODE=8
+                                      NB_PROC_NODE=16
                                   fi
                                 fi
@@ -324,8 +324,5 @@
 
         case ${COMPILER} in
-              ifort_MERCATOR_CLUSTER)
-                    #cat run_sette_test.job | sed -e"s:QUEUE:${QUEUE}:" > run_sette_test1.job 
-                    #cat run_sette_test.job | sed -e"s/NPROC_NODE/${NB_PROC_NODE}/" > run_sette_test1.job 
-                                                 #-e"s/NPROC_NODE/${NB_PROC_NODE}/" > run_sette_test1.job
+              openmpi_NAVITI_MERCATOR)
                     cat run_sette_test.job | sed -e"s/NPROC_NODE/${NB_PROC_NODE}/" \
                                                  -e"s:QUEUE:${QUEUE}:" > run_sette_test1.job
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette.sh	(revision 9987)
@@ -123,5 +123,5 @@
 # Directory to run the tests
 SETTE_DIR=$(cd $(dirname "$0"); pwd)
-MAIN_DIR=${SETTE_DIR%/SETTE}
+MAIN_DIR=$(dirname $SETTE_DIR)
 CONFIG_DIR=${MAIN_DIR}/CONFIG
 TOOLS_DIR=${MAIN_DIR}/TOOLS
@@ -140,7 +140,8 @@
 # SAS             :11 & 12
 # ISOMIP          :13 & 14
-# ORCA2_LIM_OBS:   15
-# ORCA2_AGRIF_LIM :16
-for config in  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+# ORCA2_LIM_OBS   :15
+# ORCA2_AGRIF_LIM :16 & 17 
+#                  18 & 19 
+for config in  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 
 do
@@ -1237,8 +1238,10 @@
     set_namelist namelist_cfg jpnj 2
     set_namelist namelist_cfg jpnij 2
+#
     set_namelist 1_namelist_cfg nn_it000 1
     set_namelist 1_namelist_cfg nn_itend 150
     set_namelist 1_namelist_cfg ln_ctl .false.
     set_namelist 1_namelist_cfg ln_clobber .true.
+
     if [ ${USING_MPMD} == "yes" ] ; then
        set_xio_using_server iodef.xml true
@@ -1252,3 +1255,229 @@
 fi
 
+# test code corruption with AGRIF
+# Compile and run with or without AGRIF ORCA2_LIM
+if [ ${config} -eq 17 ] ;  then
+    # First run same as 16 but without zoom
+    export TEST_NAME="SHORT_NOZOOM"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2AGUL_2_2 -r ORCA2_LIM -j 8 add_key "key_mpp_rep key_agrif" del_key "key_zdftmx" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+# 
+#   Set the number of fine grids to zero:    
+    sed -i "1s/.*/0/" ${EXE_DIR}/AGRIF_FixedGrids.in
+
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_AGRIF.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+    export TEST_NAME="SHORT_NOAGRIF"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2AGUL_2_2_NAG -r ORCA2_LIM -j 8 add_key "key_mpp_rep" del_key "key_zdftmx" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+#
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_AGRIF.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+fi
+
+## Restartability tests for ORCA2_LIM_AGRIF 
+if [ ${config} -eq 18 ] ;  then
+    export TEST_NAME="LONG"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2AGUL_LONG -r ORCA2_LIM -j 8 add_key "key_mpp_rep key_agrif" del_key "key_zdftmx" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"O2LP_LONG\"
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 150
+    set_namelist namelist_cfg nn_stock 75
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+    set_namelist namelist_cfg nn_solv 2
+#
+    set_namelist 1_namelist_cfg cn_exp \"O2LP_LONG\"
+    set_namelist 1_namelist_cfg nn_it000 1
+    set_namelist 1_namelist_cfg nn_itend 300
+    set_namelist 1_namelist_cfg nn_stock 150
+    set_namelist 1_namelist_cfg ln_ctl .false.
+    set_namelist 1_namelist_cfg ln_clobber .true.
+#
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_AGRIF.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    
+    cd ${SETTE_DIR}
+    export TEST_NAME="SHORT"
+    . ./prepare_exe_dir.sh
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"O2LP_SHORT\"
+    set_namelist namelist_cfg nn_it000 76
+    set_namelist namelist_cfg nn_itend 150
+    set_namelist namelist_cfg nn_stock 75
+    set_namelist namelist_cfg ln_rstart .true.
+    set_namelist namelist_cfg nn_rstctl 2
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+
+    set_namelist namelist_cfg jpnij 4
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist 1_namelist_cfg cn_exp \"O2LP_SHORT\"
+    set_namelist 1_namelist_cfg nn_it000 151
+    set_namelist 1_namelist_cfg nn_itend 300
+    set_namelist 1_namelist_cfg nn_stock 150
+    set_namelist 1_namelist_cfg ln_rstart .true.
+    set_namelist 1_namelist_cfg nn_rstctl 2
+    set_namelist 1_namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg cn_ocerst_in \"O2LP_LONG_00000075_restart\"
+    set_namelist namelist_ice_cfg cn_icerst_in \"O2LP_LONG_00000075_restart_ice\"
+
+    set_namelist 1_namelist_cfg cn_ocerst_in \"O2LP_LONG_00000150_restart\"
+
+    for (( i=1; i<=$NPROC; i++)) ; do
+        L_NPROC=$(( $i - 1 ))
+        L_NPROC=`printf "%04d\n" ${L_NPROC}`
+        ln -sf ../LONG/O2LP_LONG_00000075_restart_${L_NPROC}.nc .
+        ln -sf ../LONG/O2LP_LONG_00000075_restart_ice_${L_NPROC}.nc .
+        ln -sf ../LONG/1_O2LP_LONG_00000150_restart_${L_NPROC}.nc .
+    done
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_AGRIF.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+fi
+
+## Reproducibility tests for ORCA2_LIM_AGRIF
+if [ ${config} -eq 19 ] ;  then
+    export TEST_NAME="REPRO_4_4"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2AGUL_16 -r ORCA2_LIM -j 8 add_key "key_mpp_rep key_agrif" del_key "key_zdftmx" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=16
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 4
+    set_namelist namelist_cfg jpnj 4
+    set_namelist namelist_cfg jpnij 16
+    set_namelist namelist_cfg nn_solv 2
+#
+    set_namelist 1_namelist_cfg nn_it000 1
+    set_namelist 1_namelist_cfg nn_itend 150
+    set_namelist 1_namelist_cfg ln_ctl .false.
+    set_namelist 1_namelist_cfg ln_clobber .true.
+
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_AGRIF.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+    cd ${SETTE_DIR}
+    export TEST_NAME="REPRO_2_8"
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=16
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jpnij 16
+    set_namelist namelist_cfg nn_solv 2
+#
+    set_namelist 1_namelist_cfg nn_it000 1
+    set_namelist 1_namelist_cfg nn_itend 150
+    set_namelist 1_namelist_cfg ln_ctl .false.
+    set_namelist 1_namelist_cfg ln_clobber .true.
+
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_AGRIF.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+fi
+
 done
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette_rpt
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette_rpt	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette_rpt	(revision 9987)
@@ -440,4 +440,88 @@
   endif
 
+
+  if ( -d ./WORCA2AGUL_LONG ) then
+    set dorv = `ls -1rtd ./WORCA2AGUL_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WORCA2AGUL_LONG/{$mach}/{$dorv}/LONG/ocean.output
+    set f1s = ./WORCA2AGUL_LONG/{$mach}/{$dorv}/LONG/solver.stat
+    set f2o = ./WORCA2AGUL_LONG/{$mach}/{$dorv}/SHORT/ocean.output
+    set f2s = ./WORCA2AGUL_LONG/{$mach}/{$dorv}/SHORT/solver.stat
+  
+    set nl = `wc -l $f2s`
+    tail -$nl[1] $f1s > f1.tmp$$
+    cmp -s f1.tmp$$ $f2s
+    if ( $status == 0 ) then
+      echo "ORCA2_LIM_AGRIF restartability  passed"
+    else
+      echo "ORCA2_LIM_AGRIF restartability  FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff f1.tmp$$ $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+    rm f1.tmp$$
+  endif
+
+  if ( -d ./WORCA2AGUL_16 ) then
+    set dorv = `ls -1rtd ./WORCA2AGUL_16/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WORCA2AGUL_16/{$mach}/{$dorv}/REPRO_2_8/ocean.output
+    set f1s = ./WORCA2AGUL_16/{$mach}/{$dorv}/REPRO_2_8/solver.stat
+    set f2o = ./WORCA2AGUL_16/{$mach}/{$dorv}/REPRO_4_4/ocean.output
+    set f2s = ./WORCA2AGUL_16/{$mach}/{$dorv}/REPRO_4_4/solver.stat
+  
+    cmp -s $f1s $f2s
+    if ( $status == 0 ) then
+      echo "ORCA2_LIM_AGRIF reproducibility passed"
+    else
+      echo "ORCA2_LIM_AGRIF reproducibility FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff $f1s $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+  endif
+
+  if ( -d ./WORCA2AGUL_2_2_NAG ) then
+    set dorv = `ls -1rtd ./WORCA2AGUL_2_2_NAG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WORCA2AGUL_2_2_NAG/{$mach}/{$dorv}/SHORT_NOAGRIF/ocean.output
+    set f1s = ./WORCA2AGUL_2_2_NAG/{$mach}/{$dorv}/SHORT_NOAGRIF/solver.stat
+    set dorv = `ls -1rtd ./WORCA2AGUL_2_2/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f2o = ./WORCA2AGUL_2_2/{$mach}/{$dorv}/SHORT_NOZOOM/ocean.output
+    set f2s = ./WORCA2AGUL_2_2/{$mach}/{$dorv}/SHORT_NOZOOM/solver.stat
+  
+    cmp -s $f1s $f2s
+    if ( $status == 0 ) then
+      echo "ORCA2_LIM_AGRIF code corruption test passed"
+    else
+      echo "ORCA2_LIM_AGRIF code corruption test FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff $f1s $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+  endif
+
   echo "<return> for second (more detailed) pass (y/n)"
   set y = $<
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette_rpt.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette_rpt.sh	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/SETTE/sette_rpt.sh	(revision 9987)
@@ -0,0 +1,339 @@
+#!/bin/bash -f
+#
+# simple SETTE report generator.
+#
+# This version should be run in the SETTE directory. 
+# The machine name will be picked up from the sette.sh script but the location of the
+# validation directory needs to be set here (currently assumed to reside in the ../CONFIG directory)
+#
+#########################################################################################
+######################### Start of function definitions #################################
+##
+function resttest() { 
+#
+# Restartability checks. Expects LONG and SHORT run directories
+# Compares end of LONG stat files with equivalent entries from the SHORT stat files.
+#
+  vdir=$1
+  nam=$2
+  pass=$3
+  mach=$4
+#
+  if [ -d $vdir/$nam ]; then
+    dorv=`ls -1rt $vdir/$nam/$mach/ | tail -1l `
+    dorv=`echo $dorv | sed -e 's:.*/::'`
+    f1o=$vdir/$nam/$mach/$dorv/LONG/ocean.output
+    f1s=$vdir/$nam/$mach/$dorv/LONG/solver.stat
+    f1t=$vdir/$nam/$mach/$dorv/LONG/tracer.stat
+    f2o=$vdir/$nam/$mach/$dorv/SHORT/ocean.output
+    f2s=$vdir/$nam/$mach/$dorv/SHORT/solver.stat
+    f2t=$vdir/$nam/$mach/$dorv/SHORT/tracer.stat
+
+    if  [ ! -f $f1s ] &&  [ ! -f $f1t ] ; then 
+      printf "%-20s %s\n" $nam " incomplete test";
+      return; 
+    fi
+    if  [ ! -f $f2s ] &&  [ ! -f $f2t ] ; then 
+      printf "%-20s %s\n" $nam " incomplete test";
+      return; 
+    fi
+#
+    done_oce=0
+
+    if  [  -f $f1s ] && [  -f $f2s ]; then 
+      nl=(`wc -l $f2s`)
+      tail -${nl[0]} $f1s > f1.tmp$$
+      cmp -s f1.tmp$$ $f2s
+      if [ $? == 0 ]; then
+        if [ $pass == 0 ]; then 
+          printf "%-20s %s %s\n" $nam  " solver.stat restartability  passed : " $dorv
+        fi
+      else
+        printf "%-20s %s %s\n" $nam  " solver.stat restartability  FAILED : " $dorv 
+#
+# Offer view of differences on the second pass
+#
+        if [ $pass == 1 ]; then
+          echo "<return> to view solver.stat differences"
+          read y
+          sdiff f1.tmp$$ $f2s
+          echo "<return> to view ocean.output differences"
+          read y
+          sdiff $f1o $f2o | grep "|"
+          done_oce=1
+          echo "<return> to continue"
+          read y
+        fi
+      fi
+    fi
+#
+# Check tracer.stat files (if they exist)
+#
+    if  [  -f $f1t ] && [  -f $f2t ]; then
+      nl=(`wc -l $f2t`)
+      tail -${nl[0]} $f1t > f1.tmp$$
+      cmp -s f1.tmp$$ $f2t
+      if [ $? == 0 ]; then
+        if [ $pass == 0 ]; then 
+          printf "%-20s %s %s\n" $nam  " tracer.stat restartability  passed : " $dorv
+        fi
+      else
+        printf "%-20s %s %s\n" $nam  " tracer.stat restartability  FAILED : " $dorv 
+#
+# Offer view of differences on the second pass
+#
+        if [ $pass == 1 ]; then
+          echo "<return> to view tracer.stat differences"
+          read y
+          sdiff f1.tmp$$ $f2t
+#
+# Only offer ocean.output view if it has not been viewed previously
+#
+          if [ $done_oce == 0 ]; then
+            echo "<return> to view ocean.output differences"
+            read y
+            sdiff $f1o $f2o | grep "|"
+          fi
+          echo "<return> to continue"
+          read y
+        fi
+      fi
+    fi
+    rm f1.tmp$$
+  fi
+}
+
+function reprotest(){
+#
+# Reproducibility checks. Expects REPRO_N_M and REPRO_I_J run directories
+# Compares end of stat files from each
+#
+  vdir=$1
+  nam=$2
+  pass=$3
+  mach=$4
+#
+  if [ -d $vdir/$nam ]; then
+    dorv=`ls -1rt $vdir/$nam/$mach/ | tail -1l `
+    dorv=`echo $dorv | sed -e 's:.*/::'`
+    rep1=`ls -1rt $vdir/$nam/$mach/$dorv/ | tail -2l | head -1 `
+    rep2=`ls -1rt $vdir/$nam/$mach/$dorv/ | tail -1l`
+    f1o=$vdir/$nam/$mach/$dorv/$rep1/ocean.output
+    f1s=$vdir/$nam/$mach/$dorv/$rep1/solver.stat
+    f1t=$vdir/$nam/$mach/$dorv/$rep1/tracer.stat
+    f2o=$vdir/$nam/$mach/$dorv/$rep2/ocean.output
+    f2s=$vdir/$nam/$mach/$dorv/$rep2/solver.stat
+    f2t=$vdir/$nam/$mach/$dorv/$rep2/tracer.stat
+
+    if  [ ! -f $f1s ] && [ ! -f $f1t ] ; then 
+      printf "%-20s %s\n" $nam " incomplete test";
+      return; 
+    fi
+    if  [ ! -f $f2s ] && [ ! -f $f2t ] ; then 
+      printf "%-20s %s\n" $nam " incomplete test";
+      return; 
+    fi
+#
+    done_oce=0
+
+    if  [ -f $f1s ] && [ -f $f2s ] ; then
+      cmp -s $f1s $f2s
+      if [ $? == 0 ]; then
+        if [ $pass == 0 ]; then 
+          printf "%-20s %s %s\n" $nam  " solver.stat reproducibility passed : " $dorv
+        fi
+      else
+        printf "%-20s %s %s\n" $nam  " solver.stat reproducibility FAILED : " $dorv 
+#
+# Offer view of differences on the second pass
+#
+        if [ $pass == 1 ]; then
+          echo "<return> to view solver.stat differences"
+          read y
+          sdiff f1.tmp$$ $f2s
+          echo "<return> to view ocean.output differences"
+          read y
+          sdiff $f1o $f2o | grep "|"
+          done_oce=1
+          echo "<return> to continue"
+          read y
+        fi
+      fi
+    fi
+#
+# Check tracer.stat files (if they exist)
+#
+    if  [ -f $f1t ] && [ -f $f2t ] ; then
+      cmp -s $f1t $f2t
+      if [ $? == 0 ]; then
+        if [ $pass == 0 ]; then           printf "%-20s %s %s\n" $nam  " tracer.stat reproducibility passed : " $dorv
+        fi
+      else
+        printf "%-20s %s %s\n" $nam  " tracer.stat reproducibility  FAILED : " $dorv
+#
+# Offer view of differences on the second pass
+#
+        if [ $pass == 1 ]; then
+          echo "<return> to view tracer.stat differences"
+          read y
+          sdiff $f1t $f2t
+#
+# Only offer ocean.output view if it has not been viewed previously
+#
+          if [ $done_oce == 0 ]; then
+            echo "<return> to view ocean.output differences"
+            read y
+            sdiff $f1o $f2o | grep "|"
+          fi
+          echo "<return> to continue"
+          read y
+        fi
+      fi
+    fi
+  fi
+}
+
+function xiostest() { 
+#
+# XIOS functionality checks. Expects ATTACHED_MULTIPLE, ATTACHED_ONE, DETACHED_MULTIPLE and
+# DETACHED_ONE run directories.
+# Compares stat files from ATTACHED_MULTIPLE with equivalent entries from the others
+#
+  vdir=$1
+  nam=$2
+  pass=$3
+  mach=$4
+#
+  if [ -d $vdir/$nam ]; then
+    dorv=`ls -1rt $vdir/$nam/$mach/ | tail -1l `
+    dorv=`echo $dorv | sed -e 's:.*/::'`
+    f1o=$vdir/$nam/$mach/$dorv/ATTACHED_MULTIPLE/ocean.output
+    f1s=$vdir/$nam/$mach/$dorv/ATTACHED_MULTIPLE/solver.stat
+    f1t=$vdir/$nam/$mach/$dorv/ATTACHED_MULTIPLE/tracer.stat
+    if [ $pass == 0 ]; then printf "%-20s %s %s\n" $nam " checking against " "ATTACHED_MULTIPLE" ; fi
+    for OTHER in ATTACHED_ONE DETACHED_MULTIPLE DETACHED_ONE
+    do
+      f2o=$vdir/$nam/$mach/$dorv/$OTHER/ocean.output
+      f2s=$vdir/$nam/$mach/$dorv/$OTHER/solver.stat
+      f2t=$vdir/$nam/$mach/$dorv/$OTHER/tracer.stat
+
+      if  [ ! -f $f1s ] &&  [ ! -f $f1t ] ; then 
+        printf "%-20s %s %s\n" $nam " incomplete test " $OTHER;
+        return; 
+      fi
+      if  [ ! -f $f2s ] &&  [ ! -f $f2t ] ; then 
+        printf "%-20s %s %s\n" $nam " incomplete test " $OTHER;
+        return; 
+      fi
+#
+      done_oce=0
+
+      if  [  -f $f1s ] && [  -f $f2s ]; then 
+        nl=(`wc -l $f2s`)
+        tail -${nl[0]} $f1s > f1.tmp$$
+        cmp -s f1.tmp$$ $f2s
+        if [ $? == 0 ]; then
+          if [ $pass == 0 ]; then 
+            printf "%-20s %s %s %s\n" $nam  " solver.stat restartability  passed : " $dorv $OTHER
+          fi
+        else
+          printf "%-20s %s %s %s\n" $nam  " solver.stat restartability  FAILED : " $dorv  $OTHER
+#
+# Offer view of differences on the second pass
+#
+          if [ $pass == 1 ]; then
+            echo "<return> to view solver.stat differences"
+            read y
+            sdiff f1.tmp$$ $f2s
+            echo "<return> to view ocean.output differences"
+            read y
+            sdiff $f1o $f2o | grep "|"
+            done_oce=1
+            echo "<return> to continue"
+            read y
+          fi
+        fi
+      fi
+#
+# Check tracer.stat files (if they exist)
+#
+      if  [  -f $f1t ] && [  -f $f2t ]; then
+        nl=(`wc -l $f2t`)
+        tail -${nl[0]} $f1t > f1.tmp$$
+        cmp -s f1.tmp$$ $f2t
+        if [ $? == 0 ]; then
+          if [ $pass == 0 ]; then 
+            printf "%-20s %s %s %s\n" $nam  " tracer.stat restartability  passed : " $dorv $OTHER
+          fi
+        else
+          printf "%-20s %s %s %s\n" $nam  " tracer.stat restartability  FAILED : " $dorv  $OTHER
+#
+# Offer view of differences on the second pass
+#
+          if [ $pass == 1 ]; then
+            echo "<return> to view tracer.stat differences"
+            read y
+            sdiff f1.tmp$$ $f2t
+#
+# Only offer ocean.output view if it has not been viewed previously
+#
+            if [ $done_oce == 0 ]; then
+              echo "<return> to view ocean.output differences"
+              read y
+              sdiff $f1o $f2o | grep "|"
+            fi
+            echo "<return> to continue"
+            read y
+          fi
+        fi
+      fi
+      rm f1.tmp$$
+    done
+  fi
+}
+
+########################### END of function definitions #################################
+##                                                                                     ##
+##    Main script                                                                      ##
+##                                                                                     ##
+#########################################################################################
+#
+  mach1=`grep "COMPILER=" ./sette.sh | sed -e 's/COMPILER=//'`
+  mach2=`grep "COMPILER=" ./sette_xios.sh | sed -e 's/COMPILER=//'`
+  NEMO_VALID=`grep "NEMO_VALIDATION_DIR=" ./param.cfg | sed -e 's/NEMO_VALIDATION_DIR=//'`
+#
+  if [ ! -d $NEMO_VALID ]; then
+    echo "$NEMO_VALID validation directory not found"
+    exit
+  fi
+#
+# The script also needs the date or revision tag. Currently this is taken from the latest sub-directory found in each directory
+#  
+for pass in  0 1 
+do
+#
+ if [ $pass == 1 ]; then echo "---------------2nd pass------------------";fi
+#
+# Restartability test
+#
+ for restart_test in WGYRE_LONG WISOMIP_LONG WORCA2LIMPIS_LONG WORCA2OFFPIS_LONG WAMM12_LONG WORCA2LIM3_LONG WSAS_LONG WORCA2AGUL_LONG
+ do
+   resttest $NEMO_VALID $restart_test $pass $mach1
+ done
+#
+# sette_xios tests (allow for the possibility of a different compiler base)
+#
+ for xios_test in WGYRE_XIOS_LR WGYRE_XIOS_HR
+ do
+   xiostest $NEMO_VALID $xios_test $pass $mach2
+ done
+#
+# Reproducibility tests
+#
+ for repro_test in WGYRE_4 WISOMIP_4 WORCA2LIMPIS_16 WORCA2OFFPIS_16 WAMM12_32 WORCA2LIM3_16 WORCA2_LIM_OBS WSAS_32 WORCA2AGUL_1_2 WORCA2AGUL_16 WORCA2AGUL_2_2_NAG
+ do
+   reprotest $NEMO_VALID $repro_test $pass $mach1
+ done
+#
+done
+exit
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/Fmake_config.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/Fmake_config.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/Fmake_config.sh	(revision 9987)
@@ -65,4 +65,5 @@
 [ -f ${2}/EXP00/iodef.xml ] &&  \cp -R  ${2}/EXP00/iodef.xml ${1}/EXP00/.
 [ -f ${2}/EXP00/field_def.xml ] &&  \cp -R  ${2}/EXP00/field_def.xml ${1}/EXP00/.
+[ -f ${2}/EXP00/file_def.xml ] &&  \cp -R  ${2}/EXP00/file_def.xml ${1}/EXP00/.
 [ -f ${2}/EXP00/domain_def.xml ] &&  \cp -R  ${2}/EXP00/domain_def.xml ${1}/EXP00/.
 [ -f ${2}/EXP00/xmlio_server.def ] &&  \cp -R  ${2}/EXP00/xmlio_server.def ${1}/EXP00/.
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/Fprep_agrif.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/Fprep_agrif.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/Fprep_agrif.sh	(revision 9987)
@@ -57,8 +57,15 @@
 #- AGRIF conv
 if [ "$AGRIFUSE" == 1 ]; then
+#-MPI for AGRIF
+if [ ! -f ${MAIN_DIR}/EXTERNAL/AGRIF/nemo_mpi.h ];then
+   echo '#if defined key_mpp_mpi' > ${MAIN_DIR}/EXTERNAL/AGRIF/nemo_mpi.h
+   echo '#define AGRIF_MPI'      >> ${MAIN_DIR}/EXTERNAL/AGRIF/nemo_mpi.h
+   echo '#endif'                 >> ${MAIN_DIR}/EXTERNAL/AGRIF/nemo_mpi.h
+fi
 
 #- CONV
-#fcm build ${TOOLS_DIR}/conv.cfg || exit 1
-gmake -C ${MAIN_DIR}/EXTERNAL/AGRIF/LIB
+fcm build ${COMPIL_DIR}/conv.cfg || exit 1
+#C_COMPILER=${CC-cc}
+#gmake CC=${C_COMPILER} -C ${MAIN_DIR}/EXTERNAL/AGRIF/LIB
 
 #- AGRIF sources
@@ -67,5 +74,6 @@
 [ ! -d $2/$1/OPAFILES/AGRIF_MODELFILES ] && mkdir  $2/$1/OPAFILES/AGRIF_MODELFILES
 cp -f -r ${MAIN_DIR}/EXTERNAL/AGRIF/agrif_opa.in  $2/$1/OPAFILES/
-cp -f -r ${MAIN_DIR}/EXTERNAL/AGRIF/conv  $2/$1/OPAFILES/
+#cp -f -r ${MAIN_DIR}/EXTERNAL/AGRIF/conv  $2/$1/OPAFILES/
+cp -f -r $2/$1/AGRIFLIB/bin/conv  $2/$1/OPAFILES/
 
 fi
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/agrifpp.sh
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/agrifpp.sh	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/agrifpp.sh	(revision 9987)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/bld.cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/bld.cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/bld.cfg	(revision 9987)
@@ -41,5 +41,5 @@
 bld::tool::fppflags::nemo      %FPPFLAGS -I$CONFIG_DIR/$NEW_CONF/OPAFILES/inc
 bld::tool::fppflags::ioipsl    %FPPFLAGS
-bld::tool::fppflags::agrif     %FPPFLAGS
+bld::tool::fppflags::agrif     %FPPFLAGS -include ${MAIN_DIR}/EXTERNAL/AGRIF/nemo_mpi.h
 
 # Ignore the following dependencies
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/bld_preproagr.cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/bld_preproagr.cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/bld_preproagr.cfg	(revision 9987)
@@ -52,4 +52,5 @@
 bld::excl_dep	     use::ioipsl
 bld::excl_dep	     use::xios
+bld::excl_dep        use::agrif_grids
 bld::excl_dep	     use::agrif_types
 bld::excl_dep	     use::agrif_util
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/conv.cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/conv.cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/conv.cfg	(revision 9987)
@@ -8,6 +8,8 @@
 # Build information
 # ------------------------------------------------------------------------------
-inc $COMPIL_DIR/arch.fcm
+inc $COMPIL_DIR/arch_nemo.fcm
 
+bld::tool::cc        %CC
+bld::tool::cflags    %CFLAGS
 bld::tool::make      %MK
 
@@ -19,8 +21,8 @@
 dir::root            $NEMO_TDIR/$NEW_CONF/AGRIFLIB
 
-bld::tool::cflags::convsrc  -O0  
-bld::tool::ld::convsrc   cc
-bld::tool::ldflags::convsrc -O  ../obj/fortran.o ../obj/fortran.o 
-bld::pp 1
+#bld::tool::cflags::convsrc  -O0  
+#bld::tool::ld::convsrc   cc
+#bld::tool::ldflags::convsrc -O  ../obj/fortran.o ../obj/fortran.o 
+#bld::pp 1
 
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/tools.txt
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/tools.txt	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/COMPILE/tools.txt	(revision 9987)
@@ -1,1 +1,1 @@
-REBUILD 
+SIREN 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/DMP_TOOLS/src/zoom.F90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/DMP_TOOLS/src/zoom.F90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/DMP_TOOLS/src/zoom.F90	(revision 9987)
@@ -29,7 +29,4 @@
       NAMELIST/nam_zoom_dmp/lzoom_n,lzoom_e,lzoom_w,lzoom_s
       !!----------------------------------------------------------------------
-      !
-      IF( nn_timing == 1 )  CALL timing_start( 'dtacof_zoom')
-      !
       
       ! Read namelist
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MISCELLANEOUS/icb_pp.py
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MISCELLANEOUS/icb_pp.py	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MISCELLANEOUS/icb_pp.py	(revision 9987)
@@ -55,5 +55,5 @@
 if procnum < 1:
    print('Need some files to collate! procnum = ',procnum)
-   sys.exit()
+   sys.exit(11)
 
 icu = []
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MPP_PREP/src/mpp_optimiz_zoom_nc.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MPP_PREP/src/mpp_optimiz_zoom_nc.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MPP_PREP/src/mpp_optimiz_zoom_nc.f90	(revision 9987)
@@ -258,10 +258,13 @@
                  ijlb=ijdom(jni2,jnj2)
               ENDIF
+
+              ! Check wet points over the entire domain to preserve the MPI communication stencil
               isurf=0
-              DO jj=1+jprecj,ippdj(jni2,jnj2)-jprecj
-                 DO  ji=1+jpreci,ippdi(jni2,jnj2)-jpreci
+              DO jj=1,ippdj(jni2,jnj2)
+                 DO  ji=1,ippdi(jni2,jnj2)
                     IF(zmask(ji+iilb-1,jj+ijlb-1).EQ.1.) isurf=isurf+1
                  END DO
               END DO
+
               IF(isurf.EQ.0) THEN
                  ivide=ivide+1
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MPP_PREP/src/mppopt_showproc_nc.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MPP_PREP/src/mppopt_showproc_nc.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/MPP_PREP/src/mppopt_showproc_nc.f90	(revision 9987)
@@ -289,11 +289,13 @@
                  ijlb=ijdom(jni2,jnj2)
               ENDIF
+
+              ! Check wet points over the entire domain to preserve the MPI communication stencil
               isurf=0
-
-              DO jj=1+jprecj,ippdj(jni2,jnj2)-jprecj
-                 DO  ji=1+jpreci,ippdi(jni2,jnj2)-jpreci
+              DO jj=1,ippdj(jni2,jnj2)
+                 DO  ji=1,ippdi(jni2,jnj2)
                     IF(zmask(ji+iilb-1,jj+ijlb-1).EQ.1.) isurf=isurf+1
                  END DO
               END DO
+
               IF(isurf.EQ.0) THEN
                  ivide=ivide+1
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/agulhas
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/agulhas	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/agulhas	(revision 9987)
@@ -17,4 +17,5 @@
     removeclosedseas = true
     type_bathy_interp = 0 
+    rn_hmin = -3 
 /   
 
@@ -39,4 +40,8 @@
     pa1  = 245.58132232490
     N  = 31
+    ldbletanh   = .FALSE.
+    pa2         = 0.0
+    ppkth2      = 0.0
+    ppacr2      = 0.0
 /    
     
@@ -45,6 +50,6 @@
     parent_bathy_meter = 'bathy_meter.nc'
     parent_batmet_name = 'Bathymetry'
-    e3zps_min = 25.
-    e3zps_rat = 0.2
+    e3zps_min = 20.
+    e3zps_rat = 0.1
 /
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_connect_topo.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_connect_topo.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_connect_topo.f90	(revision 9987)
@@ -105,5 +105,5 @@
     IMPLICIT NONE
     !
-    REAL*8 :: za1,za0,zsur,zacr,zkth,zmin,zmax
+    REAL*8 :: za2,za1,za0,zsur,zacr,zkth,zacr2,zkth2,zmin,zmax
     TYPE(Coordinates) :: Grid
     INTEGER :: i,j
@@ -134,4 +134,5 @@
        za0  = pa0
        za1  = pa1
+       za2  = pa2
        !
     ELSE
@@ -147,19 +148,49 @@
 
     zacr = ppacr
-    zkth = ppkth 
-
+    zkth = ppkth
+    zacr2 = ppacr2
+    zkth2 = ppkth2   
     !
     ALLOCATE(gdepw(N),gdept(N),e3w(N),e3t(N))
     !
-    DO i = 1,N
-       gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
-       gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
-       e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
-       e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
-    END DO
+    IF( ppkth == 0. ) THEN            !  uniform vertical grid 
+       za1 = pphmax / FLOAT(N-1) 
+       DO i = 1, N
+          gdepw(i) = ( i - 1   ) * za1
+          gdept(i) = ( i - 0.5 ) * za1
+          e3w  (i) =  za1
+          e3t  (i) =  za1
+       END DO
+    ELSE                            ! Madec & Imbard 1996 function
+       IF( .NOT. ldbletanh ) THEN
+          DO i = 1,N
+             ! 
+             gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
+             gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
+             e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
+             e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
+             !
+          END DO
+       ELSE
+          DO i = 1,N
+             ! Double tanh function
+             gdepw(i) = ( zsur + za0*i  + za1 * zacr * LOG ( COSH( (i-zkth ) / zacr  ) )               &
+                &                       + za2 * zacr2* LOG ( COSH( (i-zkth2) / zacr2 ) )  )
+             gdept(i) = ( zsur + za0*(i+0.5) + za1 * zacr * LOG ( COSH( ((i+0.5)-zkth ) / zacr  ) )    &
+                &                            + za2 * zacr2* LOG ( COSH( ((i+0.5)-zkth2) / zacr2 ) )  )
+             e3w  (i) =          za0         + za1        * TANH(       (i-zkth ) / zacr  )            &
+                &                            + za2        * TANH(       (i-zkth2) / zacr2 )
+             e3t  (i) =          za0         + za1        * TANH(       ((i+0.5)-zkth ) / zacr  )      &
+                &                            + za2        * TANH(       ((i+0.5)-zkth2) / zacr2 )
+            END DO
+       ENDIF
+    ENDIF
     !
     gdepw(1) = 0.0
     zmax = gdepw(N) + e3t(N)
-    zmin = gdepw(4)
+    IF( rn_hmin < 0. ) THEN  ;   i = - INT( rn_hmin )                                  ! from a nb of level
+    ELSE                     ;   i = MINLOC( gdepw, mask = gdepw > rn_hmin, dim = 1 )  ! from a depth
+    ENDIF
+    zmin = gdepw(i+1)
     !
     IF ( .NOT. ASSOCIATED(Grid%bathy_level)) &
@@ -227,5 +258,5 @@
     IMPLICIT NONE
     !
-    REAL*8 :: za1,za0,zsur,zacr,zkth,zmin,zmax
+    REAL*8 :: za2,za1,za0,zsur,zacr,zkth,zacr2,zkth2,zmin,zmax
     TYPE(Coordinates) :: Grid
     INTEGER :: i,j
@@ -257,4 +288,5 @@
        za0  = pa0
        za1  = pa1
+       za2  = pa2
        !
     ELSE
@@ -264,22 +296,48 @@
        WRITE(*,*) 'please check values of variables'
        WRITE(*,*) 'in namelist vertical_grid section'
-       WRITE(*,*) ' '
-       STOP      
+       WRITE(*,*) ' ' 
+       STOP     
        !       
     ENDIF
-    !
+
     zacr = ppacr
-    zkth = ppkth 
-
+    zkth = ppkth
+    zacr2 = ppacr2
+    zkth2 = ppkth2   
     !
     ALLOCATE(gdepw(N),gdept(N),e3w(N),e3t(N))
     !
-    DO i = 1,N
-       ! 
-       gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
-       gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
-       e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
-       e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
-    END DO
+    IF( ppkth == 0. ) THEN            !  uniform vertical grid 
+       za1 = pphmax / FLOAT(N-1) 
+       DO i = 1, N
+          gdepw(i) = ( i - 1   ) * za1
+          gdept(i) = ( i - 0.5 ) * za1
+          e3w  (i) =  za1
+          e3t  (i) =  za1
+       END DO
+    ELSE                            ! Madec & Imbard 1996 function
+       IF( .NOT. ldbletanh ) THEN
+          DO i = 1,N
+             ! 
+             gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
+             gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
+             e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
+             e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
+             !
+          END DO
+       ELSE
+          DO i = 1,N
+             ! Double tanh function
+             gdepw(i) = ( zsur + za0*i  + za1 * zacr * LOG ( COSH( (i-zkth ) / zacr  ) )               &
+                &                       + za2 * zacr2* LOG ( COSH( (i-zkth2) / zacr2 ) )  )
+             gdept(i) = ( zsur + za0*(i+0.5) + za1 * zacr * LOG ( COSH( ((i+0.5)-zkth ) / zacr  ) )    &
+                &                            + za2 * zacr2* LOG ( COSH( ((i+0.5)-zkth2) / zacr2 ) )  )
+             e3w  (i) =          za0         + za1        * TANH(       (i-zkth ) / zacr  )            &
+                &                            + za2        * TANH(       (i-zkth2) / zacr2 )
+             e3t  (i) =          za0         + za1        * TANH(       ((i+0.5)-zkth ) / zacr  )      &
+                &                            + za2        * TANH(       ((i+0.5)-zkth2) / zacr2 )
+         END DO
+       ENDIF
+    ENDIF
     !
     gdepw(1) = 0.0  
@@ -684,8 +742,8 @@
   ! for consistency with fine grid bathymetry			*
   !								*
-  ! if a given coarse grid point is masked and one of the		*
-  ! child grid points contained in this coarse cell is not masked	*
-  ! the corresponding coarse grid point is unmasked with gdepw(4) *
-  ! value								*
+  ! if a given coarse grid point is masked and one of the	  *
+  ! child grid points contained in this coarse cell is not masked *
+  ! the corresponding coarse grid point is unmasked with rn_hmin  *
+  ! value						          *
   !								*
   ! - input :							*
@@ -704,5 +762,5 @@
     !
     INTEGER :: ideb,jdeb,ifin,jfin
-    REAL*8 :: za1,za0,zsur,zacr,zkth,zmin
+    REAL*8 :: za2,za1,za0,zsur,zacr,zkth,zacr2,zkth2,zmin
     INTEGER :: i,j
     INTEGER :: k1
@@ -727,4 +785,5 @@
        za0  = pa0
        za1  = pa1
+       za2  = pa2
        !
     ELSE
@@ -740,18 +799,47 @@
 
     zacr = ppacr
-    zkth = ppkth 
-
+    zkth = ppkth
+    zacr2 = ppacr2
+    zkth2 = ppkth2   
     !
     ALLOCATE(gdepw(N),gdept(N),e3w(N),e3t(N))
     !
-    DO i = 1,N
-       ! 
-       gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
-       gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
-       e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
-       e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
-    END DO
-    !
-    zmin = gdepw(4)
+    IF( ppkth == 0. ) THEN            !  uniform vertical grid 
+       za1 = pphmax / FLOAT(N-1) 
+       DO i = 1, N
+          gdepw(i) = ( i - 1   ) * za1
+          gdept(i) = ( i - 0.5 ) * za1
+          e3w  (i) =  za1
+          e3t  (i) =  za1
+       END DO
+    ELSE                            ! Madec & Imbard 1996 function
+       IF( .NOT. ldbletanh ) THEN
+          DO i = 1,N
+             ! 
+             gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
+             gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
+             e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
+             e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
+             !
+          END DO
+       ELSE
+          DO i = 1,N
+             ! Double tanh function
+             gdepw(i) = ( zsur + za0*i  + za1 * zacr * LOG ( COSH( (i-zkth ) / zacr  ) )               &
+                &                       + za2 * zacr2* LOG ( COSH( (i-zkth2) / zacr2 ) )  )
+             gdept(i) = ( zsur + za0*(i+0.5) + za1 * zacr * LOG ( COSH( ((i+0.5)-zkth ) / zacr  ) )    &
+                &                            + za2 * zacr2* LOG ( COSH( ((i+0.5)-zkth2) / zacr2 ) )  )
+             e3w  (i) =          za0         + za1        * TANH(       (i-zkth ) / zacr  )            &
+                &                            + za2        * TANH(       (i-zkth2) / zacr2 )
+             e3t  (i) =          za0         + za1        * TANH(       ((i+0.5)-zkth ) / zacr  )      &
+                &                            + za2        * TANH(       ((i+0.5)-zkth2) / zacr2 )
+          END DO
+       ENDIF
+    ENDIF
+    !
+    IF( rn_hmin < 0. ) THEN  ;   i = - INT( rn_hmin )                                  ! from a nb of level
+    ELSE                     ;   i = MINLOC( gdepw, mask = gdepw > rn_hmin, dim = 1 )  ! from a depth
+    ENDIF
+    zmin = gdepw(i+1)
     !      
     diff = 0
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_partial_steps.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_partial_steps.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_partial_steps.f90	(revision 9987)
@@ -36,5 +36,5 @@
     !       
     TYPE(Coordinates) :: Grid                     
-    REAL*8 :: za1,za0,zsur,zacr,zkth,zdepth,zdepwp,zmin,zmax,zdiff,ze3tp,ze3wp
+    REAL*8 :: za2,za1,za0,zsur,zacr,zkth,zacr2,zkth2,zdepth,zdepwp,zmin,zmax,zdiff,ze3tp,ze3wp
     INTEGER :: i,j,jk,jj,ji,jpj,jpi,ik,ii,ipt,jpt
     INTEGER, DIMENSION(1) :: k
@@ -76,4 +76,5 @@
        za0  = pa0
        za1  = pa1
+       za2  = pa2
        !
     ELSE
@@ -88,17 +89,41 @@
     ENDIF
 
-    zacr = ppacr
-    zkth = ppkth       
-    !
-    DO i = 1,N
-       ! 
-       gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
-       gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
-       e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
-       e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
-       !
-    END DO
-    !
-
+    zacr  = ppacr
+    zkth  = ppkth     
+    zacr2 = ppacr2
+    zkth2 = ppkth2  
+    !
+    IF( ppkth == 0. ) THEN            !  uniform vertical grid 
+         za1 = pphmax / FLOAT(N-1) 
+         DO i = 1, N
+            gdepw(i) = ( i - 1   ) * za1
+            gdept(i) = ( i - 0.5 ) * za1
+            e3w  (i) =  za1
+            e3t  (i) =  za1
+         END DO
+    ELSE                            ! Madec & Imbard 1996 function
+       IF( .NOT. ldbletanh ) THEN
+          DO i = 1,N
+             ! 
+             gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
+             gdept(i) = (zsur+za0*(i+0.5)+za1*zacr*LOG(COSH(((i+0.5)-zkth)/zacr)))
+             e3w(i)   = (za0 + za1 * TANH((i-zkth)/zacr))
+             e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
+             !
+          END DO
+       ELSE
+            DO i = 1,N
+               ! Double tanh function
+               gdepw(i) = ( zsur + za0*i  + za1 * zacr * LOG ( COSH( (i-zkth ) / zacr  ) )               &
+                  &                       + za2 * zacr2* LOG ( COSH( (i-zkth2) / zacr2 ) )  )
+               gdept(i) = ( zsur + za0*(i+0.5) + za1 * zacr * LOG ( COSH( ((i+0.5)-zkth ) / zacr  ) )    &
+                  &                            + za2 * zacr2* LOG ( COSH( ((i+0.5)-zkth2) / zacr2 ) )  )
+               e3w  (i) =          za0         + za1        * TANH(       (i-zkth ) / zacr  )            &
+                  &                            + za2        * TANH(       (i-zkth2) / zacr2 )
+               e3t  (i) =          za0         + za1        * TANH(       ((i+0.5)-zkth ) / zacr  )      &
+                  &                            + za2        * TANH(       ((i+0.5)-zkth2) / zacr2 )
+            END DO
+       ENDIF
+    ENDIF
     gdepw(1) = 0.0  
     !
@@ -106,5 +131,8 @@
     !
     zmax = gdepw(N) + e3t(N)
-    zmin = gdepw(4)
+    IF( rn_hmin < 0. ) THEN  ;   i = - INT( rn_hmin )                                  ! from a nb of level
+    ELSE                     ;   i = MINLOC( gdepw, mask = gdepw > rn_hmin, dim = 1 )  ! from a depth
+    ENDIF
+    zmin = gdepw(i+1)
     !
     ! Initialize bathy_level to the maximum ocean level available
@@ -235,11 +263,12 @@
     INTEGER :: i,j,ji,ij,ii,jj,jpt,ipt
     REAL,DIMENSION(N) :: gdepw,e3t
-    REAL :: za0,za1,zsur,zacr,zkth,zmin,zmax,zdepth
+    REAL :: za0,za1,za2,zsur,zacr,zacr2,zkth,zkth2,zmin,zmax,zdepth
     INTEGER :: kbathy,jk,diff
     INTEGER :: bornex,borney,bornex2,borney2
-    !       
+    !
     IF ( ( pa0 == 0 .OR. pa1 == 0 .OR. psur == 0 ) &
          .AND. ppdzmin.NE.0 .AND. pphmax.NE.0 ) THEN 
        !    
+       WRITE(*,*) 'psur,pa0,pa1 computed'
        za1=( ppdzmin - pphmax / (N-1) )          &
             / ( TANH((1-ppkth)/ppacr) - ppacr/(N-1) &
@@ -253,7 +282,9 @@
          pa0.NE.0 .AND. pa1.NE.0 ) THEN
        !       
+       WRITE(*,*) 'psur,pa0,pa1 given by namelist'
        zsur = psur
        za0  = pa0
        za1  = pa1
+       za2  = pa2
        !
     ELSE
@@ -263,19 +294,39 @@
        WRITE(*,*) 'please check values of variables'
        WRITE(*,*) 'in namelist vertical_grid section'
-       WRITE(*,*) ' '      
-       !       
-    ENDIF
-    !       
-    zacr = ppacr
-    zkth = ppkth       
-    !
-    DO i = 1,N
-       ! 
-       gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr)))
-       e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))       
-    END DO
-    !
+       WRITE(*,*) ' '  
+       STOP    
+       !       
+    ENDIF
+
+    zacr  = ppacr
+    zkth  = ppkth     
+    zacr2 = ppacr2
+    zkth2 = ppkth2  
+    !
+    IF( ppkth == 0. ) THEN            !  uniform vertical grid 
+         za1 = pphmax / FLOAT(N-1) 
+         DO i = 1, N
+            gdepw(i) = ( i - 1   ) * za1
+            e3t  (i) =  za1
+         END DO
+    ELSE                            ! Madec & Imbard 1996 function
+       IF( .NOT. ldbletanh ) THEN
+          DO i = 1,N
+             ! 
+             gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
+             e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
+             !
+          END DO
+       ELSE
+            DO i = 1,N
+               ! Double tanh function
+               gdepw(i) = ( zsur + za0*i  + za1 * zacr * LOG ( COSH( (i-zkth ) / zacr  ) )               &
+                  &                       + za2 * zacr2* LOG ( COSH( (i-zkth2) / zacr2 ) )  )
+               e3t  (i) =          za0         + za1        * TANH(       ((i+0.5)-zkth ) / zacr  )      &
+                  &                            + za2        * TANH(       ((i+0.5)-zkth2) / zacr2 )
+            END DO
+       ENDIF
+    ENDIF
     gdepw(1) = 0.0
-    !
     !
     diff = 0      
@@ -344,5 +395,8 @@
     !
     zmax = gdepw(N) + e3t(N)
-    zmin = gdepw(4) 
+    IF( rn_hmin < 0. ) THEN  ;   i = - INT( rn_hmin )                                  ! from a nb of level
+    ELSE                     ;   i = MINLOC( gdepw, mask = gdepw > rn_hmin, dim = 1 )  ! from a depth
+    ENDIF
+    zmin = gdepw(i+1)
     !
     ! check that interpolated value stays at the same level         
@@ -646,5 +700,5 @@
     REAL*8, DIMENSION(:,:,:) :: fse3u,fse3t,fse3v
     !                                  
-    REAL*8 :: za1,za0,zsur,zacr,zkth,zdepth,zdepwp,zmin,zmax,zdiff,ze3tp,ze3wp
+    REAL*8 :: za2,za1,za0,zsur,zacr,zkth,zacr2,zkth2,zdepth,zdepwp,zmin,zmax,zdiff,ze3tp,ze3wp
     INTEGER :: i,j,jk,jj,ji,jpj,jpi,ik,ii,ipt,jpt,jpk
     INTEGER, DIMENSION(1) :: k
@@ -660,5 +714,5 @@
     ALLOCATE(gdepw(jpk),e3t(jpk))
     ALLOCATE(gdepw_ps(jpi,jpj,jpk))                  
-    !       
+    !  
     IF ( ( pa0 == 0 .OR. pa1 == 0 .OR. psur == 0 ) &
          .AND. ppdzmin.NE.0 .AND. pphmax.NE.0 ) THEN 
@@ -668,6 +722,6 @@
             / ( TANH((1-ppkth)/ppacr) - ppacr/(jpk-1) &
             *  (  LOG( COSH( (jpk - ppkth) / ppacr) )      &
-            - LOG( COSH( ( 1  - ppkth) / ppacr) )  )  ) 
-       !
+            - LOG( COSH( ( 1  - ppkth) / ppacr) )  )  )
+
        za0  = ppdzmin - za1 * TANH( (1-ppkth) / ppacr )
        zsur = - za0 - za1 * ppacr * LOG( COSH( (1-ppkth) / ppacr )  )
@@ -676,18 +730,53 @@
          pa0.NE.0 .AND. pa1.NE.0 ) THEN
        !       
+       WRITE(*,*) 'psur,pa0,pa1 given by namelist'
        zsur = psur
        za0  = pa0
-       za1  = pa1   
-       !       
-    ENDIF
-
-    zacr = ppacr
-    zkth = ppkth       
+       za1  = pa1
+       za2  = pa2
+       !
+    ELSE
+       !       
+       WRITE(*,*) 'ERROR ***** bad vertical grid parameters ...' 
+       WRITE(*,*) ' '
+       WRITE(*,*) 'please check values of variables'
+       WRITE(*,*) 'in namelist vertical_grid section'
+       WRITE(*,*) ' '  
+       STOP    
+       !       
+    ENDIF
+
+    zacr  = ppacr
+    zkth  = ppkth     
+    zacr2 = ppacr2
+    zkth2 = ppkth2  
+    !
+    IF( ppkth == 0. ) THEN            !  uniform vertical grid 
+         za1 = pphmax / FLOAT(jpk-1) 
+         DO i = 1, jpk
+            gdepw(i) = ( i - 1   ) * za1
+            e3t  (i) =  za1
+         END DO
+    ELSE                            ! Madec & Imbard 1996 function
+       IF( .NOT. ldbletanh ) THEN
+          DO i = 1,jpk
+             ! 
+             gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
+             e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
+             !
+          END DO
+       ELSE
+            DO i = 1,jpk
+               ! Double tanh function
+               gdepw(i) = ( zsur + za0*i  + za1 * zacr * LOG ( COSH( (i-zkth ) / zacr  ) )               &
+                  &                       + za2 * zacr2* LOG ( COSH( (i-zkth2) / zacr2 ) )  )
+               e3t  (i) =          za0         + za1        * TANH(       ((i+0.5)-zkth ) / zacr  )      &
+                  &                            + za2        * TANH(       ((i+0.5)-zkth2) / zacr2 )
+            END DO
+       ENDIF
+    ENDIF         
     !         
     !                
     DO i = 1,jpk
-       ! 
-       gdepw(i) = (zsur+za0*i+za1*zacr*LOG(COSH((i-zkth)/zacr))) 
-       e3t(i)   = (za0 + za1 * TANH(((i+0.5)-zkth)/zacr))
        !       
        fse3t(:,:,i) = e3t(i)
@@ -700,5 +789,8 @@
     !
     zmax = gdepw(jpk) + e3t(jpk)
-    zmin = gdepw(4)
+    IF( rn_hmin < 0. ) THEN  ;   i = - INT( rn_hmin )                                  ! from a nb of level
+    ELSE                     ;   i = MINLOC( gdepw, mask = gdepw > rn_hmin, dim = 1 )  ! from a depth
+    ENDIF
+    zmin = gdepw(i+1)
     !
     DO jj = 1, jpj
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_types.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_types.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/NESTING/src/agrif_types.f90	(revision 9987)
@@ -51,7 +51,9 @@
   INTEGER jpizoom,jpjzoom,nb_connection_pts
   !      
-  REAL*8 ppacr,ppdzmin,pphmax,ppkth,smoothing_factor,e3zps_min,e3zps_rat
-  REAL*8 psur,pa0,pa1,adatrj
+  REAL*8 rn_hmin
+  REAL*8 ppkth2, ppacr2, ppkth,ppacr,ppdzmin,pphmax,smoothing_factor,e3zps_min,e3zps_rat
+  REAL*8 psur,pa0,pa1,pa2,adatrj
   !       
+  LOGICAL ldbletanh
   LOGICAL partial_steps,smoothing,bathy_update
   LOGICAL new_topo,removeclosedseas,dimg,iom_activated
@@ -70,9 +72,9 @@
   !      
   NAMELIST /bathymetry/new_topo,elevation_database,elevation_name,smoothing,smoothing_factor, &
-       nb_connection_pts,removeclosedseas,type_bathy_interp      
+       nb_connection_pts,removeclosedseas,type_bathy_interp,rn_hmin      
   !      
   NAMELIST /nesting/imin,imax,jmin,jmax,rho,rhot,bathy_update,updated_parent_file      
   !
-  NAMELIST /vertical_grid/ppkth,ppacr,ppdzmin,pphmax,psur,pa0,pa1,N
+  NAMELIST /vertical_grid/ppkth,ppacr,ppdzmin,pphmax,psur,pa0,pa1,N,ldbletanh,pa2,ppkth2,ppacr2
   ! 
   NAMELIST /partial_cells/partial_steps,parent_bathy_meter,parent_batmet_name,e3zps_min,e3zps_rat      
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/REBUILD_NEMO/icb_combrest.py
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/REBUILD_NEMO/icb_combrest.py	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/REBUILD_NEMO/icb_combrest.py	(revision 9987)
@@ -0,0 +1,275 @@
+import os
+from netCDF4 import Dataset
+from argparse import ArgumentParser
+import numpy as np
+import sys
+
+#
+# Basic iceberg trajectory restart post-processing python script.
+# This script collects iceberg information from the distributed restarts written
+# out by each processing region and writes the information into a global restart file.
+# The global restart file must already exist and contain the collated 2D spatial fields
+# as prepared by utilities such as rebuild_nemo. This python script simply adds the
+# iceberg position and state data that is held using the unlimited dimension 'n' which
+# has been ignored by rebuild_nemo. Each processing region that contains icebergs will
+# (probably) have a different number of icebergs (indicated by differing values for the
+# current size of the unlimited dimension). This script collects all icebergs into a 
+# single unordered list.
+#
+
+parser = ArgumentParser(description='produce a global trajectory restart file from distributed output\
+                                     files, e.g. \n python ./icb_pp.py \
+                                     -f  icebergs_00692992_restart_ -n 480 -o icebergs_restart.nc [-O]')
+
+parser.add_argument('-f',dest='froot',help='fileroot_of_distrbuted_data; root name of \
+                     distributed trajectory restart file (usually completed with XXXX.nc, where \
+                     XXXX is the 4 digit processor number)', 
+                     default='icebergs_00692992_restart_')
+
+parser.add_argument('-n',dest='fnum',help='number of distributed files to process', 
+                     type=int, default=None)
+
+parser.add_argument('-o',dest='fout',help='global_iceberg_restart; file name to append the \
+                     global iceberg restart data to.', default='icebergs_restart.nc')
+
+parser.add_argument('-O',dest='fcre',help='Create the output file from scratch rather than \
+                     append to an existing file.', \
+                     action='store_true', default=False)
+
+args = parser.parse_args()
+
+default_used = 0
+if args.froot is None:
+    pathstart = 'icebergs_00692992_restart_'
+    default_used = 1
+else:
+    pathstart = args.froot
+
+if args.fnum is None:
+    procnum = 0
+    default_used = 1
+else:
+    procnum = args.fnum
+
+if args.fout is None:
+    pathout = 'icebergs_restart.nc'
+    default_used = 1
+else:
+    pathout = args.fout
+
+if default_used == 1:
+   print('At least one default value will be used; command executing is:')
+   print('icb_combrest.py -f ',pathstart,' -n ',procnum,' -o ',pathout)
+
+if procnum < 1:
+   print('Need some files to collate! procnum = ',procnum)
+   sys.exit(11)
+
+icu = []
+times = []
+ntraj = 0
+nk = 0
+#
+# Loop through all distributed datasets to obtain the total number 
+# of icebergs to transfer
+#
+for n in range(procnum):
+ nn = '%4.4d' % n
+ try:
+   fw = Dataset(pathstart+nn+'.nc')
+ except:
+   print 'Error: unable to open input file: ' + pathstart+nn+'.nc'
+   sys.exit(12)
+ for d in fw.dimensions :
+  if d == 'n' :
+   if len(fw.dimensions['n']) > 0:
+#    print 'icebergs found in: ' + pathstart+nn+'.nc' 
+     if len(fw.dimensions['k']) > nk :
+       nk = len(fw.dimensions['k'])
+     ntraj = ntraj + len(fw.dimensions['n'])
+ fw.close()
+#
+print(ntraj, ' icebergs found across all datasets')
+#
+# Declare 2-D arrays to receive the data from all files
+#
+lons = np.zeros(ntraj)
+lats = np.zeros(ntraj)
+xis  = np.zeros(ntraj)
+yjs  = np.zeros(ntraj)
+uvs  = np.zeros(ntraj)
+vvs  = np.zeros(ntraj)
+mas  = np.zeros(ntraj)
+ths  = np.zeros(ntraj)
+wis  = np.zeros(ntraj)
+les  = np.zeros(ntraj)
+dys  = np.zeros(ntraj)
+mss  = np.zeros(ntraj)
+msb  = np.zeros(ntraj)
+hds  = np.zeros(ntraj)
+yrs  = np.zeros(ntraj      , dtype=int)
+num  = np.zeros((ntraj, nk), dtype=int)
+#
+# loop through distributed datasets again, this time
+# collecting all trajectory data
+#
+nt = 0
+for n in range(procnum):
+ nn = '%4.4d' % n
+ fw = Dataset(pathstart+nn+'.nc')
+ for d in fw.dimensions :
+  if d == 'n' :
+# Note many distributed datafiles will contain no iceberg data
+# so skip quickly over these
+    m  = len(fw.dimensions['n'])
+    if m > 0:
+#     print pathstart+nn+'.nc'
+      lons[nt:nt+m]  = fw.variables['lon'][:]
+      lats[nt:nt+m]  = fw.variables['lat'][:]
+      xis[nt:nt+m]   = fw.variables['xi'][:]
+      yjs[nt:nt+m]   = fw.variables['yj'][:]
+      uvs[nt:nt+m]   = fw.variables['uvel'][:]
+      vvs[nt:nt+m]   = fw.variables['vvel'][:]
+      mas[nt:nt+m]   = fw.variables['mass'][:]
+      ths[nt:nt+m]   = fw.variables['thickness'][:]
+      wis[nt:nt+m]   = fw.variables['width'][:]
+      les[nt:nt+m]   = fw.variables['length'][:]
+      dys[nt:nt+m]   = fw.variables['day'][:]
+      mss[nt:nt+m]   = fw.variables['mass_scaling'][:]
+      msb[nt:nt+m]   = fw.variables['mass_of_bits'][:]
+      hds[nt:nt+m]   = fw.variables['heat_density'][:]
+      yrs[nt:nt+m]   = fw.variables['year'][:]
+      num[nt:nt+m,:] = fw.variables['number'][:,:]
+      nt = nt + m
+ fw.close()
+
+# Finally create the output file and write out the collated sets
+#
+if args.fcre :
+  try:
+    fo = Dataset(pathout, 'w', format='NETCDF4')
+  except:
+    print 'Error accessing output file: ' + pathout
+    print 'Check it is a writable location.'
+    sys.exit(13)
+else :
+  # Copy 2D variables across to output file from input file. This step avoids problems if rebuild_nemo 
+  # has created an "n" dimension in the prototype rebuilt file (ie. if there are icebergs on the zeroth 
+  # processor). 
+  try:
+    os.rename(pathout,pathout.replace('.nc','_WORK.nc'))
+  except OSError:
+    print 'Error: unable to move icebergs restart file: '+pathout
+    sys.exit(14)
+  #
+  try:
+    fi = Dataset(pathout.replace('.nc','_WORK.nc'), 'r')
+  except:
+    print 'Error: unable to open icebergs restart file: '+pathout.replace('.nc','_WORK.nc')
+    sys.exit(15)
+  fo = Dataset(pathout, 'w')
+  for dim in ['x','y','c','k']:
+    indim = fi.dimensions[dim]
+    fo.createDimension(dim, len(indim))
+  for var in ['kount','calving','calving_hflx','stored_ice','stored_heat']:
+    invar = fi.variables[var]
+    fo.createVariable(var, invar.datatype, invar.dimensions)
+    fo.variables[var][:] = invar[:]
+    if "long_name" in invar.ncattrs():
+        fo.variables[var].long_name = invar.long_name
+    if "units" in invar.ncattrs():
+        fo.variables[var].units = invar.units
+  os.remove(pathout.replace('.nc','_WORK.nc'))
+#
+add_k = 1
+for d in fo.dimensions :
+  if d == 'n' :
+    print 'Error: dimension n already exists in output file'
+    sys.exit(16)
+  if d == 'k' :
+    add_k = 0
+onn  = fo.createDimension('n', None)
+if add_k > 0 :
+ onk = fo.createDimension('k', nk)
+olon = fo.createVariable('lon', 'f8',('n'))
+olat = fo.createVariable('lat', 'f8',('n'))
+oxis = fo.createVariable('xi', 'f8',('n'))
+oyjs = fo.createVariable('yj', 'f8',('n'))
+ouvs = fo.createVariable('uvel', 'f8',('n'))
+ovvs = fo.createVariable('vvel', 'f8',('n'))
+omas = fo.createVariable('mass', 'f8',('n'))
+oths = fo.createVariable('thickness', 'f8',('n'))
+owis = fo.createVariable('width', 'f8',('n'))
+oles = fo.createVariable('length', 'f8',('n'))
+odys = fo.createVariable('day', 'f8',('n'))
+omss = fo.createVariable('mass_scaling', 'f8',('n'))
+omsb = fo.createVariable('mass_of_bits', 'f8',('n'))
+ohds = fo.createVariable('heat_density', 'f8',('n'))
+oyrs = fo.createVariable('year', 'i4',('n'))
+onum = fo.createVariable('number', 'i4',('n','k'))
+#
+olon[:] = lons
+olon.long_name = "longitude"
+olon.units = "degrees_E" 
+#
+olat[:] = lats
+olat.long_name = "latitude"
+olat.units = "degrees_N"
+#
+oxis[:] = xis
+oxis.long_name = "x grid box position"
+oxis.units = "fractional"
+#
+oyjs[:] = yjs
+oyjs.long_name = "y grid box position"
+oyjs.units = "fractional"
+#
+ouvs[:] = uvs
+ouvs.long_name = "zonal velocity"
+ouvs.units = "m/s"
+#
+ovvs[:] = vvs
+ovvs.long_name = "meridional velocity"
+ovvs.units = "m/s"
+#
+omas[:] = mas
+omas.long_name = "mass"
+omas.units = "kg"
+#
+oths[:] = ths
+oths.long_name = "thickness"
+oths.units = "m"
+#
+owis[:] = wis
+owis.long_name = "width"
+owis.units = "m"
+#
+oles[:] = les
+oles.long_name = "length"
+oles.units = "m"
+#
+odys[:] = dys
+odys.long_name = "year day of calving event"
+odys.units = "days"
+#
+omss[:] = mss
+omss.long_name = "scaling factor for mass of calving berg"
+omss.units = "none"
+#
+omsb[:] = msb
+omsb.long_name = "mass of bergy bits"
+omsb.units = "kg"
+#
+ohds[:] = hds
+ohds.long_name = "heat density"
+ohds.units = "J/kg"
+#
+oyrs[:] = yrs
+oyrs.long_name = "calendar year of calving event"
+oyrs.units = "years"
+#
+onum[:,:] = num
+onum.long_name = "iceberg number on this processor"
+onum.units = "count"
+#
+fo.close()
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/REBUILD_NEMO/src/rebuild_nemo.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/REBUILD_NEMO/src/rebuild_nemo.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/REBUILD_NEMO/src/rebuild_nemo.f90	(revision 9987)
@@ -200,5 +200,5 @@
       WRITE(numerr,*) 'Attribute DOMAIN_number_total is : ', ndomain_file
       WRITE(numerr,*) 'Number of files specified in namelist is: ', ndomain
-      STOP
+      STOP 9
    ENDIF
   
@@ -268,5 +268,5 @@
       WRITE(numerr,*) 'Attribute DOMAIN_local_sizes is : ', local_sizes
       WRITE(numerr,*) 'Dimensions to be rebuilt are of size : ', outdimlens(rebuild_dims(1)), outdimlens(rebuild_dims(2)) 
-      STOP
+      STOP 9
    ENDIF
 
@@ -384,16 +384,21 @@
             SELECT CASE( xtype )
                CASE( NF90_BYTE )
+                  globaldata_0d_i1 = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_0d_i1 ) )
                CASE( NF90_SHORT )
+                  globaldata_0d_i2 = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_0d_i2 ) )
                CASE( NF90_INT )
+                  globaldata_0d_i4 = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_0d_i4 ) )
                CASE( NF90_FLOAT )
+                  globaldata_0d_sp = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_0d_sp ) )
                CASE( NF90_DOUBLE )
+                  globaldata_0d_dp = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_0d_dp ) )
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -403,20 +408,25 @@
                CASE( NF90_BYTE )
                   ALLOCATE(globaldata_1d_i1(indimlens(dimids(1))))
+                  globaldata_1d_i1(:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_1d_i1 ) )
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_1d_i2(indimlens(dimids(1))))
+                  globaldata_1d_i2(:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_1d_i2 ) )
                CASE( NF90_INT )
                   ALLOCATE(globaldata_1d_i4(indimlens(dimids(1))))
+                  globaldata_1d_i4(:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_1d_i4 ) )
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_1d_sp(indimlens(dimids(1))))
+                  globaldata_1d_sp(:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_1d_sp ) )
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_1d_dp(indimlens(dimids(1))))
+                  globaldata_1d_dp(:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_1d_dp ) )
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -426,20 +436,25 @@
                CASE( NF90_BYTE )
                   ALLOCATE(globaldata_2d_i1(indimlens(dimids(1)),indimlens(dimids(2))))
+                  globaldata_2d_i1(:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_2d_i1 ) )
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_2d_i2(indimlens(dimids(1)),indimlens(dimids(2))))
+                  globaldata_2d_i2(:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_2d_i2 ) )
                CASE( NF90_INT )
                   ALLOCATE(globaldata_2d_i4(indimlens(dimids(1)),indimlens(dimids(2))))
+                  globaldata_2d_i4(:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_2d_i4 ) )
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_2d_sp(indimlens(dimids(1)),indimlens(dimids(2))))
+                  globaldata_2d_sp(:,:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_2d_sp ) )
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_2d_dp(indimlens(dimids(1)),indimlens(dimids(2))))
+                  globaldata_2d_dp(:,:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_2d_dp ) )
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -450,24 +465,29 @@
                   ALLOCATE(globaldata_3d_i1(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3))))
+                  globaldata_3d_i1(:,:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_3d_i1 ) )
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_3d_i2(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3))))
+                  globaldata_3d_i2(:,:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_3d_i2 ) )
                CASE( NF90_INT )
                   ALLOCATE(globaldata_3d_i4(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3))))
+                  globaldata_3d_i4(:,:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_3d_i4 ) )
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_3d_sp(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3))))
+                  globaldata_3d_sp(:,:,:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_3d_sp ) )
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_3d_dp(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3))))
+                  globaldata_3d_dp(:,:,:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_3d_dp ) )
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -478,24 +498,29 @@
                   ALLOCATE(globaldata_4d_i1(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3)),ntchunk))
+                  globaldata_4d_i1(:,:,:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_4d_i1, start=(/1,1,1,nt/) ) )
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_4d_i2(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3)),ntchunk))
+                  globaldata_4d_i2(:,:,:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_4d_i2, start=(/1,1,1,nt/) ) )
                CASE( NF90_INT )
                   ALLOCATE(globaldata_4d_i4(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3)),ntchunk))
+                  globaldata_4d_i4(:,:,:,:) = 0
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_4d_i4, start=(/1,1,1,nt/) ) )
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_4d_sp(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3)),ntchunk))
+                  globaldata_4d_sp(:,:,:,:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_4d_sp, start=(/1,1,1,nt/) ) )
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_4d_dp(indimlens(dimids(1)),indimlens(dimids(2)),       &
                      &                      indimlens(dimids(3)),ntchunk))
+                  globaldata_4d_dp(:,:,:,:) = 0.
                   CALL check_nf90( nf90_get_var( ncid, jv, globaldata_4d_dp, start=(/1,1,1,nt/) ) )
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -517,15 +542,20 @@
                CASE( NF90_BYTE )
                   ALLOCATE(globaldata_1d_i1(outdimlens(dimids(1))))
+                  globaldata_1d_i1(:) = 0
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_1d_i2(outdimlens(dimids(1))))
+                  globaldata_1d_i2(:) = 0
                CASE( NF90_INT )
                   ALLOCATE(globaldata_1d_i4(outdimlens(dimids(1))))
+                  globaldata_1d_i4(:) = 0
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_1d_sp(outdimlens(dimids(1))))
+                  globaldata_1d_sp(:) = 0.
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_1d_dp(outdimlens(dimids(1))))
+                  globaldata_1d_dp(:) = 0.
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -535,15 +565,20 @@
                CASE( NF90_BYTE )
                   ALLOCATE(globaldata_2d_i1(outdimlens(dimids(1)),outdimlens(dimids(2))))
+                  globaldata_2d_i1(:,:) = 0
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_2d_i2(outdimlens(dimids(1)),outdimlens(dimids(2))))
+                  globaldata_2d_i2(:,:) = 0
                CASE( NF90_INT )
                   ALLOCATE(globaldata_2d_i4(outdimlens(dimids(1)),outdimlens(dimids(2))))
+                  globaldata_2d_i4(:,:) = 0
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_2d_sp(outdimlens(dimids(1)),outdimlens(dimids(2))))
+                  globaldata_2d_sp(:,:) = 0.
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_2d_dp(outdimlens(dimids(1)),outdimlens(dimids(2))))
+                  globaldata_2d_dp(:,:) = 0.
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -554,19 +589,24 @@
                   ALLOCATE(globaldata_3d_i1(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3))))
+                  globaldata_3d_i1(:,:,:) = 0
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_3d_i2(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3))))
+                  globaldata_3d_i2(:,:,:) = 0
                CASE( NF90_INT )
                   ALLOCATE(globaldata_3d_i4(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3))))
+                  globaldata_3d_i4(:,:,:) = 0
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_3d_sp(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3))))
+                  globaldata_3d_sp(:,:,:) = 0.
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_3d_dp(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3))))
+                  globaldata_3d_dp(:,:,:) = 0.
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
 
@@ -577,23 +617,28 @@
                   ALLOCATE(globaldata_4d_i1(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3)),ntchunk))
+                   globaldata_4d_i1(:,:,:,:) = 0
                CASE( NF90_SHORT )
                   ALLOCATE(globaldata_4d_i2(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3)),ntchunk))
+                  globaldata_4d_i2(:,:,:,:) = 0
                CASE( NF90_INT )
                   ALLOCATE(globaldata_4d_i4(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3)),ntchunk))
+                  globaldata_4d_i4(:,:,:,:) = 0
                CASE( NF90_FLOAT )
                   ALLOCATE(globaldata_4d_sp(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3)),ntchunk))
+                  globaldata_4d_sp(:,:,:,:) = 0.
                CASE( NF90_DOUBLE )
                   ALLOCATE(globaldata_4d_dp(outdimlens(dimids(1)),outdimlens(dimids(2)),     &
                      &                      outdimlens(dimids(3)),ntchunk))
+                  globaldata_4d_dp(:,:,:,:) = 0.
                CASE DEFAULT
                   WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-                  STOP
+                  STOP 9
             END SELECT
          ELSE
             WRITE(numerr,*) 'ERROR! : A netcdf variable has more than 4 dimensions which is not taken into account'
-            STOP
+            STOP 9
          ENDIF
 
@@ -967,5 +1012,5 @@
             IF( nthreads == 1 .AND. istop /= nf90_noerr )  THEN
                WRITE(numerr,*) '*** NEMO rebuild failed! ***'
-               STOP
+               STOP 9
             ENDIF
         
@@ -976,5 +1021,5 @@
          IF( istop /= nf90_noerr )  THEN
             WRITE(numerr,*) '*** NEMO rebuild failed! ***'
-            STOP
+            STOP 9
          ENDIF
 
@@ -1050,5 +1095,5 @@
             CASE DEFAULT   
                WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-               STOP
+               STOP 9
          END SELECT     
                       
@@ -1073,5 +1118,5 @@
             CASE DEFAULT   
                WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-               STOP
+               STOP 9
          END SELECT     
     
@@ -1096,5 +1141,5 @@
             CASE DEFAULT   
                WRITE(numerr,*) 'Unknown nf90 type: ', xtype
-               STOP
+               STOP 9
          END SELECT     
     
@@ -1146,5 +1191,5 @@
             WRITE(numerr,*) "*** NEMO rebuild failed ***"
             WRITE(numerr,*)
-            STOP
+            STOP 9
          ENDIF
       ENDIF
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/Doxyfile
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/Doxyfile	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/Doxyfile	(revision 9987)
@@ -0,0 +1,2331 @@
+# Doxyfile 1.8.8
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = "SIREN"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         = "NEMO 3.6"
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          = "System and Interface for oceanic RElocatable Nesting"
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
+# the documentation. The maximum height of the logo should not exceed 55 pixels
+# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
+# to the output directory.
+
+PROJECT_LOGO           = ./src/docsrc/Image/logoSirenNemo.png
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = ./doc
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS         = NO
+
+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
+# characters to appear in the names of generated files. If set to NO, non-ASCII
+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
+# U+3044.
+# The default value is: NO.
+
+ALLOW_UNICODE_NAMES    = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+# The default value is: YES.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
+
+ABBREVIATE_BRIEF       =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
+# description.
+# The default value is: NO.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
+
+FULL_PATH_NAMES        = YES
+
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
+# new page for each member. If set to NO, the documentation of a member will be
+# part of the file/class/namespace that contains it.
+# The default value is: NO.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 3
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
+# Fortran. In the later case the parser tries to guess whether the code is fixed
+# or free formatted code, this is the default for Fortran type files), VHDL. For
+# instance to make doxygen treat .inc files as Fortran files (default is PHP),
+# and .f files as C (default is Fortran), use: inc=Fortran f=C.
+#
+# Note For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      = 
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by by putting a % sign in front of the word
+# or globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO these classes will be included in the various overviews. This option has
+# no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES       = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
+# todo list. This list is created by putting \todo commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
+# test list. This list is created by putting \test commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES the list
+# will mention the files that were used to generate the documentation.
+# The default value is: YES.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. See also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS               = YES
+
+# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO doxygen will only warn about wrong or incomplete parameter
+# documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces.
+# Note: If this tag is empty the current directory is searched.
+
+INPUT                  = ./src ./src/docsrc
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank the
+# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
+# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
+# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
+# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
+# *.qsf, *.as and *.js.
+
+FILE_PATTERNS          = 
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
+
+EXAMPLE_PATTERNS       =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             = ./src/docsrc/Image
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER ) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX     = NO
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# cascading style sheets that are included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefor more robust against future updates.
+# Doxygen will copy the style sheet files to the output directory.
+# Note: The order of the extra stylesheet files is of importance (e.g. the last
+# stylesheet in the list overrules the setting of the previous ones in the
+# list). For an example see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the stylesheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET        = NO
+
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP      = NO
+
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
+# written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               =
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler ( hhc.exe). If non-empty
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           =
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated (
+# YES) or that it should be included in the master .chm file ( NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI           = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     =
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated (
+# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it
+# enables the Previous and Next buttons.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using prerendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
+# setting. When disabled, doxygen will generate a PHP script for searching and
+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
+# and searching needs to be provided by external tools. See the section
+# "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX         = YES
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. To get the times font for
+# instance you can specify
+# EXTRA_PACKAGES=times
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
+# $projectbrief, $projectlogo. Doxygen will replace $title with the empy string,
+# for the replacement values of the other commands the user is refered to
+# HTML_HEADER.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer. See
+# LATEX_HEADER for more information on how to generate a default footer and what
+# special commands can be used inside the footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE        = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES     = NO
+
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION          = .3
+
+# The MAN_SUBDIR tag determines the name of the directory created within
+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
+# MAN_EXTENSION with the initial . removed.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_SUBDIR             =
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+# If the DOCBOOK_PROGRAMLISTING tag is set to YES doxygen will include the
+# program listings (including syntax highlighting and cross-referencing
+# information) to the DOCBOOK output. Note that enabling this will significantly
+# increase the size of the DOCBOOK output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_PROGRAMLISTING = NO
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
+# Definitions (see http://autogen.sf.net) file that captures the structure of
+# the code including all documentation. Note that this feature is still
+# experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
+# in the source code. If set to NO only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES the includes files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to function-like macros that are alone on a line, have
+# an all uppercase name, and do not end with a semicolon. Such function macros
+# are typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have a unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
+# class index. If set to NO only the inherited external classes will be listed.
+# The default value is: NO.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
+# the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS         = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_PATH               =
+
+# If set to YES, the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: NO.
+
+HAVE_DOT               = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font in the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = YES
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH          = YES
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot.
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, jpg, gif and svg.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
+# path where java can find the plantuml.jar file. If left blank, it is assumed
+# PlantUML is not used or called during a preprocessing step. Doxygen will
+# generate a warning when it encounters a \startuml command in this case and
+# will not generate output for the diagram.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+PLANTUML_JAR_PATH      =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP            = YES
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/README
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/README	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/README	(revision 9987)
@@ -1,50 +1,7 @@
-This is a first release of SIREN.
 
-To create SIREN documentation, go to ./src and run doxygen 
+To create SIREN documentation, run doxygen in TOOLS/SIREN directory
 (http://www.stack.nl/~dimitri/doxygen/index.html version 1.8.3.1 or upper)
 then
-   open ../doc/index.html 
+   open ./TOOLS/SIREN/doc/html/index.html in your web browser 
 or 
-   run ../doc/latex/gmake and open refman.pdf 
-
-
-templates of namelists could be find in templates directory.
-read documentation for more information.
-
- 1- program to create coordinate file :
-
-   ./create_coord create_coord.nam
-
-
- Variables are extracted from the input coordinates coarse grid and
- interpolated to create fine coordinates files.
-
- 2- program to create bathymetry file:
-
- ./create_bathy create_bathy.nam
-
- Bathymetry could be extracted from fine grid Bathymetry file, or
- interpolated from coarse grid Bathymetry file.
-
- 3- program to merge bathymetry file at boundaries :
-
- ./merge_bathy merge_bathy.nam
-
- Coarse grid Bathymetry is interpolated on fine grid.
- Then fine Bathymetry and refined coarse bathymetry are merged at
- boundaries.
-
- 4- program to create restart file :
-
- ./create_restart create_restart.nam
-
- Variables are read from restart file, or standard output.
- Then theses variables are interpolated on fine grid.
- Finally table are split over new decomposition.
-
- 5- program to create boundary files (OBC) :
-
- ./create_boundary create_boundary.nam
-
- Variables are read from standard output.
- Then theses variables are interpolated on fine grid boundaries.
+   run ./TOOLS/SIREN/doc/latex/gmake and open ./TOOLS/SIREN/doc/latex/refman.pdf 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg	(revision 9987)
@@ -1,73 +1,159 @@
-# name       | units          | axis | point | standard name                | long name          | interpolation
-X            | 1              | X    |   | projection_x_coordinate          |                    |                      
-Y            | 1              | Y    |   | projection_y_coordinate          |                    |                      
-Z            | 1              | Z    |   | projection_z_coordinate          |                    |                      
-T            | 1              | T    |   | projection_t_coordinate          |                    |                      
-nav_lon      | degrees_east   | XY   | T | longitude                        | Longitude          | cubic                      
-nav_lat      | degrees_north  | XY   | T | latitude                         | Latitude           | cubic         
-nav_lev      | model_levels   | Z    | T |                                  | Model levels       | cubic        
-deptht       | m              | Z    | T | depth                            | Vertical T levels  |
-time_counter |                | T    |   | time                             | Time axis          | 
-Bathymetry   | m              | XY   | T | bathymetry                       | Bathymetry         | cubic         
-votemper     | degree_Celsius | XYZT | T | sea_water_potential_temperature  | Temperature        | cubic         
-vozocrtx     | m s-1          | XYZT | U |                                  | Zonal velocity     | cubic         
-vomecrty     | m s-1          | XYZT | V |                                  | Meridional velocity| cubic         
-vosaline     | PSU            | XYZT | T | sea_water_salinity               | Salinity           | cubic         
-sossheig     | m              | XYT  | T | sea_surface_height               | Sea Surface Height | cubic         
-glamt        | degrees_east   | XY   | T |                                  | Longitude_T        | cubic
-glamu        | degrees_east   | XY   | U |                                  | Longitude_U        | cubic            
-glamv        | degrees_east   | XY   | V |                                  | Longitude_V        | cubic          
-glamf        | degrees_east   | XY   | F |                                  | Longitude_F        | cubic         
-gphit        | degrees_north  | XY   | T |                                  | Latitude_T         | cubic         
-gphiu        | degrees_north  | XY   | U |                                  | Latitude_U         | cubic        
-gphiv        | degrees_north  | XY   | V |                                  | Latitude_V         | cubic        
-gphif        | degrees_north  | XY   | F |                                  | Latitude_F         | cubic        
-e1t          | m              | XY   | T |                                  |                    | cubic/rhoi    
-e1u          | m              | XY   | U |                                  |                    | cubic/rhoi     
-e1v          | m              | XY   | V |                                  |                    | cubic/rhoi      
-e1f          | m              | XY   | F |                                  |                    | cubic/rhoi    
-e2t          | m              | XY   | T |                                  |                    | cubic/rhoj      
-e2u          | m              | XY   | U |                                  |                    | cubic/rhoj      
-e2v          | m              | XY   | V |                                  |                    | cubic/rhoj     
-e2f          | m              | XY   | F |                                  |                    | cubic/rhoj      
-tmask        |                | XYZ  | T |                                  |                    | nearest       
-umask        |                | XYZ  | U |                                  |                    | nearest       
-vmask        |                | XYZ  | V |                                  |                    | nearest       
-fmask        |                | XYZ  | F |                                  |                    | nearest       
-weight       |                | XY   | T |                                  |                    |               
-kt           |                |      |   |                                  |                    |               
-ndastp       |                |      |   |                                  |                    |               
-adatrj       |                |      |   |                                  |                    |               
-kt           |                |      |   |                                  |                    |               
-rdt          |                |      |   |                                  |                    |               
-rdttra1      |                |      |   |                                  |                    |               
-utau_b       |                | XYT  | U |surface_downward_eastward_stress  |                    |               
-vtau_b       |                | XYT  | V |surface_downward_northward_stress |                    |               
-qns_b        |                | XYT  | T |                                  |                    |               
-emp_b        |                | XYT  | T |                                  |                    |               
-sfx_b        |                | XYT  | T |                                  |                    |               
-en           |                | XYZT | T |                                  |                    |               
-avt          |                | XYZT | T |                                  |                    |               
-avm          |                | XYZT | T |                                  |                    |               
-avmu         |                | XYZT | T |                                  |                    |               
-avmv         |                | XYZT | T |                                  |                    |               
-dissl        |                | XYZT | T |                                  |                    |               
-sbc_hc_b     |                | XYT  | T |                                  |                    |               
-sbc_sc_b     |                | XYT  | T |                                  |                    |               
-gcx          |                | XYT  | T |                                  |                    |               
-gcxb         |                | XYT  | T |                                  |                    |               
-ub           |                | XYZT | U |                                  |                    |               
-vb           |                | XYZT | V |                                  |                    |               
-tb           |                | XYZT | T |                                  |                    |               
-sb           |                | XYZT | T |                                  |                    |               
-rotb         |                | XYZT | T |                                  |                    |               
-hdivb        |                | XYZT | T |                                  |                    |               
-sshb         |                | XYT  | T |                                  |                    |               
-un           |                | XYZT | U |                                  |                    |               
-vn           |                | XYZT | V |                                  |                    |               
-tn           |                | XYZT | T |                                  |                    |               
-sn           |                | XYZT | T |                                  |                    |               
-rotn         |                | XYZT | T |                                  |                    |               
-hdivn        |                | XYZT | T |                                  |                    |               
-sshn         |                | XYT  | T |                                  |                    |               
-rhop         |                | XYZT | T |                                  |                    |               
+# name       | units          | axis | pt| interpolation   | long name                             | standard name                                  
+X            | 1              | X    |   |                 |                                       | projection_x_coordinate               
+Y            | 1              | Y    |   |                 |                                       | projection_y_coordinate               
+Z            | 1              | Z    |   |                 |                                       | projection_z_coordinate               
+T            | 1              | T    |   |                 |                                       | projection_t_coordinate               
+nav_lon      | degrees_east   | XY   | T | cubic           | Longitude                             | longitude                                   
+nav_lat      | degrees_north  | XY   | T | cubic           | Latitude                              | latitude                         
+nav_lev      | model_levels   | Z    | T | cubic           | Model levels                          |                                  
+deptht       | m              | Z    | T |                 | Vertical T levels                     | depth                            
+time_counter |                | T    |   |                 | Time axis                             | time                             
+Bathymetry   | m              | XY   | T | cubic           | Bathymetry                            | bathymetry                       
+votemper     | degree_Celsius | XYZT | T | cubic           | Temperature                           | sea_water_potential_temperature  
+vozocrtx     | m s-1          | XYZT | U | cubic           | Zonal velocity                        |                                  
+vomecrty     | m s-1          | XYZT | V | cubic           | Meridional velocity                   |                                  
+vosaline     | PSU            | XYZT | T | cubic           | Salinity                              | sea_water_salinity               
+sossheig     | m              | XYT  | T | cubic           | Sea Surface Height                    | sea_surface_height               
+sotemper     | m              | XYT  | T | cubic           |                                       |                                  
+sossheig     | m              | XYT  | T | cubic           |                                       |                                  
+glamt        | degrees_east   | XY   | T | cubic           | Longitude_T                           |                                  
+glamu        | degrees_east   | XY   | U | cubic           | Longitude_U                           |                                   
+glamv        | degrees_east   | XY   | V | cubic           | Longitude_V                           |                                  
+glamf        | degrees_east   | XY   | F | cubic           | Longitude_F                           |                                  
+gphit        | degrees_north  | XY   | T | cubic           | Latitude_T                            |                                  
+gphiu        | degrees_north  | XY   | U | cubic           | Latitude_U                            |                                  
+gphiv        | degrees_north  | XY   | V | cubic           | Latitude_V                            |                                  
+gphif        | degrees_north  | XY   | F | cubic           | Latitude_F                            |                                  
+e1t          | m              | XY   | T | cubic/rhoi      |                                       |                                  
+e1u          | m              | XY   | U | cubic/rhoi      |                                       |                                  
+e1v          | m              | XY   | V | cubic/rhoi      |                                       |                                  
+e1f          | m              | XY   | F | cubic/rhoi      |                                       |                                  
+e2t          | m              | XY   | T | cubic/rhoj      |                                       |                                  
+e2u          | m              | XY   | U | cubic/rhoj      |                                       |                                  
+e2v          | m              | XY   | V | cubic/rhoj      |                                       |                                  
+e2f          | m              | XY   | F | cubic/rhoj      |                                       |                                  
+tmask        |                | XYZ  | T | nearest         |                                       |                                  
+umask        |                | XYZ  | U | nearest         |                                       |                                  
+vmask        |                | XYZ  | V | nearest         |                                       |                                  
+fmask        |                | XYZ  | F | nearest         |                                       |                                  
+weight       |                | XY   | T |                 |                                       |                                  
+kt           |                |      |   |                 |                                       |                                  
+ndastp       |                |      |   |                 |                                       |                                  
+adatrj       |                |      |   |                 |                                       |                                  
+kt           |                |      |   |                 |                                       |                                  
+rdt          |                |      |   |                 |                                       |                                  
+rdttra1      |                |      |   |                 |                                       |                                  
+utau_b       |                | XY   | U |                 |                                       |surface_downward_eastward_stress  
+vtau_b       |                | XY   | V |                 |                                       |surface_downward_northward_stress 
+qns_b        |                | XY   | T |                 |                                       |                                  
+emp_b        |                | XY   | T |                 |                                       |                                  
+sfx_b        |                | XY   | T |                 |                                       |                                  
+en           |                | XYZ  | T |                 |                                       |                                  
+avt          |                | XYZ  | T |                 | vertical eddy diffusivity             |                                  
+avm          |                | XYZ  | T |                 | vertical eddy viscosity               |                                  
+avmu         |                | XYZ  | T |                 |                                       |                                  
+avmv         |                | XYZ  | T |                 |                                       |                                  
+dissl        |                | XYZ  | T |                 |                                       |                                  
+sbc_hc_b     |                | XY   | T |                 |                                       |                                  
+sbc_sc_b     |                | XY   | T |                 |                                       |                                  
+gcx          |                | XY   | T |                 |                                       |                                  
+gcxb         |                | XY   | T |                 |                                       |                                  
+ub           |                | XYZ  | U |                 |                                       |                                  
+vb           |                | XYZ  | V |                 |                                       |                                  
+tb           |                | XYZ  | T |                 |                                       |                                  
+sb           |                | XYZ  | T |                 |                                       |                                  
+rotb         |                | XYZ  | T |                 |                                       |                                  
+hdivb        |                | XYZ  | T |                 |                                       |                                  
+sshb         |                | XY   | T |                 |                                       |                                  
+un           |                | XYZ  | U |                 |                                       |                                  
+vn           |                | XYZ  | V |                 |                                       |                                  
+tn           |                | XYZ  | T |                 |                                       |                                  
+sn           |                | XYZ  | T |                 |                                       |                                  
+rotn         |                | XYZ  | T |                 |                                       |                                  
+hdivn        |                | XYZ  | T |                 |                                       |                                  
+sshn         |                | XYT  | T |                 |                                       |                                  
+rhop         |                | XYZ  | T |                 |                                       |                                  
+dic          |                | XYZT | T |                 | Dissolved Inorganic Carbon            | mole_concentration_of_dissolved_inorganic_caron_in_sea_water
+alkalini     |                | XYZT | T |                 | Total Alkalinity                      | sea_water_alkalinity_expressed_as_mole_equivalent
+o2           |                | XYZT | T |                 | Dissolved Oxygen                      | mole_concentration_of_dissolved_molecular_oxygen_in_sea_water
+caco3        |                | XYZT | T |                 | Calcite                               |                                  
+po4          |                | XYZT | T |                 | Phosphate                             | mole_concentration_of_phosphate_in_sea_water
+poc          |                | XYZT | T |                 | Small Particulate Organic Carbon      |                                  
+si           |                | XYZT | T |                 | Dissolved Silicate                    | mole_concentration_of_silicate_in_sea_water
+phy          |                | XYZT | T |                 | Nanophytoplankton                     |                                  
+zoo          |                | XYZT | T |                 | Microzooplankton                      | mole_concentration_of_microzooplankton_expressed_as_carbon_in_sea_water
+doc          |                | XYZT | T |                 | Dissolved Organic Carbon              |                                  
+phy2         |                | XYZT | T |                 | Diatoms                               |                                  
+zoo2         |                | XYZT | T |                 | Mesozooplankton                       | mole_concentration_of_mesozooplankton_expressed_as_carbon_in_sea_water
+gsi          |                | XYZT | T |                 | Sinking biogenic Silica               |                                  
+fer          |                | XYZT | T |                 | Dissolved Iron                        | mole_concentration_of_dissolved_iron_in_sea_water
+bfe          |                | XYZT | T |                 | Iron in the big particles             |                                  
+goc          |                | XYZT | T |                 | Big Particulate Organic Carbon        |                                  
+sfe          |                | XYZT | T |                 | Iron in the small particles           |                                  
+dfe          |                | XYZT | T |                 | Iron content of the Diatoms           |                                  
+dsi          |                | XYZT | T |                 | Silicon content of the Diatoms        |                                  
+nfe          |                | XYZT | T |                 | Iron content of the Nanophytoplankton |                                  
+nchl         |                | XYZT | T |                 | Chlorophyll of the Nanophytoplankton  |                                  
+dchl         |                | XYZT | T |                 | Chlorophyll of the Diatoms            |                                  
+no3          |                | XYZT | T |                 | Nitrate                               | mole_concentration_of_nitrate_in_sea_water
+nh4          |                | XYZT | T |                 | Ammonium                              | mole_concentration_of_ammonium_in_sea_water
+ppd          |                | XYZT | T |                 |                                       |                                  
+ppn          |                | XYZT | T |                 |                                       |                                  
+ph           |                | XYZT | T |                 |                                       |                                  
+cflx         |                | XYZT | T |                 |                                       |                                  
+oflx         |                | XYZT | T |                 |                                       |                                  
+kg           |                | XYZT | T |                 |                                       |                                  
+dpco2        |                | XYZT | T |                 |                                       |                                  
+heup         |                | XYZT | T |                 |                                       |                                  
+kz           |                | XYZT | T |                 |                                       |                                  
+irondep      |                | XYZT | T |                 |                                       |                                  
+kt_ice       |                |      |   |                 |                                       |                                  
+hicif        |                |      |   |                 |                                       |                                  
+hsnif        |                |      |   |                 |                                       |                                  
+frld         |                |      |   |                 |                                       |                                  
+sist         |                |      |   |                 |                                       |                                  
+tbif1        |                |      |   |                 |                                       |                                  
+tbif2        |                |      |   |                 |                                       |                                  
+tbif3        |                |      |   |                 |                                       |                                  
+ui_ice       |                |      |   |                 |                                       |                                  
+vi_ice       |                |      |   |                 |                                       |                                  
+qstoif       |                |      |   |                 |                                       |                                  
+fsbbq        |                |      |   |                 |                                       |                                  
+stress1_i    |                |      |   |                 |                                       |                                  
+stress2_i    |                |      |   |                 |                                       |                                  
+stress12_i   |                |      |   |                 |                                       |                                  
+sxice        |                |      |   |                 |                                       |                                  
+syice        |                |      |   |                 |                                       |                                  
+sxxice       |                |      |   |                 |                                       |                                  
+syyice       |                |      |   |                 |                                       |                                  
+sxyice       |                |      |   |                 |                                       |                                  
+sxsn         |                |      |   |                 |                                       |                                  
+sysn         |                |      |   |                 |                                       |                                  
+sxxsn        |                |      |   |                 |                                       |                                  
+syysn        |                |      |   |                 |                                       |                                  
+sxysn        |                |      |   |                 |                                       |                                  
+sxa          |                |      |   |                 |                                       |                                  
+sya          |                |      |   |                 |                                       |                                  
+sxxa         |                |      |   |                 |                                       |                                  
+syya         |                |      |   |                 |                                       |                                  
+sxya         |                |      |   |                 |                                       |                                  
+sxc0         |                |      |   |                 |                                       |                                  
+syc0         |                |      |   |                 |                                       |                                  
+sxxc0        |                |      |   |                 |                                       |                                  
+syyc0        |                |      |   |                 |                                       |                                  
+sxyc0        |                |      |   |                 |                                       |                                  
+sxc1         |                |      |   |                 |                                       |                                  
+syc1         |                |      |   |                 |                                       |                                  
+sxxc1        |                |      |   |                 |                                       |                                  
+syyc1        |                |      |   |                 |                                       |                                  
+sxyc1        |                |      |   |                 |                                       |                                  
+sxc2         |                |      |   |                 |                                       |                                  
+syc2         |                |      |   |                 |                                       |                                  
+sxxc2        |                |      |   |                 |                                       |                                  
+syyc2        |                |      |   |                 |                                       |                                  
+sxyc2        |                |      |   |                 |                                       |                                  
+sxst         |                |      |   |                 |                                       |                                  
+syst         |                |      |   |                 |                                       |                                  
+sxxst        |                |      |   |                 |                                       |                                  
+syyst        |                |      |   |                 |                                       |                                  
+sxyst        |                |      |   |                 |                                       |                                  
Index: anches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/Doxyfile
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/Doxyfile	(revision 9986)
+++ 	(revision )
@@ -1,2331 +1,0 @@
-# Doxyfile 1.8.8
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project.
-#
-# All text after a double hash (##) is considered a comment and is placed in
-# front of the TAG it is preceding.
-#
-# All text after a single hash (#) is considered a comment and will be ignored.
-# The format is:
-# TAG = value [value, ...]
-# For lists, items can also be appended using:
-# TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (\" \").
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the config file
-# that follow. The default is UTF-8 which is also the encoding used for all text
-# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
-# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
-# for the list of possible encodings.
-# The default value is: UTF-8.
-
-DOXYFILE_ENCODING      = UTF-8
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
-# double-quotes, unless you are using Doxywizard) that should identify the
-# project for which the documentation is generated. This name is used in the
-# title of most generated pages and in a few other places.
-# The default value is: My Project.
-
-PROJECT_NAME           = "SIREN"
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
-# could be handy for archiving the generated documentation or if some version
-# control system is used.
-
-PROJECT_NUMBER         = "NEMO 3.6"
-
-# Using the PROJECT_BRIEF tag one can provide an optional one line description
-# for a project that appears at the top of each page and should give viewer a
-# quick idea about the purpose of the project. Keep the description short.
-
-PROJECT_BRIEF          = "System and Interface for oceanic RElocable Nesting"
-
-# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
-# the documentation. The maximum height of the logo should not exceed 55 pixels
-# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
-# to the output directory.
-
-PROJECT_LOGO           = ./docsrc/Image/logoSirenNemo.png
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
-# into which the generated documentation will be written. If a relative path is
-# entered, it will be relative to the location where doxygen was started. If
-# left blank the current directory will be used.
-
-OUTPUT_DIRECTORY       = ../doc
-
-# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
-# directories (in 2 levels) under the output directory of each output format and
-# will distribute the generated files over these directories. Enabling this
-# option can be useful when feeding doxygen a huge amount of source files, where
-# putting all generated files in the same directory would otherwise causes
-# performance problems for the file system.
-# The default value is: NO.
-
-CREATE_SUBDIRS         = NO
-
-# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
-# characters to appear in the names of generated files. If set to NO, non-ASCII
-# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
-# U+3044.
-# The default value is: NO.
-
-ALLOW_UNICODE_NAMES    = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
-# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
-# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
-# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
-# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
-# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
-# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
-# Ukrainian and Vietnamese.
-# The default value is: English.
-
-OUTPUT_LANGUAGE        = English
-
-# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
-# descriptions after the members that are listed in the file and class
-# documentation (similar to Javadoc). Set to NO to disable this.
-# The default value is: YES.
-
-BRIEF_MEMBER_DESC      = YES
-
-# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
-# description of a member or function before the detailed description
-#
-# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-# The default value is: YES.
-
-REPEAT_BRIEF           = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator that is
-# used to form the text in various listings. Each string in this list, if found
-# as the leading text of the brief description, will be stripped from the text
-# and the result, after processing the whole list, is used as the annotated
-# text. Otherwise, the brief description is used as-is. If left blank, the
-# following values are used ($name is automatically replaced with the name of
-# the entity):The $name class, The $name widget, The $name file, is, provides,
-# specifies, contains, represents, a, an and the.
-
-ABBREVIATE_BRIEF       =
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# doxygen will generate a detailed section even if there is only a brief
-# description.
-# The default value is: NO.
-
-ALWAYS_DETAILED_SEC    = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-# The default value is: NO.
-
-INLINE_INHERITED_MEMB  = NO
-
-# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
-# before files name in the file list and in the header files. If set to NO the
-# shortest path that makes the file name unique will be used
-# The default value is: YES.
-
-FULL_PATH_NAMES        = YES
-
-# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
-# Stripping is only done if one of the specified strings matches the left-hand
-# part of the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the path to
-# strip.
-#
-# Note that you can specify absolute paths here, but also relative paths, which
-# will be relative from the directory where doxygen is started.
-# This tag requires that the tag FULL_PATH_NAMES is set to YES.
-
-STRIP_FROM_PATH        =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
-# path mentioned in the documentation of a class, which tells the reader which
-# header file to include in order to use a class. If left blank only the name of
-# the header file containing the class definition is used. Otherwise one should
-# specify the list of include paths that are normally passed to the compiler
-# using the -I flag.
-
-STRIP_FROM_INC_PATH    =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
-# less readable) file names. This can be useful is your file systems doesn't
-# support long names like on DOS, Mac, or CD-ROM.
-# The default value is: NO.
-
-SHORT_NAMES            = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
-# first line (until the first dot) of a Javadoc-style comment as the brief
-# description. If set to NO, the Javadoc-style will behave just like regular Qt-
-# style comments (thus requiring an explicit @brief command for a brief
-# description.)
-# The default value is: NO.
-
-JAVADOC_AUTOBRIEF      = NO
-
-# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
-# line (until the first dot) of a Qt-style comment as the brief description. If
-# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
-# requiring an explicit \brief command for a brief description.)
-# The default value is: NO.
-
-QT_AUTOBRIEF           = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
-# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
-# a brief description. This used to be the default behavior. The new default is
-# to treat a multi-line C++ comment block as a detailed description. Set this
-# tag to YES if you prefer the old behavior instead.
-#
-# Note that setting this tag to YES also means that rational rose comments are
-# not recognized any more.
-# The default value is: NO.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
-# documentation from any documented member that it re-implements.
-# The default value is: YES.
-
-INHERIT_DOCS           = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
-# new page for each member. If set to NO, the documentation of a member will be
-# part of the file/class/namespace that contains it.
-# The default value is: NO.
-
-SEPARATE_MEMBER_PAGES  = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
-# uses this value to replace tabs by spaces in code fragments.
-# Minimum value: 1, maximum value: 16, default value: 4.
-
-TAB_SIZE               = 3
-
-# This tag can be used to specify a number of aliases that act as commands in
-# the documentation. An alias has the form:
-# name=value
-# For example adding
-# "sideeffect=@par Side Effects:\n"
-# will allow you to put the command \sideeffect (or @sideeffect) in the
-# documentation, which will result in a user-defined paragraph with heading
-# "Side Effects:". You can put \n's in the value part of an alias to insert
-# newlines.
-
-ALIASES                =
-
-# This tag can be used to specify a number of word-keyword mappings (TCL only).
-# A mapping has the form "name=value". For example adding "class=itcl::class"
-# will allow you to use the command class in the itcl::class meaning.
-
-TCL_SUBST              =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
-# only. Doxygen will then generate output that is more tailored for C. For
-# instance, some of the names that are used will be different. The list of all
-# members will be omitted, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_FOR_C  = NO
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
-# Python sources only. Doxygen will then generate output that is more tailored
-# for that language. For instance, namespaces will be presented as packages,
-# qualified scopes will look different, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_JAVA   = NO
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources. Doxygen will then generate output that is tailored for Fortran.
-# The default value is: NO.
-
-OPTIMIZE_FOR_FORTRAN   = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for VHDL.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_VHDL   = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it
-# parses. With this tag you can assign which parser to use for a given
-# extension. Doxygen has a built-in mapping, but you can override or extend it
-# using this tag. The format is ext=language, where ext is a file extension, and
-# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
-# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
-# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
-# Fortran. In the later case the parser tries to guess whether the code is fixed
-# or free formatted code, this is the default for Fortran type files), VHDL. For
-# instance to make doxygen treat .inc files as Fortran files (default is PHP),
-# and .f files as C (default is Fortran), use: inc=Fortran f=C.
-#
-# Note For files without extension you can use no_extension as a placeholder.
-#
-# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
-# the files are not read by doxygen.
-
-EXTENSION_MAPPING      = 
-
-# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
-# according to the Markdown format, which allows for more readable
-# documentation. See http://daringfireball.net/projects/markdown/ for details.
-# The output of markdown processing is further processed by doxygen, so you can
-# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
-# case of backward compatibilities issues.
-# The default value is: YES.
-
-MARKDOWN_SUPPORT       = YES
-
-# When enabled doxygen tries to link words that correspond to documented
-# classes, or namespaces to their corresponding documentation. Such a link can
-# be prevented in individual cases by by putting a % sign in front of the word
-# or globally by setting AUTOLINK_SUPPORT to NO.
-# The default value is: YES.
-
-AUTOLINK_SUPPORT       = YES
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should set this
-# tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string);
-# versus func(std::string) {}). This also make the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-# The default value is: NO.
-
-BUILTIN_STL_SUPPORT    = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-# The default value is: NO.
-
-CPP_CLI_SUPPORT        = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
-# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
-# will parse them like normal C++ but will assume all classes use public instead
-# of private inheritance when no explicit protection keyword is present.
-# The default value is: NO.
-
-SIP_SUPPORT            = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate
-# getter and setter methods for a property. Setting this option to YES will make
-# doxygen to replace the get and set methods by a property in the documentation.
-# This will only work if the methods are indeed getting or setting a simple
-# type. If this is not the case, or you want to show the methods anyway, you
-# should set this option to NO.
-# The default value is: YES.
-
-IDL_PROPERTY_SUPPORT   = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES, then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-# The default value is: NO.
-
-DISTRIBUTE_GROUP_DOC   = NO
-
-# Set the SUBGROUPING tag to YES to allow class member groups of the same type
-# (for instance a group of public functions) to be put as a subgroup of that
-# type (e.g. under the Public Functions section). Set it to NO to prevent
-# subgrouping. Alternatively, this can be done per class using the
-# \nosubgrouping command.
-# The default value is: YES.
-
-SUBGROUPING            = YES
-
-# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
-# are shown inside the group in which they are included (e.g. using \ingroup)
-# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
-# and RTF).
-#
-# Note that this feature does not work in combination with
-# SEPARATE_MEMBER_PAGES.
-# The default value is: NO.
-
-INLINE_GROUPED_CLASSES = NO
-
-# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
-# with only public data fields or simple typedef fields will be shown inline in
-# the documentation of the scope in which they are defined (i.e. file,
-# namespace, or group documentation), provided this scope is documented. If set
-# to NO, structs, classes, and unions are shown on a separate page (for HTML and
-# Man pages) or section (for LaTeX and RTF).
-# The default value is: NO.
-
-INLINE_SIMPLE_STRUCTS  = NO
-
-# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
-# enum is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically be
-# useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-# The default value is: NO.
-
-TYPEDEF_HIDES_STRUCT   = NO
-
-# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
-# cache is used to resolve symbols given their name and scope. Since this can be
-# an expensive process and often the same symbol appears multiple times in the
-# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
-# doxygen will become slower. If the cache is too large, memory is wasted. The
-# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
-# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
-# symbols. At the end of a run doxygen will report the cache usage and suggest
-# the optimal cache size from a speed point of view.
-# Minimum value: 0, maximum value: 9, default value: 0.
-
-LOOKUP_CACHE_SIZE      = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
-# documentation are documented, even if no documentation was available. Private
-# class members and static file members will be hidden unless the
-# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
-# Note: This will also disable the warnings about undocumented members that are
-# normally produced when WARNINGS is set to YES.
-# The default value is: NO.
-
-EXTRACT_ALL            = NO
-
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
-# be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PRIVATE        = NO
-
-# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
-# scope will be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PACKAGE        = NO
-
-# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
-# included in the documentation.
-# The default value is: NO.
-
-EXTRACT_STATIC         = NO
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
-# locally in source files will be included in the documentation. If set to NO
-# only classes defined in header files are included. Does not have any effect
-# for Java sources.
-# The default value is: YES.
-
-EXTRACT_LOCAL_CLASSES  = YES
-
-# This flag is only useful for Objective-C code. When set to YES local methods,
-# which are defined in the implementation section but not in the interface are
-# included in the documentation. If set to NO only methods in the interface are
-# included.
-# The default value is: NO.
-
-EXTRACT_LOCAL_METHODS  = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base name of
-# the file that contains the anonymous namespace. By default anonymous namespace
-# are hidden.
-# The default value is: NO.
-
-EXTRACT_ANON_NSPACES   = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
-# undocumented members inside documented classes or files. If set to NO these
-# members will be included in the various overviews, but no documentation
-# section is generated. This option has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_MEMBERS     = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy. If set
-# to NO these classes will be included in the various overviews. This option has
-# no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_CLASSES     = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
-# (class|struct|union) declarations. If set to NO these declarations will be
-# included in the documentation.
-# The default value is: NO.
-
-HIDE_FRIEND_COMPOUNDS  = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
-# documentation blocks found inside the body of a function. If set to NO these
-# blocks will be appended to the function's detailed documentation block.
-# The default value is: NO.
-
-HIDE_IN_BODY_DOCS      = NO
-
-# The INTERNAL_DOCS tag determines if documentation that is typed after a
-# \internal command is included. If the tag is set to NO then the documentation
-# will be excluded. Set it to YES to include the internal documentation.
-# The default value is: NO.
-
-INTERNAL_DOCS          = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
-# names in lower-case letters. If set to YES upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# and Mac users are advised to set this option to NO.
-# The default value is: system dependent.
-
-CASE_SENSE_NAMES       = YES
-
-# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
-# their full class and namespace scopes in the documentation. If set to YES the
-# scope will be hidden.
-# The default value is: NO.
-
-HIDE_SCOPE_NAMES       = NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
-# the files that are included by a file in the documentation of that file.
-# The default value is: YES.
-
-SHOW_INCLUDE_FILES     = YES
-
-# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
-# grouped member an include statement to the documentation, telling the reader
-# which file to include in order to use the member.
-# The default value is: NO.
-
-SHOW_GROUPED_MEMB_INC  = NO
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
-# files with double quotes in the documentation rather than with sharp brackets.
-# The default value is: NO.
-
-FORCE_LOCAL_INCLUDES   = NO
-
-# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
-# documentation for inline members.
-# The default value is: YES.
-
-INLINE_INFO            = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
-# (detailed) documentation of file and class members alphabetically by member
-# name. If set to NO the members will appear in declaration order.
-# The default value is: YES.
-
-SORT_MEMBER_DOCS       = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
-# descriptions of file, namespace and class members alphabetically by member
-# name. If set to NO the members will appear in declaration order. Note that
-# this will also influence the order of the classes in the class list.
-# The default value is: NO.
-
-SORT_BRIEF_DOCS        = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
-# (brief and detailed) documentation of class members so that constructors and
-# destructors are listed first. If set to NO the constructors will appear in the
-# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
-# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
-# member documentation.
-# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
-# detailed member documentation.
-# The default value is: NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
-# of group names into alphabetical order. If set to NO the group names will
-# appear in their defined order.
-# The default value is: NO.
-
-SORT_GROUP_NAMES       = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
-# fully-qualified names, including namespaces. If set to NO, the class list will
-# be sorted only by class name, not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the alphabetical
-# list.
-# The default value is: NO.
-
-SORT_BY_SCOPE_NAME     = NO
-
-# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
-# type resolution of all parameters of a function it will reject a match between
-# the prototype and the implementation of a member function even if there is
-# only one candidate or it is obvious which candidate to choose by doing a
-# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
-# accept a match between prototype and implementation in such cases.
-# The default value is: NO.
-
-STRICT_PROTO_MATCHING  = NO
-
-# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
-# todo list. This list is created by putting \todo commands in the
-# documentation.
-# The default value is: YES.
-
-GENERATE_TODOLIST      = YES
-
-# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
-# test list. This list is created by putting \test commands in the
-# documentation.
-# The default value is: YES.
-
-GENERATE_TESTLIST      = YES
-
-# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
-# list. This list is created by putting \bug commands in the documentation.
-# The default value is: YES.
-
-GENERATE_BUGLIST       = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
-# the deprecated list. This list is created by putting \deprecated commands in
-# the documentation.
-# The default value is: YES.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional documentation
-# sections, marked by \if <section_label> ... \endif and \cond <section_label>
-# ... \endcond blocks.
-
-ENABLED_SECTIONS       =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
-# initial value of a variable or macro / define can have for it to appear in the
-# documentation. If the initializer consists of more lines than specified here
-# it will be hidden. Use a value of 0 to hide initializers completely. The
-# appearance of the value of individual variables and macros / defines can be
-# controlled using \showinitializer or \hideinitializer command in the
-# documentation regardless of this setting.
-# Minimum value: 0, maximum value: 10000, default value: 30.
-
-MAX_INITIALIZER_LINES  = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
-# the bottom of the documentation of classes and structs. If set to YES the list
-# will mention the files that were used to generate the documentation.
-# The default value is: YES.
-
-SHOW_USED_FILES        = YES
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
-# will remove the Files entry from the Quick Index and from the Folder Tree View
-# (if specified).
-# The default value is: YES.
-
-SHOW_FILES             = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
-# page. This will remove the Namespaces entry from the Quick Index and from the
-# Folder Tree View (if specified).
-# The default value is: YES.
-
-SHOW_NAMESPACES        = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command command input-file, where command is the value of the
-# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
-# by doxygen. Whatever the program writes to standard output is used as the file
-# version. For an example see the documentation.
-
-FILE_VERSION_FILTER    =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
-# by doxygen. The layout file controls the global structure of the generated
-# output files in an output format independent way. To create the layout file
-# that represents doxygen's defaults, run doxygen with the -l option. You can
-# optionally specify a file name after the option, if omitted DoxygenLayout.xml
-# will be used as the name of the layout file.
-#
-# Note that if you run doxygen from a directory containing a file called
-# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
-# tag is left empty.
-
-LAYOUT_FILE            =
-
-# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
-# the reference definitions. This must be a list of .bib files. The .bib
-# extension is automatically appended if omitted. This requires the bibtex tool
-# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
-# For LaTeX the style of the bibliography can be controlled using
-# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
-# search path. See also \cite for info how to create references.
-
-CITE_BIB_FILES         =
-
-#---------------------------------------------------------------------------
-# Configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated to
-# standard output by doxygen. If QUIET is set to YES this implies that the
-# messages are off.
-# The default value is: NO.
-
-QUIET                  = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
-# this implies that the warnings are on.
-#
-# Tip: Turn warnings on while writing the documentation.
-# The default value is: YES.
-
-WARNINGS               = YES
-
-# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
-# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
-# will automatically be disabled.
-# The default value is: YES.
-
-WARN_IF_UNDOCUMENTED   = YES
-
-# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some parameters
-# in a documented function, or documenting parameters that don't exist or using
-# markup commands wrongly.
-# The default value is: YES.
-
-WARN_IF_DOC_ERROR      = YES
-
-# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
-# are documented, but have no documentation for their parameters or return
-# value. If set to NO doxygen will only warn about wrong or incomplete parameter
-# documentation, but not about the absence of documentation.
-# The default value is: NO.
-
-WARN_NO_PARAMDOC       = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that doxygen
-# can produce. The string should contain the $file, $line, and $text tags, which
-# will be replaced by the file and line number from which the warning originated
-# and the warning text. Optionally the format may contain $version, which will
-# be replaced by the version of the file (if it could be obtained via
-# FILE_VERSION_FILTER)
-# The default value is: $file:$line: $text.
-
-WARN_FORMAT            = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning and error
-# messages should be written. If left blank the output is written to standard
-# error (stderr).
-
-WARN_LOGFILE           =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag is used to specify the files and/or directories that contain
-# documented source files. You may enter file names like myfile.cpp or
-# directories like /usr/src/myproject. Separate the files or directories with
-# spaces.
-# Note: If this tag is empty the current directory is searched.
-
-INPUT                  = . ./docsrc
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
-# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
-# documentation (see: http://www.gnu.org/software/libiconv) for the list of
-# possible encodings.
-# The default value is: UTF-8.
-
-INPUT_ENCODING         = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
-# *.h) to filter out the source-files in the directories. If left blank the
-# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
-# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
-# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
-# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
-# *.qsf, *.as and *.js.
-
-FILE_PATTERNS          = 
-
-# The RECURSIVE tag can be used to specify whether or not subdirectories should
-# be searched for input files as well.
-# The default value is: NO.
-
-RECURSIVE              = NO
-
-# The EXCLUDE tag can be used to specify files and/or directories that should be
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-#
-# Note that relative paths are relative to the directory from which doxygen is
-# run.
-
-EXCLUDE                =
-
-# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
-# directories that are symbolic links (a Unix file system feature) are excluded
-# from the input.
-# The default value is: NO.
-
-EXCLUDE_SYMLINKS       = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories.
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories for example use the pattern */test/*
-
-EXCLUDE_PATTERNS       =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories use the pattern */test/*
-
-EXCLUDE_SYMBOLS        =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or directories
-# that contain example code fragments that are included (see the \include
-# command).
-
-EXAMPLE_PATH           =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
-# *.h) to filter out the source-files in the directories. If left blank all
-# files are included.
-
-EXAMPLE_PATTERNS       =
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude commands
-# irrespective of the value of the RECURSIVE tag.
-# The default value is: NO.
-
-EXAMPLE_RECURSIVE      = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or directories
-# that contain images that are to be included in the documentation (see the
-# \image command).
-
-IMAGE_PATH             = ./docsrc/Image
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command:
-#
-# <filter> <input-file>
-#
-# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
-# name of an input file. Doxygen will then use the output that the filter
-# program writes to standard output. If FILTER_PATTERNS is specified, this tag
-# will be ignored.
-#
-# Note that the filter must not add or remove lines; it is applied before the
-# code is scanned, but not when the output code is generated. If lines are added
-# or removed, the anchors will not be placed correctly.
-
-INPUT_FILTER           =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis. Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match. The filters are a list of the form: pattern=filter
-# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
-# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
-# patterns match the file name, INPUT_FILTER is applied.
-
-FILTER_PATTERNS        =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER ) will also be used to filter the input files that are used for
-# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
-# The default value is: NO.
-
-FILTER_SOURCE_FILES    = NO
-
-# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
-# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
-# it is also possible to disable source filtering for a specific pattern using
-# *.ext= (so without naming a filter).
-# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
-
-FILTER_SOURCE_PATTERNS =
-
-# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
-# is part of the input, its contents will be placed on the main page
-# (index.html). This can be useful if you have a project on for instance GitHub
-# and want to reuse the introduction page also for the doxygen output.
-
-USE_MDFILE_AS_MAINPAGE =
-
-#---------------------------------------------------------------------------
-# Configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
-# generated. Documented entities will be cross-referenced with these sources.
-#
-# Note: To get rid of all source code in the generated output, make sure that
-# also VERBATIM_HEADERS is set to NO.
-# The default value is: NO.
-
-SOURCE_BROWSER         = NO
-
-# Setting the INLINE_SOURCES tag to YES will include the body of functions,
-# classes and enums directly into the documentation.
-# The default value is: NO.
-
-INLINE_SOURCES         = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
-# special comment blocks from generated source code fragments. Normal C, C++ and
-# Fortran comments will always remain visible.
-# The default value is: YES.
-
-STRIP_CODE_COMMENTS    = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
-# function all documented functions referencing it will be listed.
-# The default value is: NO.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES then for each documented function
-# all documented entities called/used by that function will be listed.
-# The default value is: NO.
-
-REFERENCES_RELATION    = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
-# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
-# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
-# link to the documentation.
-# The default value is: YES.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
-# source code will show a tooltip with additional information such as prototype,
-# brief description and links to the definition and documentation. Since this
-# will make the HTML file larger and loading of large files a bit slower, you
-# can opt to disable this feature.
-# The default value is: YES.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-SOURCE_TOOLTIPS        = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code will
-# point to the HTML generated by the htags(1) tool instead of doxygen built-in
-# source browser. The htags tool is part of GNU's global source tagging system
-# (see http://www.gnu.org/software/global/global.html). You will need version
-# 4.8.6 or higher.
-#
-# To use it do the following:
-# - Install the latest version of global
-# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
-# - Make sure the INPUT points to the root of the source tree
-# - Run doxygen as normal
-#
-# Doxygen will invoke htags (and that will in turn invoke gtags), so these
-# tools must be available from the command line (i.e. in the search path).
-#
-# The result: instead of the source browser generated by doxygen, the links to
-# source code will now point to the output of htags.
-# The default value is: NO.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-USE_HTAGS              = NO
-
-# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
-# verbatim copy of the header file for each class for which an include is
-# specified. Set to NO to disable this.
-# See also: Section \class.
-# The default value is: YES.
-
-VERBATIM_HEADERS       = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
-# compounds will be generated. Enable this if the project contains a lot of
-# classes, structs, unions or interfaces.
-# The default value is: YES.
-
-ALPHABETICAL_INDEX     = NO
-
-# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
-# which the alphabetical index list will be split.
-# Minimum value: 1, maximum value: 20, default value: 5.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-COLS_IN_ALPHA_INDEX    = 5
-
-# In case all classes in a project start with a common prefix, all classes will
-# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
-# can be used to specify a prefix (or a list of prefixes) that should be ignored
-# while generating the index headers.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-IGNORE_PREFIX          =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
-# The default value is: YES.
-
-GENERATE_HTML          = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_OUTPUT            = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
-# generated HTML page (for example: .htm, .php, .asp).
-# The default value is: .html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FILE_EXTENSION    = .html
-
-# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
-# each generated HTML page. If the tag is left blank doxygen will generate a
-# standard header.
-#
-# To get valid HTML the header file that includes any scripts and style sheets
-# that doxygen needs, which is dependent on the configuration options used (e.g.
-# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
-# default header using
-# doxygen -w html new_header.html new_footer.html new_stylesheet.css
-# YourConfigFile
-# and then modify the file new_header.html. See also section "Doxygen usage"
-# for information on how to generate the default header that doxygen normally
-# uses.
-# Note: The header is subject to change so you typically have to regenerate the
-# default header when upgrading to a newer version of doxygen. For a description
-# of the possible markers and block names see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_HEADER            =
-
-# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
-# generated HTML page. If the tag is left blank doxygen will generate a standard
-# footer. See HTML_HEADER for more information on how to generate a default
-# footer and what special commands can be used inside the footer. See also
-# section "Doxygen usage" for information on how to generate the default footer
-# that doxygen normally uses.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FOOTER            =
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
-# sheet that is used by each HTML page. It can be used to fine-tune the look of
-# the HTML output. If left blank doxygen will generate a default style sheet.
-# See also section "Doxygen usage" for information on how to generate the style
-# sheet that doxygen normally uses.
-# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
-# it is more robust and this tag (HTML_STYLESHEET) will in the future become
-# obsolete.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_STYLESHEET        =
-
-# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# cascading style sheets that are included after the standard style sheets
-# created by doxygen. Using this option one can overrule certain style aspects.
-# This is preferred over using HTML_STYLESHEET since it does not replace the
-# standard style sheet and is therefor more robust against future updates.
-# Doxygen will copy the style sheet files to the output directory.
-# Note: The order of the extra stylesheet files is of importance (e.g. the last
-# stylesheet in the list overrules the setting of the previous ones in the
-# list). For an example see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_STYLESHEET  =
-
-# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the HTML output directory. Note
-# that these files will be copied to the base HTML output directory. Use the
-# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
-# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
-# files will be copied as-is; there are no commands or markers available.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_FILES       =
-
-# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
-# will adjust the colors in the stylesheet and background images according to
-# this color. Hue is specified as an angle on a colorwheel, see
-# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
-# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
-# purple, and 360 is red again.
-# Minimum value: 0, maximum value: 359, default value: 220.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_HUE    = 220
-
-# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
-# in the HTML output. For a value of 0 the output will use grayscales only. A
-# value of 255 will produce the most vivid colors.
-# Minimum value: 0, maximum value: 255, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_SAT    = 100
-
-# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
-# luminance component of the colors in the HTML output. Values below 100
-# gradually make the output lighter, whereas values above 100 make the output
-# darker. The value divided by 100 is the actual gamma applied, so 80 represents
-# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
-# change the gamma.
-# Minimum value: 40, maximum value: 240, default value: 80.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_GAMMA  = 80
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting this
-# to NO can help when comparing the output of multiple runs.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_TIMESTAMP         = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_DYNAMIC_SECTIONS  = NO
-
-# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
-# shown in the various tree structured indices initially; the user can expand
-# and collapse entries dynamically later on. Doxygen will expand the tree to
-# such a level that at most the specified number of entries are visible (unless
-# a fully collapsed tree already exceeds this amount). So setting the number of
-# entries 1 will produce a full collapsed tree by default. 0 is a special value
-# representing an infinite number of entries and will result in a full expanded
-# tree by default.
-# Minimum value: 0, maximum value: 9999, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_INDEX_NUM_ENTRIES = 100
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files will be
-# generated that can be used as input for Apple's Xcode 3 integrated development
-# environment (see: http://developer.apple.com/tools/xcode/), introduced with
-# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
-# Makefile in the HTML output directory. Running make will produce the docset in
-# that directory and running make install will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
-# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
-# for more information.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_DOCSET        = NO
-
-# This tag determines the name of the docset feed. A documentation feed provides
-# an umbrella under which multiple documentation sets from a single provider
-# (such as a company or product suite) can be grouped.
-# The default value is: Doxygen generated docs.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_FEEDNAME        = "Doxygen generated docs"
-
-# This tag specifies a string that should uniquely identify the documentation
-# set bundle. This should be a reverse domain-name style string, e.g.
-# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_BUNDLE_ID       = org.doxygen.Project
-
-# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
-# the documentation publisher. This should be a reverse domain-name style
-# string, e.g. com.mycompany.MyDocSet.documentation.
-# The default value is: org.doxygen.Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
-
-# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
-# The default value is: Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_NAME  = Publisher
-
-# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
-# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
-# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
-# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
-# Windows.
-#
-# The HTML Help Workshop contains a compiler that can convert all HTML output
-# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
-# files are now used as the Windows 98 help format, and will replace the old
-# Windows help format (.hlp) on all Windows platforms in the future. Compressed
-# HTML files also contain an index, a table of contents, and you can search for
-# words in the documentation. The HTML workshop also contains a viewer for
-# compressed HTML files.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_HTMLHELP      = NO
-
-# The CHM_FILE tag can be used to specify the file name of the resulting .chm
-# file. You can add a path in front of the file if the result should not be
-# written to the html output directory.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_FILE               =
-
-# The HHC_LOCATION tag can be used to specify the location (absolute path
-# including file name) of the HTML help compiler ( hhc.exe). If non-empty
-# doxygen will try to run the HTML help compiler on the generated index.hhp.
-# The file has to be specified with full path.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-HHC_LOCATION           =
-
-# The GENERATE_CHI flag controls if a separate .chi index file is generated (
-# YES) or that it should be included in the master .chm file ( NO).
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-GENERATE_CHI           = NO
-
-# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
-# and project file content.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_INDEX_ENCODING     =
-
-# The BINARY_TOC flag controls whether a binary table of contents is generated (
-# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it
-# enables the Previous and Next buttons.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-BINARY_TOC             = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members to
-# the table of contents of the HTML help documentation and to the tree view.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-TOC_EXPAND             = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
-# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
-# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
-# (.qch) of the generated HTML documentation.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_QHP           = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
-# the file name of the resulting .qch file. The path specified is relative to
-# the HTML output folder.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QCH_FILE               =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
-# Project output. For more information please see Qt Help Project / Namespace
-# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_NAMESPACE          = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
-# Help Project output. For more information please see Qt Help Project / Virtual
-# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
-# folders).
-# The default value is: doc.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_VIRTUAL_FOLDER     = doc
-
-# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
-# filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_NAME   =
-
-# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
-# custom filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_ATTRS  =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
-# project's filter section matches. Qt Help Project / Filter Attributes (see:
-# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_SECT_FILTER_ATTRS  =
-
-# The QHG_LOCATION tag can be used to specify the location of Qt's
-# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
-# generated .qhp file.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHG_LOCATION           =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
-# generated, together with the HTML files, they form an Eclipse help plugin. To
-# install this plugin and make it available under the help contents menu in
-# Eclipse, the contents of the directory containing the HTML and XML files needs
-# to be copied into the plugins directory of eclipse. The name of the directory
-# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
-# After copying Eclipse needs to be restarted before the help appears.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_ECLIPSEHELP   = NO
-
-# A unique identifier for the Eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have this
-# name. Each documentation set should have its own identifier.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
-
-ECLIPSE_DOC_ID         = org.doxygen.Project
-
-# If you want full control over the layout of the generated HTML pages it might
-# be necessary to disable the index and replace it with your own. The
-# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
-# of each HTML page. A value of NO enables the index and the value YES disables
-# it. Since the tabs in the index contain the same information as the navigation
-# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-DISABLE_INDEX          = NO
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information. If the tag
-# value is set to YES, a side panel will be generated containing a tree-like
-# index structure (just like the one that is generated for HTML Help). For this
-# to work a browser that supports JavaScript, DHTML, CSS and frames is required
-# (i.e. any modern browser). Windows users are probably better off using the
-# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
-# further fine-tune the look of the index. As an example, the default style
-# sheet generated by doxygen has an example that shows how to put an image at
-# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
-# the same information as the tab index, you could consider setting
-# DISABLE_INDEX to YES when enabling this option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_TREEVIEW      = NO
-
-# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
-# doxygen will group on one line in the generated HTML documentation.
-#
-# Note that a value of 0 will completely suppress the enum values from appearing
-# in the overview section.
-# Minimum value: 0, maximum value: 20, default value: 4.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-ENUM_VALUES_PER_LINE   = 4
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
-# to set the initial width (in pixels) of the frame in which the tree is shown.
-# Minimum value: 0, maximum value: 1500, default value: 250.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-TREEVIEW_WIDTH         = 250
-
-# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
-# external symbols imported via tag files in a separate window.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-EXT_LINKS_IN_WINDOW    = NO
-
-# Use this tag to change the font size of LaTeX formulas included as images in
-# the HTML documentation. When you change the font size after a successful
-# doxygen run you need to manually remove any form_*.png images from the HTML
-# output directory to force them to be regenerated.
-# Minimum value: 8, maximum value: 50, default value: 10.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_FONTSIZE       = 10
-
-# Use the FORMULA_TRANPARENT tag to determine whether or not the images
-# generated for formulas are transparent PNGs. Transparent PNGs are not
-# supported properly for IE 6.0, but are supported on all modern browsers.
-#
-# Note that when changing this option you need to delete any form_*.png files in
-# the HTML output directory before the changes have effect.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_TRANSPARENT    = YES
-
-# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
-# http://www.mathjax.org) which uses client side Javascript for the rendering
-# instead of using prerendered bitmaps. Use this if you do not have LaTeX
-# installed or if you want to formulas look prettier in the HTML output. When
-# enabled you may also need to install MathJax separately and configure the path
-# to it using the MATHJAX_RELPATH option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-USE_MATHJAX            = NO
-
-# When MathJax is enabled you can set the default output format to be used for
-# the MathJax output. See the MathJax site (see:
-# http://docs.mathjax.org/en/latest/output.html) for more details.
-# Possible values are: HTML-CSS (which is slower, but has the best
-# compatibility), NativeMML (i.e. MathML) and SVG.
-# The default value is: HTML-CSS.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_FORMAT         = HTML-CSS
-
-# When MathJax is enabled you need to specify the location relative to the HTML
-# output directory using the MATHJAX_RELPATH option. The destination directory
-# should contain the MathJax.js script. For instance, if the mathjax directory
-# is located at the same level as the HTML output directory, then
-# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
-# Content Delivery Network so you can quickly see the result without installing
-# MathJax. However, it is strongly recommended to install a local copy of
-# MathJax from http://www.mathjax.org before deployment.
-# The default value is: http://cdn.mathjax.org/mathjax/latest.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
-
-# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
-# extension names that should be enabled during MathJax rendering. For example
-# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_EXTENSIONS     =
-
-# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
-# of code that will be used on startup of the MathJax code. See the MathJax site
-# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
-# example see the documentation.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_CODEFILE       =
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
-# the HTML output. The underlying search engine uses javascript and DHTML and
-# should work on any modern browser. Note that when using HTML help
-# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
-# there is already a search function so this one should typically be disabled.
-# For large projects the javascript based search engine can be slow, then
-# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
-# search using the keyboard; to jump to the search box use <access key> + S
-# (what the <access key> is depends on the OS and browser, but it is typically
-# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
-# key> to jump into the search results window, the results can be navigated
-# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
-# the search. The filter options can be selected when the cursor is inside the
-# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
-# to select a filter and <Enter> or <escape> to activate or cancel the filter
-# option.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-SEARCHENGINE           = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
-# implemented using a web server instead of a web client using Javascript. There
-# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
-# setting. When disabled, doxygen will generate a PHP script for searching and
-# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
-# and searching needs to be provided by external tools. See the section
-# "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SERVER_BASED_SEARCH    = NO
-
-# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
-# script for searching. Instead the search results are written to an XML file
-# which needs to be processed by an external indexer. Doxygen will invoke an
-# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
-# search results.
-#
-# Doxygen ships with an example indexer ( doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: http://xapian.org/).
-#
-# See the section "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH        = NO
-
-# The SEARCHENGINE_URL should point to a search engine hosted by a web server
-# which will return the search results when EXTERNAL_SEARCH is enabled.
-#
-# Doxygen ships with an example indexer ( doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: http://xapian.org/). See the section "External Indexing and
-# Searching" for details.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHENGINE_URL       =
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
-# search data is written to a file for indexing by an external tool. With the
-# SEARCHDATA_FILE tag the name of this file can be specified.
-# The default file is: searchdata.xml.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHDATA_FILE        = searchdata.xml
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
-# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
-# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
-# projects and redirect the results back to the right project.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH_ID     =
-
-# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
-# projects other than the one defined by this configuration file, but that are
-# all added to the same external search index. Each project needs to have a
-# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
-# to a relative location where the documentation can be found. The format is:
-# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTRA_SEARCH_MAPPINGS  =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
-# The default value is: YES.
-
-GENERATE_LATEX         = YES
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: latex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_OUTPUT           = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked.
-#
-# Note that when enabling USE_PDFLATEX this option is only used for generating
-# bitmaps for formulas in the HTML output, but not in the Makefile that is
-# written to the output directory.
-# The default file is: latex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_CMD_NAME         = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
-# index for LaTeX.
-# The default file is: makeindex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-MAKEINDEX_CMD_NAME     = makeindex
-
-# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-COMPACT_LATEX          = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used by the
-# printer.
-# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
-# 14 inches) and executive (7.25 x 10.5 inches).
-# The default value is: a4.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PAPER_TYPE             = a4
-
-# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
-# that should be included in the LaTeX output. To get the times font for
-# instance you can specify
-# EXTRA_PACKAGES=times
-# If left blank no extra packages will be included.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-EXTRA_PACKAGES         =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
-# generated LaTeX document. The header should contain everything until the first
-# chapter. If it is left blank doxygen will generate a standard header. See
-# section "Doxygen usage" for information on how to let doxygen write the
-# default header to a separate file.
-#
-# Note: Only use a user-defined header if you know what you are doing! The
-# following commands have a special meaning inside the header: $title,
-# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
-# $projectbrief, $projectlogo. Doxygen will replace $title with the empy string,
-# for the replacement values of the other commands the user is refered to
-# HTML_HEADER.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HEADER           =
-
-# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
-# generated LaTeX document. The footer should contain everything after the last
-# chapter. If it is left blank doxygen will generate a standard footer. See
-# LATEX_HEADER for more information on how to generate a default footer and what
-# special commands can be used inside the footer.
-#
-# Note: Only use a user-defined footer if you know what you are doing!
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_FOOTER           =
-
-# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the LATEX_OUTPUT output
-# directory. Note that the files will be copied as-is; there are no commands or
-# markers available.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_FILES      =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
-# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
-# contain links (just like the HTML output) instead of page references. This
-# makes the output suitable for online browsing using a PDF viewer.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PDF_HYPERLINKS         = YES
-
-# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
-# the PDF file directly from the LaTeX files. Set this option to YES to get a
-# higher quality PDF documentation.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-USE_PDFLATEX           = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
-# command to the generated LaTeX files. This will instruct LaTeX to keep running
-# if errors occur, instead of asking the user for help. This option is also used
-# when generating formulas in HTML.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BATCHMODE        = NO
-
-# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
-# index chapters (such as File Index, Compound Index, etc.) in the output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HIDE_INDICES     = NO
-
-# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
-# code with syntax highlighting in the LaTeX output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_SOURCE_CODE      = NO
-
-# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
-# bibliography, e.g. plainnat, or ieeetr. See
-# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
-# The default value is: plain.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BIB_STYLE        = plain
-
-#---------------------------------------------------------------------------
-# Configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
-# RTF output is optimized for Word 97 and may not look too pretty with other RTF
-# readers/editors.
-# The default value is: NO.
-
-GENERATE_RTF           = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: rtf.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_OUTPUT             = rtf
-
-# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-COMPACT_RTF            = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
-# contain hyperlink fields. The RTF file will contain links (just like the HTML
-# output) instead of page references. This makes the output suitable for online
-# browsing using Word or some other Word compatible readers that support those
-# fields.
-#
-# Note: WordPad (write) and others do not support links.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_HYPERLINKS         = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's config
-# file, i.e. a series of assignments. You only have to provide replacements,
-# missing definitions are set to their default value.
-#
-# See also section "Doxygen usage" for information on how to generate the
-# default style sheet that doxygen normally uses.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_STYLESHEET_FILE    =
-
-# Set optional variables used in the generation of an RTF document. Syntax is
-# similar to doxygen's config file. A template extensions file can be generated
-# using doxygen -e rtf extensionFile.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_EXTENSIONS_FILE    =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
-# classes and files.
-# The default value is: NO.
-
-GENERATE_MAN           = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it. A directory man3 will be created inside the directory specified by
-# MAN_OUTPUT.
-# The default directory is: man.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_OUTPUT             = man
-
-# The MAN_EXTENSION tag determines the extension that is added to the generated
-# man pages. In case the manual section does not start with a number, the number
-# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
-# optional.
-# The default value is: .3.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_EXTENSION          = .3
-
-# The MAN_SUBDIR tag determines the name of the directory created within
-# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
-# MAN_EXTENSION with the initial . removed.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_SUBDIR             =
-
-# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
-# will generate one additional man file for each entity documented in the real
-# man page(s). These additional files only source the real man page, but without
-# them the man command would be unable to find the correct page.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_LINKS              = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
-# captures the structure of the code including all documentation.
-# The default value is: NO.
-
-GENERATE_XML           = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: xml.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_OUTPUT             = xml
-
-# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
-# listings (including syntax highlighting and cross-referencing information) to
-# the XML output. Note that enabling this will significantly increase the size
-# of the XML output.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_PROGRAMLISTING     = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to the DOCBOOK output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
-# that can be used to generate PDF.
-# The default value is: NO.
-
-GENERATE_DOCBOOK       = NO
-
-# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
-# front of it.
-# The default directory is: docbook.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_OUTPUT         = docbook
-
-# If the DOCBOOK_PROGRAMLISTING tag is set to YES doxygen will include the
-# program listings (including syntax highlighting and cross-referencing
-# information) to the DOCBOOK output. Note that enabling this will significantly
-# increase the size of the DOCBOOK output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_PROGRAMLISTING = NO
-
-#---------------------------------------------------------------------------
-# Configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
-# Definitions (see http://autogen.sf.net) file that captures the structure of
-# the code including all documentation. Note that this feature is still
-# experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_AUTOGEN_DEF   = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
-# file that captures the structure of the code including all documentation.
-#
-# Note that this feature is still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_PERLMOD       = NO
-
-# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
-# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
-# output from the Perl module output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_LATEX          = NO
-
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
-# formatted so it can be parsed by a human reader. This is useful if you want to
-# understand what is going on. On the other hand, if this tag is set to NO the
-# size of the Perl module output will be much smaller and Perl will parse it
-# just the same.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_PRETTY         = YES
-
-# The names of the make variables in the generated doxyrules.make file are
-# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
-# so different doxyrules.make files included by the same Makefile don't
-# overwrite each other's variables.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
-# C-preprocessor directives found in the sources and include files.
-# The default value is: YES.
-
-ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
-# in the source code. If set to NO only conditional compilation will be
-# performed. Macro expansion can be done in a controlled way by setting
-# EXPAND_ONLY_PREDEF to YES.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-MACRO_EXPANSION        = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
-# the macro expansion is limited to the macros specified with the PREDEFINED and
-# EXPAND_AS_DEFINED tags.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES the includes files in the
-# INCLUDE_PATH will be searched if a #include is found.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by the
-# preprocessor.
-# This tag requires that the tag SEARCH_INCLUDES is set to YES.
-
-INCLUDE_PATH           =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will be
-# used.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-INCLUDE_FILE_PATTERNS  =
-
-# The PREDEFINED tag can be used to specify one or more macro names that are
-# defined before the preprocessor is started (similar to the -D option of e.g.
-# gcc). The argument of the tag is a list of macros of the form: name or
-# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
-# is assumed. To prevent a macro definition from being undefined via #undef or
-# recursively expanded use the := operator instead of the = operator.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-PREDEFINED             =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
-# tag can be used to specify a list of macro names that should be expanded. The
-# macro definition that is found in the sources will be used. Use the PREDEFINED
-# tag if you want to use a different macro definition that overrules the
-# definition found in the source code.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_AS_DEFINED      =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
-# remove all references to function-like macros that are alone on a line, have
-# an all uppercase name, and do not end with a semicolon. Such function macros
-# are typically used for boiler-plate code, and will confuse the parser if not
-# removed.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SKIP_FUNCTION_MACROS   = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES tag can be used to specify one or more tag files. For each tag
-# file the location of the external documentation should be added. The format of
-# a tag file without this location is as follows:
-# TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-# TAGFILES = file1=loc1 "file2 = loc2" ...
-# where loc1 and loc2 can be relative or absolute paths or URLs. See the
-# section "Linking to external documentation" for more information about the use
-# of tag files.
-# Note: Each tag file must have a unique name (where the name does NOT include
-# the path). If a tag file is not located in the directory in which doxygen is
-# run, you must also specify the path to the tagfile here.
-
-TAGFILES               =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
-# tag file that is based on the input files it reads. See section "Linking to
-# external documentation" for more information about the usage of tag files.
-
-GENERATE_TAGFILE       =
-
-# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
-# class index. If set to NO only the inherited external classes will be listed.
-# The default value is: NO.
-
-ALLEXTERNALS           = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
-# the modules index. If set to NO, only the current project's groups will be
-# listed.
-# The default value is: YES.
-
-EXTERNAL_GROUPS        = YES
-
-# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
-# the related pages index. If set to NO, only the current project's pages will
-# be listed.
-# The default value is: YES.
-
-EXTERNAL_PAGES         = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of 'which perl').
-# The default file (with absolute path) is: /usr/bin/perl.
-
-PERL_PATH              = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
-# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
-# NO turns the diagrams off. Note that this option also works with HAVE_DOT
-# disabled, but it is recommended to install and use dot, since it yields more
-# powerful graphs.
-# The default value is: YES.
-
-CLASS_DIAGRAMS         = YES
-
-# You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see:
-# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where
-# the mscgen tool resides. If left empty the tool is assumed to be found in the
-# default search path.
-
-MSCGEN_PATH            =
-
-# You can include diagrams made with dia in doxygen documentation. Doxygen will
-# then run dia to produce the diagram and insert it in the documentation. The
-# DIA_PATH tag allows you to specify the directory where the dia binary resides.
-# If left empty dia is assumed to be found in the default search path.
-
-DIA_PATH               =
-
-# If set to YES, the inheritance and collaboration graphs will hide inheritance
-# and usage relations if the target is undocumented or is not a class.
-# The default value is: YES.
-
-HIDE_UNDOC_RELATIONS   = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz (see:
-# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
-# Bell Labs. The other options in this section have no effect if this option is
-# set to NO
-# The default value is: NO.
-
-HAVE_DOT               = YES
-
-# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
-# to run in parallel. When set to 0 doxygen will base this on the number of
-# processors available in the system. You can set it explicitly to a value
-# larger than 0 to get control over the balance between CPU load and processing
-# speed.
-# Minimum value: 0, maximum value: 32, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_NUM_THREADS        = 0
-
-# When you want a differently looking font in the dot files that doxygen
-# generates you can specify the font name using DOT_FONTNAME. You need to make
-# sure dot is able to find the font, which can be done by putting it in a
-# standard location or by setting the DOTFONTPATH environment variable or by
-# setting DOT_FONTPATH to the directory containing the font.
-# The default value is: Helvetica.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTNAME           = Helvetica
-
-# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
-# dot graphs.
-# Minimum value: 4, maximum value: 24, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTSIZE           = 10
-
-# By default doxygen will tell dot to use the default font as specified with
-# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
-# the path where dot can find it using this tag.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTPATH           =
-
-# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
-# each documented class showing the direct and indirect inheritance relations.
-# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CLASS_GRAPH            = YES
-
-# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
-# graph for each documented class showing the direct and indirect implementation
-# dependencies (inheritance, containment, and class references variables) of the
-# class with other documented classes.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-COLLABORATION_GRAPH    = YES
-
-# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
-# groups, showing the direct groups dependencies.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GROUP_GRAPHS           = YES
-
-# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LOOK               = YES
-
-# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
-# class node. If there are many fields or methods and many nodes the graph may
-# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
-# number of items for each type to make the size more manageable. Set this to 0
-# for no limit. Note that the threshold may be exceeded by 50% before the limit
-# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
-# but if the number exceeds 15, the total amount of fields shown is limited to
-# 10.
-# Minimum value: 0, maximum value: 100, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LIMIT_NUM_FIELDS   = 10
-
-# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
-# collaboration graphs will show the relations between templates and their
-# instances.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-TEMPLATE_RELATIONS     = NO
-
-# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
-# YES then doxygen will generate a graph for each documented file showing the
-# direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDE_GRAPH          = YES
-
-# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
-# set to YES then doxygen will generate a graph for each documented file showing
-# the direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDED_BY_GRAPH      = YES
-
-# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable call graphs for selected
-# functions only using the \callgraph command.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALL_GRAPH             = NO
-
-# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable caller graphs for selected
-# functions only using the \callergraph command.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALLER_GRAPH           = NO
-
-# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
-# hierarchy of all classes instead of a textual one.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GRAPHICAL_HIERARCHY    = YES
-
-# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
-# dependencies a directory has on other directories in a graphical way. The
-# dependency relations are determined by the #include relations between the
-# files in the directories.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DIRECTORY_GRAPH        = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot.
-# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
-# to make the SVG files visible in IE 9+ (other browsers do not have this
-# requirement).
-# Possible values are: png, jpg, gif and svg.
-# The default value is: png.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_IMAGE_FORMAT       = png
-
-# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
-# enable generation of interactive SVG images that allow zooming and panning.
-#
-# Note that this requires a modern browser other than Internet Explorer. Tested
-# and working are Firefox, Chrome, Safari, and Opera.
-# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
-# the SVG files visible. Older versions of IE do not have SVG support.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INTERACTIVE_SVG        = NO
-
-# The DOT_PATH tag can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_PATH               =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the \dotfile
-# command).
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOTFILE_DIRS           =
-
-# The MSCFILE_DIRS tag can be used to specify one or more directories that
-# contain msc files that are included in the documentation (see the \mscfile
-# command).
-
-MSCFILE_DIRS           =
-
-# The DIAFILE_DIRS tag can be used to specify one or more directories that
-# contain dia files that are included in the documentation (see the \diafile
-# command).
-
-DIAFILE_DIRS           =
-
-# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
-# path where java can find the plantuml.jar file. If left blank, it is assumed
-# PlantUML is not used or called during a preprocessing step. Doxygen will
-# generate a warning when it encounters a \startuml command in this case and
-# will not generate output for the diagram.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-PLANTUML_JAR_PATH      =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
-# that will be shown in the graph. If the number of nodes in a graph becomes
-# larger than this value, doxygen will truncate the graph, which is visualized
-# by representing a node as a red box. Note that doxygen if the number of direct
-# children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
-# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-# Minimum value: 0, maximum value: 10000, default value: 50.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_GRAPH_MAX_NODES    = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
-# generated by dot. A depth value of 3 means that only nodes reachable from the
-# root by following a path via at most 3 edges will be shown. Nodes that lay
-# further from the root node will be omitted. Note that setting this option to 1
-# or 2 may greatly reduce the computation time needed for large code bases. Also
-# note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-# Minimum value: 0, maximum value: 1000, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-MAX_DOT_GRAPH_DEPTH    = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not seem
-# to support this out of the box.
-#
-# Warning: Depending on the platform used, enabling this option may lead to
-# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
-# read).
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_TRANSPARENT        = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10) support
-# this, this feature is disabled by default.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_MULTI_TARGETS      = NO
-
-# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
-# explaining the meaning of the various boxes and arrows in the dot generated
-# graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GENERATE_LEGEND        = YES
-
-# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
-# files that are used to generate the various graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_CLEANUP            = YES
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/attribute.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/attribute.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/attribute.f90	(revision 9987)
@@ -81,5 +81,6 @@
 ! REVISION HISTORY:
 !> @date November, 2013 - Initial Version
-!> @date November, 2014 - Fix memory leaks bug
+!> @date November, 2014 
+!> - Fix memory leaks bug
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -130,10 +131,10 @@
       INTEGER(i4)       :: i_type = 0        !< attribute type
       INTEGER(i4)       :: i_len  = 0        !< number of value store in attribute
-      CHARACTER(LEN=lc) :: c_value = "none"  !< attribute value if type CHAR
+      CHARACTER(LEN=lc) :: c_value = 'none'  !< attribute value if type CHAR
       REAL(dp), DIMENSION(:), POINTER :: d_value => NULL() !< attribute value if type SHORT,INT,FLOAT or DOUBLE
    END TYPE TATT
 
    INTERFACE att_init
-      MODULE PROCEDURE att__init_c
+      MODULE PROCEDURE att__init_c    
       MODULE PROCEDURE att__init_dp
       MODULE PROCEDURE att__init_dp_0d
@@ -181,5 +182,5 @@
    !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak) 
    !
@@ -234,5 +235,5 @@
 
       ! local variable
-      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_value
+      REAL(dp)         , DIMENSION(:), ALLOCATABLE :: dl_value
       !----------------------------------------------------------------
 
@@ -300,6 +301,7 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial Version
-   !> @date September, 2014 - bug fix with use of id read from attribute structure
-   !
+   !> @date September, 2014 
+   !> - bug fix with use of id read from attribute structure
+   !>
    !> @param[in] td_att    array of attribute structure
    !> @param[in] cd_name   attribute name
@@ -355,6 +357,6 @@
 
       att__init_c%c_name=TRIM(ADJUSTL(cd_name))
-
       att__init_c%i_type=NF90_CHAR
+
       att__init_c%c_value=TRIM(ADJUSTL(cd_value))
       att__init_c%i_len=LEN( TRIM(ADJUSTL(cd_value)) )
@@ -368,5 +370,5 @@
    !>
    !> @author J.Paul
-   !> @dtae November, 2013 - Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_name   attribute name
@@ -1068,5 +1070,6 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial Version
-   !> @date September, 2014 - take into account type of attribute.
+   !> @date September, 2014 
+   !> - take into account type of attribute.
    !
    !> @param[in] td_att attribute structure
@@ -1114,4 +1117,5 @@
 
             CASE(NF90_CHAR)
+
                cl_value=td_att%c_value
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/boundary.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/boundary.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/boundary.f90	(revision 9987)
@@ -26,7 +26,7 @@
 !>       - ld_west  is logical to force used of north boundary [optional]
 !>       - cd_north is string character description of north boundary [optional]
-!>       - cd_south is string character description of north boundary [optional]
-!>       - cd_east  is string character description of north boundary [optional]
-!>       - cd_west  is string character description of north boundary [optional]
+!>       - cd_south is string character description of south boundary [optional]
+!>       - cd_east  is string character description of east  boundary [optional]
+!>       - cd_west  is string character description of west  boundary [optional]
 !>       - ld_oneseg is logical to force to use only one segment for each boundary [optional]
 !>
@@ -36,4 +36,7 @@
 !>    to know if boundary is use:<br/>
 !>    - tl_bdy\%l_use
+!>
+!>    to know if boundary come from namelist (cn_north,..):<br/>
+!>    - tl_bdy\%l_nam
 !>
 !>    to get the number of segment in boundary:<br/>
@@ -105,6 +108,12 @@
 ! REVISION HISTORY:
 !> @date November, 2013 - Initial Version
-!> @date September, 2014 - add boundary description
-!> @date November, 2014 - Fix memory leaks bug
+!> @date September, 2014 
+!> - add boundary description
+!> @date November, 2014 
+!> - Fix memory leaks bug
+!> @date February, 2015 
+!> - Do not change indices read from namelist
+!> - Change string character format of boundary read from namelist, 
+!>  see boundary__get_info
 !> 
 !> @todo add schematic to boundary structure description
@@ -157,5 +166,5 @@
    PRIVATE :: seg__init       ! initialise segment structure
    PRIVATE :: seg__clean      ! clean segment structure
-   PRIVATE :: seg__clean_unit ! clean segment structure
+   PRIVATE :: seg__clean_unit ! clean one segment structure
    PRIVATE :: seg__clean_arr  ! clean array of segment structure
    PRIVATE :: seg__copy       ! copy segment structure in another
@@ -173,8 +182,10 @@
       CHARACTER(LEN=lc) :: c_card = ''          !< boundary cardinal
       LOGICAL           :: l_use  = .FALSE.     !< boundary use or not 
+      LOGICAL           :: l_nam  = .FALSE.     !< boundary get from namelist
       INTEGER(i4)       :: i_nseg = 0           !< number of segment in boundary
       TYPE(TSEG), DIMENSION(:), POINTER :: t_seg => NULL() !<  array of segment structure
    END TYPE TBDY
 
+   ! module variable
    INTEGER(i4), PARAMETER :: im_width=10
 
@@ -223,5 +234,5 @@
    !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak)
    !
@@ -260,5 +271,5 @@
    !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak)
    !
@@ -353,8 +364,20 @@
    END SUBROUTINE boundary__clean_arr
    !------------------------------------------------------------------- 
-   !> @brief This function put cardinal name inside file name.
+   !> @brief This function put cardinal name and date inside file name.
    ! 
    !> @details 
-   ! 
+   !>    Examples :
+   !>       cd_file="boundary.nc"
+   !>       cd_card="west" 
+   !>       id_seg =2
+   !>       cd_date=y2015m07d16
+   !> 
+   !>       function return "boundary_west_2_y2015m07d16.nc"
+   !> 
+   !>       cd_file="boundary.nc"
+   !>       cd_card="west" 
+   !> 
+   !>       function return "boundary_west.nc"
+   !> 
    !> @author J.Paul 
    !> @date November, 2013 - Initial Version 
@@ -385,4 +408,8 @@
       CHARACTER(LEN=lc) :: cl_date
       CHARACTER(LEN=lc) :: cl_name
+
+      INTEGER(i4)       :: il_ind
+      INTEGER(i4)       :: il_indend
+
       ! loop indices 
       !---------------------------------------------------------------- 
@@ -400,18 +427,31 @@
          cl_suffix=fct_split(TRIM(cl_basename),2,'.')
          
+         ! add segment number
          IF( PRESENT(id_seg) )THEN
-            cl_segnum="_"//TRIM(fct_str(id_seg))//"_"
+            cl_segnum="_"//TRIM(fct_str(id_seg))
          ELSE
             cl_segnum=""
          ENDIF
 
+         ! add date
          IF( PRESENT(cd_date) )THEN
-            cl_date=TRIM(ADJUSTL(cd_date))
+            cl_date="_"//TRIM(ADJUSTL(cd_date))
          ELSE
             cl_date=""
          ENDIF
 
-         cl_name=TRIM(cl_base)//"_"//TRIM(cd_card)//TRIM(cl_segnum)//&
-         &        TRIM(cl_date)//"."//TRIM(cl_suffix)
+         ! special case for obcdta
+         il_ind=INDEX(cl_base,'_obcdta_')
+         IF( il_ind/=0 )THEN
+            il_ind=il_ind-1+8
+            il_indend=LEN_TRIM(cl_base)
+
+            cl_name=TRIM(cl_base(1:il_ind))//TRIM(cd_card)//&
+               &     TRIM(cl_segnum)//"_"//TRIM(cl_base(il_ind+1:il_indend))//&
+               &     TRIM(cl_date)//"."//TRIM(cl_suffix)
+         ELSE
+            cl_name=TRIM(cl_base)//"_"//TRIM(cd_card)//TRIM(cl_segnum)//&
+               &     TRIM(cl_date)//"."//TRIM(cl_suffix)
+         ENDIF
 
          boundary_set_filename=TRIM(cl_dirname)//"/"//TRIM(cl_name)
@@ -442,6 +482,6 @@
    !> ex : cn_north='index1,first1,last1(width)|index2,first2,last2'
    !>
-   !> @note boundaries are compute on T point. change will be done to get data
-   !> on other point when need be. 
+   !> @note Boundaries are compute on T point, but expressed on U,V point.
+   !> change will be done to get data on other point when need be. 
    !>
    !> @author J.Paul 
@@ -581,8 +621,13 @@
 
                ! get namelist information
-               tl_tmp=boundary__get_info(cl_card(jk))
+               tl_tmp=boundary__get_info(cl_card(jk),jk)
+
+               ! get segments indices
                DO ji=1,tl_tmp%i_nseg
                   CALL boundary__add_seg(tl_bdy(jk),tl_tmp%t_seg(ji))
                ENDDO
+               ! indices from namelist or not
+               tl_bdy(jk)%l_nam=tl_tmp%l_nam
+
                CALL boundary_clean(tl_tmp)
 
@@ -642,9 +687,10 @@
    !> @return boundary structure
    !------------------------------------------------------------------- 
-   FUNCTION boundary__init( cd_card, ld_use, td_seg ) 
+   FUNCTION boundary__init( cd_card, ld_use, ld_nam, td_seg ) 
       IMPLICIT NONE 
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_card
       LOGICAL         , INTENT(IN), OPTIONAL :: ld_use 
+      LOGICAL         , INTENT(IN), OPTIONAL :: ld_nam 
       TYPE(TSEG)      , INTENT(IN), OPTIONAL :: td_seg
 
@@ -664,4 +710,7 @@
             boundary__init%l_use=.TRUE.
             IF( PRESENT(ld_use) ) boundary__init%l_use=ld_use
+
+            boundary__init%l_nam=.FALSE.
+            IF( PRESENT(ld_nam) ) boundary__init%l_nam=ld_nam
 
             IF( PRESENT(td_seg) )THEN
@@ -778,16 +827,21 @@
    !> orthogonal index, first and last indices, of each segment. 
    !> And also the width of all segments of this boundary.
-   !>   cn_north='index1,first1,last1(width)|index2,first2,last2'
+   !>   cn_north='index1,first1:last1(width)|index2,first2:last2'
    !> 
    !> @author J.Paul 
    !> @date November, 2013 - Initial Version 
+   !> @date february, 2015 
+   !> - do not change indices read from namelist
+   !> - change format cn_north
    ! 
    !> @param[in] cd_card   boundary description
+   !> @param[in] id_jcard  boundary index
    !> @return boundary structure
    !------------------------------------------------------------------- 
-   FUNCTION boundary__get_info(cd_card) 
+   FUNCTION boundary__get_info(cd_card, id_jcard) 
       IMPLICIT NONE 
       ! Argument 
       CHARACTER(LEN=lc), INTENT(IN) :: cd_card
+      INTEGER(i4)      , INTENT(IN) :: id_jcard
 
       ! function 
@@ -802,4 +856,5 @@
       CHARACTER(LEN=lc) :: cl_index
       CHARACTER(LEN=lc) :: cl_width
+      CHARACTER(LEN=lc) :: cl_tmp
       CHARACTER(LEN=lc) :: cl_first
       CHARACTER(LEN=lc) :: cl_last 
@@ -818,4 +873,9 @@
       ! width should be the same for all segment of one boundary
       IF( TRIM(cl_seg)   /= '' )THEN
+
+         ! initialise boundary
+         ! temporaty boundary, so it doesn't matter which caridnal is used
+         boundary__get_info=boundary__init('north',ld_nam=.TRUE.)
+
          il_ind1=SCAN(fct_lower(cl_seg),'(')
          IF( il_ind1 /=0 )THEN
@@ -831,4 +891,5 @@
             ENDIF
          ENDIF
+
       ENDIF 
 
@@ -839,5 +900,5 @@
          il_ind1=SCAN(fct_lower(cl_index),'(')
          IF( il_ind1 /=0 )THEN
-            il_ind2=SCAN(fct_lower(cl_index),'(')
+            il_ind2=SCAN(fct_lower(cl_index),')')
             IF( il_ind2 /=0 )THEN
                cl_index=TRIM(cl_index(:il_ind1-1))//TRIM(cl_index(il_ind2+1:))
@@ -848,9 +909,13 @@
          ENDIF
       
-         cl_first=fct_split(cl_seg,2,',')
+         
+         cl_tmp=fct_split(cl_seg,2,',')
+
+
+         cl_first=fct_split(cl_tmp,1,':')
          ! remove potential width information
          il_ind1=SCAN(fct_lower(cl_first),'(')
          IF( il_ind1 /=0 )THEN
-            il_ind2=SCAN(fct_lower(cl_first),'(')
+            il_ind2=SCAN(fct_lower(cl_first),')')
             IF( il_ind2 /=0 )THEN
                cl_first=TRIM(cl_first(:il_ind1-1))//TRIM(cl_first(il_ind2+1:))
@@ -861,9 +926,9 @@
          ENDIF         
          
-         cl_last =fct_split(cl_seg,3,',')
+         cl_last =fct_split(cl_tmp,2,':')
          ! remove potential width information
          il_ind1=SCAN(fct_lower(cl_last),'(')
          IF( il_ind1 /=0 )THEN
-            il_ind2=SCAN(fct_lower(cl_last),'(')
+            il_ind2=SCAN(fct_lower(cl_last),')')
             IF( il_ind2 /=0 )THEN
                cl_last=TRIM(cl_last(:il_ind1-1))//TRIM(cl_last(il_ind2+1:))
@@ -879,4 +944,10 @@
          IF( TRIM(cl_first) /= '' ) READ(cl_first,*) tl_seg%i_first
          IF( TRIM(cl_last)  /= '' ) READ(cl_last ,*) tl_seg%i_last
+
+         ! index expressed on U,V point, move on T point.
+         SELECT CASE(id_jcard)
+            CASE(jp_north, jp_east)
+               tl_seg%i_index=tl_seg%i_index+1
+         END SELECT
 
          IF( (tl_seg%i_first == 0 .AND.  tl_seg%i_last == 0) .OR. &
@@ -943,5 +1014,5 @@
 
       DO jk=1,ip_ncard
-         IF( .NOT. td_bdy(jk)%l_use .OR. td_bdy(jk)%i_nseg > 1 )THEN
+         IF( .NOT. td_bdy(jk)%l_use .OR. td_bdy(jk)%l_nam )THEN
             ! nothing to be done
          ELSE
@@ -1480,5 +1551,5 @@
       il_max(jp_east )=td_var%t_dim(2)%i_len
       il_max(jp_west )=td_var%t_dim(2)%i_len
-      
+ 
       il_maxindex(jp_north)=td_var%t_dim(2)%i_len-ip_ghost
       il_maxindex(jp_south)=td_var%t_dim(2)%i_len-ip_ghost
@@ -1515,5 +1586,5 @@
          ENDIF
       ENDDO
-      
+ 
       CALL boundary_check_corner(td_bdy, td_var)
 
@@ -1650,5 +1721,5 @@
    !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak)
    !
@@ -1687,5 +1758,5 @@
    !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak)
    !
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_bathy.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_bathy.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_bathy.f90	(revision 9987)
@@ -20,5 +20,11 @@
 !>    ./SIREN/bin/create_bathy create_bathy.nam
 !> @endcode
-!>    
+!> <br/>    
+!> \image html  bathy_40.png 
+!> \image latex bathy_30.png
+!>
+!> @note 
+!>    you could find a template of the namelist in templates directory.
+!>
 !>    create_bathy.nam comprise 7 namelists:<br/>
 !>       - logger namelist (namlog)
@@ -37,5 +43,5 @@
 !>       - cn_logfile   : log filename
 !>       - cn_verbosity : verbosity ('trace','debug','info',
-!> 'warning','error','fatal')
+!> 'warning','error','fatal','none')
 !>       - in_maxerror  : maximum number of error allowed
 !>
@@ -52,18 +58,21 @@
 !>       - cn_coord1 : coordinate file
 !>       - in_perio1 : periodicity index
-!>       - ln_fillclosed : fill closed sea or not
+!>       - ln_fillclosed : fill closed sea or not (default is .TRUE.)
 !>
 !>    * _variable namelist (namvar)_:<br/>
 !>       - cn_varinfo : list of variable and extra information about request(s) 
 !>       to be used.<br/>
-!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          each elements of *cn_varinfo* is a string character
+!>          (separated by ',').<br/>
 !>          it is composed of the variable name follow by ':', 
 !>          then request(s) to be used on this variable.<br/> 
 !>          request could be:
-!>             - interpolation method
-!>             - extrapolation method
-!>             - filter method
-!>             - > minimum value
-!>             - < maximum value
+!>             - int = interpolation method
+!>             - ext = extrapolation method
+!>             - flt = filter method
+!>             - min = minimum value
+!>             - max = maximum value
+!>             - unt = new units
+!>             - unf = unit scale factor (linked to new units)
 !>
 !>                requests must be separated by ';'.<br/>
@@ -72,5 +81,5 @@
 !>          informations about available method could be find in @ref interp,
 !>          @ref extrap and @ref filter modules.<br/>
-!>          Example: 'Bathymetry: 2*hamming(2,3); > 0'
+!>          Example: 'Bathymetry: flt=2*hamming(2,3); min=0'
 !>          @note 
 !>             If you do not specify a method which is required, 
@@ -90,5 +99,4 @@
 !>                - ',' for line
 !>                - '/' for row
-!>                - '\' for level<br/>
 !>                Example:<br/>
 !>                   3,2,3/1,4,5  =>  @f$ \left( \begin{array}{ccc}
@@ -99,7 +107,4 @@
 !>             - 'Bathymetry:gridT.nc'
 !>             - 'Bathymetry:5000,5000,5000/5000,3000,5000/5000,5000,5000'
-!>
-!>          \image html  bathy_40.png 
-!>          \image latex bathy_30.png
 !>
 !>    * _nesting namelist (namnst)_:<br/>
@@ -119,5 +124,13 @@
 !> - add header for user
 !> - Bug fix, compute offset depending of grid point
+!> @date June, 2015
+!> - extrapolate all land points.
+!> - allow to change unit.
 !
+!> @todo
+!> - use create_bathy_check_depth as in create_boundary
+!> - use create_bathy_check_time  as in create_boundary
+!> - check tl_multi is not empty
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
 !----------------------------------------------------------------------
@@ -482,5 +495,10 @@
    ENDIF
 
+   ! use additional request
    DO jk=1,tl_multi%i_nvar
+
+         ! change unit and apply factor
+         CALL var_chg_unit(tl_var(jk))
+
          ! forced min and max value
          CALL var_limit_value(tl_var(jk))
@@ -557,5 +575,5 @@
 
    ! add other variables
-   DO jk=1,tl_multi%i_nvar
+   DO jk=tl_multi%i_nvar,1,-1
       CALL file_add_var(tl_fileout, tl_var(jk))
       CALL var_clean(tl_var(jk))
@@ -623,5 +641,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_var    variable structure 
@@ -759,5 +777,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_var    variable structure 
@@ -878,5 +896,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_var    variable structure
@@ -897,10 +915,10 @@
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_var  
-      TYPE(TMPP) , INTENT(IN) :: td_mpp 
-      INTEGER(i4), INTENT(IN) :: id_imin
-      INTEGER(i4), INTENT(IN) :: id_imax
-      INTEGER(i4), INTENT(IN) :: id_jmin
-      INTEGER(i4), INTENT(IN) :: id_jmax
+      TYPE(TVAR)                 , INTENT(IN) :: td_var  
+      TYPE(TMPP)                 , INTENT(IN) :: td_mpp 
+      INTEGER(i4)                , INTENT(IN) :: id_imin
+      INTEGER(i4)                , INTENT(IN) :: id_imax
+      INTEGER(i4)                , INTENT(IN) :: id_jmin
+      INTEGER(i4)                , INTENT(IN) :: id_jmax
       INTEGER(i4), DIMENSION(:,:), INTENT(IN) :: id_offset
       INTEGER(i4), DIMENSION(:)  , INTENT(IN) :: id_rho
@@ -989,5 +1007,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure 
@@ -1073,7 +1091,5 @@
 
       ! extrapolate variable
-      CALL extrap_fill_value( td_var, id_offset=id_offset(:,:), &
-      &                               id_rho=id_rho(:),         &
-      &                               id_iext=il_iext, id_jext=il_jext )
+      CALL extrap_fill_value( td_var )
 
       ! interpolate Bathymetry
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_boundary.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_boundary.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_boundary.f90	(revision 9987)
@@ -23,5 +23,11 @@
 !>    ./SIREN/bin/create_boundary create_boundary.nam
 !> @endcode
-!>    
+!>  <br/> 
+!> \image html  boundary_NEATL36_70.png 
+!> \image latex boundary_NEATL36_70.png
+!>
+!> @note 
+!>    you could find a template of the namelist in templates directory.
+!>
 !>    create_boundary.nam comprise 9 namelists:<br/>
 !>       - logger namelist (namlog)
@@ -42,5 +48,5 @@
 !>       - cn_logfile   : log filename
 !>       - cn_verbosity : verbosity ('trace','debug','info',
-!> 'warning','error','fatal')
+!> 'warning','error','fatal','none')
 !>       - in_maxerror  : maximum number of error allowed
 !>
@@ -79,12 +85,14 @@
 !>    * _variable namelist (namvar)_:<br/>
 !>       - cn_varinfo : list of variable and extra information about request(s)
-!> to be used.<br/>
+!>          to be used (separated by ',').<br/>
 !>          each elements of *cn_varinfo* is a string character.<br/>
 !>          it is composed of the variable name follow by ':', 
 !>          then request(s) to be used on this variable.<br/> 
 !>          request could be:
-!>             - interpolation method
-!>             - extrapolation method
-!>             - filter method
+!>             - int = interpolation method
+!>             - ext = extrapolation method
+!>             - flt = filter method
+!>             - unt = new units
+!>             - unf = unit scale factor (linked to new units)
 !>
 !>                requests must be separated by ';'.<br/>
@@ -94,5 +102,5 @@
 !>          @ref extrap and @ref filter.<br/>
 !>
-!>          Example: 'votemper:linear;hann;dist_weight', 'vosaline:cubic'
+!>          Example: 'votemper:int=linear;flt=hann;ext=dist_weight', 'vosaline:int=cubic'
 !>          @note 
 !>             If you do not specify a method which is required, 
@@ -136,9 +144,9 @@
 !>          segments are separated by '|'.<br/>
 !>          each segments of the boundary is composed of:
-!>             - orthogonal indice (.ie. for north boundary,
-!>             J-indice where boundary are). 
-!>             - first indice of boundary (I-indice for north boundary) 
-!>             - last  indice of boundary (I-indice for north boundary)<br/>
-!>                indices must be separated by ',' .<br/>
+!>             - indice of velocity (orthogonal to boundary .ie. 
+!>                for north boundary, J-indice). 
+!>             - indice of segemnt start (I-indice for north boundary) 
+!>             - indice of segment end   (I-indice for north boundary)<br/>
+!>                indices must be separated by ':' .<br/>
 !>             - optionally, boundary size could be added between '(' and ')' 
 !>             in the first segment defined.
@@ -147,19 +155,26 @@
 !>
 !>          Examples:
-!>             - cn_north='index1,first1,last1(width)'
-!>             - cn_north='index1(width),first1,last1|index2,first2,last2'
-!>
-!>          \image html  boundary_50.png 
-!>          \image latex boundary_50.png
-!>
+!>             - cn_north='index1,first1:last1(width)'
+!>             - cn_north='index1(width),first1:last1|index2,first2:last2'
+!>             \image html  boundary_50.png 
+!>             \image latex boundary_50.png
 !>       - cn_south  : south boundary indices on fine grid
 !>       - cn_east   : east  boundary indices on fine grid
 !>       - cn_west   : west  boundary indices on fine grid
 !>       - ln_oneseg : use only one segment for each boundary or not
-!>       - in_extrap : number of mask point to be extrapolated
-!>
-!>   * _output namelist (namout)_:<br/>
+!>
+!>    * _output namelist (namout)_:<br/>
 !>       - cn_fileout : fine grid boundary basename
 !>         (cardinal and segment number will be automatically added)
+!>       - dn_dayofs  : date offset in day (change only ouput file name)
+!>       - ln_extrap  : extrapolate land point or not
+!>
+!>          Examples: 
+!>             - cn_fileout=boundary.nc<br/>
+!>                if time_counter (16/07/2015 00h) is read on input file (see varfile), 
+!>                west boundary will be named boundary_west_y2015m07d16
+!>             - dn_dayofs=-2.<br/>
+!>                if you use day offset you get boundary_west_y2015m07d14
+!>       
 !>
 !> @author J.Paul
@@ -169,5 +184,10 @@
 !> - add header for user
 !> - take into account grid point to compue boundaries
-!> - reorder output dimension for north and south boundaries 
+!> - reorder output dimension for north and south boundaries
+!> @date June, 2015
+!> - extrapolate all land points, and add ln_extrap in namelist.
+!> - allow to change unit.
+!> @date July, 2015
+!> - add namelist parameter to shift date of output file name.  
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -191,5 +211,5 @@
    USE dom                             ! domain manager
    USE grid                            ! grid manager
-   USE vgrid                           ! vartical grid manager
+   USE vgrid                           ! vertical grid manager
    USE extrap                          ! extrapolation manager
    USE interp                          ! interpolation manager
@@ -213,5 +233,4 @@
    INTEGER(i4)                                        :: il_status
    INTEGER(i4)                                        :: il_fileid
-   INTEGER(i4)                                        :: il_dim
    INTEGER(i4)                                        :: il_imin0
    INTEGER(i4)                                        :: il_imax0
@@ -239,4 +258,6 @@
 
    TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
+
+   TYPE(TDATE)                                        :: tl_date
    
    TYPE(TBDY)       , DIMENSION(ip_ncard)             :: tl_bdy
@@ -265,22 +286,37 @@
    ! namelist variable
    ! namlog
-   CHARACTER(LEN=lc)                       :: cn_logfile = 'create_boundary.log' 
-   CHARACTER(LEN=lc)                       :: cn_verbosity = 'warning' 
-   INTEGER(i4)                             :: in_maxerror = 5
+   CHARACTER(LEN=lc)  :: cn_logfile = 'create_boundary.log' 
+   CHARACTER(LEN=lc)  :: cn_verbosity = 'warning' 
+   INTEGER(i4)        :: in_maxerror = 5
 
    ! namcfg
-   CHARACTER(LEN=lc)                       :: cn_varcfg = 'variable.cfg' 
+   CHARACTER(LEN=lc)  :: cn_varcfg = 'variable.cfg' 
 
    ! namcrs
-   CHARACTER(LEN=lc)                       :: cn_coord0 = '' 
-   INTEGER(i4)                             :: in_perio0 = -1
+   CHARACTER(LEN=lc)  :: cn_coord0 = '' 
+   INTEGER(i4)        :: in_perio0 = -1
 
    ! namfin
-   CHARACTER(LEN=lc)                       :: cn_coord1 = '' 
-   CHARACTER(LEN=lc)                       :: cn_bathy1 = '' 
-   INTEGER(i4)                             :: in_perio1 = -1
+   CHARACTER(LEN=lc)  :: cn_coord1 = '' 
+   CHARACTER(LEN=lc)  :: cn_bathy1 = '' 
+   INTEGER(i4)        :: in_perio1 = -1
 
    !namzgr
-   INTEGER(i4)                             :: in_nlevel = 75
+   REAL(dp)          :: dn_pp_to_be_computed = 0._dp
+   REAL(dp)          :: dn_ppsur     = -3958.951371276829_dp
+   REAL(dp)          :: dn_ppa0      =   103.9530096000000_dp
+   REAL(dp)          :: dn_ppa1      =     2.4159512690000_dp
+   REAL(dp)          :: dn_ppa2      =   100.7609285000000_dp
+   REAL(dp)          :: dn_ppkth     =    15.3510137000000_dp
+   REAL(dp)          :: dn_ppkth2    =    48.0298937200000_dp
+   REAL(dp)          :: dn_ppacr     =     7.0000000000000_dp
+   REAL(dp)          :: dn_ppacr2    =    13.000000000000_dp
+   REAL(dp)          :: dn_ppdzmin   = 6._dp
+   REAL(dp)          :: dn_pphmax    = 5750._dp
+   INTEGER(i4)       :: in_nlevel    = 75
+
+   !namzps
+   REAL(dp)          :: dn_e3zps_min = 25._dp
+   REAL(dp)          :: dn_e3zps_rat = 0.2_dp
 
    ! namvar
@@ -289,21 +325,22 @@
 
    ! namnst
-   INTEGER(i4)                             :: in_rhoi  = 0
-   INTEGER(i4)                             :: in_rhoj  = 0
+   INTEGER(i4)       :: in_rhoi  = 0
+   INTEGER(i4)       :: in_rhoj  = 0
 
    ! nambdy
-   LOGICAL                                 :: ln_north   = .TRUE.
-   LOGICAL                                 :: ln_south   = .TRUE.
-   LOGICAL                                 :: ln_east    = .TRUE.
-   LOGICAL                                 :: ln_west    = .TRUE.
-   CHARACTER(LEN=lc)                       :: cn_north   = ''
-   CHARACTER(LEN=lc)                       :: cn_south   = ''
-   CHARACTER(LEN=lc)                       :: cn_east    = ''
-   CHARACTER(LEN=lc)                       :: cn_west    = ''
-   LOGICAL                                 :: ln_oneseg  = .TRUE.
-   INTEGER(i4)                             :: in_extrap  = 0
+   LOGICAL           :: ln_north   = .TRUE.
+   LOGICAL           :: ln_south   = .TRUE.
+   LOGICAL           :: ln_east    = .TRUE.
+   LOGICAL           :: ln_west    = .TRUE.
+   CHARACTER(LEN=lc) :: cn_north   = ''
+   CHARACTER(LEN=lc) :: cn_south   = ''
+   CHARACTER(LEN=lc) :: cn_east    = ''
+   CHARACTER(LEN=lc) :: cn_west    = ''
+   LOGICAL           :: ln_oneseg  = .TRUE.
 
    ! namout
-   CHARACTER(LEN=lc)                       :: cn_fileout = 'boundary.nc' 
+   CHARACTER(LEN=lc) :: cn_fileout = 'boundary.nc' 
+   REAL(dp)          :: dn_dayofs  = 0._dp
+   LOGICAL           :: ln_extrap  = .FALSE.
    !-------------------------------------------------------------------
 
@@ -319,5 +356,5 @@
    &  cn_coord0,     &  !< coordinate file
    &  in_perio0         !< periodicity index
-   
+ 
    NAMELIST /namfin/ &  !< fine grid namelist
    &  cn_coord1,     &  !< coordinate file
@@ -326,10 +363,25 @@
  
    NAMELIST /namzgr/ &
-   &  in_nlevel
+   &  dn_pp_to_be_computed, &
+   &  dn_ppsur,     &
+   &  dn_ppa0,      &
+   &  dn_ppa1,      &
+   &  dn_ppa2,      &
+   &  dn_ppkth,     &
+   &  dn_ppkth2,    &
+   &  dn_ppacr,     &
+   &  dn_ppacr2,    &
+   &  dn_ppdzmin,   &
+   &  dn_pphmax,    &
+   &  in_nlevel         !< number of vertical level
+
+   NAMELIST /namzps/ &
+   &  dn_e3zps_min, &
+   &  dn_e3zps_rat
 
    NAMELIST /namvar/ &  !< variable namelist
    &  cn_varinfo,    &  !< list of variable and method to apply on. (ex: 'votemper:linear','vosaline:cubic' )
    &  cn_varfile        !< list of variable and file where find it. (ex: 'votemper:GLORYS_gridT.nc' ) 
-   
+ 
    NAMELIST /namnst/ &  !< nesting namelist
    &  in_rhoi,       &  !< refinement factor in i-direction
@@ -345,9 +397,10 @@
    &  cn_east ,      &  !< east  boundary indices on fine grid
    &  cn_west ,      &  !< west  boundary indices on fine grid
-   &  ln_oneseg,     &  !< use only one segment for each boundary or not
-   &  in_extrap         !< number of mask point to be extrapolated
+   &  ln_oneseg         !< use only one segment for each boundary or not
 
    NAMELIST /namout/ &  !< output namelist
-   &  cn_fileout    !< fine grid boundary file basename   
+   &  cn_fileout,    &  !< fine grid boundary file basename   
+   &  dn_dayofs,     &  !< date offset in day (change only ouput file name)
+   &  ln_extrap         !< extrapolate or not
    !-------------------------------------------------------------------
 
@@ -448,7 +501,16 @@
    ! check
    ! check output file do not already exist
+   ! WARNING: do not work when use time to create output file name
    DO jk=1,ip_ncard
       cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
       &                                TRIM(cp_card(jk)), 1 )
+      INQUIRE(FILE=TRIM(cl_bdyout), EXIST=ll_exist)
+      IF( ll_exist )THEN
+         CALL logger_fatal("CREATE BOUNDARY: output file "//TRIM(cl_bdyout)//&
+         &  " already exist.")
+      ENDIF
+
+      cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+      &                                TRIM(cp_card(jk)) )
       INQUIRE(FILE=TRIM(cl_bdyout), EXIST=ll_exist)
       IF( ll_exist )THEN
@@ -490,9 +552,10 @@
 
    CALL iom_mpp_open(tl_bathy1)
-   
+ 
    tl_var1=iom_mpp_read_var(tl_bathy1,'Bathymetry')
-   
+ 
    CALL iom_mpp_close(tl_bathy1)
 
+   ! get boundaries indices
    tl_bdy(:)=boundary_init(tl_var1, ln_north, ln_south, ln_east, ln_west, &
    &                                cn_north, cn_south, cn_east, cn_west, &
@@ -505,8 +568,8 @@
    tl_level(:)=vgrid_get_level(tl_bathy1, cl_namelist )
 
-   ! get coordinate on each segment of each boundary
+   ! get coordinate for each segment of each boundary
    ALLOCATE( tl_segdom1(ip_npoint,ip_maxseg,ip_ncard) )
    ALLOCATE( tl_seglvl1(ip_npoint,ip_maxseg,ip_ncard) )
-   
+ 
    DO jl=1,ip_ncard
       IF( tl_bdy(jl)%l_use )THEN
@@ -516,4 +579,11 @@
             tl_segdom1(:,jk,jl)=create_boundary_get_dom( tl_bathy1, &
             &                                            tl_bdy(jl), jk )
+
+            IF( .NOT. ln_extrap )THEN
+               ! get fine grid level
+               tl_seglvl1(:,jk,jl)= &
+                  & create_boundary_get_level( tl_level(:), &
+                  &                            tl_segdom1(:,jk,jl))
+            ENDIF
 
             ! add extra band to fine grid domain (if possible)
@@ -523,8 +593,4 @@
                &                  il_rho(jp_I), il_rho(jp_J))
             ENDDO
-
-            ! get fine grid level
-            tl_seglvl1(:,jk,jl)=create_boundary_get_level( tl_level(:), &
-                                                           tl_segdom1(:,jk,jl))
 
          ENDDO
@@ -594,8 +660,4 @@
                         &                          in_nlevel )
 
-                        ! use mask
-                        CALL create_boundary_use_mask( tl_segvar1(jvar,jk,jl), &
-                        &                         tl_seglvl1(jpoint,jk,jl))
-
                         !del extra
                         CALL dom_del_extra( tl_segvar1(jvar,jk,jl), &
@@ -654,5 +716,6 @@
                   IF( tl_bdy(jl)%l_use )THEN
                      
-                     WRITE(*,'(2x,a,a)') 'work on '//TRIM(tl_bdy(jl)%c_card)//' boundary'
+                     WRITE(*,'(2x,a,a)') 'work on '//TRIM(tl_bdy(jl)%c_card)//&
+                        &  ' boundary'
                      DO jk=1,tl_bdy(jl)%i_nseg
                         ! compute domain on fine grid
@@ -662,5 +725,6 @@
                            
                            cl_name=tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name
-                           WRITE(*,'(4x,a,a)') "work on variable "//TRIM(cl_name)
+                           WRITE(*,'(4x,a,a)') "work on (extract) variable "//&
+                              &  TRIM(cl_name)
 
                            cl_point=tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_point
@@ -678,5 +742,4 @@
 
                            tl_dom1=dom_copy(tl_segdom1(jpoint,jk,jl))
-                           tl_lvl1=var_copy(tl_seglvl1(jpoint,jk,jl))
 
                            ! open mpp files
@@ -687,8 +750,4 @@
                            &                     tl_mpp, TRIM(cl_name), tl_dom1)
 
-                           ! use mask
-                           CALL create_boundary_use_mask( &
-                           &                 tl_segvar1(jvar+jj,jk,jl), tl_lvl1)
-
                            ! del extra point
                            CALL dom_del_extra( tl_segvar1(jvar+jj,jk,jl), &
@@ -699,11 +758,14 @@
 
                            ! add attribute to variable
-                           tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
+                           tl_att=att_init('src_file', &
+                              &  TRIM(fct_basename(tl_mpp%c_name)))
                            CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
 
-                           tl_att=att_init('src_i_indices',(/tl_dom1%i_imin, tl_dom1%i_imax/))
+                           tl_att=att_init('src_i_indices', &
+                              &  (/tl_dom1%i_imin, tl_dom1%i_imax/))
                            CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
 
-                           tl_att=att_init('src_j_indices',(/tl_dom1%i_jmin, tl_dom1%i_jmax/))
+                           tl_att=att_init('src_j_indices', &
+                              &  (/tl_dom1%i_jmin, tl_dom1%i_jmax/))
                            CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
 
@@ -736,11 +798,12 @@
                   IF( tl_bdy(jl)%l_use )THEN
 
-                     WRITE(*,'(2x,a,a)') 'work on '//TRIM(tl_bdy(jl)%c_card)//' boundary'
+                     WRITE(*,'(2x,a,a)') 'work on '//TRIM(tl_bdy(jl)%c_card)//&
+                        &  ' boundary'
                      DO jk=1,tl_bdy(jl)%i_nseg
                         
                         ! for each variable of this file
                         DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
-                           
-                           WRITE(*,'(4x,a,a)') "work on variable "//&
+ 
+                           WRITE(*,'(4x,a,a)') "work on (interp) variable "//&
                            &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
 
@@ -759,5 +822,4 @@
 
                            tl_dom1=dom_copy(tl_segdom1(jpoint,jk,jl))
-                           tl_lvl1=var_copy(tl_seglvl1(jpoint,jk,jl))
 
                            CALL create_boundary_get_coord( tl_coord1, tl_dom1, &
@@ -795,5 +857,6 @@
                            &                 il_jmin0, il_jmax0 )
 
-                           ! add extra band (if possible) to compute interpolation
+                           ! add extra band (if possible) to compute 
+                           ! interpolation
                            CALL dom_add_extra(tl_dom0)
 
@@ -815,8 +878,4 @@
                            CALL dom_del_extra( tl_segvar1(jvar+jj,jk,jl), &
                            &                   tl_dom0, il_rho(:) )
-
-                           ! use mask
-                           CALL create_boundary_use_mask( &
-                           &     tl_segvar1(jvar+jj,jk,jl), tl_lvl1)
 
                            ! del extra point on fine grid
@@ -889,20 +948,11 @@
 
    IF( jvar /= tl_multi%i_nvar )THEN
-      CALL logger_error("CREATE BOUNDARY: it seems some variable can not be read")
+      CALL logger_error("CREATE BOUNDARY: it seems some variable "//&
+         &  "can not be read")
    ENDIF
-
-   CALL var_clean(tl_seglvl1(:,:,:))
-   DEALLOCATE( tl_seglvl1 )
 
    ! write file for each segment of each boundary
    DO jl=1,ip_ncard
       IF( tl_bdy(jl)%l_use )THEN
-
-         SELECT CASE(TRIM(tl_bdy(jk)%c_card))
-         CASE('north','south')
-            il_dim=1
-         CASE('east','west')
-            il_dim=2
-         END SELECT   
 
          DO jk=1,tl_bdy(jl)%i_nseg
@@ -911,4 +961,8 @@
             &                               'T', tl_lon1, tl_lat1 )
 
+            ! force to use nav_lon, nav_lat as variable name
+            tl_lon1%c_name='nav_lon'
+            tl_lat1%c_name='nav_lat'
+
             ! del extra point on fine grid
             CALL dom_del_extra( tl_lon1, tl_segdom1(jp_T,jk,jl) )
@@ -924,7 +978,9 @@
             CALL boundary_swap(tl_lat1, tl_bdy(jl))
             DO jvar=1,tl_multi%i_nvar
-               CALL boundary_swap(tl_segvar1(jvar,jk,jl), tl_bdy(jl))
 
                ! use additional request
+               ! change unit and apply factor
+               CALL var_chg_unit(tl_segvar1(jvar,jk,jl))
+
                ! forced min and max value
                CALL var_limit_value(tl_segvar1(jvar,jk,jl))
@@ -933,9 +989,23 @@
                CALL filter_fill_value(tl_segvar1(jvar,jk,jl))
 
-               ! extrapolate
-               CALL extrap_fill_value( tl_segvar1(jvar,jk,jl), &
-               &                       id_iext=in_extrap,      &
-               &                       id_jext=in_extrap,      &
-               &                       id_kext=in_extrap )
+               IF( .NOT. ln_extrap )THEN
+                  ! use mask
+                  SELECT CASE(TRIM(tl_segvar1(jvar,jk,jl)%c_point))
+                  CASE DEFAULT !'T'
+                     jpoint=jp_T
+                  CASE('U')
+                     jpoint=jp_U
+                  CASE('V')
+                     jpoint=jp_V
+                  CASE('F')
+                     jpoint=jp_F
+                  END SELECT
+
+                  CALL create_boundary_use_mask(tl_segvar1(jvar,jk,jl), &
+                  &                             tl_seglvl1(jpoint,jk,jl))
+               ENDIF
+
+               ! swap dimension order
+               CALL boundary_swap(tl_segvar1(jvar,jk,jl), tl_bdy(jl))
 
             ENDDO
@@ -944,13 +1014,32 @@
             ! create file structure
             ! set file namearray of level variable structure
-            IF( ASSOCIATED(tl_time%d_value) )THEN
-               cl_fmt="('y',i0.4,'m',i0.2,'d',i0.2)"
-               cl_date=date_print( var_to_date(tl_time), cl_fmt ) 
-
-               cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
-               &                                TRIM(tl_bdy(jl)%c_card), jk, TRIM(cl_date) )
+            IF( tl_bdy(jl)%i_nseg > 1 )THEN
+               IF( ASSOCIATED(tl_time%d_value) )THEN
+                  cl_fmt="('y',i0.4,'m',i0.2,'d',i0.2)"
+                  tl_date=var_to_date(tl_time)
+                  tl_date=tl_date+dn_dayofs
+                  cl_date=date_print( tl_date, cl_fmt ) 
+
+                  cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+                  &                                TRIM(tl_bdy(jl)%c_card), jk,&
+                  &                                cd_date=TRIM(cl_date) )
+               ELSE
+                  cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+                  &                                TRIM(tl_bdy(jl)%c_card), jk )
+               ENDIF
             ELSE
-               cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
-               &                                TRIM(tl_bdy(jl)%c_card), jk )
+               IF( ASSOCIATED(tl_time%d_value) )THEN
+                  cl_fmt="('y',i0.4,'m',i0.2,'d',i0.2)"
+                  tl_date=var_to_date(tl_time)
+                  tl_date=tl_date+dn_dayofs
+                  cl_date=date_print( tl_date, cl_fmt )
+
+                  cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+                  &                                TRIM(tl_bdy(jl)%c_card), &
+                  &                                cd_date=TRIM(cl_date) )
+               ELSE
+                  cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+                  &                                TRIM(tl_bdy(jl)%c_card) )
+               ENDIF
             ENDIF
             ! 
@@ -960,19 +1049,9 @@
             tl_dim(:)=var_max_dim(tl_segvar1(:,jk,jl))
 
-            CALL dim_unorder(tl_dim(:))
             SELECT CASE(TRIM(tl_bdy(jl)%c_card))
                CASE DEFAULT ! 'north','south'
                   cl_dimorder='xyzt'
-                  CALL dim_reorder(tl_dim(:),TRIM(cl_dimorder))
                CASE('east','west')
                   cl_dimorder='yxzt'
-                  CALL dim_reorder(tl_dim(:),TRIM(cl_dimorder))
-                  ! reorder coordinates dimension
-                  CALL var_reorder(tl_lon1,TRIM(cl_dimorder))
-                  CALL var_reorder(tl_lat1,TRIM(cl_dimorder))
-                  ! reorder other variable dimension
-                  DO jvar=1,tl_multi%i_nvar
-                     CALL var_reorder(tl_segvar1(jvar,jk,jl),TRIM(cl_dimorder))
-                  ENDDO
             END SELECT
 
@@ -992,16 +1071,22 @@
             ENDIF
             
+
+
             IF( tl_dim(3)%l_use )THEN
-               ! add depth
-               CALL file_add_var(tl_fileout, tl_depth)
+               IF( ASSOCIATED(tl_depth%d_value) )THEN
+                  ! add depth
+                  CALL file_add_var(tl_fileout, tl_depth)
+               ENDIF
             ENDIF
 
             IF( tl_dim(4)%l_use )THEN
-               ! add time
-               CALL file_add_var(tl_fileout, tl_time)
+               IF( ASSOCIATED(tl_time%d_value) )THEN
+                  ! add time
+                  CALL file_add_var(tl_fileout, tl_time)
+               ENDIF
             ENDIF
 
             ! add other variable
-            DO jvar=1,tl_multi%i_nvar
+            DO jvar=tl_multi%i_nvar,1,-1
                CALL file_add_var(tl_fileout, tl_segvar1(jvar,jk,jl))
                CALL var_clean(tl_segvar1(jvar,jk,jl))
@@ -1048,5 +1133,5 @@
 
             ! write file
-            CALL iom_write_file(tl_fileout)
+            CALL iom_write_file(tl_fileout, cl_dimorder)
 
             ! close file
@@ -1066,4 +1151,7 @@
    DEALLOCATE( tl_segdom1 )
    DEALLOCATE( tl_segvar1 )
+   CALL var_clean(tl_seglvl1(:,:,:))
+   DEALLOCATE( tl_seglvl1 )
+
 
    CALL mpp_clean(tl_coord1)
@@ -1082,5 +1170,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - take into account grid point to compute boundary indices
@@ -1186,9 +1274,10 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine get coordinates over boudnary domain
+   !> This subroutine get coordinates over boundary domain
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !> @date September, 2014 - take into account grid point
+   !> @date November, 2013 - Initial Version
+   !> @date September, 2014 
+   !> - take into account grid point
    !>
    !> @param[in] td_coord1 coordinates file structure
@@ -1237,10 +1326,10 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine interpolate variable over boundary
+   !> This subroutine interpolate variable on boundary
    !> 
    !> @details 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure 
@@ -1296,5 +1385,5 @@
 
       ! extrapolate variable
-      CALL extrap_fill_value( td_var, id_iext=il_iext, id_jext=il_jext )
+      CALL extrap_fill_value( td_var )
 
       ! interpolate Bathymetry
@@ -1303,5 +1392,6 @@
 
       ! remove extraband
-      CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
+      CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), &
+         &                               il_jext*id_rho(jp_J))
 
    END SUBROUTINE create_boundary_interp
@@ -1317,5 +1407,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_var    variable structure 
@@ -1422,5 +1512,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure 
@@ -1475,5 +1565,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_level  array of level variable structure
@@ -1537,5 +1627,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2014- Initial Version
+   !> @date November, 2014 - Initial Version
    !>
    !> @param[in] td_mpp       mpp structure
@@ -1588,5 +1678,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2014- Initial Version
+   !> @date November, 2014 - Initial Version
    !>
    !> @param[in] td_mpp      mpp structure
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_coord.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_coord.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_coord.f90	(revision 9987)
@@ -24,4 +24,7 @@
 !> @endcode
 !>    
+!> @note 
+!>    you could find a template of the namelist in templates directory.
+!>
 !>    create_coord.nam comprise 6 namelists:<br/>
 !>       - logger namelist (namlog)
@@ -39,5 +42,5 @@
 !>       - cn_logfile   : log filename
 !>       - cn_verbosity : verbosity ('trace','debug','info',
-!> 'warning','error','fatal')
+!> 'warning','error','fatal','none')
 !>       - in_maxerror  : maximum number of error allowed
 !>
@@ -54,11 +57,12 @@
 !>       - cn_varinfo : list of variable and extra information about request(s)
 !> to be used.<br/>
-!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          each elements of *cn_varinfo* is a string character 
+!>          (separated by ',').<br/>
 !>          it is composed of the variable name follow by ':', 
 !>          then request(s) to be used on this variable.<br/> 
 !>          request could be:
-!>             - interpolation method
-!>             - extrapolation method
-!>             - filter method
+!>             - int = interpolation method
+!>             - ext = extrapolation method
+!>             - flt = filter method
 !> 
 !>                requests must be separated by ';' .<br/>
@@ -68,6 +72,6 @@
 !>          @ref extrap and @ref filter modules.<br/>
 !>
-!>          Example: 'votemper: linear; hann(2,3); dist_weight', 
-!>          'vosaline: cubic'<br/>
+!>          Example: 'votemper: int=linear; flt=hann(2,3); ext=dist_weight', 
+!>          'vosaline: int=cubic'<br/>
 !>          @note 
 !>             If you do not specify a method which is required, 
@@ -90,5 +94,5 @@
 !>
 !>    * _output namelist (namout)_:
-!>       - cn_fileout : output coordinate file
+!>       - cn_fileout : output coordinate file name
 !>
 !> @author J.Paul
@@ -152,12 +156,4 @@
    TYPE(TFILE)                                          :: tl_fileout
 
-   ! check 
-!   INTEGER(i4)                                          :: il_imin0
-!   INTEGER(i4)                                          :: il_imax0
-!   INTEGER(i4)                                          :: il_jmin0
-!   INTEGER(i4)                                          :: il_jmax0
-!   INTEGER(i4)      , DIMENSION(2,2)                    :: il_ind2
-!   TYPE(TMPP)                                           :: tl_mppout
-
    ! loop indices
    INTEGER(i4) :: ji
@@ -165,15 +161,20 @@
 
    ! namelist variable
+   ! namlog
    CHARACTER(LEN=lc) :: cn_logfile = 'create_coord.log' 
    CHARACTER(LEN=lc) :: cn_verbosity = 'warning' 
    INTEGER(i4)       :: in_maxerror = 5
 
+   ! namcfg
+   CHARACTER(LEN=lc) :: cn_varcfg = '../cfg/variable.cfg' 
+
+   ! namcrs
    CHARACTER(LEN=lc) :: cn_coord0 = '' 
    INTEGER(i4)       :: in_perio0 = -1
 
-   CHARACTER(LEN=lc) :: cn_varcfg = '../cfg/variable.cfg' 
-
+   ! namvar
    CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varinfo = ''
 
+   !namnst
    INTEGER(i4)       :: in_imin0 = 0
    INTEGER(i4)       :: in_imax0 = 0
@@ -183,4 +184,5 @@
    INTEGER(i4)       :: in_rhoj  = 1
 
+   !namout
    CHARACTER(LEN=lc) :: cn_fileout= 'coord_fine.nc'
    !-------------------------------------------------------------------
@@ -305,5 +307,4 @@
 
       il_offset(:,:,:)=create_coord_get_offset(il_rho(:))
-
    ENDIF
 
@@ -348,8 +349,4 @@
       CALL dom_del_extra( tl_var(ji), tl_dom, il_rho(:), .true. )
 
-      ! do not add ghost cell. 
-      ! ghost cell already replace by value for coordinates 
-      ! CALL grid_add_ghost(tl_var(ji),tl_dom%i_ghost(:,:))
-
       ! filter
       CALL filter_fill_value(tl_var(ji))      
@@ -375,9 +372,8 @@
 
    ! add variables
-   DO ji=1,il_nvar
+   DO ji=il_nvar,1,-1
       CALL file_add_var(tl_fileout, tl_var(ji))
+      CALL var_clean(tl_var(ji))
    ENDDO
-
-   ! recompute some attribute
 
    ! add some attribute
@@ -440,37 +436,4 @@
 
    CALL file_clean(tl_fileout)
-
-!   ! check domain
-!   tl_coord0=mpp_init( file_init(TRIM(cn_coord0)), id_perio=in_perio0)
-!   tl_mppout=mpp_init( file_init(TRIM(cn_fileout)) )
-!   CALL grid_get_info(tl_coord0)
-!   CALL iom_mpp_open(tl_mppout)
-!
-!   il_ind2(:,:)=grid_get_coarse_index( tl_coord0, tl_mppout, &
-!   &                                   id_rho=il_rho(:) )
-!
-!   il_imin0=il_ind2(1,1) ; il_imax0=il_ind2(1,2)
-!   il_jmin0=il_ind2(2,1) ; il_jmax0=il_ind2(2,2)
-!
-!   IF( il_imin0 /= in_imin0 .OR. &
-!   &   il_imax0 /= in_imax0 .OR. &
-!   &   il_jmin0 /= in_jmin0 .OR. &
-!   &   il_jmax0 /= in_jmax0 )THEN
-!      CALL logger_debug("CREATE COORD: output indices ("//&
-!      &                 TRIM(fct_str(il_imin0))//","//&
-!      &                 TRIM(fct_str(il_imax0))//") ("//&
-!      &                 TRIM(fct_str(il_jmin0))//","//&
-!      &                 TRIM(fct_str(il_jmax0))//")" ) 
-!      CALL logger_debug("CREATE COORD: input indices ("//&
-!      &                 TRIM(fct_str(in_imin0))//","//&
-!      &                 TRIM(fct_str(in_imax0))//") ("//&
-!      &                 TRIM(fct_str(in_jmin0))//","//&
-!      &                 TRIM(fct_str(in_jmax0))//")" ) 
-!      CALL logger_fatal("CREATE COORD: output domain not confrom "//&
-!      &                 "with input indices")
-!   ENDIF
-!
-!   CALL iom_mpp_close(tl_coord0)
-!   CALL iom_mpp_close(tl_mppout)
 
    ! close log file
@@ -539,4 +502,6 @@
    !> @param[in] id_iext   number of points to be extrapolated in i-direction
    !> @param[in] id_jext   number of points to be extrapolated in j-direction
+   !>
+   !> @todo check if mask is really needed
    !-------------------------------------------------------------------
    SUBROUTINE create_coord_interp( td_var,          &
@@ -626,5 +591,5 @@
 
          ! extrapolate variable
-         CALL extrap_fill_value( td_var, id_iext=il_iext, id_jext=il_jext )
+         CALL extrap_fill_value( td_var )
 
          ! interpolate variable
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_restart.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_restart.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/create_restart.f90	(revision 9987)
@@ -25,4 +25,7 @@
 !> @endcode
 !>    
+!> @note 
+!>    you could find a template of the namelist in templates directory.
+!>
 !>    create_restart.nam comprise 9 namelists:<br/>
 !>       - logger namelist (namlog)
@@ -43,5 +46,5 @@
 !>       - cn_logfile   : log filename
 !>       - cn_verbosity : verbosity ('trace','debug','info',
-!> 'warning','error','fatal')
+!> 'warning','error','fatal','none')
 !>       - in_maxerror  : maximum number of error allowed
 !>
@@ -59,6 +62,4 @@
 !>       - cn_bathy1 : bathymetry file
 !>       - in_perio1 : NEMO periodicity index
-!>       - in_extrap : number of land point to be extrapolated 
-!>       before writing file
 !>
 !>    * _vertical grid namelist (namzgr)_:<br/>
@@ -83,13 +84,16 @@
 !>       - cn_varinfo : list of variable and extra information about request(s) 
 !>       to be used.<br/>
-!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          each elements of *cn_varinfo* is a string character
+!>          (separated by ',').<br/>
 !>          it is composed of the variable name follow by ':', 
 !>          then request(s) to be used on this variable.<br/> 
 !>          request could be:
-!>             - interpolation method
-!>             - extrapolation method
-!>             - filter method
-!>             - > minimum value
-!>             - < maximum value
+!>             - int = interpolation method
+!>             - ext = extrapolation method
+!>             - flt = filter method
+!>             - min = minimum value
+!>             - max = maximum value
+!>             - unt = new units
+!>             - unf = unit scale factor (linked to new units)
 !>
 !>             requests must be separated by ';'.<br/>
@@ -98,5 +102,5 @@
 !>          informations about available method could be find in @ref interp,
 !>          @ref extrap and @ref filter.<br/>
-!>          Example: 'votemper: linear; hann; dist_weight','vosaline: cubic'
+!>          Example: 'votemper: int=linear; flt=hann; ext=dist_weight','vosaline: int=cubic'
 !>          @note 
 !>             If you do not specify a method which is required, 
@@ -136,7 +140,8 @@
 !>    * _output namelist (namout)_:<br/>
 !>       - cn_fileout : output file
-!>       - in_nproc  : total number of processor to be used
+!>       - ln_extrap : extrapolate land point or not
 !>       - in_niproc : i-direction number of processor
 !>       - in_njproc : j-direction numebr of processor
+!>       - in_nproc  : total number of processor to be used
 !>       - cn_type   : output format ('dimg', 'cdf')
 !>
@@ -148,4 +153,7 @@
 !> - offset computed considering grid point
 !> - add attributes in output variable
+!> @date June, 2015
+!> - extrapolate all land points, and add ln_extrap in namelist.
+!> - allow to change unit.
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -165,5 +173,5 @@
    USE iom                             ! I/O manager
    USE grid                            ! grid manager
-   USE vgrid                           ! vertical grid manager
+   USE vgrid                            ! vertical grid manager
    USE extrap                          ! extrapolation manager
    USE interp                          ! interpolation manager
@@ -249,5 +257,4 @@
    CHARACTER(LEN=lc) :: cn_bathy1 = ''
    INTEGER(i4)       :: in_perio1 = -1
-   INTEGER(i4)       :: in_extrap = 0
 
    !namzgr
@@ -279,4 +286,5 @@
    ! namout
    CHARACTER(LEN=lc) :: cn_fileout = 'restart.nc' 
+   LOGICAL           :: ln_extrap  = .FALSE.
    INTEGER(i4)       :: in_nproc   = 0
    INTEGER(i4)       :: in_niproc  = 0
@@ -301,6 +309,5 @@
    &  cn_coord1,   &    !< coordinate file
    &  cn_bathy1,   &    !< bathymetry file
-   &  in_perio1,   &    !< periodicity index
-   &  in_extrap
+   &  in_perio1         !< periodicity index
  
    NAMELIST /namzgr/ &
@@ -332,7 +339,8 @@
    NAMELIST /namout/ &  !< output namlist
    &  cn_fileout, &     !< fine grid bathymetry file
-   &  in_nproc,   &     !< number of processor to be used
+   &  ln_extrap,  &     !< extrapolate or not
    &  in_niproc,  &     !< i-direction number of processor
    &  in_njproc,  &     !< j-direction numebr of processor
+   &  in_nproc,   &     !< number of processor to be used
    &  cn_type           !< output type format (dimg, cdf)
    !-------------------------------------------------------------------
@@ -347,5 +355,5 @@
       CALL GET_COMMAND_ARGUMENT(1,cl_namelist) !f03 intrinsec
    ENDIF
-   
+
    ! read namelist
    INQUIRE(FILE=TRIM(cl_namelist), EXIST=ll_exist)
@@ -434,5 +442,9 @@
    ! check
    ! check output file do not already exist
-   cl_fileout=file_rename(cn_fileout,1)
+   IF( in_nproc > 0 )THEN
+      cl_fileout=file_rename(cn_fileout,1)
+   ELSE
+      cl_fileout=file_rename(cn_fileout)
+   ENDIF
    INQUIRE(FILE=TRIM(cl_fileout), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -468,16 +480,6 @@
    &                            il_rho(:) )
 
-   ! compute level
-   ALLOCATE(tl_level(ip_npoint))
-   tl_level(:)=vgrid_get_level(tl_bathy1, cl_namelist )
-
-   ! remove ghost cell
+   ! fine grid ghost cell
    il_xghost(:,:)=grid_get_ghost(tl_bathy1)
-   DO ji=1,ip_npoint
-      CALL grid_del_ghost(tl_level(ji), il_xghost(:,:))
-   ENDDO
-
-   ! clean
-   CALL mpp_clean(tl_bathy1)
 
    ! work on variables
@@ -514,5 +516,8 @@
                tl_var(jvar) = create_restart_matrix( &
                &  tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj), tl_coord1, &
-               &  in_nlevel, tl_level(:) )
+               &  in_nlevel, il_xghost(:,:) )
+
+               ! add ghost cell
+               CALL grid_add_ghost(tl_var(jvar), il_xghost(:,:))
 
             ENDDO
@@ -535,4 +540,5 @@
             ! open mpp file
             CALL iom_mpp_open(tl_mpp)
+
 
             ! get or check depth value
@@ -579,5 +585,5 @@
                DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
 
-                  WRITE(*,'(2x,a,a)') "work on variable "//&
+                  WRITE(*,'(2x,a,a)') "work on (extract) variable "//&
                   &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
 
@@ -600,9 +606,6 @@
                   CALL att_clean(tl_att)
 
-                  ! use mask
-                  CALL create_restart_mask(tl_var(jvar), tl_level(:))
-
                   ! add ghost cell
-                  CALL grid_add_ghost( tl_var(jvar), tl_dom1%i_ghost(:,:) )
+                  CALL grid_add_ghost(tl_var(jvar), tl_dom1%i_ghost(:,:))
 
                ENDDO
@@ -631,5 +634,5 @@
                DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
 
-                  WRITE(*,'(2x,a,a)') "work on variable "//&
+                  WRITE(*,'(2x,a,a)') "work on (interp) variable "//&
                   &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
 
@@ -646,8 +649,7 @@
                   &                                   id_rho=il_rho(:), &
                   &                                   cd_point=TRIM(tl_var(jvar)%c_point))
-                  
 
                   ! interpolate variable
-                  CALL create_restart_interp(tl_var(jvar), tl_level(:), &
+                  CALL create_restart_interp(tl_var(jvar), & 
                   &                          il_rho(:), &
                   &                          id_offset=il_offset(:,:))
@@ -675,11 +677,6 @@
                   CALL att_clean(tl_att)
 
-                  ! use mask
-                  CALL create_restart_mask(tl_var(jvar), tl_level(:))
-
                   ! add ghost cell
-                  CALL grid_add_ghost( tl_var(jvar), il_xghost(:,:) )
-
-
+                  CALL grid_add_ghost(tl_var(jvar), il_xghost(:,:))
                ENDDO
 
@@ -705,7 +702,19 @@
    CALL mpp_clean(tl_coord0)
 
+   IF( .NOT. ln_extrap )THEN
+      ! compute level
+      ALLOCATE(tl_level(ip_npoint))
+      tl_level(:)=vgrid_get_level(tl_bathy1, cl_namelist )
+   ENDIF
+
+   ! clean
+   CALL mpp_clean(tl_bathy1)
+
    ! use additional request
    DO jvar=1,il_nvar
 
+      ! change unit and apply factor
+      CALL var_chg_unit(tl_var(jvar))
+
       ! forced min and max value
       CALL var_limit_value(tl_var(jvar))
@@ -714,8 +723,8 @@
       CALL filter_fill_value(tl_var(jvar))
 
-      ! extrapolate
-      CALL extrap_fill_value(tl_var(jvar), id_iext=in_extrap, &
-      &                                    id_jext=in_extrap, &
-      &                                    id_kext=in_extrap)
+      IF( .NOT. ln_extrap )THEN
+         ! use mask
+         CALL create_restart_mask(tl_var(jvar), tl_level(:))
+      ENDIF
 
    ENDDO
@@ -724,5 +733,5 @@
    IF( in_niproc == 0 .AND. &
    &   in_njproc == 0 .AND. &
-   &   in_nproc  == 0 )THEN
+   &   in_nproc == 0 )THEN
       in_niproc = 1
       in_njproc = 1
@@ -782,5 +791,5 @@
          CALL mpp_add_var(tl_mppout, tl_depth)
       ELSE
-         CALL logger_error("CREATE RESTART: no value for depth variable.")
+         CALL logger_warn("CREATE RESTART: no value for depth variable.")
       ENDIF
    ENDIF
@@ -792,5 +801,5 @@
          CALL mpp_add_var(tl_mppout, tl_time)
       ELSE
-         CALL logger_error("CREATE RESTART: no value for time variable.")
+         CALL logger_warn("CREATE RESTART: no value for time variable.")
       ENDIF
    ENDIF
@@ -798,5 +807,5 @@
 
    ! add other variable
-   DO jvar=1,il_nvar
+   DO jvar=il_nvar,1,-1
       ! check if variable already add
       il_index=var_get_index(tl_mppout%t_proc(1)%t_var(:), tl_var(jvar)%c_name)
@@ -807,9 +816,4 @@
    ENDDO
 
-!   DO ji=1,4
-!      CALL grid_add_ghost( tl_level(ji), il_xghost(:,:) )
-!      CALL var_clean(tl_level(ji))
-!   ENDDO
-
    ! add some attribute
    tl_att=att_init("Created_by","SIREN create_restart")
@@ -839,4 +843,7 @@
    ENDIF
 
+   ! print
+   CALL mpp_print(tl_mppout)
+
    ! create file
    CALL iom_mpp_create(tl_mppout)
@@ -847,13 +854,12 @@
    CALL iom_mpp_close(tl_mppout)
 
-   ! print
-   CALL mpp_print(tl_mppout)
-
    ! clean
    CALL att_clean(tl_att)
    CALL var_clean(tl_var(:))
    DEALLOCATE(tl_var)
-   CALL var_clean(tl_level(:))
-   DEALLOCATE(tl_level)
+   IF( .NOT. ln_extrap )THEN
+      CALL var_clean(tl_level(:))
+      DEALLOCATE(tl_level)
+   ENDIF
 
    CALL mpp_clean(tl_mppout)
@@ -876,19 +882,21 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - do not use level anymore 
    !>
    !> @param[in] td_var    variable structure 
    !> @param[in] td_coord  coordinate file structure 
    !> @param[in] id_nlevel number of vertical level  
-   !> @param[in] td_level  array of level on T,U,V,F point (variable structure) 
+   !> @param[in] id_xghost ghost cell array
    !> @return variable structure 
    !-------------------------------------------------------------------
-   FUNCTION create_restart_matrix(td_var, td_coord, id_nlevel, td_level)
+   FUNCTION create_restart_matrix(td_var, td_coord, id_nlevel, id_xghost)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR)              , INTENT(IN) :: td_var
-      TYPE(TMPP)              , INTENT(IN) :: td_coord
-      INTEGER(i4)             , INTENT(IN) :: id_nlevel
-      TYPE(TVAR), DIMENSION(:), INTENT(IN) :: td_level
+      TYPE(TVAR)                 , INTENT(IN) :: td_var
+      TYPE(TMPP)                 , INTENT(IN) :: td_coord
+      INTEGER(i4)                , INTENT(IN) :: id_nlevel
+      INTEGER(i4), DIMENSION(:,:), INTENT(IN) :: id_xghost
 
       ! function
@@ -899,5 +907,4 @@
       INTEGER(i4)      , DIMENSION(3)                    :: il_size
       INTEGER(i4)      , DIMENSION(3)                    :: il_rest
-      INTEGER(i4)      , DIMENSION(2,2)                  :: il_xghost
 
       INTEGER(i4)      , DIMENSION(:)      , ALLOCATABLE :: il_ishape
@@ -915,7 +922,4 @@
       !----------------------------------------------------------------
 
-      ! look for ghost cell
-      il_xghost(:,:)=grid_get_ghost( td_coord )
-
       ! write value on grid
       ! get matrix dimension
@@ -929,6 +933,6 @@
 
       ! remove ghost cell
-      tl_dim(jp_I)%i_len=tl_dim(jp_I)%i_len - SUM(il_xghost(jp_I,:))*ip_ghost
-      tl_dim(jp_J)%i_len=tl_dim(jp_J)%i_len - SUM(il_xghost(jp_J,:))*ip_ghost
+      tl_dim(jp_I)%i_len=tl_dim(jp_I)%i_len - SUM(id_xghost(jp_I,:))*ip_ghost
+      tl_dim(jp_J)%i_len=tl_dim(jp_J)%i_len - SUM(id_xghost(jp_J,:))*ip_ghost
 
       ! split output domain in N subdomain depending of matrix dimension 
@@ -992,10 +996,4 @@
       DEALLOCATE(dl_value)
 
-      ! use mask
-      CALL create_restart_mask(create_restart_matrix, td_level(:))
-
-      ! add ghost cell
-      CALL grid_add_ghost( create_restart_matrix, il_xghost(:,:) )
-
       ! clean 
       DEALLOCATE(il_ishape)
@@ -1009,5 +1007,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure
@@ -1071,8 +1069,9 @@
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - do not use level anymore (for extrapolation)
    !>
    !> @param[inout] td_var    variable structure 
-   !> @param[inout] td_level  fine grid level, array of variable structure
    !> @param[in] id_rho       array of refinment factor
    !> @param[in] id_offset    array of offset between fine and coarse grid
@@ -1080,5 +1079,5 @@
    !> @param[in] id_jext      j-direction size of extra bands (default=im_minext)
    !-------------------------------------------------------------------
-   SUBROUTINE create_restart_interp( td_var, td_level,&
+   SUBROUTINE create_restart_interp( td_var, & 
    &                                 id_rho,          &
    &                                 id_offset,       &
@@ -1089,5 +1088,4 @@
       ! Argument
       TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
-      TYPE(TVAR) , DIMENSION(:)  , INTENT(INOUT) :: td_level
       INTEGER(i4), DIMENSION(:)  , INTENT(IN   ) :: id_rho
       INTEGER(i4), DIMENSION(:,:), INTENT(IN   ) :: id_offset
@@ -1119,5 +1117,4 @@
          il_jext=2
       ENDIF
-
       ! work on variable
       ! add extraband
@@ -1125,8 +1122,5 @@
 
       ! extrapolate variable
-      CALL extrap_fill_value( td_var, td_level(:),    &
-      &                               id_offset(:,:), &
-      &                               id_rho(:),      &
-      &                               id_iext=il_iext, id_jext=il_jext )
+      CALL extrap_fill_value( td_var )
 
       ! interpolate variable
@@ -1146,5 +1140,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2014- Initial Version
+   !> @date November, 2014 - Initial Version
    !>
    !> @param[in] td_mpp       mpp structure
@@ -1197,5 +1191,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2014- Initial Version
+   !> @date November, 2014 - Initial Version
    !>
    !> @param[in] td_mpp      mpp structure
@@ -1220,4 +1214,5 @@
 
       ! get or check depth value
+
       IF( td_mpp%t_proc(1)%i_timeid /= 0 )THEN
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/dimension.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/dimension.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/dimension.f90	(revision 9987)
@@ -78,5 +78,5 @@
 !>
 !>    This subroutine filled dimension structure with unused dimension, 
-!>    then switch from "unordered" dimension to "ordered" dimension.<br/>
+!>    then switch from "disordered" dimension to "ordered" dimension.<br/>
 !>    The dimension structure return will be:<br/>
 !>    tl_dim(1) => 'X', i_len=10, l_use=T, l_uld=F<br/>
@@ -94,8 +94,8 @@
 !>    - cl_neworder : character(len=4) (example: 'yxzt')
 !>
-!>    to switch dimension array from ordered dimension to unordered
+!>    to switch dimension array from ordered dimension to disordered
 !> dimension:<br/>
 !> @code
-!>    CALL dim_unorder(tl_dim(:))
+!>    CALL dim_disorder(tl_dim(:))
 !> @endcode
 !>
@@ -111,7 +111,7 @@
 !>    CALL dim_reshape_2xyzt(tl_dim(:), value(:,:,:,:))
 !> @endcode
-!>       - value must be a 4D array of real(8) value "unordered"
-!>
-!>    to reshape array of value in "unordered" dimension:<br/>
+!>       - value must be a 4D array of real(8) value "disordered"
+!>
+!>    to reshape array of value in "disordered" dimension:<br/>
 !> @code
 !>    CALL dim_reshape_xyzt2(tl_dim(:), value(:,:,:,:))
@@ -123,10 +123,10 @@
 !>    CALL dim_reorder_2xyzt(tl_dim(:), tab(:))
 !> @endcode
-!>       - tab must be a 1D array with 4 elements "unordered".
+!>       - tab must be a 1D array with 4 elements "disordered".
 !>       It could be composed of character, integer(4), or logical
 !> 
-!>    to reorder a 1D array of 4 elements in "unordered" dimension:<br/>
-!> @code
-!>    CALL dim_reorder_2xyzt(tl_dim(:), tab(:))
+!>    to reorder a 1D array of 4 elements in "disordered" dimension:<br/>
+!> @code
+!>    CALL dim_reorder_xyzt2(tl_dim(:), tab(:))
 !> @endcode
 !>       - tab must be a 1D array with 4 elements "ordered".
@@ -173,6 +173,6 @@
    PUBLIC :: dim_print         !< print dimension information
    PUBLIC :: dim_copy          !< copy dimension structure
-   PUBLIC :: dim_reorder       !< filled dimension structure to switch from unordered to ordered dimension
-   PUBLIC :: dim_unorder       !< switch dimension array from ordered to unordered dimension
+   PUBLIC :: dim_reorder       !< filled dimension structure to switch from disordered to ordered dimension
+   PUBLIC :: dim_disorder      !< switch dimension array from ordered to disordered dimension
    PUBLIC :: dim_fill_unused   !< filled dimension structure with unused dimension 
    PUBLIC :: dim_reshape_2xyzt !< reshape array dimension to ('x','y','z','t')
@@ -321,5 +321,6 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial Version
-   !> @date September, 2014 - do not check if dimension used
+   !> @date September, 2014 
+   !> - do not check if dimension used
    !>
    !> @param[in] td_dim    array of dimension structure
@@ -502,8 +503,14 @@
    !> Optionally length could be inform, as well as short name and if dimension
    !> is unlimited or not.<br/>
-   !> define dimension is supposed to be used.
-   !>
-   !> @author J.Paul
-   !> @date November, 2013 - Initial Version
+   !> By default, define dimension is supposed to be used.
+   !> Optionally you could force a defined dimension to be unused. 
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - add optional argument to define dimension unused
+   !> @date July, 2015
+   !> - Bug fix: inform order to disorder table instead of disorder to order
+   !> table
    !
    !> @param[in] cd_name   dimension name
@@ -511,7 +518,8 @@
    !> @param[in] ld_uld    dimension unlimited
    !> @param[in] cd_sname  dimension short name
+   !> @param[in] ld_uld    dimension use or not
    !> @return dimension structure
    !-------------------------------------------------------------------
-   TYPE(TDIM) FUNCTION dim_init( cd_name, id_len, ld_uld, cd_sname)
+   TYPE(TDIM) FUNCTION dim_init( cd_name, id_len, ld_uld, cd_sname, ld_use)
       IMPLICIT NONE
 
@@ -521,4 +529,5 @@
       LOGICAL,          INTENT(IN), OPTIONAL :: ld_uld
       CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_sname
+      LOGICAL,          INTENT(IN), OPTIONAL :: ld_use
 
       ! local variable
@@ -543,5 +552,9 @@
 
       ! define dimension is supposed to be used
-      dim_init%l_use=.TRUE.
+      IF( PRESENT(ld_use) )THEN
+         dim_init%l_use=ld_use
+      ELSE
+         dim_init%l_use=.TRUE.
+      ENDIF
 
       IF( PRESENT(cd_sname) )THEN
@@ -590,6 +603,6 @@
       ENDIF
       
-      ! get dimension orderer index
-      dim_init%i_2xyzt=SCAN(TRIM(cp_dimorder),TRIM(dim_init%c_sname))
+      ! get dimension order indices
+      dim_init%i_xyzt2=SCAN(TRIM(cp_dimorder),TRIM(dim_init%c_sname))
 
    END FUNCTION dim_init
@@ -655,4 +668,6 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - Bug fix: use order to disorder table (see dim_init)
    !>
    !> @param[in] td_dim array of dimension structure
@@ -686,6 +701,6 @@
          ! search missing dimension
          IF( INDEX(cl_dimin,TRIM(fct_lower(cp_dimorder(ji:ji)))) == 0 )THEN
-            ! search first empty dimension
-            il_ind(:)=MINLOC( tl_dim(:)%i_2xyzt, tl_dim(:)%i_2xyzt == 0 )
+            ! search first empty dimension (see dim_init)
+            il_ind(:)=MINLOC( tl_dim(:)%i_xyzt2, tl_dim(:)%i_xyzt2 == 0 )
 
             ! put missing dimension instead of empty one
@@ -693,5 +708,5 @@
             ! update output structure
             tl_dim(il_ind(1))%c_name=fct_lower(cp_dimorder(ji:ji))
-            tl_dim(il_ind(1))%i_2xyzt=ji
+            tl_dim(il_ind(1))%i_xyzt2=ji
             tl_dim(il_ind(1))%i_len=1
             tl_dim(il_ind(1))%l_use=.FALSE.
@@ -711,5 +726,5 @@
    !> This subroutine switch element of an array (4 elts) of dimension 
    !> structure 
-   !> from unordered dimension to ordered dimension <br/>
+   !> from disordered dimension to ordered dimension <br/>
    !>
    !> @details
@@ -722,5 +737,6 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial Version
-   !> @date September, 2014 - allow to choose ordered dimension to be output
+   !> @date September, 2014 
+   !> - allow to choose ordered dimension to be output
    !>
    !> @param[inout] td_dim    array of dimension structure
@@ -811,5 +827,5 @@
    !-------------------------------------------------------------------
    !> @brief This subroutine switch dimension array from ordered dimension ('x','y','z','t')
-   !> to unordered dimension. <br/>
+   !> to disordered dimension. <br/>
    !> @details
    !> Example: (/'x','y','z','t'/) => (/'z','x','t','y'/)<br/>
@@ -822,5 +838,5 @@
    !> @param[inout] td_dim array of dimension structure
    !-------------------------------------------------------------------
-   SUBROUTINE dim_unorder(td_dim)
+   SUBROUTINE dim_disorder(td_dim)
       IMPLICIT NONE
       ! Argument      
@@ -835,5 +851,5 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM UNORDER: invalid dimension of array dimension.")
+         CALL logger_error("DIM DISORDER: invalid dimension of array dimension.")
       ELSE      
          ! add dummy xyzt2 id to unused dimension
@@ -868,5 +884,5 @@
       ENDIF
 
-   END SUBROUTINE dim_unorder
+   END SUBROUTINE dim_disorder
    !-------------------------------------------------------------------
    !> @brief This function reshape real(8) 4D array   
@@ -908,5 +924,6 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM RESHAPE 2 XYZT: invalid dimension of array dimension.")
+         CALL logger_error("DIM RESHAPE 2 XYZT: invalid dimension of "//&
+            &  "array dimension.")
       ELSE      
 
@@ -914,6 +931,6 @@
 
             CALL logger_fatal( &
-            &  "  DIM RESHAPE 2 XYZT: you should have run dim_reorder &
-            &     before running RESHAPE" )
+            &  "  DIM RESHAPE 2 XYZT: you should have run dim_reorder"// &
+            &  "   before running RESHAPE" )
 
          ENDIF
@@ -972,5 +989,5 @@
    !-------------------------------------------------------------------
    !> @brief This function reshape ordered real(8) 4D array with dimension 
-   !> (/'x','y','z','t'/) to an "unordered" array.<br/>
+   !> (/'x','y','z','t'/) to an "disordered" array.<br/>
    !> @details
    !> Example: (/'x','y','z','t'/) => (/'z','x','t','y'/)
@@ -1009,5 +1026,6 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM RESHAPE XYZT 2: invalid dimension of array dimension.")
+         CALL logger_error("DIM RESHAPE XYZT 2: invalid dimension of "//&
+            &  "array dimension.")
       ELSE
 
@@ -1015,6 +1033,6 @@
 
             CALL logger_fatal( &
-            &  "  DIM RESHAPE XYZT 2: you should have run dim_reorder &
-            &     before running RESHAPE" )
+            &  "  DIM RESHAPE XYZT 2: you should have run dim_reorder"// &
+            &  "   before running RESHAPE" )
 
          ENDIF        
@@ -1104,6 +1122,6 @@
 
             CALL logger_error( &
-            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder &
-            &     before running REORDER" )
+            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder"//&
+            &  "   before running REORDER" )
 
          ENDIF        
@@ -1116,5 +1134,5 @@
    END FUNCTION dim__reorder_2xyzt_i4
    !-------------------------------------------------------------------
-   !> @brief This function unordered integer(4) 1D array to be suitable with
+   !> @brief This function disordered integer(4) 1D array to be suitable with
    !> initial dimension order (ex: dimension read in file).
    !> @note you must have run dim_reorder before use this subroutine
@@ -1143,12 +1161,12 @@
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
       &   SIZE(id_arr(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM REORDER XYZT 2: invalid dimension of array dimension"//&
-         &              " or of array of value.")
+         CALL logger_error("DIM REORDER XYZT 2: invalid dimension of "//&
+            &  "array dimension or of array of value.")
       ELSE      
          IF( ANY(td_dim(:)%i_xyzt2==0) )THEN
 
             CALL logger_error( &
-            &  "  DIM REORDER XYZT 2: you should have run dim_reorder &
-            &     before running REORDER" )
+            &  "  DIM REORDER XYZT 2: you should have run dim_reorder"// &
+            &  "   before running REORDER" )
 
          ENDIF        
@@ -1166,5 +1184,5 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013 - Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_dim array of dimension structure
@@ -1193,6 +1211,6 @@
 
             CALL logger_error( &
-            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder &
-            &     before running REORDER" )
+            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder"// &
+            &  "   before running REORDER" )
 
          ENDIF        
@@ -1205,5 +1223,5 @@
    END FUNCTION dim__reorder_2xyzt_l
    !-------------------------------------------------------------------
-   !> @brief This function unordered logical 1D array to be suitable with
+   !> @brief This function disordered logical 1D array to be suitable with
    !> initial dimension order (ex: dimension read in file).
    !> @note you must have run dim_reorder before use this subroutine
@@ -1238,6 +1256,6 @@
 
             CALL logger_error( &
-            &  "  DIM REORDER XYZT 2: you should have run dim_reorder &
-            &     before running REORDER" )
+            &  "  DIM REORDER XYZT 2: you should have run dim_reorder"//&
+            &  "  before running REORDER" )
 
          ENDIF        
@@ -1294,10 +1312,10 @@
    END FUNCTION dim__reorder_2xyzt_c
    !-------------------------------------------------------------------
-   !> @brief This function unordered string 1D array to be suitable with
+   !> @brief This function disordered string 1D array to be suitable with
    !> initial dimension order (ex: dimension read in file).
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> @date Nov, 2013 - Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_dim array of dimension structure
@@ -1326,6 +1344,6 @@
          IF( ANY(td_dim(:)%i_xyzt2==0) )THEN
             CALL logger_error( &
-            &  "  DIM REORDER XYZT 2: you should have run dim_reorder &
-            &     before running REORDER" )
+            &  "  DIM REORDER XYZT 2: you should have run dim_reorder"// &
+            &  "   before running REORDER" )
 
          ENDIF        
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/1_install.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/1_install.md	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/1_install.md	(revision 9987)
@@ -13,13 +13,20 @@
 # Fortran Compiler
    SIREN codes were succesfully tested with :
-   - ifort (version 12.0.4)
-   - gfortran (version 4.7.2 20121109)
+   - ifort (version 15.0.1)
+   - gfortran (version 4.8.2 20140120) 
 <!--   - pgf95 (version 13.9-0) -->
 
- <HR>
-   <b>
-   - @ref index
-   - @ref md_docsrc_3_codingRules
-   - @ref md_docsrc_4_changeLog
-   - @ref todo
-   </b>
+# Fortran Compiler #
+SIREN codes were succesfully tested with :
+  - ifort (version 15.0.1)
+  - gfortran (version 4.8.2 20140120) 
+
+<HR>
+  <b>
+  - @ref index
+  - @ref md_src_docsrc_2_quickstart
+  - @ref md_src_docsrc_3_support_bug
+  - @ref md_src_docsrc_4_codingRules
+  - @ref md_src_docsrc_5_changeLog
+  - @ref todo
+  </b>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/2_quickstart.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/2_quickstart.md	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/2_quickstart.md	(revision 9987)
@@ -0,0 +1,598 @@
+# How To Use (Quick Start)
+
+@tableofcontents
+
+SIREN is a software to set up regional configuration with
+ [NEMO](http://www.nemo-ocean.eu).<br/> 
+Actually SIREN creates all the input files you need to run a NEMO regional configuration.<br/>
+ 
+SIREN is composed of a set of 5 Fortran programs :
+<ul>
+ <li>create_coord.f90 to create regional grid coordinates.</li>
+ <li>create_bathy.f90 to create regional grid bathymetry.</li>
+ <li>merge_bathy.f90 to merge regional grid bathymetry with wider grid bathymetry
+ at boundaries. 
+ @note the goal of this step is to avoid break in Bathymetry.
+ This break may cause inconsistency between forcing fields  at boundary and regional fields.
+ </li>
+ <li>create_restart.f90 to create initial state file from coarse grid restart
+ or standard outputs.
+ @note this program could also be used to refined other input fields from a wider
+ configuations (as runoff, chlorophyll etc...)
+ </li>
+ <li>create_boundary.F90 to create boundaries conditions from wider configurations
+ output fields.
+ </li>
+</ul>
+
+@warning SIREN can not:
+<ul>
+<li>create global configuration.</li>
+<li>create configuarion around or close to North pole.</li>
+<li>change number of vertical level.</li>
+</ul>
+
+Here after we briefly describe how to use each programs,
+and so how to create your own regional configuration.
+@note As demonstrator for a first start a set of GLORYS files (global reanalysis on *ORCA025* grid), as well as examples of namelists are available [here](https://cloud.mercator-ocean.fr/public.php?service=files&t=877fb1b6e4f589340fc0df1ea6a53228).
+
+<!-- ######################################################################  -->
+# Create coordinates file # {#coord}
+
+To create your own configuration, you first have to create a coordinates file on your domain of study.<br/>
+SIREN allows you to create this coordinates file from a wider coordinates file.<br/>
+The coordinates file created could simply be an extraction, or a refinment of
+the wide grid.<br/>
+
+To create this new cooridnates file, you have to run :
+~~~~~~~~~~~~~~~~~~
+./SIREN/create_coord.exe create_coord.nam
+~~~~~~~~~~~~~~~~~~
+
+Here after is an example of namelist for *create_coord.exe*.<br/>
+In this example, you create a coordinates file named *coord_fine.nc*.<br/>
+This new coordinates file is refined from an extraction of *coordinates_ORCA025.nc*. 
+~~~~~~~~~~~
+&namlog
+/
+
+&namcfg
+   cn_varcfg = "PATH/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0 = "PATH/coordinates_ORCA025.nc"
+   in_perio0 = 4
+/
+
+&namvar
+/
+
+&namnst
+   in_imin0 = 1070
+   in_imax0 = 1072
+   in_jmin0 = 607
+   in_jmax0 = 609
+
+   in_rhoi = 2
+   in_rhoj = 3
+/
+
+&namout
+   cn_fileout = "PATH/coord_fine.nc"
+/
+~~~~~~~~~~~
+
+Let's get describe this namelist.<br/>
+First we have the **namlog** sub-namelist. This sub-namelist set parameters of the log
+file.<br/>
+All the parameters of this sub-namelist have default value, so you could let it
+empty, as done here.<br/> This will create a log file named *create_coord.log*
+
+The **namcfg** sub-namelist defines where found SIREN configuration file.<br/>
+This configuration file defines standard name, default interpolation method,
+axis,... to be used for some known variables.<br/>
+Obviously, you could add other variables to those already list, in this file.
+
+@note You could find the generic version of *variable.cfg* in the directory *NEMOGCM/TOOLS/SIREN/cfg*.
+
+The **namcrs** sub-namelist set parameters of the wide
+coordinates file,<br/> as path to find it, and NEMO periodicity of the wide grid.<br/>
+
+@note the NEMO periodicity could be choose between 0 to 6:
+<dl>
+<dt>in_perio=0</dt>
+<dd>standard regional model</dd>
+<dt>in_perio=1</dt>
+<dd>east-west cyclic model</dd>
+<dt>in_perio=2</dt>
+<dd>model with symmetric boundary condition across the equator</dd>
+<dt>in_perio=3</dt>
+<dd>regional model with North fold boundary and T-point pivot</dd>
+<dt>in_perio=4</dt>
+<dd>global model with a T-point pivot.<br/>
+example: ORCA2, ORCA025, ORCA12</dd>
+<dt>in_perio=5</dt>
+<dd>regional model with North fold boundary and F-point pivot</dd>
+<dt>in_perio=6</dt>
+<dd>global model with a F-point pivot<br/>
+example: ORCA05</dd>
+</dl>
+@sa For more information see @ref md_src_docsrc_6_perio
+</dd>
+</dl>
+
+The **namvar** sub-namelist lists variables to be used.<br/>
+By default all the variables of the wider coordinates file are used to create
+the new coordinates file.<br/> 
+The interpolation methods to be used are defined in the configuration variables file (see
+below). So you do not need to fill this sub-namelist too.
+
+The **namnst** sub-namelist defines the subdomain to be used as well as refinment factor.<br/>
+@note Subdomain is defined by indices of the coarse/wide grid.<br/>
+
+<ul>
+<li>you can select area quite every where (excepted too close from the North
+pole), and use the refinment factor you want.</li>
+
+~~~~~~~~~~~
+&namvar
+   in_imin0 = 1070
+   in_imax0 = 1072
+   in_jmin0 = 607
+   in_jmax0 = 609
+
+   in_rhoi = 2
+   in_rhoj = 3
+/
+~~~~~~~~~~~
+@image html grid_zoom_60.png
+@image latex grid_zoom_40.png
+<!-- @note ghost cells all around the grid are not shown here. -->
+
+<li>you can select area crossing the east-west overlap of the global ORCA grid.</li>
+
+~~~~~~~~~~~
+&namvar          
+   in_imin0 = 1402 
+   in_imax0 = 62
+   in_jmin0 = 490 
+   in_jmax0 = 570 
+
+   in_rhoi = 5
+   in_rhoj = 5 
+/                
+~~~~~~~~~~~
+@image html grid_glob_over_30.png
+@image latex grid_glob_over_20.png
+<!-- @note in blue, the east-west overlap band of ORCA grid. -->
+
+<li>you can select east-west cyclic area.</li>
+
+~~~~~~~~~~~
+&namvar
+   in_imin0 = 0
+   in_imax0 = 0
+   in_jmin0 = 390
+   in_jmax0 = 450
+
+   in_rhoi = 1
+   in_rhoj = 1
+/
+~~~~~~~~~~~
+@image html grid_glob_band_30.png
+@image latex grid_glob_band_20.png
+
+</ul>
+
+Finally the **namout** sub-namelist defines the output file.<br/>
+
+@note All the output files created by SIREN include information about NEMO
+periodicity, as well as source file, indices and refinment used.
+
+@sa For more information about how to create coordinates, see create_coord.f90
+
+<!-- ######################################################################  -->
+# Create bathymetry file # {#bathy}
+
+Then you need a Bathymetry file.<br/>
+SIREN allows you to create a Bathymetry extracted or refined from a wider
+Bathymetry grid.<br/>
+
+To create this new bathymetry, you have to run :
+~~~~~~~~~~~~~~~~~~
+./SIREN/create_bathy.exe create_bathy.nam
+~~~~~~~~~~~~~~~~~~
+
+Here after is an example of namelist for *create_bathy.exe*.<br/>
+In this example, you create a bathymetry file named *bathy_fine.nc*.<br/>
+This new bathymetry file is refined from an extraction of *bathy_meter_ORCA025.nc*.<br/>
+Moreover a minimum value of 5m is imposed to the output Bathymetry.
+~~~~~~~~~~~~~~~~~~
+&namlog
+/
+
+&namcfg
+   cn_varcfg = "PATH/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0 = "PATH/coordinates_ORCA025.nc"
+   in_perio0 = 4
+/
+
+&namfin
+   cn_coord1 = "PATH/coord_fine.nc"
+/
+
+&namvar
+   cn_varfile = "Bathymetry:PATH/bathy_meter_ORCA025.nc"
+   cn_varinfo = "Bathymetry: min=5"
+/
+
+&namnst
+   in_rhoi = 2
+   in_rhoj = 3
+/
+
+&namout
+   cn_fileout = "PATH/bathy_fine.nc"      
+/
+~~~~~~~~~~~~~~~~~~
+
+Let's get describe this namelist.<br/>
+
+First as previously, we have the **namlog** and **namcfg** sub-namelist (see above for more
+explanation).<br/>
+
+Then the **namcrs** sub-namelist set parameters of the wide
+coordinates file.<br/>
+@note in all SIREN namelist: <br/>
+0 referred to the coarse/wide grid.<br/>
+1 referred to the fine grid.
+
+In the same way, the **namfin** sub-namelist  set parameters of the fine
+coordinates file.<br/>
+@note in this namelist example, there is no need to set the variable *in_perio1* to define the NEMO
+periodicity of the fine grid.<br/> Indeed, if this variable is not inform, SIREN tries to read it in the attributes of the file.<br/> 
+So if you created the fine coordinates with SIREN, you do not have to
+fill it. In other case, you should add it to the namelist.
+
+The **namvar** sub-namelist lists variables to be used:
+<dl>
+   <dt>cn_varfile</dt>
+      <dd> defines the variable name ("Bathymetry" here) and the input file associated with.
+            @warning The domain of the input Bathymetry have to be larger than the output domain.
+         @note 
+         <ul>
+            <li>if the input file is at coarse grid resolution (same than *cn_coord0*), the ouptut Bathymetry will be refined on fine grid.</li>
+            <li>if the input file is a wider bathymetry (already at fine grid resolution), the output Bathymetry will be extracted from this one.</li>
+         </ul>
+      </dd>
+   <dt>cn_varinfo</dt>
+      <dd> defines user's requests for a variable.
+         @note Default interpolation method for the Bathymetry, is *cubic* interpolation.<br/>
+         So you may want to specify a minimum value to avoid negative value, or to change interpolation method.<br/>
+         example: <ul><li>cn_varinfo="Bathymetry: min=1"'</li>
+                      <li>cn_varinfo="Bathymetry: int=linear"</li></ul>
+      </dd>
+</dl>
+
+The **namnst** sub-namelist defines the subdomain refinment factor.<br/>
+Of course those refinment factors have to be convenient with refinment
+from coarse grid *cn_coord0* to fine grid *cn_coord1*.
+@note subdomain indices are automatically deduced from fine and coarse grid
+coordinates.
+
+Finally, this **namout** sub-namelist defines the output file.<br/>
+
+@note All the output files create by SIREN include information about 
+source file, indices, refinment and interpolation method used.
+
+@sa For more information about how to create bathymetry, see
+create_bathy.f90
+
+<!-- ######################################################################  -->
+# Merge bathymetry file # {#merge}
+
+The Bathymetry you build differs from the wider one.<br/>
+To avoid issue with boundaries forcing fields, you should merge fine and coarse Bathymetry on boundaries.<br/>
+SIREN allows you to do this.<br/>
+
+To create this merged bathymetry, you have to run :
+~~~~~~~~~~~~~~~~~~
+./SIREN/merge_bathy.exe merge_bathy.nam
+~~~~~~~~~~~~~~~~~~
+
+Here after is an example of namelist for *merge_bathy.exe*.<br/>
+~~~~~~~~~~~~~~~~~~
+&namlog
+/
+
+&namcfg
+   cn_varcfg = "PATH/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg"
+/
+
+&namcrs
+   cn_bathy0 = "PATH/bathy_meter_ORCA025.nc"
+   in_perio0 = 4
+/
+
+&namfin
+   cn_bathy1 = "PATH/bathy_fine.nc"
+/
+
+&namnst
+   in_rhoi = 3
+   in_rhoj = 3
+/
+
+&nambdy
+/
+
+&namout
+   cn_fileout = "PATH/bathy_merged.nc"      
+/
+~~~~~~~~~~~~~~~~~~
+In this namelist, you find again the **namlog**, **namcfg** describe above.
+
+Then the **namcrs** sub-namelist sets parameters of the wider grid.
+However this time, this is the coarse/wide grid Bathymetry wich have to be informed.
+
+The **namfin** sub-namelist defines parameters of the fine grid Bathymetry.
+@note here again you could add the *in_perio1* parameter if need be i.e. if your
+fine grid Bathymetry was not created by SIREN.
+
+The **namnst** sub-namelist defines the subdomain refinment factor.
+
+
+The **nambdy** sub-namelist defines the subdomain boundaries.<br/>
+By default SIREN tries to create boundaries for each side. Boundary exist if there is at least one sea point on the second row of each side.<br/>
+So you could let this namelist empty.
+
+@sa For more information about boundaries, see @ref boundary
+
+Finally, this **namout** sub-namelist defines the output file.<br/>
+
+@sa For more information about how to merge bathymetry, see
+merge_bathy.f90
+
+<!-- ######################################################################  -->
+# Create initial state # {#restart}
+
+To run your configuration you need an inital state of the ocean.<br/>
+You could start from a restart file (with all NEMO variables fields at one
+time step). Or you could start from "partial" information about ocean state (Temperature and Salinity for example).
+
+Siren allows you to create both of those initial state.<br/>
+To create the initial state, you have to run:<br/>
+~~~~~~~~~~~~~~~~~~
+./SIREN/create_restart.exe create_restart.nam
+~~~~~~~~~~~~~~~~~~
+
+Here after is an example of namelist for *create_restart.exe*.<br/>
+In this example, you create an initial state split on 81 "processors", and named restar_out.nc.<br/>
+The initial state is composed of temperature and salinity refined from an extraction of GLORYS fields.
+~~~~~~~~~~~~~~~~~~
+&namlog
+/
+
+&namcfg
+   cn_varcfg = "PATH/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0 = "PATH/coordinates_ORCA025.nc"
+   in_perio0 = 4
+/
+
+&namfin
+   cn_coord1 = "PATH/coord_fine.nc"
+   cn_bathy1 = "PATH/bathy_merged.nc"
+/
+
+&namzgr
+/
+
+&namzps
+/
+
+&namvar
+   cn_varfile = "votemper:GLORYS_gridT.nc",
+                "vosaline:GLORYS_gridS.nc"
+/
+
+&namnst
+   in_rhoi = 3
+   in_rhoj = 3
+/
+
+&namout
+   cn_fileout = "PATH/restart_out.nc"      
+   in_nproc = 81
+/
+~~~~~~~~~~~~~~~~~~
+Let's get describe this namelist more accurately.<br/>
+
+As previously, we have the **namlog** and **namcfg** sub-namelists, as well as 
+the **namcrs** sub-namelist to set parameters of the wide coordinates file (see above for more
+explanation).<br/>
+
+Then the **namfin** sub-namelist set parameters of the fine
+grid coordinates and bathymetry.<br/>
+
+The **namzgr** and **namzps** sub-namelists define respectively parameters for vertical grid
+and partial step.<br>
+By default, those parameters are defined the same way than in GLORYS (i.e. 75 vertical levels).<br/>
+So you could let it empty.
+@note If you use forcing fields other than GLORYS, you have to be sure it uses the same vertical grid. In other case, you need to get information about the parametrisation use, and to put it in those sub-namelist (see create_restart.f90).
+
+the **namvar** sub-namelist lists variables to be used.<br/>
+Here we use *votemper* (temperature) get from *GLORYS_gridT.nc* file, and *vosaline*
+(salinity) get from *GLORYS_gridS.nc* file.
+@note To get all variables of a restart file. You have to use:
+~~~~~~~~~~~~~~~~~~
+cn_varfile = "all:PATH/restart.dimg"
+~~~~~~~~~~~~~~~~~~
+
+The **namnst** sub-namelist defines the subdomain refinment factor, as seen previously.<br/>
+
+Finally, this **namout** sub-namelist defines the output files.<br/>
+Here we ask for output on 81 processors, with *restart_out.nc* as file "basename".<br/>
+So SIREN computes the optimal layout for 81 porcessors
+available,<br/>
+and split restart on output files named *restart_out_num.nc*, where *num* is the porc number.
+
+@note SIREN could also create the other fields you may need for
+your configuration.<br/>
+To do so, you just have to run *create_restart.exe* with other variable(s) from other input file(s).<br/>
+For example, to get runoff fields, you could use:
+~~~~~~~~~~~~~~~~~~
+cn_varfile = "sorunoff:PATH/runoff_GLORYS.nc"
+...
+cn_fileout = "PATH/runoff_out.nc"
+~~~~~~~~~~~~~~~~~~
+
+@sa For more information about how to create initial state or other fields, see
+create_restart.f90
+
+<!-- ######################################################################  -->
+# Create boundaries conditions # {#boundary}
+
+Finally to force your configuration, you may need boundaries conditions.<br/>
+NEMO read physical boundaries conditions from temperature, salinity, currents, and sea
+surface height.
+
+To create the boundaries condition with SIREN, you have to run:<br/>
+~~~~~~~~~~~~~~~~~~
+./SIREN/create_boundary.exe create_boundary.nam
+~~~~~~~~~~~~~~~~~~
+
+Here after is an example of namelist for *create_boundary.exe*.<br/>
+In this example, you create boundaries conditions named *boundary_out.nc* on
+each side of the domain.<br/>
+The boundaries contain information about temperature, salinity, currents and sea surface height refined from an extraction of GLORYS fields.
+~~~~~~~~~~~~~~~~~~
+&namlog
+/
+
+&namcfg
+   cn_varcfg = "PATH/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0 = "PATH/coordinates_ORCA025.nc"
+   in_perio0 = 4
+/
+
+&namfin
+   cn_coord1 = "PATH/coord_fine.nc"
+   cn_bathy1 = "PATH/bathy_fine.nc"
+/
+
+&namzgr
+/
+
+&namzps
+/
+
+&namvar
+   cn_varfile="votemper:GLORYS_gridT.nc",
+              "vosaline:GLORYS_gridS.nc",
+              "vozocrtx:GLORYS_gridU.nc",
+              "vomecrty:GLORYS_gridV.nc",
+              "sossheig:GLORYS_grid2D.nc"
+/
+
+&namnst
+   in_rhoi = 3
+   in_rhoj = 3
+/
+
+&nambdy
+/
+
+&namout
+   cn_fileout = "PATH/boundary_out.nc"      
+/
+~~~~~~~~~~~~~~~~~~
+
+Let's get describe this namelist more accurately.<br/>
+
+As previously, we have the **namlog** and **namcfg** sub-namelists, as well as 
+the **namcrs** sub-namelist to set parameters of the wide coordinates file (see above for more
+explanation).<br/>
+
+Then the **namfin** sub-namelist set parameters of the fine
+grid coordinates and bathymetry.<br/>
+
+The **namzgr** and **namzps** sub-namelists define respectively parameters for vertical grid
+and partial step.<br>
+By default, those parameters are defined the same way than in GLORYS (i.e. 75 vertical levels).<br/>
+So you could let it empty.
+@note If you use forcing fields other than GLORYS, you have to be sure it uses the same vertical grid. In other case, you need to get information about the parametrisation use, and to put it in those sub-namelist (see create_boundary.F90).
+
+the **namvar** sub-namelist lists variables to be used.<br/>
+Here we get *votemper* (temperature) from *GLORYS_gridT.nc* file, *vosaline*
+(salinity) from *GLORYS_gridS.nc* file, *vozocrtx* (zonal velocity) from
+*GLORYS_gridU.nc*, *vomecrty* (meridional velocity) from *GLORYS_gridV.nc*, and sossheig (sea surface
+height) from *GLORYS_grid2D.nc*.
+
+The **namnst** sub-namelist defines the subdomain refinment factor.<br/>
+
+The **nambdy** sub-namelist defines the subdomain boundaries.<br/>
+By default SIREN tries to create boundaries for each side (Boundary is created if sea point exist on the second row of each side).<br/>
+So you could let this namelist empty.
+
+@note SIREN allows you to place boundaries away from the side of the domain.
+To do so you have to define your boundary.<br/>
+That means you have to give on fine
+grid the index of the boundary (how far from the border your boundary is),
+the width of your boundary, and finally first and last point of your boundary (the length of your boundary).<br/>
+So to define a north boundary, you have to add in the sub-namelist *nambdy*, the parameter:
+~~~~~~~~~~~~~~~~~~
+cn_north="index,first:last(width)"
+~~~~~~~~~~~~~~~~~~
+
+Finally, this **namout** sub-namelist defines the output files.<br/>
+Here we ask for output with *boundary_out.nc* as file "basename".<br/>
+So SIREN creates output files named *boundary_out_west.nc*,
+*boundary_out_east.nc*, *boundary_out_north.nc*, and *boundary_out_south.nc*
+depending if boundary exist or not.
+
+@sa For more information about how to create boundaries condition, see
+create_boundary.F90
+
+# Create and run NEMO configuration # {#NEMOconf}
+
+So now you created all the input files you need for your physical configuration, you have to create the "NEMO configuration".<br/>
+To do so, go to the directory *NEMOGCM/CONFIG/*, and run:
+~~~~~~~~~~~~~~~~~~
+./makenemo -n MY_CONFIG -d "OPA_SRC"
+~~~~~~~~~~~~~~~~~~
+This creates your configuration "MY_CONFIG" in the directory *NEMOGCM/CONFIG*.<br/>
+you could check the cpp_keys used in file *cpp_MY_CONFIG.fcm*, and re-run *makenemo*
+if need be.
+
+Once *makenemo* has run successfully, the *opa* executable is available in
+directory *NEMOGCM/CONFIG/MY_CONFIG/EXP00*.<br/>
+Then you just have to put all your input files in this directory, fill the namelist *namelist_cfg*, and run:
+~~~~~~~~~~~~~~~~~~
+mpirun ./opa
+~~~~~~~~~~~~~~~~~~
+
+@note no surface forcing here.
+weighted function needed to do interpolation on the fly, could be created by WEIGHT tools already inside NEMO.
+
+@sa For more information about how to create NEMO configuration see [NEMO Quick Start Guide](http://www.nemo-ocean.eu/Using-NEMO/User-Guides/Basics/NEMO-Quick-Start-Guide).
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_src_docsrc_1_install
+   - @ref md_src_docsrc_2_quickstart
+   - @ref md_src_docsrc_3_support_bug
+   - @ref md_src_docsrc_4_codingRules
+   - @ref md_src_docsrc_5_changeLog
+   - @ref todo
+   </b>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/3_codingRules.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/3_codingRules.md	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/3_codingRules.md	(revision 9987)
@@ -80,5 +80,5 @@
 
 # Implicit none {#implicit}
-All subroutines and functions will include an IMPLICTI NONE statement.
+All subroutines and functions will include an IMPLICIT NONE statement.
 
 # Header {#header}
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/3_support_bug.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/3_support_bug.md	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/3_support_bug.md	(revision 9987)
@@ -0,0 +1,28 @@
+# Support
+
+# How to get support
+  If you have questions regarding the use of SIREN, please have a look at the [NEMO configuration manager forum](https://forge.ipsl.jussieu.fr/nemo/discussion/forum/2).<br/>
+  If you don't find an answer in the archives, feel free to register and post your question.
+
+# How to Help
+   The development of SIREN highly depends on your input!<br/>
+   If you are trying SIREN let me know what you think of it (do you miss certain features?). Even if you decide not to use it, please let me know why.
+
+# How to report a bug
+   If you believe you have found a new bug, please report it.<br/>
+   Before submitting a new bug, first search through the database if the same bug has already been submitted by others
+
+   If you send only a (vague) description of a bug, you are usually not very
+   helpful and it will cost much more time to figure out what you mean. In
+   the worst-case your bug report may even be completely ignored.
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_src_docsrc_1_install
+   - @ref md_src_docsrc_2_quickstart
+   - @ref md_src_docsrc_3_support_bug
+   - @ref md_src_docsrc_4_codingRules
+   - @ref md_src_docsrc_5_changeLog
+   - @ref todo
+   </b>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/4_codingRules.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/4_codingRules.md	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/4_codingRules.md	(revision 9987)
@@ -0,0 +1,100 @@
+# Coding Rules
+
+The conventions used in SIREN coding are based on the NEMO coding rules
+(see [NEMO coding
+conventions](http://www.nemo-ocean.eu/content/download/15483/73221/file/NEMO_coding.conv_v3.pdf)).<br/>
+However some modifications were added to improve readibility of the code.<br/>
+Some of the NEMO coding rules are reminded here, and extensions are described.
+
+@tableofcontents
+
+# Fortran Standard {#std}
+
+SIREN software adhere to strict __FORTRAN 95__ standard.<br/>
+There is only one exception. The use of functions _COMMAND_ARGUMENT_COUNT_ and
+_GET_COMMAND_ARGUMENT_.<br/>
+There exist no equivalent for those Fortran 03 intrinsec functions in Fortran
+95.<br/> At least none convenient for compilers tested (see @ref md_src_docsrc_1_install). 
+
+#  Free Form Source {#free}
+Free Form Source will be used, however a self imposed limit of 80 should
+enhance readibility.
+
+#  Indentation {#indent}
+Code as well as comments lines will be indented 3 characters for readibility.<br/>
+__Indentation should be write without hard tabs__.
+
+Example for vi  :
+~~~~~~~~~~~~~~~~~~~~~
+:set expandtab tabstop=3 shiftwidth=3
+~~~~~~~~~~~~~~~~~~~~~
+
+#  Naming conventions : variable {#namvar}
+All variables should be named as explicitly as possible.<br/>
+The naming conventions concerns prefix letters of these name, in order to
+identify the variable type and status.<br/> It must be composed of two
+letters defining type and status follow by an underscore.<br/>
+table below list the starting letters to be used for variable naming,
+depending on their type and status.
+
+ | Type / Status     | byte (integer(1)) <br/> __b__ | short (integer(2)) <br/> __s__ | integer(4) <br/> __i__  | integer(8) <br/> __k__ | real(4) <br/> __r__ | real(8) <br/> __d__ | logical <br/> __l__ | character <br/> __c__ | complex <br/> __y__ | structure <br/> __t__  |
+ | :----:            | :----: | :----: | :----: | :----: | :----: | :----: | :----: | :----: | :----: | :----: |
+ |global <br/> __g__           | bg_  | sg_  | ig_  | kg_  | rg_  | dg_  | lg_  | cg_  | yg_  | tg_  |
+ |global parameter <br/> __p__ | bp_  | sp_  | ip_  | kp_  | rp_  | dp_  | lp_  | cp_  | yp_  | tp_  |
+ |module <br/> __m__           | bm_  | sm_  | im_  | km_  | rm_  | dm_  | lm_  | cm_  | ym_  | tm_  |
+ |namelist <br/> __n__         | bn_  | sn_  | in_  | kn_  | rn_  | dn_  | ln_  | cn_  | yn_  | tn_  |
+ |dummy argument <br/> __d__   | bd_  | sd_  | id_  | kd_  | rd_  | dd_  | ld_  | cd_  | yd_  | td_  |
+ |local <br/> __l__            | bl_  | sl_  | il_  | kl_  | rl_  | dl_  | ll_  | cl_  | yl_  | tl_  |
+ |loop control       |      |      | j?   |      |      |      |      |      |      |      |
+
+# Naming conventions : structure {#namstr}
+The structure name should be written in capital letter, and start with
+__T__<br/> Example: TTRACER <br/>
+Variables inside the structure should be named as explicitly as possible.<br/>
+For those variables, the prefix naming conventions only concern the type of variable.<br/>
+It must be composed of one letter defining type follows by an
+underscore.<br/>
+see table of variable conventions.<br/>
+
+Example: __tl\_type\%i\_year__<br/> _year_ is an integer(4) variable in a local strucure
+named _type_. <br/>
+
+# Naming conventions : function-subroutine {#namsub}
+Functions or Subroutines are defined in a module.<br/>
+Their name should start with the module name then with their "functional" name. So it will be
+easy to find it.<br/>
+Example:<br/> a function to realise addition written in a module
+__math__ should be called __math\_add__.<br/>
+
+__PUBLIC__  function or subroutine should used one undescrore: _math_add_<br/>
+__PRIVATE__ function or subroutine should used two undescrores: _math__add_<br/>
+
+# Precision {#precision}
+__All variables should make use of kinds__.<br/>
+Numerical constant need to have a suffix of __kindvalue__
+
+# Declaration for global variable and constants {#global}
+All global data must be accompanied with a comment field on the same
+line.<br/>
+_Note that using doxygen (see [header](#header)), we will use symbol !< instead of !: as separator_
+
+# Implicit none {#implicit}
+All subroutines and functions will include an IMPLICIT NONE statement.
+
+# Header {#header}
+
+SIREN use __doxigen auto documentation__ tool.<br/>
+Information could be find on
+[doxygen](http://www.stack.nl/~dimitri/doxygen/index.html) web page.<br/>
+Some basic tag are described
+[here](http://www.msg.chem.iastate.edu/gamess/DoxygenRules.oct10.pdf).
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_src_docsrc_1_install
+   - @ref md_src_docsrc_2_quickstart
+   - @ref md_src_docsrc_3_support_bug
+   - @ref md_src_docsrc_5_changeLog
+   - @ref todo
+   </b>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/5_changeLog.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/5_changeLog.md	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/5_changeLog.md	(revision 9987)
@@ -0,0 +1,20 @@
+# Change log
+
+@tableofcontents
+
+# Release
+Initial release (2016-04-11)
+
+## Changes
+## New Features
+## Bug fixes
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_src_docsrc_1_install
+   - @ref md_src_docsrc_2_quickstart
+   - @ref md_src_docsrc_3_support_bug
+   - @ref md_src_docsrc_4_codingRules
+   - @ref todo
+   </b>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/6_perio.md
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/6_perio.md	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/6_perio.md	(revision 9987)
@@ -0,0 +1,63 @@
+# NEMO periodicity
+
+NEMO periodicity is defined as follow :<br/> 
+<dl>
+<dt>closed boundary (in_perio=0)</dt>
+<dd>ghost cells (solid walls) are imposed at all model boundaries.</dd> 
+@image html perio0_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio0_20.png}
+\end{center}
+@endlatexonly
+<dt>cyclic east-west boundary (in_perio=1)</dt>
+<dd>first and last rows are closed, whilst the first column is set to the value of the last-but-one column and the last column to the value of the second one.</dd>  
+@image html perio1_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio1_20.png}
+\end{center}
+@endlatexonly
+<dt>symmetric boundary condition across the equator. (in_perio=2)</dt>
+<dd>last row, and first and last columns are closed. </dd> 
+@image html perio2_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio2_20.png}
+\end{center}
+@endlatexonly
+<dt>North fold boundary with a T -point pivot (in_perio=3)</dt>
+<dd>first row, and first and last columns are closed. </dd> 
+@image html perio3_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio3_20.png}
+\end{center}
+@endlatexonly
+<dt>North fold boundary with a T -point pivot and cyclic east-west boundary (in_perio=4)</dt>
+<dd>first row is closed. The first column is set to the value of the last-but-one column and the last column to the value of the second one. </dd> 
+@image html perio4_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio4_20.png}
+\end{center}
+@endlatexonly
+<dt>North fold boundary with a F -point pivot (in_perio=5)</dt>
+<dd>first row, and first and last columns are closed. </dd> 
+@image html perio5_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio5_20.png}
+\end{center}
+@endlatexonly
+<dt>North fold boundary with a F -point pivot and cyclic east-west boundary (in_perio=6)</dt>
+<dd>first row is closed. The first column is set to the value of the last-but-one column and the last column to the value of the second one.</dd> 
+@image html perio6_20.png 
+@image html perio5_20.png 
+@latexonly
+\begin{center}
+\includegraphics{perio6_20.png}
+\end{center}
+@endlatexonly
+</dl>
+@sa For more information about NEMO periodicity, see _Model Boundary Condition_ chapter in [NEMO documentation](http://www.nemo-ocean.eu/About-NEMO/Reference-manuals))
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/main.dox
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/main.dox	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/docsrc/main.dox	(revision 9987)
@@ -13,29 +13,26 @@
    - create_boundary.f90 to create boundary condition from coarse grid standard outputs.
 
-To install those programs see @ref md_docsrc_1_install.
+ SIREN is a software to set up regional configuration with [NEMO](http://www.nemo-ocean.eu).<br/> 
+ Actually SIREN creates the input files you need to run a NEMO regional configuration.<br/>
+ 
+ SIREN allows you to create your own regional configuration embedded in a wider one.<br/>
 
- @note SIREN can not:
- - create global configuration
- - create configuarion around or close to north pole
- - change number of vertical level
- - change grid (horizontal or vertical)
+ To know how to install SIREN see @ref md_src_docsrc_1_install.
 
- @section howto How to use
-   @subsection howto_coord to create fine grid coordinate file
-   see create_coord.f90
-   @subsection howto_bathy to create fine grid bathymetry
-   see create_bathy.f90
-   @subsection howto_merge to merge fine grid bathymetry
-   see merge_bathy.f90
-   @subsection howto_restart to create initial state file
-   see create_restart.f90
-   @subsection howto_boundary to create boundary condition
-   see create_boundary.f90
+ You could find a tutorial for a quick start with SIREN in @ref md_src_docsrc_2_quickstart.<br/>
+ For more information about how to use each component of SIREN
+ - see create_coord.f90 to create fine grid coordinate file
+ - see create_bathy.f90 to create fine grid bathymetry
+ - see merge_bathy.f90 to merge fine grid bathymetry
+ - see create_restart.f90 to create initial state file, or other fields.
+ - see create_boundary.F90 to create boundary condition
 
 <HR>
    <b>
-   - @ref md_docsrc_1_install
-   - @ref md_docsrc_3_codingRules
-   - @ref md_docsrc_4_changeLog
+   - @ref md_src_docsrc_1_install
+   - @ref md_src_docsrc_2_quickstart
+   - @ref md_src_docsrc_3_support_bug
+   - @ref md_src_docsrc_4_codingRules
+   - @ref md_src_docsrc_5_changeLog
    - @ref todo
    </b>
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/domain.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/domain.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/domain.f90	(revision 9987)
@@ -246,5 +246,5 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_dom dom structure
@@ -294,5 +294,5 @@
    !
    !> @author J.Paul
-   !> - June, 2013- Initial Version
+   !> @date June, 2013 - Initial Version
    !> @date September, 2014
    !> - add boundary index
@@ -362,6 +362,7 @@
 
          IF( td_mpp%i_perio < 0 .OR. td_mpp%i_perio > 6 )THEN
-            CALL logger_error("DOM INIT: invalid grid periodicity. "//&
-            &  "you should use grid_get_perio to compute it")
+            CALL logger_error("DOM INIT: invalid grid periodicity ("//&
+            &  TRIM(fct_str(td_mpp%i_perio))//&
+            &  ") you should use grid_get_perio to compute it")
          ELSE
             dom__init_mpp%i_perio0=td_mpp%i_perio
@@ -424,5 +425,5 @@
    !
    !> @author J.Paul
-   !> - June, 2013- Initial Version
+   !> @date June, 2013 - Initial Version
    !> @date September, 2014
    !> - add boundary index
@@ -489,6 +490,7 @@
 
          IF( td_file%i_perio < 0 .OR. td_file%i_perio > 6 )THEN
-            CALL logger_error("DOM INIT: invalid grid periodicity. "//&
-            &  "you should use grid_get_perio to compute it")
+            CALL logger_error("DOM INIT: invalid grid periodicity ("//&
+            &  TRIM(fct_str(td_file%i_perio))//&
+            &  ") you should use grid_get_perio to compute it")
          ELSE
             dom__init_file%i_perio0=td_file%i_perio
@@ -548,5 +550,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain structure
@@ -653,5 +655,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !> @date September, 2014
    !> - use zero indice to defined cyclic or global domain
@@ -721,5 +723,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial verison
    !
    !> @param[inout] td_dom domain strcuture
@@ -755,5 +757,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -774,5 +776,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -806,5 +808,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -824,5 +826,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -862,5 +864,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -912,5 +914,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -951,5 +953,5 @@
    !>
    !> @author J.Paul
-   !> - April, 2013- Subroutine written
+   !> @date April, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -979,5 +981,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -1041,5 +1043,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -1082,5 +1084,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -1180,5 +1182,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -1292,5 +1294,5 @@
    !>
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !> @date September, 2014
    !> - take into account number of ghost cell
@@ -1433,5 +1435,5 @@
    !
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
@@ -1476,5 +1478,5 @@
    !> 
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !> @date September, 2014
    !> - take into account boundary for one point size domain
@@ -1715,5 +1717,5 @@
    !
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_dom domain strcuture
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/extrap.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/extrap.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/extrap.f90	(revision 9987)
@@ -19,30 +19,19 @@
 !>    defining string character _cn\_varinfo_. By default _dist_weight_.<br/>
 !>    Example:
-!>       - cn_varinfo='varname1:dist_weight', 'varname2:min_error'
+!>       - cn_varinfo='varname1:ext=dist_weight', 'varname2:ext=min_error'
 !>
 !>    to detect point to be extrapolated:<br/>
 !> @code
-!>    il_detect(:,:,:)=extrap_detect(td_var, [td_level], [id_offset,] [id_rho,] [id_ext]) 
+!>    il_detect(:,:,:)=extrap_detect(td_var)
 !> @endcode
 !>       - il_detect(:,:,:) is 3D array of point to be extrapolated
 !>       - td_var  is coarse grid variable to be extrapolated
-!>       - td_level is fine grid array of level (see vgrid_get_level) [optional]
-!>       - id_offset is array of offset between fine and coarse grid [optional]
-!>       - id_rho    is array of refinment factor [optional]
-!>       - id_ext    is array of number of points to be extrapolated [optional]
 !>
 !>    to extrapolate variable:<br/>
 !> @code
-!>    CALL extrap_fill_value( td_var, [td_level], [id_offset], [id_rho], [id_iext], [id_jext], [id_kext], [id_radius], [id_maxiter])
+!>    CALL extrap_fill_value( td_var, [id_radius])
 !> @endcode
 !>       - td_var  is coarse grid variable to be extrapolated
-!>       - td_level is fine grid array of level (see vgrid_get_level) [optional]
-!>       - id_offset is array of offset between fine and coarse grid [optional]
-!>       - id_rho    is array of refinment factor [optional]
-!>       - id_iext   is number of points to be extrapolated in i-direction [optional]
-!>       - id_jext   is number of points to be extrapolated in j-direction [optional]
-!>       - id_kext   is number of points to be extrapolated in k-direction [optional]
 !>       - id_radius is radius of the halo used to compute extrapolation [optional]
-!>       - id_maxiter is maximum number of iteration [optional]
 !>
 !>    to add extraband to the variable (to be extrapolated):<br/>
@@ -62,30 +51,4 @@
 !>       - id_jsize : j-direction size of extra bands [optional]
 !>
-!>    to compute first derivative of 1D array:<br/>
-!> @code
-!>    dl_value(:)=extrap_deriv_1D( dd_value(:), dd_fill, [ld_discont] )
-!> @endcode
-!>       - dd_value is 1D array of variable
-!>       - dd_fill is FillValue of variable
-!>       - ld_discont is logical to take into account longitudinal East-West discontinuity [optional]
-!>
-!>    to compute first derivative of 2D array:<br/>
-!> @code
-!>    dl_value(:,:)=extrap_deriv_2D( dd_value(:,:), dd_fill, cd_dim, [ld_discont] )
-!> @endcode
-!>       - dd_value is 2D array of variable
-!>       - dd_fill is FillValue of variable
-!>       - cd_dim is character to compute derivative on first (I) or second (J) dimension
-!>       - ld_discont is logical to take into account longitudinal East-West discontinuity [optional]
-!>
-!>    to compute first derivative of 3D array:<br/>
-!> @code
-!>    dl_value(:,:,:)=extrap_deriv_3D( dd_value(:,:,:), dd_fill, cd_dim, [ld_discont] )
-!> @endcode
-!>       - dd_value is 3D array of variable
-!>       - dd_fill is FillValue of variable
-!>       - cd_dim is character to compute derivative on first (I), second (J), or third (K) dimension
-!>       - ld_discont is logical to take into account longitudinal East-West discontinuity [optional]
-!>
 !> @warning _FillValue must not be zero (use var_chg_FillValue())
 !>
@@ -93,10 +56,17 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
 !> @date September, 2014
 !> - add header
+!> @date June, 2015
+!> - extrapolate all land points (_FillValue)
+!> - move deriv function to math module
+!> @date July, 2015
+!> - compute extrapolation from north west to south east, 
+!> and from south east to north west
 !>
 !> @todo
 !> - create module for each extrapolation method
+!> - smooth extrapolated points
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -110,4 +80,5 @@
    USE date                            ! date manager
    USE logger                          ! log file manager
+   USE math                            ! mathematical function
    USE att                             ! attribute manager
    USE dim                             ! dimension manager
@@ -118,5 +89,4 @@
 
    ! type and variable
-   PRIVATE :: im_maxiter   !< default maximum number of iteration 
    PRIVATE :: im_minext    !< default minumum number of point to extrapolate
    PRIVATE :: im_mincubic  !< default minumum number of point to extrapolate for cubic interpolation
@@ -127,7 +97,4 @@
    PUBLIC :: extrap_add_extrabands !< add extraband to the variable (to be extrapolated) 
    PUBLIC :: extrap_del_extrabands !< delete extraband of the variable 
-   PUBLIC :: extrap_deriv_1D       !< compute first derivative of 1D array 
-   PUBLIC :: extrap_deriv_2D       !< compute first derivative of 2D array 
-   PUBLIC :: extrap_deriv_3D       !< compute first derivative of 3D array
 
    PRIVATE :: extrap__detect_wrapper      ! detected point to be extrapolated wrapper
@@ -141,5 +108,4 @@
    PRIVATE :: extrap__3D_dist_weight_fill ! 
 
-   INTEGER(i4), PARAMETER :: im_maxiter = 10 !< default maximum number of iteration
    INTEGER(i4), PARAMETER :: im_minext  = 2  !< default minumum number of point to extrapolate
    INTEGER(i4), PARAMETER :: im_mincubic= 4  !< default minumum number of point to extrapolate for cubic interpolation
@@ -171,22 +137,15 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - do not use level to select points to be extrapolated
    !
    !> @param[in] td_var0   coarse grid variable to extrapolate
-   !> @param[in] td_level1 fine grid array of level
-   !> @param[in] id_offset array of offset between fine and coarse grid 
-   !> @param[in] id_rho    array of refinment factor 
-   !> @param[in] id_ext    array of number of points to be extrapolated
    !> @return array of point to be extrapolated
    !-------------------------------------------------------------------
-   FUNCTION extrap__detect( td_var0, td_level1, &
-   &                        id_offset, id_rho, id_ext )
+   FUNCTION extrap__detect( td_var0 ) 
       IMPLICIT NONE
       ! Argument
       TYPE(TVAR) ,                 INTENT(IN   ) :: td_var0
-      TYPE(TVAR) , DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: td_level1
-      INTEGER(i4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
-      INTEGER(i4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
-      INTEGER(i4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_ext
 
       ! function
@@ -196,180 +155,12 @@
 
       ! local variable
-      CHARACTER(LEN=lc)                                :: cl_level
-
-      INTEGER(i4)                                      :: il_ind
-      INTEGER(i4)      , DIMENSION(:,:,:), ALLOCATABLE :: il_detect
-      INTEGER(i4)      , DIMENSION(:,:,:), ALLOCATABLE :: il_tmp
-      INTEGER(i4)      , DIMENSION(:,:)  , ALLOCATABLE :: il_offset
-      INTEGER(i4)      , DIMENSION(:,:)  , ALLOCATABLE :: il_level1
-      INTEGER(i4)      , DIMENSION(:,:)  , ALLOCATABLE :: il_level1_G0
-      INTEGER(i4)      , DIMENSION(:,:)  , ALLOCATABLE :: il_extra
-      INTEGER(i4)      , DIMENSION(:)    , ALLOCATABLE :: il_ext
-      INTEGER(i4)      , DIMENSION(:)    , ALLOCATABLE :: il_rho
-      INTEGER(i4)      , DIMENSION(:)    , ALLOCATABLE :: il_dim0
-
-      TYPE(TVAR)                                       :: tl_var1
-
       ! loop indices
       INTEGER(i4) :: ji0
       INTEGER(i4) :: jj0
       INTEGER(i4) :: jk0
-      INTEGER(i4) :: ji1
-      INTEGER(i4) :: jj1
-      INTEGER(i4) :: ji1m
-      INTEGER(i4) :: jj1m
-      INTEGER(i4) :: ji1p
-      INTEGER(i4) :: jj1p
       !----------------------------------------------------------------
 
-      ! init
-      extrap__detect(:,:,:)=0
-
-      ALLOCATE( il_dim0(3) )
-      il_dim0(:)=td_var0%t_dim(1:3)%i_len
-
-      ! optional argument
-      ALLOCATE( il_rho(ip_maxdim) )
-      il_rho(:)=1
-      IF( PRESENT(id_rho) ) il_rho(1:SIZE(id_rho(:)))=id_rho(:)
-
-      ALLOCATE( il_offset(ip_maxdim,2) )
-      il_offset(:,:)=0
-      IF( PRESENT(id_offset) )THEN
-         il_offset(1:SIZE(id_offset(:,:),DIM=1),&
-         &         1:SIZE(id_offset(:,:),DIM=2) )= id_offset(:,:)
-      ELSE
-         il_offset(jp_I,:)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5)
-         il_offset(jp_J,:)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5)
-      ENDIF
-
-      ALLOCATE( il_ext(ip_maxdim) )
-      il_ext(:)=im_minext
-      IF( PRESENT(id_ext) ) il_ext(1:SIZE(id_ext(:)))=id_ext(:)
-
-      ALLOCATE( il_detect(il_dim0(1),&
-      &                   il_dim0(2),&
-      &                   il_dim0(3)) )
-      il_detect(:,:,:)=0
-
-      ! select point already inform
-      DO jk0=1,td_var0%t_dim(3)%i_len
-         DO jj0=1,td_var0%t_dim(2)%i_len
-            DO ji0=1,td_var0%t_dim(1)%i_len
-               IF( td_var0%d_value(ji0,jj0,jk0,1) /= td_var0%d_fill ) il_detect(ji0,jj0,jk0)=1
-            ENDDO
-         ENDDO
-      ENDDO
- 
-      IF( PRESENT(td_level1) )THEN
-         SELECT CASE(TRIM(td_var0%c_point))
-            CASE DEFAULT !'T'
-               cl_level='tlevel'
-            CASE('U')
-               cl_level='ulevel'
-            CASE('V')
-               cl_level='vlevel'
-            CASE('F')
-               cl_level='flevel'
-         END SELECT
-
-         il_ind=var_get_index(td_level1(:),TRIM(cl_level))
-         IF( il_ind == 0 )THEN
-            CALL logger_error("EXTRAP DETECT: can not compute point to be "//&
-            &     "extrapolated for variable "//TRIM(td_var0%c_name)//&
-            &      ". can not find "//&
-            &     "level for variable point "//TRIM(TRIM(td_var0%c_point)))
-         ELSE
-            tl_var1=var_copy(td_level1(il_ind))
-
-            ALLOCATE( il_level1_G0( il_dim0(1), il_dim0(2)) )
-            IF( ALL(tl_var1%t_dim(1:2)%i_len == il_dim0(1:2)) )THEN
-
-               ! variable to be extrapolated use same resolution than level
-               il_level1_G0(:,:)=INT(tl_var1%d_value(:,:,1,1),i4)
-               
-            ELSE
-               ! variable to be extrapolated do not use same resolution than level
-               ALLOCATE( il_level1(tl_var1%t_dim(1)%i_len, &
-               &                   tl_var1%t_dim(2)%i_len) )
-               ! match fine grid vertical level with coarse grid
-               il_level1(:,:)=INT(tl_var1%d_value(:,:,1,1),i4)/il_rho(jp_K)
-
-               ALLOCATE( il_extra(ip_maxdim,2) )
-               ! coarsening fine grid level
-               il_extra(jp_I,1)=CEILING(REAL(il_rho(jp_I)-1,dp)*0.5_dp)
-               il_extra(jp_I,2)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5_dp)
-
-               il_extra(jp_J,1)=CEILING(REAL(il_rho(jp_J)-1,dp)*0.5_dp)
-               il_extra(jp_J,2)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5_dp)
-
-               DO jj0=1,td_var0%t_dim(2)%i_len
-                  
-                  jj1=(jj0-1)*il_rho(jp_J)+1-il_offset(jp_J,1)
-
-                  jj1m=MAX( jj1-il_extra(jp_J,1), 1 )
-                  jj1p=MIN( jj1+il_extra(jp_J,2), &
-                  &         tl_var1%t_dim(2)%i_len-il_offset(jp_J,2) )
-                  
-                  DO ji0=1,td_var0%t_dim(1)%i_len
-
-                     ji1=(ji0-1)*il_rho(jp_I)+1-id_offset(jp_I,1)
-
-                     ji1m=MAX( ji1-il_extra(jp_I,1), 1 )
-                     ji1p=MIN( ji1+il_extra(jp_I,2), &
-                     &         tl_var1%t_dim(1)%i_len-id_offset(jp_I,2) )
-               
-                     il_level1_G0(ji0,jj0)=MAXVAL(il_level1(ji1m:ji1p,jj1m:jj1p))
-
-                  ENDDO
-               ENDDO
-
-               ! clean
-               DEALLOCATE( il_extra )
-               DEALLOCATE( il_level1 )
-
-            ENDIF
-
-            ! look for sea point
-            DO jk0=1,td_var0%t_dim(3)%i_len
-               WHERE( il_level1_G0(:,:) >= jk0)
-                  il_detect(:,:,jk0)=1
-               END WHERE
-            ENDDO
-
-            ! clean
-            DEALLOCATE( il_level1_G0 )
-            CALL var_clean(tl_var1)
-
-         ENDIF
-      ENDIF
-
-      ! clean
-      DEALLOCATE( il_offset )
- 
-      ALLOCATE( il_tmp(il_dim0(1),&
-      &                il_dim0(2),&
-      &                il_dim0(3)) )
-      il_tmp(:,:,:)=il_detect(:,:,:)
-      ! select extra point depending on interpolation method
-      ! compute point near grid point already inform
-      DO jk0=1,il_dim0(3)
-         DO jj0=1,il_dim0(2)
-            DO ji0=1,il_dim0(1)
-
-               IF( il_tmp(ji0,jj0,jk0) == 1 )THEN
-                  il_detect( &
-                  &  MAX(1,ji0-il_ext(jp_I)):MIN(ji0+il_ext(jp_I),il_dim0(1)),&
-                  &  MAX(1,jj0-il_ext(jp_J)):MIN(jj0+il_ext(jp_J),il_dim0(2)),&
-                  &  MAX(1,jk0-il_ext(jp_K)):MIN(jk0+il_ext(jp_K),il_dim0(3)) &
-                  &  ) = 1 
-               ENDIF
-
-            ENDDO
-         ENDDO
-      ENDDO
-      
-      ! clean
-      DEALLOCATE( il_tmp )
+      ! force to extrapolated all points
+      extrap__detect(:,:,:)=1
 
       ! do not compute grid point already inform
@@ -377,17 +168,10 @@
          DO jj0=1,td_var0%t_dim(2)%i_len
             DO ji0=1,td_var0%t_dim(1)%i_len
-               IF( td_var0%d_value(ji0,jj0,jk0,1) /= td_var0%d_fill ) il_detect(ji0,jj0,jk0)=0
+               IF( td_var0%d_value(ji0,jj0,jk0,1) /= td_var0%d_fill )THEN
+                  extrap__detect(ji0,jj0,jk0)=0
+               ENDIF
             ENDDO
          ENDDO
       ENDDO
-
-      ! save result
-      extrap__detect(:,:,:)=il_detect(:,:,:)
-
-      ! clean
-      DEALLOCATE( il_dim0 )
-      DEALLOCATE( il_ext )
-      DEALLOCATE( il_detect )
-      DEALLOCATE( il_rho )
 
    END FUNCTION extrap__detect
@@ -398,23 +182,16 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - select all land points for extrapolation
    !>
    !> @param[in] td_var    coarse grid variable to extrapolate
-   !> @param[in] td_level  fine grid array of level
-   !> @param[in] id_offset array of offset between fine and coarse grid 
-   !> @param[in] id_rho    array of refinment factor 
-   !> @param[in] id_ext    array of number of points to be extrapolated
    !> @return 3D array of point to be extrapolated
    !-------------------------------------------------------------------
-   FUNCTION extrap__detect_wrapper( td_var, td_level, &
-   &                                id_offset, id_rho, id_ext )
+   FUNCTION extrap__detect_wrapper( td_var )
 
       IMPLICIT NONE
       ! Argument
       TYPE(TVAR) ,                 INTENT(IN   ) :: td_var
-      TYPE(TVAR) , DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: td_level
-      INTEGER(i4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
-      INTEGER(i4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
-      INTEGER(i4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_ext
 
       ! function
@@ -439,8 +216,5 @@
          &              " for variable "//TRIM(td_var%c_name) )
          
-         extrap__detect_wrapper(:,:,:)=extrap__detect( td_var, td_level, &
-         &                                             id_offset, &
-         &                                             id_rho,    &
-         &                                             id_ext     )
+         extrap__detect_wrapper(:,:,:)=extrap__detect( td_var )
 
       ELSE IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
@@ -450,8 +224,5 @@
          &              " for variable "//TRIM(td_var%c_name) )
          
-         extrap__detect_wrapper(:,:,1:1)=extrap__detect( td_var , td_level,&
-         &                                               id_offset, &
-         &                                               id_rho,    &
-         &                                               id_ext     )
+         extrap__detect_wrapper(:,:,1:1)=extrap__detect( td_var )
 
       ELSE IF( td_var%t_dim(3)%l_use )THEN
@@ -461,8 +232,5 @@
          &              " for variable "//TRIM(td_var%c_name) )
          
-         extrap__detect_wrapper(1:1,1:1,:)=extrap__detect( td_var , td_level, &
-         &                                                 id_offset, &
-         &                                                 id_rho,    &
-         &                                                 id_ext     )
+         extrap__detect_wrapper(1:1,1:1,:)=extrap__detect( td_var )
 
       ENDIF              
@@ -489,39 +257,20 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - select all land points for extrapolation
    !
    !> @param[inout] td_var    variable structure
-   !> @param[in] td_level     fine grid array of level
-   !> @param[in] id_offset    array of offset between fine and coarse grid 
-   !> @param[in] id_rho       array of refinment factor 
-   !> @param[in] id_iext      number of points to be extrapolated in i-direction
-   !> @param[in] id_jext      number of points to be extrapolated in j-direction
-   !> @param[in] id_kext      number of points to be extrapolated in k-direction
    !> @param[in] id_radius    radius of the halo used to compute extrapolation 
-   !> @param[in] id_maxiter   maximum number of iteration
-   !-------------------------------------------------------------------
-   SUBROUTINE extrap__fill_value_wrapper( td_var, td_level, &
-   &                                      id_offset,        &
-   &                                      id_rho,           &
-   &                                      id_iext, id_jext, id_kext, &
-   &                                      id_radius, id_maxiter )
+   !-------------------------------------------------------------------
+   SUBROUTINE extrap__fill_value_wrapper( td_var, & 
+   &                                      id_radius )
       IMPLICIT NONE
       ! Argument
       TYPE(TVAR) ,                  INTENT(INOUT) :: td_var
-      TYPE(TVAR) ,  DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: td_level
-      INTEGER(i4),  DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
-      INTEGER(i4),  DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
-      INTEGER(i4),                  INTENT(IN   ), OPTIONAL :: id_iext
-      INTEGER(i4),                  INTENT(IN   ), OPTIONAL :: id_jext
-      INTEGER(i4),                  INTENT(IN   ), OPTIONAL :: id_kext
       INTEGER(i4),                  INTENT(IN   ), OPTIONAL :: id_radius
-      INTEGER(i4),                  INTENT(IN   ), OPTIONAL :: id_maxiter
 
       ! local variable
-      INTEGER(i4) :: il_iext
-      INTEGER(i4) :: il_jext
-      INTEGER(i4) :: il_kext
       INTEGER(i4) :: il_radius
-      INTEGER(i4) :: il_maxiter
 
       CHARACTER(LEN=lc) :: cl_method
@@ -544,66 +293,18 @@
          END SELECT
 
-         il_iext=im_minext
-         IF( PRESENT(id_iext) ) il_iext=id_iext
-         il_jext=im_minext
-         IF( PRESENT(id_jext) ) il_jext=id_jext
-         il_kext=0
-         IF( PRESENT(id_kext) ) il_kext=id_kext
-
-         IF( TRIM(td_var%c_interp(1)) == 'cubic')THEN
-            IF( il_iext > 0 .AND. il_iext < im_mincubic ) il_iext=im_mincubic
-            IF( il_jext > 0 .AND. il_jext < im_mincubic ) il_jext=im_mincubic
+         ! number of point use to compute box
+         il_radius=1
+         IF( PRESENT(id_radius) ) il_radius=id_radius
+         IF( il_radius < 0 )THEN
+            CALL logger_error("EXTRAP FILL VALUE: invalid "//&
+            &  " radius of the box used to compute extrapolation "//&
+            &  "("//TRIM(fct_str(il_radius))//")")
          ENDIF
 
-         IF( il_iext < 0 )THEN
-            CALL logger_error("EXTRAP FILL VALUE: invalid "//&
-            &  " number of points to be extrapolated in i-direction "//&
-            &  "("//TRIM(fct_str(il_iext))//")")
-         ENDIF
-
-         IF( il_jext < 0 )THEN
-            CALL logger_error("EXTRAP FILL VALUE: invalid "//&
-            &  " number of points to be extrapolated in j-direction "//&
-            &  "("//TRIM(fct_str(il_jext))//")")
-         ENDIF
-
-         IF( il_kext < 0 )THEN
-            CALL logger_error("EXTRAP FILL VALUE: invalid "//&
-            &  " number of points to be extrapolated in k-direction "//&
-            &  "("//TRIM(fct_str(il_kext))//")")
-         ENDIF
-
-         IF( (il_iext /= 0 .AND. td_var%t_dim(1)%l_use) .OR. &
-         &   (il_jext /= 0 .AND. td_var%t_dim(2)%l_use) .OR. &
-         &   (il_kext /= 0 .AND. td_var%t_dim(3)%l_use) )THEN
-
-            ! number of point use to compute box
-            il_radius=1
-            IF( PRESENT(id_radius) ) il_radius=id_radius
-            IF( il_radius < 0 )THEN
-               CALL logger_error("EXTRAP FILL VALUE: invalid "//&
-               &  " radius of the box used to compute extrapolation "//&
-               &  "("//TRIM(fct_str(il_radius))//")")
-            ENDIF
-
-            ! maximum number of iteration
-            il_maxiter=im_maxiter
-            IF( PRESENT(id_maxiter) ) il_maxiter=id_maxiter
-            IF( il_maxiter < 0 )THEN
-               CALL logger_error("EXTRAP FILL VALUE: invalid "//&
-               &  " maximum nuber of iteration "//&
-               &  "("//TRIM(fct_str(il_maxiter))//")")
-            ENDIF
-
-            CALL logger_info("EXTRAP FILL: extrapolate "//TRIM(td_var%c_name)//&
-            &  " using "//TRIM(cl_method)//" method." )
-
-            CALL extrap__fill_value( td_var, cl_method, &
-            &                        il_iext, il_jext, il_kext,   &
-            &                        il_radius, il_maxiter,       &
-            &                        td_level,                    &
-            &                        id_offset, id_rho )
- 
-         ENDIF
+         CALL logger_info("EXTRAP FILL: extrapolate "//TRIM(td_var%c_name)//&
+         &  " using "//TRIM(cl_method)//" method." )
+
+         CALL extrap__fill_value( td_var, cl_method, &
+         &                        il_radius )
  
       ENDIF
@@ -621,35 +322,19 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - select all land points for extrapolation
    !
    !> @param[inout] td_var    variable structure
    !> @param[in] cd_method    extrapolation method
-   !> @param[in] id_iext      number of points to be extrapolated in i-direction
-   !> @param[in] id_jext      number of points to be extrapolated in j-direction
-   !> @param[in] id_kext      number of points to be extrapolated in k-direction
    !> @param[in] id_radius    radius of the halo used to compute extrapolation
-   !> @param[in] id_maxiter   maximum number of iteration
-   !> @param[in] td_level     fine grid array of level
-   !> @param[in] id_offset    array of offset between fine and coarse grid 
-   !> @param[in] id_rho       array of refinment factor
    !-------------------------------------------------------------------
    SUBROUTINE extrap__fill_value( td_var, cd_method, &
-   &                              id_iext, id_jext, id_kext, &
-   &                              id_radius, id_maxiter, &
-   &                              td_level,          &
-   &                              id_offset,         &
-   &                              id_rho )
+   &                              id_radius )
       IMPLICIT NONE
       ! Argument
       TYPE(TVAR)      ,                 INTENT(INOUT) :: td_var
       CHARACTER(LEN=*),                 INTENT(IN   ) :: cd_method
-      INTEGER(i4)     ,                 INTENT(IN   ) :: id_iext
-      INTEGER(i4)     ,                 INTENT(IN   ) :: id_jext
-      INTEGER(i4)     ,                 INTENT(IN   ) :: id_kext
       INTEGER(i4)     ,                 INTENT(IN   ) :: id_radius
-      INTEGER(i4)     ,                 INTENT(IN   ) :: id_maxiter
-      TYPE(TVAR)      , DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: td_level
-      INTEGER(i4)     , DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
-      INTEGER(i4)     , DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
 
       ! local variable
@@ -668,8 +353,6 @@
       &                    td_var%t_dim(3)%i_len) )
 
-      il_detect(:,:,:) = extrap_detect( td_var, td_level, &
-      &                                 id_offset,        &
-      &                                 id_rho,           &
-      &                                 id_ext=(/id_iext, id_jext, id_kext/) )
+      il_detect(:,:,:) = extrap_detect( td_var )
+
       !2- add attribute to variable
       cl_extrap=fct_concat(td_var%c_extrap(:))
@@ -679,12 +362,21 @@
       CALL att_clean(tl_att)
 
-      CALL logger_info(" EXTRAP FILL: "//&
-         &              TRIM(fct_str(SUM(il_detect(:,:,:))))//&
-         &              " point(s) to extrapolate " )
-
-      !3- extrapolate
-      CALL extrap__3D(td_var%d_value(:,:,:,:), td_var%d_fill,    &
-      &               il_detect(:,:,:),                           &
-      &               cd_method, id_radius, id_maxiter  )
+      IF( ALL(il_detect(:,:,:)==1) )THEN
+         CALL logger_warn(" EXTRAP FILL: "//&
+            &  " can not extrapolate "//TRIM(td_var%c_name)//&
+            &  ". no value inform." )
+      ELSE
+         CALL logger_info(" EXTRAP FILL: "//&
+            &              TRIM(fct_str(SUM(il_detect(:,:,:))))//&
+            &              " point(s) to extrapolate " )
+
+         CALL logger_info(" EXTRAP FILL: method "//&
+            &  TRIM(cd_method) )
+
+         !3- extrapolate
+         CALL extrap__3D(td_var%d_value(:,:,:,:), td_var%d_fill, &
+         &               il_detect(:,:,:),                       &
+         &               cd_method, id_radius )
+      ENDIF
 
       DEALLOCATE(il_detect)
@@ -705,5 +397,8 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - compute coef indices to be used
+   !> - bug fix: force coef indice to 1, for dimension lenth equal to 1
    !
    !> @param[inout] dd_value  3D array of variable to be extrapolated
@@ -714,26 +409,31 @@
    !-------------------------------------------------------------------
    SUBROUTINE extrap__3D( dd_value, dd_fill, id_detect,&
-   &                      cd_method, id_radius, id_maxiter )
+   &                      cd_method, id_radius )
       IMPLICIT NONE
       ! Argument
       REAL(dp)   , DIMENSION(:,:,:,:), INTENT(INOUT) :: dd_value
-      REAL(dp)   ,                   INTENT(IN   ) :: dd_fill
-      INTEGER(i4), DIMENSION(:,:,:), INTENT(INOUT) :: id_detect
-      CHARACTER(LEN=*),              INTENT(IN   ) :: cd_method
-      INTEGER(i4),                   INTENT(IN   ) :: id_radius
-      INTEGER(i4),                   INTENT(IN   ) :: id_maxiter
+      REAL(dp)   ,                     INTENT(IN   ) :: dd_fill
+      INTEGER(i4), DIMENSION(:,:,:)  , INTENT(INOUT) :: id_detect
+      CHARACTER(LEN=*),                INTENT(IN   ) :: cd_method
+      INTEGER(i4),                     INTENT(IN   ) :: id_radius
 
       ! local variable
-      INTEGER(i4) :: il_imin
-      INTEGER(i4) :: il_imax
-      INTEGER(i4) :: il_jmin
-      INTEGER(i4) :: il_jmax
-      INTEGER(i4) :: il_kmin
-      INTEGER(i4) :: il_kmax
-      INTEGER(i4) :: il_iter
-      INTEGER(i4) :: il_radius
-
-      INTEGER(i4), DIMENSION(4) :: il_shape
-      INTEGER(i4), DIMENSION(3) :: il_dim
+      INTEGER(i4)                                :: il_imin
+      INTEGER(i4)                                :: il_imax
+      INTEGER(i4)                                :: il_jmin
+      INTEGER(i4)                                :: il_jmax
+      INTEGER(i4)                                :: il_kmin
+      INTEGER(i4)                                :: il_kmax
+      INTEGER(i4)                                :: il_iter
+      INTEGER(i4)                                :: il_radius
+      INTEGER(i4)                                :: il_i1
+      INTEGER(i4)                                :: il_i2
+      INTEGER(i4)                                :: il_j1
+      INTEGER(i4)                                :: il_j2
+      INTEGER(i4)                                :: il_k1
+      INTEGER(i4)                                :: il_k2
+
+      INTEGER(i4), DIMENSION(4)                  :: il_shape
+      INTEGER(i4), DIMENSION(3)                  :: il_dim
 
       INTEGER(i4), DIMENSION(:,:,:), ALLOCATABLE :: il_detect
@@ -743,4 +443,6 @@
       REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_dfdz
       REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_coef
+
+      LOGICAL                                    :: ll_iter
 
       ! loop indices
@@ -765,5 +467,6 @@
             DO WHILE( ANY(il_detect(:,:,:)==1) )
                ! change extend value to minimize number of iteration
-               il_radius=id_radius+(il_iter/id_maxiter)
+               il_radius=id_radius+(il_iter-1)
+               ll_iter=.TRUE.
 
                ALLOCATE( dl_dfdx(il_shape(1), il_shape(2), il_shape(3)) ) 
@@ -774,5 +477,6 @@
                dl_dfdx(:,:,:)=dd_fill
                IF( il_shape(1) > 1 )THEN
-                  dl_dfdx(:,:,:)=extrap_deriv_3D( dd_value(:,:,:,jl), dd_fill, 'I' )
+                  dl_dfdx(:,:,:)=math_deriv_3D( dd_value(:,:,:,jl), &
+                     &                          dd_fill, 'I' )
                ENDIF
 
@@ -780,5 +484,6 @@
                dl_dfdy(:,:,:)=dd_fill
                IF( il_shape(2) > 1 )THEN
-                  dl_dfdy(:,:,:)=extrap_deriv_3D( dd_value(:,:,:,jl), dd_fill, 'J' )
+                  dl_dfdy(:,:,:)=math_deriv_3D( dd_value(:,:,:,jl), &
+                     &                          dd_fill, 'J' )
                ENDIF
  
@@ -786,5 +491,6 @@
                dl_dfdz(:,:,:)=dd_fill
                IF( il_shape(3) > 1 )THEN
-                  dl_dfdz(:,:,:)=extrap_deriv_3D( dd_value(:,:,:,jl), dd_fill, 'K' )
+                  dl_dfdz(:,:,:)=math_deriv_3D( dd_value(:,:,:,jl), &
+                     &                          dd_fill, 'K' )
                ENDIF
  
@@ -804,4 +510,5 @@
 
                DO jk=1,il_shape(3)
+                  ! from North West(1,1) to South East(il_shape(1),il_shape(2))
                   IF( ALL(il_detect(:,:,jk) == 0) ) CYCLE
                   DO jj=1,il_shape(2)
@@ -813,21 +520,40 @@
                            il_imin=MAX(ji-il_radius,1)
                            il_imax=MIN(ji+il_radius,il_shape(1))
+                           ! coef indices to be used
+                           il_i1 = il_radius-(ji-il_imin)+1
+                           il_i2 = il_radius+(il_imax-ji)+1
                            IF( il_dim(1) == 1 )THEN
                               il_imin=ji
                               il_imax=ji
-                           ENDIF
+                              ! coef indices to be used
+                              il_i1 = 1
+                              il_i2 = 1
+                           ENDIF
+
 
                            il_jmin=MAX(jj-il_radius,1)
                            il_jmax=MIN(jj+il_radius,il_shape(2))
+                           ! coef indices to be used
+                           il_j1 = il_radius-(jj-il_jmin)+1
+                           il_j2 = il_radius+(il_jmax-jj)+1
                            IF( il_dim(2) == 1 )THEN
                               il_jmin=jj
                               il_jmax=jj
+                              ! coef indices to be used
+                              il_j1 = 1
+                              il_j2 = 1
                            ENDIF
 
                            il_kmin=MAX(jk-il_radius,1)
                            il_kmax=MIN(jk+il_radius,il_shape(3))
+                           ! coef indices to be used
+                           il_k1 = il_radius-(jk-il_kmin)+1
+                           il_k2 = il_radius+(il_kmax-jk)+1
                            IF( il_dim(3) == 1 )THEN
                               il_kmin=jk
                               il_kmax=jk
+                              ! coef indices to be used
+                              il_k1 = 1
+                              il_k2 = 1
                            ENDIF
 
@@ -845,8 +571,85 @@
                            &            il_jmin:il_jmax, &
                            &            il_kmin:il_kmax ), &
-                           &  dl_coef(:,:,:) )
+                           &  dl_coef(il_i1:il_i2, &
+                           &          il_j1:il_j2, &
+                           &          il_k1:il_k2) )
 
                            IF( dd_value(ji,jj,jk,jl) /= dd_fill )THEN
                               il_detect(ji,jj,jk)= 0
+                              ll_iter=.FALSE.
+                           ENDIF
+
+                        ENDIF
+
+                     ENDDO
+                  ENDDO
+                  ! from South East(il_shape(1),il_shape(2)) to North West(1,1)
+                  IF( ALL(il_detect(:,:,jk) == 0) ) CYCLE
+                  DO jj=il_shape(2),1,-1
+                     IF( ALL(il_detect(:,jj,jk) == 0) ) CYCLE
+                     DO ji=il_shape(1),1,-1
+
+                        IF( il_detect(ji,jj,jk) == 1 )THEN
+                          
+                           il_imin=MAX(ji-il_radius,1)
+                           il_imax=MIN(ji+il_radius,il_shape(1))
+                           ! coef indices to be used
+                           il_i1 = il_radius-(ji-il_imin)+1
+                           il_i2 = il_radius+(il_imax-ji)+1
+                           IF( il_dim(1) == 1 )THEN
+                              il_imin=ji
+                              il_imax=ji
+                              ! coef indices to be used
+                              il_i1 = 1
+                              il_i2 = 1
+                           ENDIF
+
+
+                           il_jmin=MAX(jj-il_radius,1)
+                           il_jmax=MIN(jj+il_radius,il_shape(2))
+                           ! coef indices to be used
+                           il_j1 = il_radius-(jj-il_jmin)+1
+                           il_j2 = il_radius+(il_jmax-jj)+1
+                           IF( il_dim(2) == 1 )THEN
+                              il_jmin=jj
+                              il_jmax=jj
+                              ! coef indices to be used
+                              il_j1 = 1
+                              il_j2 = 1
+                           ENDIF
+
+                           il_kmin=MAX(jk-il_radius,1)
+                           il_kmax=MIN(jk+il_radius,il_shape(3))
+                           ! coef indices to be used
+                           il_k1 = il_radius-(jk-il_kmin)+1
+                           il_k2 = il_radius+(il_kmax-jk)+1
+                           IF( il_dim(3) == 1 )THEN
+                              il_kmin=jk
+                              il_kmax=jk
+                              ! coef indices to be used
+                              il_k1 = 1
+                              il_k2 = 1
+                           ENDIF
+
+                           dd_value(ji,jj,jk,jl)=extrap__3D_min_error_fill( &
+                           &  dd_value( il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax,jl ), dd_fill, il_radius, &
+                           &  dl_dfdx(  il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax ), &
+                           &  dl_dfdy(  il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax ), &
+                           &  dl_dfdz(  il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax ), &
+                           &  dl_coef(il_i1:il_i2, &
+                           &          il_j1:il_j2, &
+                           &          il_k1:il_k2) )
+
+                           IF( dd_value(ji,jj,jk,jl) /= dd_fill )THEN
+                              il_detect(ji,jj,jk)= 0
+                              ll_iter=.FALSE.
                            ENDIF
 
@@ -862,5 +665,5 @@
                DEALLOCATE( dl_coef )
 
-               il_iter=il_iter+1
+               IF( ll_iter ) il_iter=il_iter+1
             ENDDO
          ENDDO
@@ -875,5 +678,6 @@
             DO WHILE( ANY(il_detect(:,:,:)==1) )
                ! change extend value to minimize number of iteration
-               il_radius=id_radius+(il_iter/id_maxiter)
+               il_radius=id_radius+(il_iter-1)
+               ll_iter=.TRUE.
 
                il_dim(1)=2*il_radius+1
@@ -886,10 +690,11 @@
                ALLOCATE( dl_coef(il_dim(1), il_dim(2), il_dim(3)) )
 
-               dl_coef(:,:,:)=extrap__3D_dist_weight_coef(dd_value(1:il_dim(1), &
-               &                                                   1:il_dim(2), &
-               &                                                   1:il_dim(3), &
+               dl_coef(:,:,:)=extrap__3D_dist_weight_coef(dd_value(1:il_dim(1),&
+               &                                                   1:il_dim(2),&
+               &                                                   1:il_dim(3),&
                &                                                   jl ) )
-
+               
                DO jk=1,il_shape(3)
+                  ! from North West(1,1) to South East(il_shape(1),il_shape(2))
                   IF( ALL(il_detect(:,:,jk) == 0) ) CYCLE
                   DO jj=1,il_shape(2)
@@ -901,21 +706,39 @@
                            il_imin=MAX(ji-il_radius,1)
                            il_imax=MIN(ji+il_radius,il_shape(1))
+                           ! coef indices to be used
+                           il_i1 = il_radius-(ji-il_imin)+1
+                           il_i2 = il_radius+(il_imax-ji)+1
                            IF( il_dim(1) == 1 )THEN
                               il_imin=ji
                               il_imax=ji
+                              ! coef indices to be used
+                              il_i1 = 1
+                              il_i2 = 1
                            ENDIF
 
                            il_jmin=MAX(jj-il_radius,1)
                            il_jmax=MIN(jj+il_radius,il_shape(2))
+                           ! coef indices to be used
+                           il_j1 = il_radius-(jj-il_jmin)+1
+                           il_j2 = il_radius+(il_jmax-jj)+1
                            IF( il_dim(2) == 1 )THEN
                               il_jmin=jj
                               il_jmax=jj
+                              ! coef indices to be used
+                              il_j1 = 1
+                              il_j2 = 1
                            ENDIF
 
                            il_kmin=MAX(jk-il_radius,1)
                            il_kmax=MIN(jk+il_radius,il_shape(3))
+                           ! coef indices to be used
+                           il_k1 = il_radius-(jk-il_kmin)+1
+                           il_k2 = il_radius+(il_kmax-jk)+1
                            IF( il_dim(3) == 1 )THEN
                               il_kmin=jk
                               il_kmax=jk
+                              ! coef indices to be used
+                              il_k1 = 1
+                              il_k2 = 1
                            ENDIF
 
@@ -925,8 +748,76 @@
                            &            il_kmin:il_kmax, &
                            &            jl), dd_fill, il_radius, &
-                           &  dl_coef(:,:,:) )
+                           &  dl_coef(il_i1:il_i2, &
+                           &          il_j1:il_j2, &
+                           &          il_k1:il_k2) )
 
                            IF( dd_value(ji,jj,jk,jl) /= dd_fill )THEN
                               il_detect(ji,jj,jk)= 0
+                              ll_iter=.FALSE.
+                           ENDIF
+
+                        ENDIF
+
+                     ENDDO
+                  ENDDO
+                  ! from South East(il_shape(1),il_shape(2)) to North West(1,1)
+                  IF( ALL(il_detect(:,:,jk) == 0) ) CYCLE
+                  DO jj=il_shape(2),1,-1
+                     IF( ALL(il_detect(:,jj,jk) == 0) ) CYCLE
+                     DO ji=il_shape(1),1,-1
+
+                        IF( il_detect(ji,jj,jk) == 1 )THEN
+                           
+                           il_imin=MAX(ji-il_radius,1)
+                           il_imax=MIN(ji+il_radius,il_shape(1))
+                           ! coef indices to be used
+                           il_i1 = il_radius-(ji-il_imin)+1
+                           il_i2 = il_radius+(il_imax-ji)+1
+                           IF( il_dim(1) == 1 )THEN
+                              il_imin=ji
+                              il_imax=ji
+                              ! coef indices to be used
+                              il_i1 = 1
+                              il_i2 = 1
+                           ENDIF
+
+                           il_jmin=MAX(jj-il_radius,1)
+                           il_jmax=MIN(jj+il_radius,il_shape(2))
+                           ! coef indices to be used
+                           il_j1 = il_radius-(jj-il_jmin)+1
+                           il_j2 = il_radius+(il_jmax-jj)+1
+                           IF( il_dim(2) == 1 )THEN
+                              il_jmin=jj
+                              il_jmax=jj
+                              ! coef indices to be used
+                              il_j1 = 1
+                              il_j2 = 1
+                           ENDIF
+
+                           il_kmin=MAX(jk-il_radius,1)
+                           il_kmax=MIN(jk+il_radius,il_shape(3))
+                           ! coef indices to be used
+                           il_k1 = il_radius-(jk-il_kmin)+1
+                           il_k2 = il_radius+(il_kmax-jk)+1
+                           IF( il_dim(3) == 1 )THEN
+                              il_kmin=jk
+                              il_kmax=jk
+                              ! coef indices to be used
+                              il_k1 = 1
+                              il_k2 = 1
+                           ENDIF
+
+                           dd_value(ji,jj,jk,jl)=extrap__3D_dist_weight_fill( &
+                           &  dd_value( il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax, &
+                           &            jl), dd_fill, il_radius, &
+                           &  dl_coef(il_i1:il_i2, &
+                           &          il_j1:il_j2, &
+                           &          il_k1:il_k2) )
+
+                           IF( dd_value(ji,jj,jk,jl) /= dd_fill )THEN
+                              il_detect(ji,jj,jk)= 0
+                              ll_iter=.FALSE.
                            ENDIF
 
@@ -936,7 +827,10 @@
                   ENDDO
                ENDDO
-
+               CALL logger_info(" EXTRAP 3D: "//&
+               &              TRIM(fct_str(SUM(il_detect(:,:,:))))//&
+               &              " point(s) to extrapolate " )
+            
                DEALLOCATE( dl_coef )
-               il_iter=il_iter+1
+               IF( ll_iter ) il_iter=il_iter+1
             ENDDO
          ENDDO            
@@ -946,546 +840,4 @@
 
    END SUBROUTINE extrap__3D
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This function compute derivative of 1D array.
-   !> 
-   !> @details 
-   !> optionaly you could specify to take into account east west discontinuity
-   !> (-180° 180° or 0° 360° for longitude variable)
-   !>
-   !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
-   !> @param[in] dd_value     1D array of variable to be extrapolated
-   !> @param[in] dd_fill      FillValue of variable
-   !> @param[in] ld_discont   logical to take into account east west discontinuity 
-   !-------------------------------------------------------------------
-   PURE FUNCTION extrap_deriv_1D( dd_value, dd_fill, ld_discont )
-
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)   , DIMENSION(:), INTENT(IN) :: dd_value
-      REAL(dp)                 , INTENT(IN) :: dd_fill
-      LOGICAL                  , INTENT(IN), OPTIONAL :: ld_discont
-
-      ! function
-      REAL(dp), DIMENSION(SIZE(dd_value,DIM=1) ) :: extrap_deriv_1D
-
-      ! local variable
-      INTEGER(i4)                            :: il_imin
-      INTEGER(i4)                            :: il_imax
-      INTEGER(i4), DIMENSION(1)              :: il_shape
-
-      REAL(dp)                               :: dl_min
-      REAL(dp)                               :: dl_max
-      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_value
-
-      LOGICAL                                :: ll_discont
-
-      ! loop indices
-      INTEGER(i4) :: ji
-
-      INTEGER(i4) :: i1
-      INTEGER(i4) :: i2
-      !----------------------------------------------------------------
-      ! init
-      extrap_deriv_1D(:)=dd_fill
-
-      ll_discont=.FALSE.
-      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
-
-      il_shape(:)=SHAPE(dd_value(:))
-
-      ALLOCATE( dl_value(3))
-
-      ! compute derivative in i-direction
-      DO ji=1,il_shape(1)
-         
-            il_imin=MAX(ji-1,1)
-            il_imax=MIN(ji+1,il_shape(1))
-
-            IF( il_imin==ji-1 .AND. il_imax==ji+1 )THEN
-               i1=1  ; i2=3
-            ELSEIF( il_imin==ji .AND. il_imax==ji+1 )THEN
-               i1=1  ; i2=2
-            ELSEIF( il_imin==ji-1 .AND. il_imax==ji )THEN
-               i1=2  ; i2=3
-            ENDIF
-
-            dl_value(i1:i2)=dd_value(il_imin:il_imax)
-            IF( il_imin == 1 )THEN
-               dl_value(:)=EOSHIFT( dl_value(:), &
-               &                    DIM=1,         &
-               &                    SHIFT=-1,      &
-               &                    BOUNDARY=dl_value(1) )
-            ENDIF
-            IF( il_imax == il_shape(1) )THEN
-               dl_value(:)=EOSHIFT( dl_value(:), &
-               &                    DIM=1,         &
-               &                    SHIFT=1,       &
-               &                    BOUNDARY=dl_value(3))
-            ENDIF
-
-            IF( ll_discont )THEN
-               dl_min=MINVAL( dl_value(:), dl_value(:)/=dd_fill )
-               dl_max=MAXVAL( dl_value(:), dl_value(:)/=dd_fill )
-               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                  WHERE( dl_value(:) < 0._dp ) 
-                     dl_value(:) = dl_value(:)+360._dp
-                  END WHERE
-               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                  WHERE( dl_value(:) > 180._dp ) 
-                     dl_value(:) = dl_value(:)-180._dp
-                  END WHERE
-               ENDIF
-            ENDIF
-
-         IF( dl_value( 2) /= dd_fill .AND. & ! ji
-         &   dl_value( 3) /= dd_fill .AND. & ! ji+1
-         &   dl_value( 1) /= dd_fill )THEN   ! ji-1
-
-            extrap_deriv_1D(ji)=&
-            &  ( dl_value(3) - dl_value(1) ) / &
-            &  REAL( il_imax-il_imin ,dp)
-
-         ENDIF
-
-      ENDDO
-
-      DEALLOCATE( dl_value )
-
-   END FUNCTION extrap_deriv_1D
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This function compute derivative of 2D array.
-   !> you have to specify in which direction derivative have to be computed:
-   !> first (I) or second (J) dimension. 
-   !>
-   !> @details 
-   !> optionaly you could specify to take into account east west discontinuity
-   !> (-180° 180° or 0° 360° for longitude variable)
-   !>
-   !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
-   !> @param[in] dd_value     2D array of variable to be extrapolated
-   !> @param[in] dd_fill      FillValue of variable
-   !> @param[in] cd_dim       compute derivative on first (I) or second (J) dimension 
-   !> @param[in] ld_discont   logical to take into account east west discontinuity 
-   !-------------------------------------------------------------------
-   FUNCTION extrap_deriv_2D( dd_value, dd_fill, cd_dim, ld_discont )
-
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)   , DIMENSION(:,:), INTENT(IN) :: dd_value
-      REAL(dp)                   , INTENT(IN) :: dd_fill
-      CHARACTER(LEN=*)           , INTENT(IN) :: cd_dim
-      LOGICAL                    , INTENT(IN), OPTIONAL :: ld_discont
-
-      ! function
-      REAL(dp), DIMENSION(SIZE(dd_value,DIM=1), &
-      &                   SIZE(dd_value,DIM=2) ) :: extrap_deriv_2D
-
-      ! local variable
-      INTEGER(i4)                              :: il_imin
-      INTEGER(i4)                              :: il_imax
-      INTEGER(i4)                              :: il_jmin
-      INTEGER(i4)                              :: il_jmax
-      INTEGER(i4), DIMENSION(2)                :: il_shape
-
-      REAL(dp)                                 :: dl_min
-      REAL(dp)                                 :: dl_max
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_value
-
-      LOGICAL                                  :: ll_discont
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-
-      INTEGER(i4) :: i1
-      INTEGER(i4) :: i2
-
-      INTEGER(i4) :: j1
-      INTEGER(i4) :: j2
-      !----------------------------------------------------------------
-      ! init
-      extrap_deriv_2D(:,:)=dd_fill
-
-      ll_discont=.FALSE.
-      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
-
-      il_shape(:)=SHAPE(dd_value(:,:))
-
-      SELECT CASE(TRIM(fct_upper(cd_dim)))
-
-      CASE('I')
-
-         ALLOCATE( dl_value(3,il_shape(2)) )
-         ! compute derivative in i-direction
-         DO ji=1,il_shape(1)
-
-            ! init
-            dl_value(:,:)=dd_fill
-            
-            il_imin=MAX(ji-1,1)
-            il_imax=MIN(ji+1,il_shape(1))
-
-            IF( il_imin==ji-1 .AND. il_imax==ji+1 )THEN
-               i1=1  ; i2=3
-            ELSEIF( il_imin==ji .AND. il_imax==ji+1 )THEN
-               i1=1  ; i2=2
-            ELSEIF( il_imin==ji-1 .AND. il_imax==ji )THEN
-               i1=2  ; i2=3
-            ENDIF
-
-            dl_value(i1:i2,:)=dd_value(il_imin:il_imax,:)
-            IF( il_imin == 1 )THEN
-               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
-               &                      DIM=1,         &
-               &                      SHIFT=-1,      &
-               &                      BOUNDARY=dl_value(1,:) )
-            ENDIF
-            IF( il_imax == il_shape(1) )THEN
-               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
-               &                      DIM=1,         &
-               &                      SHIFT=1,       &
-               &                      BOUNDARY=dl_value(3,:))
-            ENDIF
-
-            IF( ll_discont )THEN
-               dl_min=MINVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
-               dl_max=MAXVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
-               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                  WHERE( dl_value(:,:) < 0_dp ) 
-                     dl_value(:,:) = dl_value(:,:)+360._dp
-                  END WHERE
-               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                  WHERE( dl_value(:,:) > 180 ) 
-                     dl_value(:,:) = dl_value(:,:)-180._dp
-                  END WHERE
-               ENDIF
-            ENDIF
-            
-            WHERE( dl_value(2,:) /= dd_fill .AND. &  ! ji
-            &      dl_value(3,:) /= dd_fill .AND. &  ! ji+1
-            &      dl_value(1,:) /= dd_fill )        ! ji-1
-
-               extrap_deriv_2D(ji,:)=&
-               &  ( dl_value(3,:) - dl_value(1,:) ) / &
-               &    REAL( il_imax-il_imin,dp)
-
-            END WHERE
-
-         ENDDO
-
-      CASE('J')
-
-         ALLOCATE( dl_value(il_shape(1),3) )
-         ! compute derivative in j-direction
-         DO jj=1,il_shape(2)
-         
-            il_jmin=MAX(jj-1,1)
-            il_jmax=MIN(jj+1,il_shape(2))
-
-            IF( il_jmin==jj-1 .AND. il_jmax==jj+1 )THEN
-               j1=1  ; j2=3
-            ELSEIF( il_jmin==jj .AND. il_jmax==jj+1 )THEN
-               j1=1  ; j2=2
-            ELSEIF( il_jmin==jj-1 .AND. il_jmax==jj )THEN
-               j1=2  ; j2=3
-            ENDIF
-
-            dl_value(:,j1:j2)=dd_value(:,il_jmin:il_jmax)
-            IF( il_jmin == 1 )THEN
-               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
-               &                      DIM=2,         &
-               &                      SHIFT=-1,      &
-               &                      BOUNDARY=dl_value(:,1))
-            ENDIF
-            IF( il_jmax == il_shape(2) )THEN
-               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
-               &                      DIM=2,         &
-               &                      SHIFT=1,       &
-               &                      BOUNDARY=dl_value(:,3))
-            ENDIF
-
-            IF( ll_discont )THEN
-               dl_min=MINVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
-               dl_max=MAXVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
-               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                  WHERE( dl_value(:,:) < 0_dp ) 
-                     dl_value(:,:) = dl_value(:,:)+360._dp
-                  END WHERE
-               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                  WHERE( dl_value(:,:) > 180 ) 
-                     dl_value(:,:) = dl_value(:,:)-180._dp
-                  END WHERE
-               ENDIF
-            ENDIF
-
-            WHERE( dl_value(:, 2) /= dd_fill .AND. & ! jj
-            &      dl_value(:, 3) /= dd_fill .AND. & ! jj+1
-            &      dl_value(:, 1) /= dd_fill )       ! jj-1
-
-               extrap_deriv_2D(:,jj)=&
-               &  ( dl_value(:,3) - dl_value(:,1) ) / &
-               &   REAL(il_jmax-il_jmin,dp)         
-
-            END WHERE
-
-         ENDDO
-         
-      END SELECT
-
-      DEALLOCATE( dl_value )
-
-   END FUNCTION extrap_deriv_2D
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This function compute derivative of 3D array.
-   !> you have to specify in which direction derivative have to be computed:
-   !> first (I), second (J) or third (K) dimension.
-   !> 
-   !> @details 
-   !> optionaly you could specify to take into account east west discontinuity
-   !> (-180° 180° or 0° 360° for longitude variable)
-   !>
-   !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
-   !> @param[inout] dd_value  3D array of variable to be extrapolated
-   !> @param[in] dd_fill      FillValue of variable
-   !> @param[in] cd_dim       compute derivative on first (I) second (J) or third (K) dimension   
-   !> @param[in] ld_discont   logical to take into account east west discontinuity
-   !-------------------------------------------------------------------
-   PURE FUNCTION extrap_deriv_3D( dd_value, dd_fill, cd_dim, ld_discont )
-
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:,:,:), INTENT(IN) :: dd_value
-      REAL(dp)                          , INTENT(IN) :: dd_fill
-      CHARACTER(LEN=*)                  , INTENT(IN) :: cd_dim
-      LOGICAL                           , INTENT(IN), OPTIONAL :: ld_discont
-
-      ! function
-      REAL(dp), DIMENSION(SIZE(dd_value,DIM=1), &
-      &                   SIZE(dd_value,DIM=2), &
-      &                   SIZE(dd_value,DIM=3)) :: extrap_deriv_3D
-
-      ! local variable
-      INTEGER(i4)                                :: il_imin
-      INTEGER(i4)                                :: il_imax
-      INTEGER(i4)                                :: il_jmin
-      INTEGER(i4)                                :: il_jmax
-      INTEGER(i4)                                :: il_kmin
-      INTEGER(i4)                                :: il_kmax
-      INTEGER(i4), DIMENSION(3)                  :: il_shape
-
-      REAL(dp)                                   :: dl_min
-      REAL(dp)                                   :: dl_max
-      REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_value
-
-      LOGICAL                                    :: ll_discont
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      INTEGER(i4) :: jk
-
-      INTEGER(i4) :: i1
-      INTEGER(i4) :: i2
-
-      INTEGER(i4) :: j1
-      INTEGER(i4) :: j2
-      
-      INTEGER(i4) :: k1
-      INTEGER(i4) :: k2      
-      !----------------------------------------------------------------
-      ! init
-      extrap_deriv_3D(:,:,:)=dd_fill
-
-      ll_discont=.FALSE.
-      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
-
-      il_shape(:)=SHAPE(dd_value(:,:,:))
-
-
-      SELECT CASE(TRIM(fct_upper(cd_dim)))
-
-      CASE('I')
-
-         ALLOCATE( dl_value(3,il_shape(2),il_shape(3)) )
-         ! compute derivative in i-direction
-         DO ji=1,il_shape(1)
-            
-            il_imin=MAX(ji-1,1)
-            il_imax=MIN(ji+1,il_shape(1))
-
-            IF( il_imin==ji-1 .AND. il_imax==ji+1 )THEN
-               i1=1  ; i2=3
-            ELSEIF( il_imin==ji .AND. il_imax==ji+1 )THEN
-               i1=1  ; i2=2
-            ELSEIF( il_imin==ji-1 .AND. il_imax==ji )THEN
-               i1=2  ; i2=3
-            ENDIF
-
-            dl_value(i1:i2,:,:)=dd_value(il_imin:il_imax,:,:)
-            IF( il_imin == 1 )THEN
-               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
-               &                      DIM=1,         &
-               &                      SHIFT=-1,      &
-               &                      BOUNDARY=dl_value(1,:,:) )
-            ENDIF
-            IF( il_imax == il_shape(1) )THEN
-               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
-               &                      DIM=1,         &
-               &                      SHIFT=1,       &
-               &                      BOUNDARY=dl_value(3,:,:))
-            ENDIF
-
-            IF( ll_discont )THEN
-               dl_min=MINVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
-               dl_max=MAXVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
-               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                  WHERE( dl_value(:,:,:) < 0_dp ) 
-                     dl_value(:,:,:) = dl_value(:,:,:)+360._dp
-                  END WHERE
-               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                  WHERE( dl_value(:,:,:) > 180 ) 
-                     dl_value(:,:,:) = dl_value(:,:,:)-180._dp
-                  END WHERE
-               ENDIF
-            ENDIF
-
-            WHERE( dl_value(2,:,:) /= dd_fill .AND. & ! ji
-            &      dl_value(3,:,:) /= dd_fill .AND. & !ji+1 
-            &      dl_value(1,:,:) /= dd_fill )       !ji-1
-
-               extrap_deriv_3D(ji,:,:)= &
-               &  ( dl_value(3,:,:) - dl_value(1,:,:) ) / &
-               &  REAL( il_imax-il_imin ,dp)
-
-            END WHERE
-
-         ENDDO
-
-      CASE('J')
-
-         ALLOCATE( dl_value(il_shape(1),3,il_shape(3)) )
-         ! compute derivative in j-direction
-         DO jj=1,il_shape(2)
-         
-            il_jmin=MAX(jj-1,1)
-            il_jmax=MIN(jj+1,il_shape(2))
-
-            IF( il_jmin==jj-1 .AND. il_jmax==jj+1 )THEN
-               j1=1  ; j2=3
-            ELSEIF( il_jmin==jj .AND. il_jmax==jj+1 )THEN
-               j1=1  ; j2=2
-            ELSEIF( il_jmin==jj-1 .AND. il_jmax==jj )THEN
-               j1=2  ; j2=3
-            ENDIF
-
-            dl_value(:,j1:j2,:)=dd_value(:,il_jmin:il_jmax,:)
-            IF( il_jmin == 1 )THEN
-               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
-               &                      DIM=2,         &
-               &                      SHIFT=-1,      &
-               &                      BOUNDARY=dl_value(:,1,:) )
-            ENDIF
-            IF( il_jmax == il_shape(2) )THEN
-               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
-               &                      DIM=2,         &
-               &                      SHIFT=1,       &
-               &                      BOUNDARY=dl_value(:,3,:))
-            ENDIF
-
-            IF( ll_discont )THEN
-               dl_min=MINVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
-               dl_max=MAXVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
-               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                  WHERE( dl_value(:,:,:) < 0_dp ) 
-                     dl_value(:,:,:) = dl_value(:,:,:)+360._dp
-                  END WHERE
-               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                  WHERE( dl_value(:,:,:) > 180 ) 
-                     dl_value(:,:,:) = dl_value(:,:,:)-180._dp
-                  END WHERE
-               ENDIF
-            ENDIF
-
-            WHERE( dl_value(:, 2,:) /= dd_fill .AND. & ! jj
-               &   dl_value(:, 3,:) /= dd_fill .AND. & ! jj+1
-            &      dl_value(:, 1,:) /= dd_fill )       ! jj-1
-
-               extrap_deriv_3D(:,jj,:)=&
-               &  ( dl_value(:,3,:) - dl_value(:,1,:) ) / &
-               &  REAL( il_jmax - il_jmin ,dp)         
-
-            END WHERE
-
-         ENDDO
-         
-      CASE('K')
-         ! compute derivative in k-direction
-         DO jk=1,il_shape(3)
-
-            il_kmin=MAX(jk-1,1)
-            il_kmax=MIN(jk+1,il_shape(3))
-
-            IF( il_kmin==jk-1 .AND. il_kmax==jk+1 )THEN
-               k1=1  ; k2=3
-            ELSEIF( il_kmin==jk .AND. il_kmax==jk+1 )THEN
-               k1=1  ; k2=2
-            ELSEIF( il_kmin==jk-1 .AND. il_kmax==jk )THEN
-               k1=2  ; k2=3
-            ENDIF
-
-            dl_value(:,:,k1:k2)=dd_value(:,:,il_kmin:il_kmax)
-            IF( il_kmin == 1 )THEN
-               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
-               &                      DIM=3,         &
-               &                      SHIFT=-1,      &
-               &                      BOUNDARY=dl_value(:,:,1) )
-            ENDIF
-            IF( il_kmax == il_shape(3) )THEN
-               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
-               &                        DIM=3,         &
-               &                        SHIFT=1,       &
-               &                        BOUNDARY=dl_value(:,:,3))
-            ENDIF
-
-            IF( ll_discont )THEN
-               dl_min=MINVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
-               dl_max=MAXVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
-               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                  WHERE( dl_value(:,:,:) < 0_dp ) 
-                     dl_value(:,:,:) = dl_value(:,:,:)+360._dp
-                  END WHERE
-               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                  WHERE( dl_value(:,:,:) > 180 ) 
-                     dl_value(:,:,:) = dl_value(:,:,:)-180._dp
-                  END WHERE
-               ENDIF
-            ENDIF         
-
-            WHERE( dl_value(:,:, 2) /= dd_fill .AND. & ! jk
-               &   dl_value(:,:, 3) /= dd_fill .AND. & ! jk+1
-               &   dl_value(:,:, 1) /= dd_fill )       ! jk-1
-
-               extrap_deriv_3D(:,:,jk)=&
-               &  ( dl_value(:,:,3) - dl_value(:,:,1) ) / &
-               &  REAL( il_kmax-il_kmin,dp)         
-
-            END WHERE
-
-         ENDDO
-
-      END SELECT
-
-      DEALLOCATE( dl_value )
-
-   END FUNCTION extrap_deriv_3D
    !-------------------------------------------------------------------
    !> @brief
@@ -1493,9 +845,11 @@
    !> 
    !> @details 
-   !> coefficients are  "grid distance" to the center of the box choosed to compute
-   !> extrapolation.
+   !> coefficients are  "grid distance" to the center of the box 
+   !> choosed to compute extrapolation.
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - decrease weight of third dimension
    !
    !> @param[in] dd_value  3D array of variable to be extrapolated
@@ -1544,7 +898,8 @@
 
                ! compute distance
+               ! "vertical weight" is lower than horizontal 
                dl_dist(ji,jj,jk) = (ji-il_imid)**2 + &
                &                   (jj-il_jmid)**2 + &
-               &                   (jk-il_kmid)**2
+               &                 3*(jk-il_kmid)**2
 
                IF( dl_dist(ji,jj,jk) /= 0 )THEN
@@ -1569,5 +924,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] dd_value  3D array of variable to be extrapolated
@@ -1658,5 +1013,7 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - decrease weight of third dimension
    !
    !> @param[in] dd_value  3D array of variable to be extrapolated
@@ -1705,7 +1062,8 @@
 
                ! compute distance
+               ! "vertical weight" is lower than horizontal 
                dl_dist(ji,jj,jk) = (ji-il_imid)**2 + &
                &                   (jj-il_jmid)**2 + &
-               &                   (jk-il_kmid)**2
+               &                 3*(jk-il_kmid)**2
 
                IF( dl_dist(ji,jj,jk) /= 0 )THEN
@@ -1732,5 +1090,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_value  3D array of variable to be extrapolated
@@ -1763,5 +1121,4 @@
       INTEGER(i4) :: jj
       INTEGER(i4) :: jk
-
       !----------------------------------------------------------------
 
@@ -1793,4 +1150,5 @@
             ENDDO
          ENDDO
+
 
          ! return value
@@ -1815,5 +1173,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013-Initial version
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_var variable 
@@ -1917,5 +1275,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013-Initial version
+   !> @date November, 2013 - Initial version
    !>
    !> @param[inout] td_var variable 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/file.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/file.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/file.f90	(revision 9987)
@@ -137,6 +137,7 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date November, 2013- Initial Version
-!> @date November, 2014 - Fix memory leaks bug
+!> @date November, 2013 - Initial Version
+!> @date November, 2014 
+!> - Fix memory leaks bug
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -288,7 +289,7 @@
    !>   
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak)
    !
@@ -409,7 +410,7 @@
    !>   
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
-   !>    - use function instead of overload assignment operator 
+   !> - use function instead of overload assignment operator 
    !> (to avoid memory leak)
    !
@@ -448,5 +449,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_file   file name
@@ -553,5 +554,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_file   file name
@@ -589,5 +590,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -604,6 +605,7 @@
       CHARACTER(LEN=lc) :: cl_dim
       LOGICAL           :: ll_error
-
-      INTEGER(i4) :: il_ind
+      LOGICAL           :: ll_warn 
+
+      INTEGER(i4)       :: il_ind
 
       ! loop indices
@@ -614,4 +616,5 @@
       ! check used dimension 
       ll_error=.FALSE.
+      ll_warn=.FALSE.
       DO ji=1,ip_maxdim
          il_ind=dim_get_index( td_file%t_dim(:), &
@@ -619,21 +622,18 @@
          &                     TRIM(td_var%t_dim(ji)%c_sname))
          IF( il_ind /= 0 )THEN
-         IF( td_var%t_dim(ji)%l_use  .AND. &
-         &   td_file%t_dim(il_ind)%l_use .AND. &
-         &   td_var%t_dim(ji)%i_len /= td_file%t_dim(il_ind)%i_len )THEN
-            ll_error=.TRUE.
-         ENDIF
+            IF( td_var%t_dim(ji)%l_use  .AND. &
+            &   td_file%t_dim(il_ind)%l_use .AND. &
+            &   td_var%t_dim(ji)%i_len /= td_file%t_dim(il_ind)%i_len )THEN
+               IF( INDEX( TRIM(td_var%c_axis), &
+               &          TRIM(fct_upper(td_var%t_dim(ji)%c_name))) == 0 )THEN
+                  ll_warn=.TRUE.
+               ELSE
+                  ll_error=.TRUE.
+               ENDIF
+            ENDIF
          ENDIF
       ENDDO
 
       IF( ll_error )THEN
-
-         file_check_var_dim=.FALSE.
-
-         CALL logger_error( &
-         &  " FILE CHECK VAR DIM: variable and file dimension differ"//&
-         &  " for variable "//TRIM(td_var%c_name)//&
-         &  " and file "//TRIM(td_file%c_name))
-
 
          cl_dim='(/'
@@ -659,4 +659,17 @@
          CALL logger_debug( " variable dimension: "//TRIM(cl_dim) )
 
+         file_check_var_dim=.FALSE.
+
+         CALL logger_error( &
+         &  " FILE CHECK VAR DIM: variable and file dimension differ"//&
+         &  " for variable "//TRIM(td_var%c_name)//&
+         &  " and file "//TRIM(td_file%c_name))
+
+      ELSEIF( ll_warn )THEN
+         CALL logger_warn( &
+         &  " FILE CHECK VAR DIM: variable and file dimension differ"//&
+         &  " for variable "//TRIM(td_var%c_name)//&
+         &  " and file "//TRIM(td_file%c_name)//". you should use"//&
+         &  " var_check_dim to remove useless dimension.")
       ELSE
 
@@ -679,5 +692,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - add dimension to file if need be
@@ -707,7 +720,7 @@
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " FILE ADD VAR: structure file unknown" )
          CALL logger_debug( " FILE ADD VAR: you should have used file_init before "//&
          & "running file_add_var" )
+         CALL logger_error( " FILE ADD VAR: structure file unknown" )
 
       ELSE
@@ -723,5 +736,6 @@
                &                                       td_var%c_stdname )
             ENDIF
-
+            CALL logger_debug( &
+            &  " FILE ADD VAR: ind "//TRIM(fct_str(il_ind)) )
             IF( il_ind /= 0 )THEN
 
@@ -739,5 +753,5 @@
             ELSE
 
-               CALL logger_trace( &
+               CALL logger_debug( &
                &  " FILE ADD VAR: add variable "//TRIM(td_var%c_name)//&
                &  ", standard name "//TRIM(td_var%c_stdname)//&
@@ -770,6 +784,4 @@
                         !il_rec=td_file%t_dim(3)%i_len
                   END SELECT
-                  CALL logger_info( &
-                     &  " FILE ADD VAR: variable index "//TRIM(fct_str(il_ind)))
 
                   IF( td_file%i_nvar > 0 )THEN
@@ -806,5 +818,5 @@
                         ENDIF
 
-                        IF( il_ind < td_file%i_nvar )THEN
+                        IF( il_ind < td_file%i_nvar+1 )THEN
                            ! variable with more dimension than new variable
                            td_file%t_var( il_ind+1 : td_file%i_nvar+1 ) = &
@@ -893,5 +905,7 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - define local variable structure to avoid mistake with pointer
    !
    !> @param[inout] td_file   file structure
@@ -907,4 +921,5 @@
       ! local variable
       INTEGER(i4)       :: il_ind
+      TYPE(TVAR)        :: tl_var
       !----------------------------------------------------------------
 
@@ -928,9 +943,10 @@
             IF( il_ind /= 0 )THEN
    
-               CALL file_del_var(td_file, td_file%t_var(il_ind))
+               tl_var=var_copy(td_file%t_var(il_ind))
+               CALL file_del_var(td_file, tl_var)
 
             ELSE
 
-               CALL logger_warn( &
+               CALL logger_debug( &
                &  " FILE DEL VAR NAME: there is no variable with name or "//&
                &  "standard name "//TRIM(cd_name)//" in file "//&
@@ -953,5 +969,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_file   file structure
@@ -1096,5 +1112,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1131,5 +1147,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1247,5 +1263,8 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - define local attribute structure to avoid mistake
+   !> with pointer
    !
    !> @param[inout] td_file   file structure
@@ -1261,4 +1280,5 @@
       ! local variable
       INTEGER(i4)       :: il_ind
+      TYPE(TATT)        :: tl_att
       !----------------------------------------------------------------
 
@@ -1282,9 +1302,10 @@
             IF( il_ind /= 0 )THEN
    
-               CALL file_del_att(td_file, td_file%t_att(il_ind))
+               tl_att=att_copy(td_file%t_att(il_ind))
+               CALL file_del_att(td_file, tl_att)
 
             ELSE
 
-               CALL logger_warn( &
+               CALL logger_debug( &
                &  " FILE DEL ATT NAME: there is no attribute with name "//&
                &  TRIM(cd_name)//" in file "//TRIM(td_file%c_name))
@@ -1305,5 +1326,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1403,5 +1424,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1444,5 +1465,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - do not reorder dimension, before put in file
@@ -1529,5 +1550,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1609,5 +1630,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1652,5 +1673,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1717,5 +1738,5 @@
          WRITE(*,'(/a)') " File variable"
          DO ji=1,td_file%i_nvar
-            CALL var_print(td_file%t_var(ji))!,.FALSE.)
+            CALL var_print(td_file%t_var(ji),.FALSE.)
          ENDDO
       ENDIF
@@ -1730,5 +1751,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_file   file structure
@@ -1769,5 +1790,10 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - add case to not return date (yyyymmdd) at the end of filename
+   !> @date February, 2015 
+   !> - add case to not return release number
+   !> we assume release number only on one digit (ex : file_v3.5.nc)
    !
    !> @param[in] cd_file   file name (without suffix)
@@ -1803,4 +1829,10 @@
          IF( .NOT. fct_is_num(file__get_number(2:)) )THEN
             file__get_number=''
+         ELSEIF( LEN(TRIM(file__get_number))-1 == 8 )THEN
+            ! date case yyyymmdd
+            file__get_number=''
+         ELSEIF( LEN(TRIM(file__get_number))-1 == 1 )THEN
+            ! release number case 
+            file__get_number=''
          ENDIF
       ELSE
@@ -1816,5 +1848,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1879,5 +1911,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1906,5 +1938,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -2019,5 +2051,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   array of file structure
@@ -2057,5 +2089,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[in] td_file   array of file 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/filter.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/filter.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/filter.f90	(revision 9987)
@@ -18,5 +18,6 @@
 !>          - rad > cutoff : @f$ filter=0 @f$               
 !>       - 'blackman'
-!>          - rad < cutoff : @f$ filter=0.42 + 0.5*COS(\pi*\frac{rad}{cutoff}) + 0.08*COS(2\pi*\frac{rad}{cutoff}) @f$
+!>          - rad < cutoff : @f$ filter=0.42 + 0.5*COS(\pi*\frac{rad}{cutoff}) + 
+!>                                      0.08*COS(2\pi*\frac{rad}{cutoff}) @f$
 !>          - rad > cutoff : @f$ filter=0 @f$
 !>       - 'gauss'
@@ -29,7 +30,10 @@
 !>
 !>    td_var\%c_filter(2) string character is the number of turn to be done<br/>
-!>    td_var\%c_filter(3) string character is the cut-off frequency (count in number of mesh grid)<br/>
-!>    td_var\%c_filter(4) string character is the halo radius (count in number of mesh grid)<br/>
-!>    td_var\%c_filter(5) string character is the alpha parameter (for gauss and butterworth method)<br/>
+!>    td_var\%c_filter(3) string character is the cut-off frequency 
+! >                       (count in number of mesh grid)<br/>
+!>    td_var\%c_filter(4) string character is the halo radius 
+!>                        (count in number of mesh grid)<br/>
+!>    td_var\%c_filter(5) string character is the alpha parameter 
+!>                        (for gauss and butterworth method)<br/>
 !>    
 !>    @note Filter method could be specify for each variable in namelist _namvar_,
@@ -40,5 +44,6 @@
 !>    The number of turn is specify using '*' separator.<br/>
 !>    Example:
-!>       - cn_varinfo='varname1:2*hamming(@f$cutoff@f$,@f$radius@f$)', 'varname2:gauss(@f$cutoff@f$,@f$radius@f$,@f$\alpha@f$)'
+!>       - cn_varinfo='varname1:flt=2*hamming(@f$cutoff@f$,@f$radius@f$)', 
+!>                    'varname2:flt=gauss(@f$cutoff@f$,@f$radius@f$,@f$\alpha@f$)'
 !>
 !>    to filter variable value:<br/>
@@ -106,5 +111,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure 
@@ -250,5 +255,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable 
@@ -296,5 +301,5 @@
 
       !3-extrapolate
-      CALL extrap_fill_value( td_var, id_iext=id_radius, id_jext=id_radius )
+      CALL extrap_fill_value( td_var ) !, id_iext=id_radius, id_jext=id_radius )
 
       !4-filtering
@@ -341,5 +346,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] dd_value  array of value to be filtered 
@@ -393,5 +398,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] dd_value  array of value to be filtered 
@@ -439,5 +444,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] dd_value  array of value to be filtered 
@@ -482,5 +487,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] dd_value  array of value to be filtered 
@@ -537,5 +542,5 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] dd_value  array of value to be filtered 
@@ -590,5 +595,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_name   filter name
@@ -649,5 +654,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_name   filter name
@@ -695,5 +700,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_cutoff cut-off frequency
@@ -749,5 +754,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_cutoff cut-off frequency
@@ -808,5 +813,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_cutoff cut-off frequency
@@ -863,5 +868,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_cutoff cut-off frequency
@@ -922,5 +927,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_cutoff cut-off frequency
@@ -978,5 +983,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] dd_cutoff cut-off frequency
@@ -1038,5 +1043,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] dd_cutoff cut-off frequency
@@ -1090,5 +1095,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] dd_cutoff cut-off frequency
@@ -1146,5 +1151,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] dd_cutoff cut-off frequency
@@ -1198,5 +1203,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] dd_cutoff cut-off frequency
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/function.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/function.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/function.f90	(revision 9987)
@@ -51,4 +51,9 @@
 !> @endcode
 !>
+!>  to check if character is real
+!> @code
+!>  ll_is_real=fct_is_real(cd_var)
+!> @endcode
+!>
 !>  to split string into substring and return one of the element:<br/>  
 !> @code
@@ -89,5 +94,6 @@
 ! REVISION HISTORY:
 !> @date November, 2013 - Initial Version
-!> @date September, 2014 - add header
+!> @date September, 2014 
+!> - add header
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -106,4 +112,5 @@
    PUBLIC :: fct_lower    !< convert character from upper to lower case
    PUBLIC :: fct_is_num   !< check if character is numeric
+   PUBLIC :: fct_is_real  !< check if character is real
    PUBLIC :: fct_split    !< split string into substring
    PUBLIC :: fct_basename !< return basename (name without path)
@@ -153,5 +160,5 @@
    ! 
    !> @author J.Paul 
-   !> - September, 2014- Initial Version 
+   !> @date September, 2014 - Initial Version 
    ! 
    !> @param[in] cd_char   string character
@@ -177,5 +184,5 @@
    ! 
    !> @author J.Paul 
-   !> - September, 2014- Initial Version 
+   !> @date September, 2014 - Initial Version 
    ! 
    !> @param[in] cd_char   string character
@@ -201,5 +208,5 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
+   !> @date November, 2013 - Initial Version 
    ! 
    !> @param[in] cd_char   string character
@@ -225,5 +232,5 @@
    ! 
    !> @author J.Paul 
-   !> - November, 2013- Initial Version 
+   !> @date November, 2013 - Initial Version 
    ! 
    !> @param[in] cd_char   string character
@@ -249,5 +256,5 @@
    ! 
    !> @author J.Paul 
-   !> - November, 2013- Initial Version 
+   !> @date November, 2013 - Initial Version 
    ! 
    !> @param[in] cd_char   string character
@@ -273,5 +280,5 @@
    !>
    !> @author J.Paul 
-   !> - November, 2013- Initial Version 
+   !> @date November, 2013 - Initial Version 
    !>
    !> @param[in] cd_char   string character
@@ -297,5 +304,5 @@
    !>
    !> @author J.Paul 
-   !> - November, 2013- Initial Version 
+   !> @date November, 2013 - Initial Version 
    !>
    !> @param[in] cd_char   string character
@@ -321,5 +328,5 @@
    !>
    !> @author J.Paul 
-   !> - November, 2013- Initial Version 
+   !> @date November, 2013 - Initial Version 
    !>
    !> @return file id 
@@ -344,5 +351,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] id_status
@@ -365,5 +372,5 @@
    !
    !> @author J.Paul
-   !> - November, 2014- Initial Version
+   !> @date November, 2014 - Initial Version
    !>
    !> @param[in] cd_msg optional message to be added
@@ -387,5 +394,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] ld_var logical variable
@@ -409,5 +416,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] bd_var integer(1) variable
@@ -431,5 +438,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] sd_var integer(2) variable
@@ -453,5 +460,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] id_var integer(4) variable
@@ -475,5 +482,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] kd_var integer(8) variable
@@ -497,5 +504,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] rd_var real(4) variable
@@ -519,5 +526,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_var real(8) variable
@@ -544,5 +551,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_arr array of character
@@ -590,5 +597,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_var character
@@ -647,5 +654,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_var character
@@ -697,5 +704,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_var character
@@ -723,4 +730,67 @@
    END FUNCTION fct_is_num
    !-------------------------------------------------------------------
+   !> @brief This function check if character is real number.
+   !
+   !> @details
+   !> it allows exponantial and decimal number
+   !> exemple :  1e6, 2.3
+   !>
+   !> @author J.Paul
+   !> @date June, 2015 - Initial Version
+   !
+   !> @param[in] cd_var character
+   !> @return character is numeric
+   !-------------------------------------------------------------------
+   PURE LOGICAL FUNCTION fct_is_real(cd_var)
+      IMPLICIT NONE
+      ! Argument      
+      CHARACTER(LEN=*), INTENT(IN) :: cd_var
+   
+      ! local variables
+      LOGICAL :: ll_exp
+      LOGICAL :: ll_dec
+   
+      ! loop indices
+      INTEGER :: ji
+      !----------------------------------------------------------------
+   
+      ll_exp=.TRUE.
+      ll_dec=.FALSE.
+      DO ji=1,LEN(TRIM(cd_var))
+         IF( IACHAR(cd_var(ji:ji)) >= IACHAR('0') .AND. &
+         &   IACHAR(cd_var(ji:ji)) <= IACHAR('9') )THEN
+   
+            fct_is_real=.TRUE.
+            ll_exp=.FALSE.
+      
+         ELSEIF( TRIM(cd_var(ji:ji))=='e' )THEN
+         
+            IF( ll_exp .OR. ji== LEN(TRIM(cd_var)) )THEN
+               fct_is_real=.FALSE.
+               EXIT
+            ELSE 
+               ll_exp=.TRUE.
+            ENDIF
+   
+         ELSEIF( TRIM(cd_var(ji:ji))=='.' )THEN
+   
+            IF( ll_dec )THEN
+               fct_is_real=.FALSE.
+               EXIT
+            ELSE
+               fct_is_real=.TRUE.
+               ll_dec=.TRUE.
+            ENDIF
+   
+         ELSE
+   
+            fct_is_real=.FALSE.
+            EXIT
+   
+         ENDIF
+      ENDDO
+   
+   END FUNCTION fct_is_real
+   !-------------------------------------------------------------------
    !> @brief This function split string of character 
    !> using separator character, by default '|',
@@ -728,5 +798,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_string string of character
@@ -808,5 +878,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_string string of character
@@ -873,5 +943,5 @@
    !> Optionally you could specify another separator.
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_string filename
@@ -914,5 +984,5 @@
    !> Optionally you could specify another separator.
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_string filename
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/grid.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/grid.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/grid.f90	(revision 9987)
@@ -149,5 +149,5 @@
 !>    CALL grid_check_coincidence(td_coord0, td_coord1, 
 !>                                id_imin0, id_imax0, id_jmin0, id_jmax0
-!>                                [,id_rho])
+!>                                ,id_rho)
 !> @endcode
 !>       - td_coord0 is coarse grid coordinate mpp structure
@@ -161,5 +161,5 @@
 !>       - id_jmax0  is coarse grid upper right corner j-indice of fine grid 
 !> domain 
-!>       - id_rho    is array of refinement factor (default 1)
+!>       - id_rho    is array of refinement factor 
 !>
 !>    to add ghost cell at boundaries:<br/>
@@ -213,4 +213,6 @@
 !> @date October, 2014
 !> - use mpp file structure instead of file
+!> @date February, 2015
+!> - add function grid_fill_small_msk to fill small domain inside bigger one
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -255,4 +257,5 @@
    PUBLIC :: grid_split_domain         !< compute closed sea domain 
    PUBLIC :: grid_fill_small_dom       !< fill small closed sea with fill value 
+   PUBLIC :: grid_fill_small_msk       !< fill small domain inside bigger one 
 
                                      ! get closest coarse grid indices of fine grid domain
@@ -352,5 +355,5 @@
    !> @note need all processor files to be there
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @param[inout] td_file file structure 
@@ -466,7 +469,7 @@
    !> - compute East West overlap
    !>
-   !> @note need all processor files to be there
+   !> @note need all processor files
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @param[in] td_mpp mpp structure 
@@ -496,4 +499,5 @@
       il_ew   =-1
 
+      CALL logger_info("GRID GET INFO: look for "//TRIM(td_mpp%c_name))
       ! copy structure
       tl_mpp=mpp_copy(td_mpp)
@@ -523,9 +527,11 @@
       ENDIF
 
+      CALL logger_info("GRID GET INFO: perio "//TRIM(fct_str(il_perio)))
+
       SELECT CASE(il_perio)
       CASE(3,4)
+         il_pivot=1
+      CASE(5,6)
          il_pivot=0
-      CASE(5,6)
-         il_pivot=1
       CASE(0,1,2)
          il_pivot=1
@@ -534,4 +540,5 @@
       IF( il_pivot < 0 .OR. il_pivot > 1 )THEN
          ! get pivot
+         CALL logger_info("GRID GET INFO: look for pivot ")
          il_pivot=grid_get_pivot(tl_mpp)
       ENDIF
@@ -539,4 +546,5 @@
       IF( il_perio < 0 .OR. il_perio > 6 )THEN
          ! get periodicity
+         CALL logger_info("GRID GET INFO: look for perio ")
          il_perio=grid_get_perio(tl_mpp, il_pivot)
       ENDIF
@@ -544,4 +552,5 @@
       IF( il_ew < 0 )THEN
          ! get periodicity
+         CALL logger_info("GRID GET INFO: look for overlap ")
          il_ew=grid_get_ew_overlap(tl_mpp)
       ENDIF
@@ -595,5 +604,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !> @date September, 2014
    !> - add dummy loop in case variable not over right point.
@@ -708,5 +717,5 @@
    !> 
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !
    !> @param[in] dd_value array of value
@@ -783,5 +792,5 @@
 
          IF( ll_check )THEN
-            CALL logger_info("GRID GET PIVOT: T-pivot")
+            CALL logger_info("GRID GET PIVOT: F-pivot")
             grid__get_pivot_varT=0
          ENDIF
@@ -801,5 +810,5 @@
    !> 
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !
    !> @param[in] dd_value array of value
@@ -876,5 +885,5 @@
 
          IF( ll_check )THEN
-            CALL logger_info("GRID GET PIVOT: T-pivot")
+            CALL logger_info("GRID GET PIVOT: F-pivot")
             grid__get_pivot_varU=0
          ENDIF
@@ -894,5 +903,5 @@
    !> 
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !
    !> @param[in] dd_value array of value
@@ -969,5 +978,5 @@
 
          IF( ll_check )THEN
-            CALL logger_info("GRID GET PIVOT: T-pivot")
+            CALL logger_info("GRID GET PIVOT: F-pivot")
             grid__get_pivot_varV=0
          ENDIF
@@ -987,5 +996,5 @@
    !> 
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !
    !> @param[in] dd_value array of value
@@ -1062,5 +1071,5 @@
 
          IF( ll_check )THEN
-            CALL logger_info("GRID GET PIVOT: T-pivot")
+            CALL logger_info("GRID GET PIVOT: F-pivot")
             grid__get_pivot_varF=0
          ENDIF
@@ -1083,5 +1092,5 @@
    !>
    !> @author J.Paul
-   !> - Ocotber, 2014- Initial version
+   !> @date Ocotber, 2014 - Initial version
    !
    !> @param[in] td_file file structure
@@ -1172,5 +1181,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !
    !> @param[in] td_mpp   mpp file structure
@@ -1277,13 +1286,13 @@
    !> 1: cyclic east-west boundary
    !> 2: symmetric boundary condition across the equator
-   !> 3: North fold boundary (with a F-point pivot)
-   !> 4: North fold boundary (with a F-point pivot) and cyclic east-west boundary
-   !> 5: North fold boundary (with a T-point pivot)
-   !> 6: North fold boundary (with a T-point pivot) and cyclic east-west boundary
+   !> 3: North fold boundary (with a T-point pivot)
+   !> 4: North fold boundary (with a T-point pivot) and cyclic east-west boundary
+   !> 5: North fold boundary (with a F-point pivot)
+   !> 6: North fold boundary (with a F-point pivot) and cyclic east-west boundary
    !>
    !> @warning pivot point should have been computed before run this script. see grid_get_pivot.
    !>
    !> @author J.Paul
-   !> - November, 2013- Subroutine written
+   !> @date November, 2013 - Initial version
    !> @date October, 2014
    !> - work on variable structure instead of file structure
@@ -1452,5 +1461,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !>
    !> @param[in] td_file   file structure
@@ -1537,13 +1546,13 @@
    !> 1: cyclic east-west boundary
    !> 2: symmetric boundary condition across the equator
-   !> 3: North fold boundary (with a F-point pivot)
-   !> 4: North fold boundary (with a F-point pivot) and cyclic east-west boundary
-   !> 5: North fold boundary (with a T-point pivot)
-   !> 6: North fold boundary (with a T-point pivot) and cyclic east-west boundary
+   !> 3: North fold boundary (with a T-point pivot)
+   !> 4: North fold boundary (with a T-point pivot) and cyclic east-west boundary
+   !> 5: North fold boundary (with a F-point pivot)
+   !> 6: North fold boundary (with a F-point pivot) and cyclic east-west boundary
    !>
    !> @warning pivot point should have been computed before run this script. see grid_get_pivot.
    !>
    !> @author J.Paul
-   !> - October, 2014 - Initial version
+   !> @date October, 2014 - Initial version
    !
    !> @param[in] td_mpp   mpp file structure
@@ -1634,5 +1643,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -1746,5 +1755,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @param[in] td_file file structure 
@@ -1797,5 +1806,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -1853,5 +1862,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_lat latitude variable structure 
@@ -1890,5 +1899,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -1978,9 +1987,12 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use grid point to read coordinates variable. 
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
+   !> @date February, 2015
+   !> - use longitude or latitude as standard name, if can not find 
+   !> longitude_T, latitude_T...
    !>
    !> @param[in] td_coord0 coarse grid coordinate mpp structure
@@ -2004,24 +2016,25 @@
 
       ! local variable
-      TYPE(TMPP) :: tl_coord0
-      TYPE(TMPP) :: tl_coord1
-
-      TYPE(TVAR)  :: tl_lon0
-      TYPE(TVAR)  :: tl_lat0
-      TYPE(TVAR)  :: tl_lon1
-      TYPE(TVAR)  :: tl_lat1
-
-      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
-
-      INTEGER(i4), DIMENSION(2,2)         :: il_xghost0
-      INTEGER(i4), DIMENSION(2,2)         :: il_xghost1
-
-      INTEGER(i4) :: il_imin0
-      INTEGER(i4) :: il_imax0
-      INTEGER(i4) :: il_jmin0
-      INTEGER(i4) :: il_jmax0
-
-      CHARACTER(LEN= 1) :: cl_point
-      CHARACTER(LEN=lc) :: cl_name
+      CHARACTER(LEN= 1)                        :: cl_point
+      CHARACTER(LEN=lc)                        :: cl_name
+
+      INTEGER(i4)                              :: il_imin0
+      INTEGER(i4)                              :: il_imax0
+      INTEGER(i4)                              :: il_jmin0
+      INTEGER(i4)                              :: il_jmax0
+      INTEGER(i4)                              :: il_ind
+
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost0
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost1
+
+      INTEGER(i4), DIMENSION(:)  , ALLOCATABLE :: il_rho
+
+      TYPE(TVAR)                               :: tl_lon0
+      TYPE(TVAR)                               :: tl_lat0
+      TYPE(TVAR)                               :: tl_lon1
+      TYPE(TVAR)                               :: tl_lat1
+
+      TYPE(TMPP)                               :: tl_coord0
+      TYPE(TMPP)                               :: tl_coord1
 
       ! loop indices
@@ -2057,6 +2070,21 @@
          ! read coarse longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
          
@@ -2077,6 +2105,21 @@
          ! read fine longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name)) 
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
  
@@ -2127,9 +2170,12 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use grid point to read coordinates variable.
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
+   !> @date February, 2015
+   !> - use longitude or latitude as standard name, if can not find 
+   !> longitude_T, latitude_T...
    !>
    !> @param[in] td_longitude0   coarse grid longitude
@@ -2154,15 +2200,17 @@
 
       ! local variable
-      TYPE(TMPP)  :: tl_coord1
-
-      TYPE(TVAR)  :: tl_lon1
-      TYPE(TVAR)  :: tl_lat1
-
-      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
-
-      INTEGER(i4), DIMENSION(2,2)       :: il_xghost
-
-      CHARACTER(LEN= 1) :: cl_point
-      CHARACTER(LEN=lc) :: cl_name
+      CHARACTER(LEN= 1)                        :: cl_point
+      CHARACTER(LEN=lc)                        :: cl_name
+
+      INTEGER(i4)                              :: il_ind
+
+      INTEGER(i4), DIMENSION(:)  , ALLOCATABLE :: il_rho
+
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost
+
+      TYPE(TVAR)                               :: tl_lon1
+      TYPE(TVAR)                               :: tl_lat1
+
+      TYPE(TMPP)                               :: tl_coord1
 
       ! loop indices
@@ -2209,6 +2257,21 @@
          ! read fine longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//"in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//"in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
          
@@ -2244,9 +2307,12 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use grid point to read coordinates variable.
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
+   !> @date February, 2015
+   !> - use longitude or latitude as standard name, if can not find 
+   !> longitude_T, latitude_T...
    !> 
    !> @param[in] td_coord0 coarse grid coordinate mpp structure
@@ -2271,20 +2337,21 @@
 
       ! local variable
-      TYPE(TMPP)  :: tl_coord0
-
-      TYPE(TVAR)  :: tl_lon0
-      TYPE(TVAR)  :: tl_lat0
-
-      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
-
-      INTEGER(i4), DIMENSION(2,2)       :: il_xghost
-
-      INTEGER(i4) :: il_imin0
-      INTEGER(i4) :: il_imax0
-      INTEGER(i4) :: il_jmin0
-      INTEGER(i4) :: il_jmax0
-
-      CHARACTER(LEN= 1) :: cl_point
-      CHARACTER(LEN=lc) :: cl_name      
+      CHARACTER(LEN= 1)                        :: cl_point
+      CHARACTER(LEN=lc)                        :: cl_name      
+
+      INTEGER(i4)                              :: il_imin0
+      INTEGER(i4)                              :: il_imax0
+      INTEGER(i4)                              :: il_jmin0
+      INTEGER(i4)                              :: il_jmax0
+      INTEGER(i4)                              :: il_ind
+
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE   :: il_rho
+
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost
+
+      TYPE(TVAR)                               :: tl_lon0
+      TYPE(TVAR)                               :: tl_lat0
+
+      TYPE(TMPP)                               :: tl_coord0
 
       ! loop indices
@@ -2330,6 +2397,21 @@
          ! read coarse longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//"in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET COARSE INDEX: no variable "//&
+            &  TRIM(cl_name)//"in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
 
@@ -2377,5 +2459,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - check grid point
@@ -2520,5 +2602,5 @@
             CALL grid_del_ghost(tl_lon0, il_xghost0(:,:))
             CALL grid_del_ghost(tl_lat0, il_xghost0(:,:))
-            
+ 
             ! "global" coarse grid indice
             il_imin0=1
@@ -2568,4 +2650,10 @@
             IF( dl_lon1_ll == tl_lon1%d_fill .OR. &
             &   dl_lat1_ll == tl_lat1%d_fill )THEN
+               CALL logger_debug("GRID GET COARSE INDEX: lon "//&
+               &  TRIM(fct_str(dl_lon1_ll))//" "//&
+               &  TRIM(fct_str(tl_lon1%d_fill)) )
+               CALL logger_debug("GRID GET COARSE INDEX: lat "//&
+               &  TRIM(fct_str(dl_lat1_ll))//" "//&
+               &  TRIM(fct_str(tl_lat1%d_fill)) )
                CALL logger_error("GRID GET COARSE INDEX: lower left corner "//&
                &                 "point is FillValue. remove ghost cell "//&
@@ -2632,5 +2720,4 @@
             ji = il_iul(1)
             jj = il_iul(2)
-
             IF( ABS(tl_lon0%d_value(ji,jj,1,1)-dl_lon1_ul) > dp_delta )THEN
                IF(tl_lon0%d_value(ji,jj,1,1) > dl_lon1_ul )THEN
@@ -2647,5 +2734,4 @@
                ENDIF
             ENDIF
-
             IF( ABS(tl_lat0%d_value(ji,jj,1,1)-dl_lat1_ul) > dp_delta )THEN
                IF(tl_lat0%d_value(ji,jj,1,1) < dl_lat1_ul )THEN
@@ -2798,5 +2884,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_lon longitude structure 
@@ -2866,5 +2952,6 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 - change dichotomy method to manage ORCA grid
    !
    !> @param[in] dd_lon0   coarse grid array of longitude
@@ -2872,8 +2959,8 @@
    !> @param[in] dd_lon1   fine   grid longitude
    !> @param[in] dd_lat1   fine   grid latitude
+   !> @param[in] dd_fill   fill value
    !> @return coarse grid indices of closest point of fine grid point
-   !>
-   !-------------------------------------------------------------------
-   FUNCTION grid_get_closest( dd_lon0, dd_lat0, dd_lon1, dd_lat1  )
+   !-------------------------------------------------------------------
+   FUNCTION grid_get_closest( dd_lon0, dd_lat0, dd_lon1, dd_lat1, dd_fill )
       IMPLICIT NONE
       ! Argument
@@ -2882,4 +2969,5 @@
       REAL(dp),                 INTENT(IN) :: dd_lon1
       REAL(dp),                 INTENT(IN) :: dd_lat1
+      REAL(dp),                 INTENT(IN), OPTIONAL :: dd_fill
 
       ! function
@@ -2929,46 +3017,71 @@
 
       ll_north=.FALSE.
-      ll_continue=.TRUE.
-
-      ! look for meridian 0°/360°
-      il_jmid = il_jinf + INT(il_shape(2)/2)
-      il_ind(:) = MAXLOC( dl_lon0(:,il_jmid), dl_lon0(:,il_jmid) <= 360._dp )
-
-      il_imid=il_ind(1)
-
-      IF( dl_lon1 == dl_lon0(il_imid,il_jmid) .AND. &
-      &   dd_lat1 == dd_lat0(il_imid,il_jmid) )THEN
-
-         il_iinf = il_imid ;  il_isup = il_imid
-         il_jinf = il_jmid ;  il_jsup = il_jmid
-
-         ll_continue=.FALSE.
-
-      ELSE
-         IF( dl_lon1 < dl_lon0(il_isup,il_jmid) .AND. &
-         &   il_imid /= il_isup )THEN
-
-            ! point east
-            il_iinf = il_imid
-      
-         ELSE IF( dl_lon1 > dl_lon0(il_iinf,il_jmid) .AND. &
-         &        il_imid /= il_iinf )THEN
-
-            ! point west
-            il_isup = il_imid
-
-         ENDIF
+      ll_continue=.FALSE.
+
+      ! avoid to use fillvalue for reduce domain on first time
+      IF( PRESENT(dd_fill) )THEN
+         DO WHILE( ALL(dl_lon0(il_isup,:) == dd_fill) )
+            il_isup=il_isup-1
+         ENDDO
+         DO WHILE( ALL(dl_lon0(il_iinf,:) == dd_fill) )
+            il_iinf=il_iinf+1
+         ENDDO
+         DO WHILE( ALL(dd_lat0(:,il_jsup) == dd_fill) )
+            il_jsup=il_jsup-1
+         ENDDO
+         DO WHILE( ALL(dd_lat0(:,il_jinf) == dd_fill) )
+            il_jinf=il_jinf+1
+         ENDDO
 
          il_shape(1)= il_isup - il_iinf + 1
          il_shape(2)= il_jsup - il_jinf + 1
 
-         il_imid = il_iinf + INT(il_shape(1)/2) 
+      ENDIF
+
+      ! special case for north ORCA grid
+      IF( dd_lat1 > 19. .AND. dl_lon1 < 74.  )THEN
+         ll_north=.TRUE.
+      ENDIF
+
+      IF( .NOT. ll_north )THEN
+         ! look for meridian 0°/360°
          il_jmid = il_jinf + INT(il_shape(2)/2)
-
-         ! exit if too close from north fold (safer)
-         IF( dd_lat0(il_imid,il_jmid) > 50.0 ) ll_north=.TRUE.
-
-         ! exit when close enough of point
-         IF( ANY(il_shape(:) < 10 ) ) ll_continue=.FALSE.
+         il_ind(:) = MAXLOC( dl_lon0(il_iinf:il_isup,il_jmid), &
+         &                   dl_lon0(il_iinf:il_isup,il_jmid) <= 360._dp )
+
+         il_imid=il_ind(1)
+
+         IF( dl_lon1 == dl_lon0(il_imid,il_jmid) .AND. &
+         &   dd_lat1 == dd_lat0(il_imid,il_jmid) )THEN
+
+            il_iinf = il_imid ;  il_isup = il_imid
+            il_jinf = il_jmid ;  il_jsup = il_jmid
+
+         ELSE
+            IF( ALL(dl_lon0(il_isup,il_jinf:il_jsup) >  dl_lon1 ) .AND. &
+            &   il_imid /= il_isup )THEN
+               ! 0 < lon1 < lon0(isup)
+               ! point east
+               il_iinf = il_imid+1
+               ll_continue=.TRUE.
+         
+            ELSE IF( ALL(dl_lon0(il_iinf,il_jinf:il_jsup) <  dl_lon1 ) .AND. &
+            &        il_imid /= il_iinf )THEN
+               ! lon0(iinf) < lon1 < 360
+               ! point west
+               il_isup = il_imid
+               ll_continue=.TRUE.
+
+            ENDIF
+
+            il_shape(1)= il_isup - il_iinf + 1
+            il_shape(2)= il_jsup - il_jinf + 1
+
+            il_imid = il_iinf + INT(il_shape(1)/2) 
+            il_jmid = il_jinf + INT(il_shape(2)/2)
+
+            ! exit when close enough of point
+            IF( ANY(il_shape(:) < 10 ) ) ll_continue=.FALSE.
+         ENDIF
       ENDIF
 
@@ -2976,4 +3089,5 @@
       DO WHILE( ll_continue .AND. .NOT. ll_north )
 
+         ll_continue=.FALSE.
          IF( dl_lon1 == dl_lon0(il_imid,il_jmid) .AND. &
          &   dd_lat1 == dd_lat0(il_imid,il_jmid) )THEN
@@ -2982,28 +3096,30 @@
             il_jinf = il_jmid ;  il_jsup = il_jmid
 
-            ll_continue=.FALSE.
-
          ELSE
-            IF( dl_lon1 > dl_lon0(il_imid,il_jmid) )THEN
+            IF( ALL(dl_lon0(il_imid,il_jinf:il_jsup) <  dl_lon1) )THEN    
 
                ! point east
                il_iinf = il_imid
+               ll_continue=.TRUE.
         
-            ELSE IF(dl_lon1 < dl_lon0(il_imid,il_jmid) )THEN
+            ELSE IF( ALL(dl_lon0(il_imid,il_jinf:il_jsup) >  dl_lon1) )THEN    
 
                ! point west
                il_isup = il_imid
+               ll_continue=.TRUE.
 
             ENDIF
 
-            IF( dd_lat1 > dd_lat0(il_imid,il_jmid) )THEN
+            IF( ALL(dd_lat0(il_iinf:il_isup,il_jmid) <  dd_lat1) )THEN    
                
                ! point north
                il_jinf = il_jmid
-
-            ELSE IF(dd_lat1 < dd_lat0(il_imid,il_jmid) )THEN
+               ll_continue=.TRUE.
+
+            ELSE IF( ALL(dd_lat0(il_iinf:il_isup,il_jmid) > dd_lat1) )THEN    
 
                ! point south
                il_jsup = il_jmid
+               ll_continue=.TRUE.
             
             ENDIF
@@ -3014,7 +3130,4 @@
             il_imid = il_iinf + INT(il_shape(1)/2) 
             il_jmid = il_jinf + INT(il_shape(2)/2)
-
-            ! exit if too close from north fold (safer)
-            IF( dd_lat0(il_imid,il_jmid) > 50.0 ) ll_north=.TRUE.
 
             ! exit when close enough of point
@@ -3049,5 +3162,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_lon    grid longitude array
@@ -3055,7 +3168,8 @@
    !> @param[in] dd_lonA   longitude of point A
    !> @param[in] dd_latA   latitude  of point A
+   !> @param[in] dd_fill
    !> @return array of distance between point A and grid points.
    !-------------------------------------------------------------------
-   FUNCTION grid_distance(dd_lon, dd_lat, dd_lonA, dd_latA)
+   FUNCTION grid_distance(dd_lon, dd_lat, dd_lonA, dd_latA )
       IMPLICIT NONE
       ! Argument      
@@ -3110,9 +3224,10 @@
          DO ji=1,il_shape(1)
             IF( dl_lon(ji,jj) == dl_lonA .AND. &
-            &   dl_lat(ji,jj) == dl_laTA )THEN
+            &   dl_lat(ji,jj) == dl_latA )THEN
                grid_distance(ji,jj)=0.0
             ELSE
                dl_tmp= SIN(dl_latA)*SIN(dl_lat(ji,jj)) + &
-               &       COS(dl_latA)*COS(dl_lat(ji,jj))*COS(dl_lon(ji,jj)-dl_lonA)
+               &       COS(dl_latA)*COS(dl_lat(ji,jj)) * &
+               &       COS(dl_lon(ji,jj)-dl_lonA)
                ! check to avoid mistake with ACOS
                IF( dl_tmp < -1.0 ) dl_tmp = -1.0
@@ -3136,5 +3251,5 @@
    !
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -3170,16 +3285,17 @@
 
       ! local variable
-      INTEGER(i4) :: il_imin0
-      INTEGER(i4) :: il_jmin0
-      INTEGER(i4) :: il_imax0
-      INTEGER(i4) :: il_jmax0
+      INTEGER(i4)                              :: il_imin0
+      INTEGER(i4)                              :: il_jmin0
+      INTEGER(i4)                              :: il_imax0
+      INTEGER(i4)                              :: il_jmax0
+      INTEGER(i4)                              :: il_ind
       
-      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE   :: il_rho
       
-      INTEGER(i4), DIMENSION(2,2)         :: il_xghost0
-      INTEGER(i4), DIMENSION(2,2)         :: il_xghost1
-
-      CHARACTER(LEN= 1) :: cl_point
-      CHARACTER(LEN=lc) :: cl_name
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost0
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost1
+
+      CHARACTER(LEN= 1)                        :: cl_point
+      CHARACTER(LEN=lc)                        :: cl_name
 
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon0
@@ -3188,11 +3304,11 @@
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat1
 
-      TYPE(TVAR) :: tl_lon0
-      TYPE(TVAR) :: tl_lat0
-      TYPE(TVAR) :: tl_lon1
-      TYPE(TVAR) :: tl_lat1
-
-      TYPE(TMPP) :: tl_coord0
-      TYPE(TMPP) :: tl_coord1
+      TYPE(TVAR)                               :: tl_lon0
+      TYPE(TVAR)                               :: tl_lat0
+      TYPE(TVAR)                               :: tl_lon1
+      TYPE(TVAR)                               :: tl_lat1
+
+      TYPE(TMPP)                               :: tl_coord0
+      TYPE(TMPP)                               :: tl_coord1
       
       ! loop indices
@@ -3227,6 +3343,21 @@
          ! read coarse longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
          
@@ -3267,6 +3398,21 @@
          ! read fine longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
  
@@ -3318,5 +3464,5 @@
    !
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -3354,18 +3500,18 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+      INTEGER(i4)                              :: il_ind
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost1
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE   :: il_rho
       
-      INTEGER(i4), DIMENSION(2,2)         :: il_xghost1
-
-      CHARACTER(LEN= 1) :: cl_point
-      CHARACTER(LEN=lc) :: cl_name
+      CHARACTER(LEN= 1)                        :: cl_point
+      CHARACTER(LEN=lc)                        :: cl_name
 
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon1
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat1
 
-      TYPE(TVAR) :: tl_lon1
-      TYPE(TVAR) :: tl_lat1
-
-      TYPE(TMPP) :: tl_coord1
+      TYPE(TVAR)                               :: tl_lon1
+      TYPE(TVAR)                               :: tl_lat1
+
+      TYPE(TMPP)                               :: tl_coord1
       ! loop indices
       !----------------------------------------------------------------
@@ -3397,6 +3543,21 @@
          ! read fine longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord1%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord1%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
  
@@ -3446,5 +3607,5 @@
    !
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -3483,23 +3644,24 @@
 
       ! local variable
-      INTEGER(i4) :: il_imin0
-      INTEGER(i4) :: il_jmin0
-      INTEGER(i4) :: il_imax0
-      INTEGER(i4) :: il_jmax0
+      INTEGER(i4)                              :: il_imin0
+      INTEGER(i4)                              :: il_jmin0
+      INTEGER(i4)                              :: il_imax0
+      INTEGER(i4)                              :: il_jmax0
+      INTEGER(i4)                              :: il_ind
       
-      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE   :: il_rho
       
-      INTEGER(i4), DIMENSION(2,2)         :: il_xghost0
-
-      CHARACTER(LEN= 1) :: cl_point
-      CHARACTER(LEN=lc) :: cl_name
+      INTEGER(i4), DIMENSION(2,2)              :: il_xghost0
+
+      CHARACTER(LEN= 1)                        :: cl_point
+      CHARACTER(LEN=lc)                        :: cl_name
 
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon0
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat0
 
-      TYPE(TVAR) :: tl_lon0
-      TYPE(TVAR) :: tl_lat0
-
-      TYPE(TMPP) :: tl_coord0
+      TYPE(TVAR)                               :: tl_lon0
+      TYPE(TVAR)                               :: tl_lat0
+
+      TYPE(TMPP)                               :: tl_coord0
       ! loop indices
       !----------------------------------------------------------------
@@ -3530,6 +3692,21 @@
          ! read coarse longitue and latitude
          WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use longitude.")
+            WRITE(cl_name,*) 'longitude'
+         ENDIF
          tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+
          WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         il_ind=var_get_id(tl_coord0%t_proc(1)%t_var(:), cl_name)
+         IF( il_ind == 0 )THEN
+            CALL logger_warn("GRID GET FINE OFFSET: no variable "//&
+            &  TRIM(cl_name)//" in file "//TRIM(tl_coord0%c_name)//". &
+            &  try to use latitude.")
+            WRITE(cl_name,*) 'latitude'
+         ENDIF
          tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
          
@@ -3585,7 +3762,10 @@
    !
    !> @author J.Paul
-   !> - November, 2013 - Initial Version
-   !> @date September, 2014 - rename from grid_get_fine_offset
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date September, 2014 
+   !> - rename from grid_get_fine_offset
+   !> @date May, 2015 
+   !> - improve way to find offset
+   !>
    !> @param[in] dd_lon0   coarse grid longitude array 
    !> @param[in] dd_lat0   coarse grid latitude  array
@@ -3620,8 +3800,12 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(2) :: il_shape0
-      INTEGER(i4), DIMENSION(2) :: il_shape1
+      INTEGER(i4), DIMENSION(2)                :: il_shape0
+      INTEGER(i4), DIMENSION(2)                :: il_shape1
+
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon0
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon1
+
+      LOGICAL                                  :: ll_ii
+      LOGICAL                                  :: ll_ij
       
       ! loop indices
@@ -3657,11 +3841,14 @@
       grid__get_fine_offset_cc(:,:)=-1
 
-      IF( il_shape1(1) > 1 )THEN
-
-         ! look for i-direction left offset 
+      IF( il_shape1(jp_J) == 1 )THEN
+          
+         grid__get_fine_offset_cc(jp_J,:)=((id_rho(jp_J)-1)/2)
+
+         ! work on i-direction
+         ! look for i-direction left offset
          IF( dl_lon1(1,1) < dl_lon0(id_imin0+1,id_jmin0) )THEN
             DO ji=1,id_rho(jp_I)+2
                IF( dl_lon1(ji,1) > dl_lon0(id_imin0+1,id_jmin0) - dp_delta )THEN
-                  grid__get_fine_offset_cc(1,1)=(id_rho(jp_I)+1)-ji
+                  grid__get_fine_offset_cc(jp_I,1)=(id_rho(jp_I)+1)-ji
                   EXIT
                ENDIF
@@ -3671,11 +3858,10 @@
             &                 " not match fine grid lower left corner.")
          ENDIF
-
          ! look for i-direction right offset
-         IF( dl_lon1(il_shape1(1),1) > dl_lon0(id_imax0-1,id_jmin0) )THEN
+         IF( dl_lon1(il_shape1(jp_I),1) > dl_lon0(id_imax0-1,id_jmin0) )THEN
             DO ji=1,id_rho(jp_I)+2
-               ii=il_shape1(1)-ji+1
+               ii=il_shape1(jp_I)-ji+1
                IF( dl_lon1(ii,1) < dl_lon0(id_imax0-1,id_jmin0) + dp_delta )THEN
-                  grid__get_fine_offset_cc(1,2)=(id_rho(jp_I)+1)-ji
+                  grid__get_fine_offset_cc(jp_I,2)=(id_rho(jp_I)+1)-ji
                   EXIT
                ENDIF
@@ -3686,9 +3872,9 @@
          ENDIF
 
-      ELSE
-         grid__get_fine_offset_cc(1,:)=((id_rho(jp_I)-1)/2)
-      ENDIF
-
-      IF( il_shape1(2) > 1 )THEN
+      ELSEIF( il_shape1(jp_I) == 1 )THEN
+         
+         grid__get_fine_offset_cc(jp_I,:)=((id_rho(jp_I)-1)/2)
+         
+         ! work on j-direction
 
          ! look for j-direction lower offset 
@@ -3696,5 +3882,5 @@
             DO jj=1,id_rho(jp_J)+2
                IF( dd_lat1(1,jj) > dd_lat0(id_imin0,id_jmin0+1) - dp_delta )THEN
-                  grid__get_fine_offset_cc(2,1)=(id_rho(jp_J)+1)-jj
+                  grid__get_fine_offset_cc(jp_J,1)=(id_rho(jp_J)+1)-jj
                   EXIT
                ENDIF
@@ -3706,9 +3892,9 @@
 
          ! look for j-direction upper offset 
-         IF( dd_lat1(1,il_shape1(2)) > dd_lat0(id_imin0,id_jmax0-1) )THEN
+         IF( dd_lat1(1,il_shape1(jp_J)) > dd_lat0(id_imin0,id_jmax0-1) )THEN
             DO jj=1,id_rho(jp_J)+2
-               ij=il_shape1(2)-jj+1
+               ij=il_shape1(jp_J)-jj+1
                IF( dd_lat1(1,ij) < dd_lat0(id_imin0,id_jmax0-1) + dp_delta )THEN
-                  grid__get_fine_offset_cc(2,2)=(id_rho(jp_J)+1)-jj
+                  grid__get_fine_offset_cc(jp_J,2)=(id_rho(jp_J)+1)-jj
                   EXIT
                ENDIF
@@ -3717,7 +3903,81 @@
             CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
             &                 " not match fine grid upper right corner.")
-         ENDIF
-      ELSE
-         grid__get_fine_offset_cc(2,:)=((id_rho(jp_J)-1)/2)
+         ENDIF         
+
+      ELSE ! il_shape1(1) > 1 .AND. il_shape1(2) > 1 
+
+         ! look for lower left offset
+         IF( dl_lon1(1,1) < dl_lon0(id_imin0+1,id_jmin0+1) )THEN
+
+            ii=1
+            ij=1
+            DO ji=1,(id_rho(jp_I)+2)*(id_rho(jp_J)+2)
+
+               ll_ii=.FALSE.
+               ll_ij=.FALSE.
+
+               IF( dl_lon1(ii,ij) >= dl_lon0(id_imin0+1,id_jmin0+1)-dp_delta .AND. &
+               &   dd_lat1(ii,ij) >= dd_lat0(id_imin0+1,id_jmin0+1)-dp_delta )THEN
+                  grid__get_fine_offset_cc(jp_I,1)=(id_rho(jp_I)+1)-ii
+                  grid__get_fine_offset_cc(jp_J,1)=(id_rho(jp_J)+1)-ij
+                  EXIT
+               ENDIF
+
+               IF( dl_lon1(ii+1,ij) <= dl_lon0(id_imin0+1,id_jmin0+1)+dp_delta .AND. &
+               &   dd_lat1(ii+1,ij) <= dd_lat0(id_imin0+1,id_jmin0+1)+dp_delta )THEN
+                  ll_ii=.TRUE.
+               ENDIF
+               IF( dl_lon1(ii,ij+1) <= dl_lon0(id_imin0+1,id_jmin0+1)+dp_delta .AND. &
+               &   dd_lat1(ii,ij+1) <= dd_lat0(id_imin0+1,id_jmin0+1)+dp_delta )THEN
+                  ll_ij=.TRUE.
+               ENDIF
+
+               IF( ll_ii ) ii=ii+1
+               IF( ll_ij ) ij=ij+1
+
+            ENDDO
+
+         ELSE
+            CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
+            &                 " not match fine grid lower left corner.")
+         ENDIF
+
+         ! look for upper right offset
+         IF( dl_lon1(il_shape1(jp_I),il_shape1(jp_J)) > &
+            & dl_lon0(id_imax0-1,id_jmax0-1) )THEN
+
+            ii=il_shape1(jp_I)
+            ij=il_shape1(jp_J)
+            DO ji=1,(id_rho(jp_I)+2)*(id_rho(jp_J)+2)
+
+               ll_ii=.FALSE.
+               ll_ij=.FALSE.
+
+               IF( dl_lon1(ii,ij) <= dl_lon0(id_imax0-1,id_jmax0-1)+dp_delta .AND. &
+               &   dd_lat1(ii,ij) <= dd_lat0(id_imax0-1,id_jmax0-1)+dp_delta )THEN
+                  grid__get_fine_offset_cc(jp_I,2)=(id_rho(jp_I)+1)-(il_shape1(jp_I)+1-ii)
+                  grid__get_fine_offset_cc(jp_J,2)=(id_rho(jp_J)+1)-(il_shape1(jp_J)+1-ij)
+                  EXIT
+               ENDIF
+
+               IF( dl_lon1(ii-1,ij) >= dl_lon0(id_imax0-1,id_jmax0-1)-dp_delta .AND. &
+               &   dd_lat1(ii-1,ij) >= dd_lat0(id_imax0-1,id_jmax0-1)-dp_delta )THEN
+                  ll_ii=.TRUE.
+               ENDIF
+               IF( dl_lon1(ii,ij-1) >= dl_lon0(id_imax0-1,id_jmax0-1)-dp_delta .AND. &
+               &   dd_lat1(ii,ij-1) >= dd_lat0(id_imax0-1,id_jmax0-1)-dp_delta )THEN
+                  ll_ij=.TRUE.
+               ENDIF
+
+               IF( ll_ii ) ii=ii-1
+               IF( ll_ij ) ij=ij-1
+
+            ENDDO
+
+         ELSE
+            CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
+            &                 " not match fine grid upper right corner.")
+         ENDIF
+
       ENDIF
 
@@ -3732,5 +3992,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013- Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -3742,5 +4002,5 @@
    !> @param[in] id_jmin0  coarse grid lower left  corner j-indice of fine grid domain 
    !> @param[in] id_jmax0  coarse grid upper right corner j-indice of fine grid domain  
-   !> @param[in] id_rho    array of refinement factor (default 1) 
+   !> @param[in] id_rho    array of refinement factor 
    !-------------------------------------------------------------------
    SUBROUTINE grid_check_coincidence( td_coord0, td_coord1, &
@@ -4042,5 +4302,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_lon0   array of coarse grid longitude
@@ -4103,5 +4363,4 @@
       dl_lon1 = dd_lon1(il_imin1, il_jmin1)
       dl_lat1 = dd_lat1(il_imin1, il_jmin1)
-
 
       IF( (ABS(dl_lon1-dl_lon0)>dp_delta) .AND. (dl_lon1 < dl_lon0 ) .OR. & 
@@ -4202,5 +4461,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] dd_lat0   array of coarse grid latitude 
@@ -4272,5 +4531,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013-Initial version
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_var array of variable structure 
@@ -4348,5 +4607,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013-Initial version
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_var array of variable structure 
@@ -4374,6 +4633,8 @@
       IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
 
-         CALL logger_warn( "GRID DEL GHOST: dimension change in variable "//&
-         &              TRIM(td_var%c_name) )
+         IF( ANY(id_ghost(:,:)/=0) )THEN
+            CALL logger_warn( "GRID DEL GHOST: dimension change in variable "//&
+            &              TRIM(td_var%c_name) )
+         ENDIF
 
          ! copy variable
@@ -4425,5 +4686,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[in] td_var variable sturcture 
@@ -4555,5 +4816,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014 - Initial Version
+   !> @date September, 2014 - Initial Version
    !> @date October, 2014
    !> - work on mpp file structure instead of file structure
@@ -4592,4 +4853,5 @@
           tl_mpp=mpp_copy(td_mpp)
 
+          CALL logger_info("GRID GET FINE GHOST perio"//TRIM(fct_str(tl_mpp%i_perio)))
           IF( tl_mpp%i_perio < 0 )THEN
              ! compute NEMO periodicity index
@@ -4627,5 +4889,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var    variable strucutre 
@@ -4694,4 +4956,5 @@
                         il_tmp(jim:jip,jjm:jjp)=1
                      END WHERE
+
                   ENDIF
                ENDDO
@@ -4720,10 +4983,10 @@
    !>
    !> @details
-   !> the minimum size (nbumber of point) of closed sea to be kept could be
+   !> the minimum size (number of point) of closed sea to be kept could be
    !> sepcify with id_minsize.
    !> By default only the biggest sea is preserve.
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var    variable structure
@@ -4782,4 +5045,101 @@
 
    END SUBROUTINE grid_fill_small_dom
+   !-------------------------------------------------------------------
+   !> @brief This subroutine fill small domain inside bigger one. 
+   !>
+   !> @details
+   !> the minimum size (number of point) of domain sea to be kept could be
+   !> is sepcified with id_minsize.
+   !> smaller domain are included in the one they are embedded.
+   !>
+   !> @author J.Paul
+   !> @date Ferbruay, 2015 - Initial Version
+   !>
+   !> @param[inout] id_mask      domain mask (from grid_split_domain)
+   !> @param[in] id_minsize   minimum size of sea to be kept
+   !-------------------------------------------------------------------
+   SUBROUTINE grid_fill_small_msk(id_mask, id_minsize)
+      IMPLICIT NONE
+      ! Argument      
+      INTEGER(i4), DIMENSION(:,:), INTENT(INOUT) :: id_mask
+      INTEGER(i4),                 INTENT(IN   ) :: id_minsize
+
+      ! local variable
+      INTEGER(i4)                              :: il_ndom
+      INTEGER(i4)                              :: il_minsize
+      INTEGER(i4)                              :: il_msk
+      
+      INTEGER(i4)                              :: jim
+      INTEGER(i4)                              :: jjm
+      INTEGER(i4)                              :: jip
+      INTEGER(i4)                              :: jjp
+
+      INTEGER(i4), DIMENSION(2)                :: il_shape
+      INTEGER(i4), DIMENSION(:,:), ALLOCATABLE :: il_tmp
+
+      ! loop indices
+      INTEGER(i4) :: ii
+      INTEGER(i4) :: ij
+
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+
+      il_shape(:)=SHAPE(id_mask(:,:))
+      il_ndom=MINVAL(id_mask(:,:))
+
+      ALLOCATE( il_tmp(il_shape(1),il_shape(2)) )
+      il_tmp(:,:)=0
+      DO ji=-1,il_ndom,-1
+         WHERE( id_mask(:,:)==ji ) 
+            il_tmp(:,:)=SUM(id_mask(:,:),id_mask(:,:)==ji)/ji
+         END WHERE
+      ENDDO
+
+      DO WHILE( id_minsize > MINVAL(il_tmp(:,:)) )
+
+         DO jj=1,il_shape(2)
+            DO ji=1,il_shape(1)
+
+               IF( il_tmp(ji,jj) < il_minsize )THEN
+                  jim=MAX(1,ji-1)   ;  jip=MIN(il_shape(1),ji+1)
+                  jjm=MAX(1,jj-1)   ;  jjp=MIN(il_shape(2),jj+1)
+                  
+                  il_msk=0
+                  DO ij=jjm,jjp
+                     DO ii=jim,jip
+                        IF( id_mask(ii,ij) /= id_mask(ji,jj) )THEN
+                           IF( il_msk == 0 )THEN
+                              il_msk=id_mask(ii,ij)
+                           ELSEIF( il_msk /= id_mask(ii,ij) )THEN
+                              CALL logger_error("GRID FILL SMALL MSK: "//&
+                              &  "small domain not embedded in bigger one"//&
+                              &  ". point should be between two different"//&
+                              &  " domain.")
+                           ENDIF
+                        ENDIF
+                     ENDDO
+                  ENDDO
+                  IF( il_msk /= 0 ) id_mask(ji,jj)=il_msk
+
+               ENDIF
+
+            ENDDO
+         ENDDO
+
+
+         il_tmp(:,:)=0
+         DO ji=-1,il_ndom,-1
+            WHERE( id_mask(:,:)==ji ) 
+               il_tmp(:,:)=SUM(id_mask(:,:),id_mask(:,:)==ji)/ji
+            END WHERE
+         ENDDO            
+
+      ENDDO
+
+      DEALLOCATE( il_tmp )
+
+
+   END SUBROUTINE grid_fill_small_msk
 END MODULE grid
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp.f90	(revision 9987)
@@ -27,5 +27,5 @@
 !>    defining string character _cn\_varinfo_.<br/>
 !>    Example:
-!>       - cn_varinfo='varname1:cubic/rhoi', 'varname2:linear' 
+!>       - cn_varinfo='varname1:int=cubic/rhoi', 'varname2:int=linear' 
 !>
 !>    to create mixed grid (with coarse grid point needed to compute
@@ -137,5 +137,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_method interpolation method
@@ -179,5 +179,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_mix mixed grid variable (to interpolate)
@@ -244,5 +244,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_mix mixed grid variable (to interpolate)
@@ -363,5 +363,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_var    coarse grid variable (should be extrapolated)
@@ -449,5 +449,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_mix mixed grid variable
@@ -610,5 +610,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use offset to save useful domain
@@ -716,5 +716,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure
@@ -828,5 +828,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use interpolation method modules
@@ -947,4 +947,5 @@
 
       DEALLOCATE(il_detect)
+
       !4- save useful domain (remove offset)
       CALL interp_clean_mixed_grid( tl_mix, td_var, &
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_cubic.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_cubic.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_cubic.f90	(revision 9987)
@@ -26,4 +26,6 @@
 ! REVISION HISTORY:
 !> @date September, 2014 -Initial version
+!> @date June, 2015
+!> - use math module
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -36,5 +38,5 @@
    USE logger                          ! log file manager
    USE fct                             ! basic useful function
-   USE extrap                          ! extrapolation manager
+   USE math                            ! mathematical function
 
    IMPLICIT NONE
@@ -61,5 +63,7 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
+   !> @date July, 2015 
+   !> - reinitialise detect array for each level
    !>
    !> @param[inout] dd_value  2D array of variable value 
@@ -82,11 +86,13 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(4)                :: il_shape
-
-      LOGICAL                                  :: ll_discont
-
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_IJ
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_I
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_J
+      INTEGER(i4), DIMENSION(4)                  :: il_shape
+
+      INTEGER(I4), DIMENSION(:,:,:), ALLOCATABLE :: il_detect
+
+      LOGICAL                                    :: ll_discont
+
+      REAL(dp)   , DIMENSION(:,:)  , ALLOCATABLE :: dl_weight_IJ
+      REAL(dp)   , DIMENSION(:,:)  , ALLOCATABLE :: dl_weight_I
+      REAL(dp)   , DIMENSION(:,:)  , ALLOCATABLE :: dl_weight_J
       
       ! loop indices
@@ -113,5 +119,8 @@
       &                               id_rho(jp_J), ld_even(jp_J))
 
+      ALLOCATE(il_detect(il_shape(1),il_shape(2),il_shape(3)))
+
       DO jl=1,il_shape(4)
+         il_detect(:,:,:)=id_detect(:,:,:)
          ! loop on vertical level
          DO jk=1,il_shape(3)
@@ -119,17 +128,17 @@
             ! I-J plan
             CALL interp_cubic__2D(dd_value(:,:,jk,jl), dd_fill, &
-            &                     id_detect(:,:,jk),            &
+            &                     il_detect(:,:,jk),            &
             &                     dl_weight_IJ(:,:),            &
             &                     id_rho(jp_I), id_rho(jp_J),   &
             &                     ll_discont)            
-            IF( ANY(id_detect(:,:,jk)==1) )THEN
+            IF( ANY(il_detect(:,:,jk)==1) )THEN
                ! I direction
                DO jj=1,il_shape(2)
                   CALL interp_cubic__1D( dd_value(:,jj,jk,jl), dd_fill, &
-                  &                      id_detect(:,jj,jk),            &
+                  &                      il_detect(:,jj,jk),            &
                   &                      dl_weight_I(:,:),              &
                   &                      id_rho(jp_I), ll_discont )
                ENDDO
-               IF( ALL(id_detect(:,:,jk)==0) )THEN
+               IF( ALL(il_detect(:,:,jk)==0) )THEN
                   CYCLE
                ELSE
@@ -137,5 +146,5 @@
                   DO ji=1,il_shape(1)
                      CALL interp_cubic__1D( dd_value(ji,:,jk,jl), dd_fill, &
-                     &                      id_detect(ji,:,jk),            &
+                     &                      il_detect(ji,:,jk),            &
                      &                      dl_weight_J(:,:),              &
                      &                      id_rho(jp_J), ll_discont )
@@ -147,4 +156,7 @@
       ENDDO
 
+      id_detect(:,:,:)=il_detect(:,:,:)
+      DEALLOCATE(il_detect)
+
       DEALLOCATE(dl_weight_IJ)
       DEALLOCATE(dl_weight_I)
@@ -159,5 +171,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  2D array of variable value 
@@ -181,5 +193,5 @@
       REAL(dp)                        , INTENT(IN   ) :: dd_fill 
       INTEGER(I4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
-      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight 
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
       INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
       INTEGER(I4)                     , INTENT(IN   ) :: id_rhoj
@@ -230,9 +242,9 @@
 
          ! compute derivative on coarse grid
-         dl_dfdx(:,:)=extrap_deriv_2D(dl_coarse(:,:), dd_fill, 'I', ld_discont)
-         dl_dfdy(:,:)=extrap_deriv_2D(dl_coarse(:,:), dd_fill, 'J', ld_discont)
+         dl_dfdx(:,:)=math_deriv_2D(dl_coarse(:,:), dd_fill, 'I', ld_discont)
+         dl_dfdy(:,:)=math_deriv_2D(dl_coarse(:,:), dd_fill, 'J', ld_discont)
 
          ! compute cross derivative on coarse grid
-         dl_d2fdxy(:,:)=extrap_deriv_2D(dl_dfdx(:,:), dd_fill, 'J', ld_discont)
+         dl_d2fdxy(:,:)=math_deriv_2D(dl_dfdx(:,:), dd_fill, 'J', ld_discont)
 
          ALLOCATE( dl_tmp(2,2) )
@@ -319,5 +331,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  1D array of variable value 
@@ -339,5 +351,5 @@
       REAL(dp)                        , INTENT(IN   ) :: dd_fill 
       INTEGER(I4)     , DIMENSION(:)  , INTENT(INOUT) :: id_detect
-      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight 
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
       INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
       LOGICAL                         , INTENT(IN   ) :: ld_discont
@@ -376,5 +388,5 @@
 
          ! compute derivative on coarse grid
-         dl_dfdx(:)=extrap_deriv_1D(dl_coarse(:), dd_fill, ld_discont)
+         dl_dfdx(:)=math_deriv_1D(dl_coarse(:), dd_fill, ld_discont)
 
          ALLOCATE( dl_tmp(2) )
@@ -440,5 +452,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_value  2D array of value
@@ -503,5 +515,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  2D array of mixed grid value
@@ -565,5 +577,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_value  1D array of value
@@ -608,5 +620,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  1D array of mixed grid value
@@ -659,5 +671,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_weight interpolation weight of 2D array
@@ -740,5 +752,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_weight interpolation weight of 1D array
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_linear.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_linear.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_linear.f90	(revision 9987)
@@ -24,5 +24,5 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date September, 2014 -Initial version
+!> @date September, 2014 - Initial version
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -63,5 +63,6 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
+   !> @date July, 2015 - reinitialise detect array for each level
    !>
    !> @param[inout] dd_value  2D array of variable value 
@@ -84,11 +85,13 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(4)                :: il_shape
-
-      LOGICAL                                  :: ll_discont
-      
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_IJ
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_I
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_J
+      INTEGER(i4), DIMENSION(4)                  :: il_shape
+
+      INTEGER(I4), DIMENSION(:,:,:), ALLOCATABLE :: il_detect
+
+      LOGICAL                                    :: ll_discont
+ 
+      REAL(dp)   , DIMENSION(:,:)  , ALLOCATABLE :: dl_weight_IJ
+      REAL(dp)   , DIMENSION(:,:)  , ALLOCATABLE :: dl_weight_I
+      REAL(dp)   , DIMENSION(:,:)  , ALLOCATABLE :: dl_weight_J
       
       ! loop indices
@@ -104,10 +107,10 @@
 
       ! compute vect2D
-      ALLOCATE(dl_weight_IJ(16,((id_rho(jp_I)+1)*(id_rho(jp_J)+1))) )
+      ALLOCATE(dl_weight_IJ(4,((id_rho(jp_I)+1)*(id_rho(jp_J)+1))) )
       CALL interp_linear__get_weight2D(dl_weight_IJ(:,:), &
       &                               id_rho(:), ld_even(:))
 
-      ALLOCATE( dl_weight_I( 4,((id_rho(jp_I)+1)                 )) )
-      ALLOCATE( dl_weight_J( 4,(                 (id_rho(jp_J)+1))) )
+      ALLOCATE( dl_weight_I( 2,((id_rho(jp_I)+1)                 )) )
+      ALLOCATE( dl_weight_J( 2,(                 (id_rho(jp_J)+1))) )
       CALL interp_linear__get_weight1D(dl_weight_I(:,:), &
       &                               id_rho(jp_I), ld_even(jp_I))
@@ -115,5 +118,8 @@
       &                               id_rho(jp_J), ld_even(jp_J))
 
+      ALLOCATE(il_detect(il_shape(1),il_shape(2),il_shape(3)))
+
       DO jl=1,il_shape(4)
+         il_detect(:,:,:)=id_detect(:,:,:)
          ! loop on vertical level
          DO jk=1,il_shape(3)
@@ -121,17 +127,17 @@
             ! I-J plan
             CALL interp_linear__2D(dd_value(:,:,jk,jl), dd_fill,&
-            &                     id_detect(:,:,jk),            &
+            &                     il_detect(:,:,jk),            &
             &                     dl_weight_IJ(:,:),            &
             &                     id_rho(jp_I), id_rho(jp_J),   &
             &                     ll_discont)            
-            IF( ANY(id_detect(:,:,jk)==1) )THEN
+            IF( ANY(il_detect(:,:,jk)==1) )THEN
                ! I direction
                DO jj=1,il_shape(2)
                   CALL interp_linear__1D( dd_value(:,jj,jk,jl), dd_fill,&
-                  &                       id_detect(:,jj,jk),           &
+                  &                       il_detect(:,jj,jk),           &
                   &                       dl_weight_I(:,:),             &
                   &                       id_rho(jp_I), ll_discont )
                ENDDO
-               IF( ALL(id_detect(:,:,jk)==0) )THEN
+               IF( ALL(il_detect(:,:,jk)==0) )THEN
                   CYCLE
                ELSE
@@ -139,5 +145,5 @@
                   DO ji=1,il_shape(1)
                      CALL interp_linear__1D( dd_value(ji,:,jk,jl), dd_fill,&
-                     &                       id_detect(ji,:,jk),           &
+                     &                       il_detect(ji,:,jk),           &
                      &                       dl_weight_J(:,:),             &
                      &                       id_rho(jp_J), ll_discont )
@@ -149,8 +155,11 @@
       ENDDO
 
+      id_detect(:,:,:)=il_detect(:,:,:)
+      DEALLOCATE(il_detect)
+
       DEALLOCATE(dl_weight_IJ)
       DEALLOCATE(dl_weight_I)
       DEALLOCATE(dl_weight_J)
-      
+ 
    END SUBROUTINE interp_linear_fill
    !-------------------------------------------------------------------
@@ -161,5 +170,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  2D array of variable value 
@@ -235,5 +244,5 @@
                IF( ALL(id_detect(ji:ji+id_rhoi,   &
                &                 jj:jj+id_rhoj)==0) ) CYCLE
-               ! check data to needed to interpolate
+               ! check data needed to interpolate
                IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill) ) CYCLE
                ! check longitude discontinuity
@@ -296,5 +305,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  1D array of variable value 
@@ -408,5 +417,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_value  2D array of value
@@ -445,6 +454,6 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
-   !> 
+   !> @date September, 2014 - Initial Version
+   !>
    !> @param[inout] dd_value  2D array of mixed grid value
    !> @param[inout] id_detect 2D array of point to be interpolated
@@ -477,25 +486,25 @@
       !----------------------------------------------------------------
 
-         IF( ANY( dd_coef(:)==dd_fill ) )THEN
-            CALL logger_error("INTERP LINEAR FILL: fill value detected in coef. "//&
-            &              "can not compute interpolation.")
-         ELSE
-
-            ii=0
-            DO jj=1,id_rhoj+1
-               DO ji=1,id_rhoi+1
-
-                  ii=ii+1
-                  IF(id_detect(ji,jj)==1)THEN
-
-                     dd_value(ji,jj)=DOT_PRODUCT(dd_coef(:),dd_weight(:,ii))
-                     id_detect(ji,jj)=0
-
-                  ENDIF
-
-               ENDDO
+      IF( ANY( dd_coef(:)==dd_fill ) )THEN
+         CALL logger_error("INTERP LINEAR FILL: fill value detected in coef. "//&
+         &              "can not compute interpolation.")
+      ELSE
+
+         ii=0
+         DO jj=1,id_rhoj+1
+            DO ji=1,id_rhoi+1
+
+               ii=ii+1
+               IF(id_detect(ji,jj)==1)THEN
+
+                  dd_value(ji,jj)=DOT_PRODUCT(dd_coef(:),dd_weight(:,ii))
+                  id_detect(ji,jj)=0
+
+               ENDIF
+
             ENDDO
-
-         ENDIF
+         ENDDO
+
+      ENDIF
 
    END SUBROUTINE interp_linear__2D_fill
@@ -505,5 +514,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_value  1D array of value
@@ -540,5 +549,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !> 
    !> @param[inout] dd_value  1D array of mixed grid value
@@ -591,5 +600,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_weight interpolation weight of 2D array
@@ -660,5 +669,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] dd_weight interpolation weight of 1D array
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_nearest.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_nearest.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/interp_nearest.f90	(revision 9987)
@@ -24,5 +24,5 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date September, 2014 -Initial version
+!> @date September, 2014 - Initial version
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -55,5 +55,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  2D array of variable value 
@@ -69,5 +69,7 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(4)                :: il_shape
+      INTEGER(i4), DIMENSION(4)                  :: il_shape
+
+      INTEGER(I4), DIMENSION(:,:,:), ALLOCATABLE :: il_detect
 
       ! loop indices
@@ -80,5 +82,7 @@
       il_shape(:)=SHAPE(dd_value)
 
+      ALLOCATE(il_detect(il_shape(1),il_shape(2),il_shape(3)))
       DO jl=1,il_shape(4)
+         il_detect(:,:,:)=id_detect(:,:,:)
          ! loop on vertical level
          DO jk=1,il_shape(3)
@@ -86,14 +90,14 @@
             ! I-J plan
             CALL interp_nearest__2D(dd_value(:,:,jk,jl),&
-            &                       id_detect(:,:,jk),  &
+            &                       il_detect(:,:,jk),  &
             &                       id_rho(jp_I), id_rho(jp_J) )            
-            IF( ANY(id_detect(:,:,jk)==1) )THEN
+            IF( ANY(il_detect(:,:,jk)==1) )THEN
                ! I direction
                DO jj=1,il_shape(2)
                   CALL interp_nearest__1D( dd_value(:,jj,jk,jl),&
-                  &                        id_detect(:,jj,jk),  &
+                  &                        il_detect(:,jj,jk),  &
                   &                        id_rho(jp_I) )
                ENDDO
-               IF( ALL(id_detect(:,:,jk)==0) )THEN
+               IF( ALL(il_detect(:,:,jk)==0) )THEN
                   CYCLE
                ELSE
@@ -101,5 +105,5 @@
                   DO ji=1,il_shape(1)
                      CALL interp_nearest__1D( dd_value(ji,:,jk,jl),&
-                     &                        id_detect(ji,:,jk),  &
+                     &                        il_detect(ji,:,jk),  &
                      &                        id_rho(jp_J) )
                   ENDDO
@@ -110,4 +114,7 @@
       ENDDO
 
+      id_detect(:,:,:)=il_detect(:,:,:)
+      DEALLOCATE(il_detect)
+
    END SUBROUTINE interp_nearest_fill
    !-------------------------------------------------------------------
@@ -116,5 +123,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  2D array of variable value 
@@ -171,5 +178,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  1D array of variable value 
@@ -216,5 +223,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  2D array of mixed grid value
@@ -300,5 +307,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[inout] dd_value  1D array of mixed grid value
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom.f90	(revision 9987)
@@ -156,5 +156,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file file structure
@@ -186,5 +186,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file file structure
@@ -223,5 +223,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file file structure
@@ -252,5 +252,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file      file structure
@@ -300,5 +300,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -338,5 +338,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file      file structure
@@ -386,5 +386,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file      file structure
@@ -422,5 +422,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -452,5 +452,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -485,5 +485,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -529,5 +529,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -564,21 +564,27 @@
    !-------------------------------------------------------------------
    !> @brief This subroutine write file structure in an opened file.
-   !
-   !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !>
+   !> @details
+   !> optionally, you could specify dimension order (default 'xyzt')
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 - add dimension order option
    !
    !> @param[in] td_file   file structure
    !-------------------------------------------------------------------
-   SUBROUTINE iom_write_file(td_file)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
-      !----------------------------------------------------------------
-
-      ! open file
-      SELECT CASE(TRIM(td_file%c_type))
-         CASE('cdf')
-            CALL iom_cdf_write_file(td_file)
-         CASE('dimg')
+   SUBROUTINE iom_write_file(td_file, cd_dimorder)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TFILE)     , INTENT(INOUT) :: td_file
+      CHARACTER(LEN=*), INTENT(IN   ), OPTIONAL :: cd_dimorder
+      !----------------------------------------------------------------
+
+      ! open file
+      SELECT CASE(TRIM(td_file%c_type))
+         CASE('cdf')
+            CALL iom_cdf_write_file(td_file, cd_dimorder)
+         CASE('dimg')
+            ! note: can not change dimension order in restart dimg file
             CALL iom_rstdimg_write_file(td_file)
          CASE DEFAULT
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_cdf.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_cdf.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_cdf.f90	(revision 9987)
@@ -144,16 +144,24 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date May, 2015 - add optional message to netcdf error message
+   !>
    !> @param[in] id_status error status
-   !-------------------------------------------------------------------
-   SUBROUTINE iom_cdf__check(id_status)
-      IMPLICIT NONE
-      ! Argument      
-      INTEGER(i4), INTENT(IN) :: id_status
-      !----------------------------------------------------------------
+   !> @param[in] cd_msg    message
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_cdf__check(id_status, cd_msg)
+      IMPLICIT NONE
+      ! Argument      
+      INTEGER(i4)     , INTENT(IN)           :: id_status
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_msg
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_msg
+      !----------------------------------------------------------------
+
+      cl_msg=""
+      IF( PRESENT(cd_msg) ) cl_msg=cd_msg
 
       IF( id_status /= NF90_NOERR )THEN
-         CALL logger_error(TRIM(NF90_STRERROR(id_status)))
+         CALL logger_error(TRIM(cl_msg)//TRIM(NF90_STRERROR(id_status)))
       ENDIF
 
@@ -173,5 +181,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -203,8 +211,9 @@
             CALL logger_info( " IOM CDF CREATE: file "//TRIM(td_file%c_name) )
 
-            il_status = NF90_CREATE( TRIM(td_file%c_name),&
-            &                        NF90_WRITE,               &
-            &                        td_file%i_id)
-            CALL iom_cdf__check(il_status)
+            il_status = NF90_CREATE(TRIM(td_file%c_name),&
+            &                       cmode=NF90_64BIT_OFFSET,&
+            &                       ncid=td_file%i_id)
+         !NF90_WRITE,               &
+            CALL iom_cdf__check(il_status," IOM CDF CREATE: ")
 
             td_file%l_def=.TRUE.
@@ -228,7 +237,8 @@
                &                      NF90_NOWRITE,         &
                &                      td_file%i_id)
-               CALL iom_cdf__check(il_status)
-
-               CALL logger_trace("IOM CDF OPEN "//TRIM(td_file%c_name)//" "//TRIM(fct_str(td_file%i_id)))
+               CALL iom_cdf__check(il_status," IOM CDF OPEN: ")
+
+               CALL logger_trace("IOM CDF OPEN "//TRIM(td_file%c_name)//" "//&
+                  &  TRIM(fct_str(td_file%i_id)))
             ELSE
 
@@ -239,5 +249,5 @@
                &                      NF90_WRITE,           &
                &                      td_file%i_id)
-               CALL iom_cdf__check(il_status)
+               CALL iom_cdf__check(il_status,"IOM CDF OPEN: ")
 
             ENDIF
@@ -267,5 +277,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -291,5 +301,5 @@
 
          il_status = NF90_CLOSE(td_file%i_id)
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF CLOSE: ")
 
          td_file%i_id = 0
@@ -307,5 +317,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -326,5 +336,5 @@
       il_status=NF90_INQUIRE(td_file%i_id, td_file%i_ndim, &
       &     td_file%i_nvar, td_file%i_natt, td_file%i_uldid, il_fmt)
-      CALL iom_cdf__check(il_status)
+      CALL iom_cdf__check(il_status,"IOM CDF GET INFO: ")
 
       SELECT CASE(il_fmt)
@@ -345,5 +355,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -396,5 +406,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use attribute periodicity read from the file if present.
@@ -439,5 +449,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -480,12 +490,12 @@
 
             ! look for depth id
-            IF( INDEX(TRIM(td_file%t_var(ji)%c_name),'depth') /= 0 )THEN
+            IF( INDEX(TRIM(fct_lower(td_file%t_var(ji)%c_name)),'depth')/=0 )THEN
                IF( td_file%i_depthid == 0 )THEN
                   td_file%i_depthid=ji
                ELSE
                   IF( td_file%i_depthid /= ji )THEN
-                     CALL logger_error("IOM CDF GET FILE VAR: find more than one "//&
-                     &                 "depth variable in file "//&
-                     &                 TRIM(td_file%c_name) )
+                     CALL logger_error("IOM CDF GET FILE VAR: find more"//&
+                        &  " than one depth variable in file "//&
+                        &  TRIM(td_file%c_name) )
                   ENDIF
                ENDIF
@@ -493,5 +503,5 @@
 
             ! look for time id
-            IF( INDEX(TRIM(td_file%t_var(ji)%c_name),'time') /= 0 )THEN
+            IF( INDEX(TRIM(fct_lower(td_file%t_var(ji)%c_name)),'time')/=0 )THEN
                IF( td_file%i_timeid == 0 )THEN
                   td_file%i_timeid=ji
@@ -504,7 +514,6 @@
                      td_file%i_timeid=ji
                   !ELSE
-                  !   print *,'error'
-                  !   CALL logger_error("IOM OPEN: find more than one "//&
-                  !   &                 "time variable in file "//&
+                  !   CALL logger_error("IOM CDF GET FILE VAR: find more "//&
+                  !   &                 "than one time variable in file "//&
                   !   &                 TRIM(td_file%c_name) )
                   ENDIF
@@ -526,5 +535,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -567,5 +576,7 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 - create unused dimension, when reading dimension
+   !> of length less or equal to zero
    !
    !> @param[in] td_file   file structure
@@ -583,4 +594,5 @@
       INTEGER(i4)       :: il_len
       CHARACTER(LEN=lc) :: cl_name
+      LOGICAL           :: ll_use
       !----------------------------------------------------------------
 
@@ -601,7 +613,15 @@
          il_status=NF90_INQUIRE_DIMENSION(td_file%i_id, id_dimid, &
          &                                cl_name, il_len )
-         CALL iom_cdf__check(il_status)
-
-         iom_cdf__read_dim_id=dim_init(cl_name, il_len)
+         CALL iom_cdf__check(il_status,"IOM CDF READ DIM: ")
+
+         ll_use=.TRUE.
+         IF( il_len <= 0 )THEN
+            CALL logger_warn( &
+         &  " IOM CDF READ DIM: dimension "//TRIM(fct_str(id_dimid))//&
+         &  " in file "//TRIM(td_file%c_name)//" is less or equel to zero")
+            il_len=1
+            ll_use=.FALSE.
+         ENDIF
+         iom_cdf__read_dim_id=dim_init(cl_name, il_len, ld_use=ll_use)
 
       ENDIF
@@ -613,5 +633,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -634,5 +654,6 @@
 
          CALL logger_error( &
-         &  " IOM CDF READ DIM: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ DIM: no id associated to file "//&
+         &  TRIM(td_file%c_name))
 
       ELSE      
@@ -640,5 +661,5 @@
          il_status=NF90_INQ_DIMID( td_file%i_id, TRIM(ADJUSTL(cd_name)), &
          &                         il_dimid)
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF READ DIM: ")
 
          iom_cdf__read_dim_name=iom_cdf_read_dim(td_file, il_dimid)
@@ -652,5 +673,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -714,9 +735,9 @@
          &                                il_len, &
          &                                il_attid )
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")
 
          !! get attribute value
-         CALL logger_debug( " IOM CDF READ ATT: get attribute "//TRIM(cl_name)//&
-         &               " in file "//TRIM(td_file%c_name))
+         CALL logger_debug( " IOM CDF READ ATT: get attribute "//&
+            &            TRIM(cl_name)//" in file "//TRIM(td_file%c_name))
 
          SELECT CASE( il_type )
@@ -728,6 +749,6 @@
 
                   CALL logger_error( &
-                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
-                  &  TRIM(cl_name) )
+                  &  " IOM CDF READ ATT: not enough space to put "//&
+                  &  "attribute "//TRIM(cl_name) )
 
                ELSE
@@ -737,5 +758,5 @@
                   &                      cl_name, &
                   &                      cl_value )
-                  CALL iom_cdf__check(il_status)
+                  CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")
 
                   iom_cdf__read_att_name=att_init(cl_name, cl_value)
@@ -758,5 +779,5 @@
                   &                      cl_name, &
                   &                      bl_value(:))
-                  CALL iom_cdf__check(il_status)   
+                  CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")   
 
                   iom_cdf__read_att_name=att_init(cl_name, bl_value(:))
@@ -773,6 +794,6 @@
 
                   CALL logger_error( &
-                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
-                  &  TRIM(cl_name) )
+                  &  " IOM CDF READ ATT: not enough space to put "//&
+                  &  "attribute "//TRIM(cl_name) )
 
                ELSE
@@ -782,5 +803,5 @@
                   &                      cl_name, &
                   &                      sl_value(:))
-                  CALL iom_cdf__check(il_status)   
+                  CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")   
 
                   iom_cdf__read_att_name=att_init(cl_name, sl_value(:))
@@ -797,6 +818,6 @@
 
                   CALL logger_error( &
-                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
-                  &  TRIM(cl_name) )
+                  &  " IOM CDF READ ATT: not enough space to put "//&
+                  &  "attribute "//TRIM(cl_name) )
 
                ELSE
@@ -806,5 +827,5 @@
                   &                      cl_name, &
                   &                      il_value(:))
-                  CALL iom_cdf__check(il_status)   
+                  CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")   
 
                   iom_cdf__read_att_name=att_init(cl_name, il_value(:))
@@ -820,6 +841,6 @@
 
                   CALL logger_error( &
-                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
-                  &  TRIM(cl_name) )
+                  &  " IOM CDF READ ATT: not enough space to put "//&
+                  &  "attribute "//TRIM(cl_name) )
 
                ELSE
@@ -829,5 +850,5 @@
                   &                      cl_name, &
                   &                      fl_value(:))
-                  CALL iom_cdf__check(il_status)   
+                  CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")   
 
                   iom_cdf__read_att_name=att_init(cl_name, fl_value(:))
@@ -844,6 +865,6 @@
 
                   CALL logger_error( &
-                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
-                  &  TRIM(cl_name) )
+                  &  " IOM CDF READ ATT: not enough space to put "//&
+                  &  "attribute "//TRIM(cl_name) )
 
                ELSE
@@ -853,5 +874,5 @@
                   &                      cl_name, &
                   &                      dl_value(:))
-                  CALL iom_cdf__check(il_status)   
+                  CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")   
 
                   iom_cdf__read_att_name=att_init(cl_name, dl_value(:))
@@ -873,5 +894,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -902,5 +923,5 @@
          ! get attribute name
          il_status=NF90_INQ_ATTNAME(td_file%i_id, id_varid, id_attid, cl_name)
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF READ ATT: ")
 
          ! read attribute
@@ -918,5 +939,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -976,5 +997,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1043,5 +1064,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1085,5 +1106,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1148,5 +1169,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1199,5 +1220,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - force to use FillValue=1.e20 if no FillValue for coordinate variable.
@@ -1240,5 +1261,5 @@
 
          ! inquire variable
-         CALL logger_trace( &
+         CALL logger_debug( &
          &  " IOM CDF READ VAR META: inquire variable "//&
          &  TRIM(fct_str(id_varid))//&
@@ -1253,7 +1274,8 @@
          &                                il_dimid(:),&
          &                                il_natt )
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF READ VAR META: ")
          !!! fill variable dimension structure
          tl_dim(:)=iom_cdf__read_var_dim( td_file, il_ndim, il_dimid(:) )
+
          IF( il_natt /= 0 )THEN
             ALLOCATE( tl_att(il_natt) )
@@ -1276,10 +1298,10 @@
                ELSE
                   ! create attribute _FillValue
-                  SELECT CASE(TRIM(cl_name))
+                  SELECT CASE(TRIM(fct_lower(cl_name)))
                      CASE DEFAULT
                         CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
                         &                "zero for variable "//TRIM(cl_name) )
                         tl_fill=att_init('_FillValue',0.)
-                     CASE('nav_lon','nav_lat', &
+                     CASE('nav_lon','nav_lat', 'nav_lev', &
                         &  'glamt','glamu','glamv','glamf', &
                         &  'gphit','gphiu','gphiv','gphif')
@@ -1311,5 +1333,5 @@
             ALLOCATE(tl_att(il_natt+1) )
             ! create attribute _FillValue
-            SELECT CASE(TRIM(cl_name))
+            SELECT CASE(TRIM(fct_lower(cl_name)))
                CASE DEFAULT
                   CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
@@ -1353,6 +1375,8 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - Bug fix: use order to disorder table (see dim_init)
+   !>
    !> @param[in] td_file   file structure
    !> @param[in] id_ndim   number of dimension
@@ -1371,5 +1395,5 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_2xyzt
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_xyzt2
 
       TYPE(TDIM) , DIMENSION(ip_maxdim) :: tl_dim
@@ -1395,17 +1419,17 @@
 
          DO ji = 1, id_ndim
-            CALL logger_trace( " IOM CDF READ VAR DIM: get variable dimension "//&
-            &               TRIM(fct_str(ji)) )
-
-            il_2xyzt(ji)=td_file%t_dim(id_dimid(ji))%i_2xyzt
+            CALL logger_debug( " IOM CDF READ VAR DIM: get variable "//&
+               &  "dimension "//TRIM(fct_str(ji)) )
+
+            il_xyzt2(ji)=td_file%t_dim(id_dimid(ji))%i_xyzt2
 
             ! read dimension information
-            tl_dim(ji) = dim_init( td_file%t_dim(il_2xyzt(ji))%c_name, &
-            &                      td_file%t_dim(il_2xyzt(ji))%i_len )
+            tl_dim(ji) = dim_init( td_file%t_dim(il_xyzt2(ji))%c_name, &
+            &                      td_file%t_dim(il_xyzt2(ji))%i_len )
          ENDDO
 
          ! reorder dimension to ('x','y','z','t')
          CALL dim_reorder(tl_dim(:))
-      
+ 
          iom_cdf__read_var_dim(:)=dim_copy(tl_dim(:))
 
@@ -1426,5 +1450,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1475,5 +1499,7 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - use scale factor and offset, as soon as read variable value
    !
    !> @param[in] td_file   file structure
@@ -1482,7 +1508,4 @@
    !> @param[in] id_count  number of indices selected along each dimension
    !> @return variable structure completed 
-   !
-   !> @todo
-   !> - warning do not change fill value when use scale factor..
    !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__read_var_value(td_file, td_var, &
@@ -1496,12 +1519,13 @@
 
       ! local variable
-      INTEGER(i4)                       :: il_status
-      INTEGER(i4)                       :: il_tmp1
-      INTEGER(i4)                       :: il_tmp2
-      INTEGER(i4)                       :: il_varid
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start_ord
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count_ord
+      INTEGER(i4)                                    :: il_status
+      INTEGER(i4)                                    :: il_tmp1
+      INTEGER(i4)                                    :: il_tmp2
+      INTEGER(i4)                                    :: il_varid
+      INTEGER(i4), DIMENSION(ip_maxdim)              :: il_start
+      INTEGER(i4), DIMENSION(ip_maxdim)              :: il_count
+      INTEGER(i4), DIMENSION(ip_maxdim)              :: il_start_ord
+      INTEGER(i4), DIMENSION(ip_maxdim)              :: il_count_ord
+
       REAL(dp)   , DIMENSION(:,:,:,:)  , ALLOCATABLE :: dl_value
       REAL(dp)   , DIMENSION(:,:,:,:)  , ALLOCATABLE :: dl_tmp
@@ -1518,6 +1542,6 @@
          IF( (       PRESENT(id_start)  .AND. (.NOT. PRESENT(id_count))) .OR. &
              ((.NOT. PRESENT(id_start)) .AND.        PRESENT(id_count) ) )THEN
-            CALL logger_warn( &
-            &  "IOM CDF READ VAR VALUE: id_start and id_count should be both specify")
+            CALL logger_warn( "IOM CDF READ VAR VALUE: id_start and id_count"//&
+               & " should be both specify")
          ENDIF
          IF( PRESENT(id_start).AND.PRESENT(id_count) )THEN
@@ -1525,7 +1549,7 @@
             IF( SIZE(id_start(:)) /= ip_maxdim .OR. &
             &   SIZE(id_count(:)) /= ip_maxdim )THEN
-               CALL logger_error("IOM CDF READ VAR: dimension of array start or count "//&
-               &      " are invalid to read variable "//TRIM(td_var%c_name)//&
-               &      " in file "//TRIM(td_file%c_name) )
+               CALL logger_error("IOM CDF READ VAR: dimension of array start"//&
+                  &  " or count are invalid to read variable "//&
+                  &  TRIM(td_var%c_name)//" in file "//TRIM(td_file%c_name) )
             ENDIF
 
@@ -1564,7 +1588,4 @@
             &    td_var%t_dim( 4 )%i_len &
             &                                            /)) )THEN
-
-            CALL logger_error( "IOM CDF READ VAR VALUE: start + count exceed "//&
-            &  "variable dimension for "//TRIM(td_var%c_name) )
 
             DO ji = 1, ip_maxdim
@@ -1575,8 +1596,10 @@
                &  TRIM(fct_str(il_tmp2)))
             ENDDO
+            CALL logger_error( "IOM CDF READ VAR VALUE: start + count exceed "//&
+            &  "variable dimension for "//TRIM(td_var%c_name) )
 
          ELSE
 
-            ! Allocate space to hold variable value (unorder)
+            ! Allocate space to hold variable value (disorder)
             ALLOCATE(dl_value( il_count(1), &
                &               il_count(2), &
@@ -1601,5 +1624,5 @@
             &                                       start = il_start(:),&
             &                                       count = il_count(:) )
-            CALL iom_cdf__check(il_status)
+            CALL iom_cdf__check(il_status,"IOM CDF READ VAR VALUE: ")
 
             ! Allocate space to hold variable value in structure
@@ -1663,4 +1686,11 @@
                CALL var_chg_FillValue(td_var)
             ENDIF
+
+            ! use scale factor and offset
+            WHERE( td_var%d_value(:,:,:,:) /= td_var%d_fill )
+               td_var%d_value(:,:,:,:) = &
+               &  td_var%d_value(:,:,:,:)*td_var%d_scf + td_var%d_ofs
+            END WHERE
+
          ENDIF
       ELSE
@@ -1673,17 +1703,25 @@
    !-------------------------------------------------------------------
    !> @brief This subroutine write file structure in an opened netcdf file.
-   !
-   !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !>
+   !> @details
+   !> optionally, you could specify dimension order (default 'xyzt')
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - add dimension order option 
    !
    !> @param[inout] td_file   file structure
    !-------------------------------------------------------------------
-   SUBROUTINE iom_cdf_write_file(td_file)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
+   SUBROUTINE iom_cdf_write_file(td_file, cd_dimorder)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TFILE)     , INTENT(INOUT) :: td_file
+      CHARACTER(LEN=*), INTENT(IN   ), OPTIONAL :: cd_dimorder
 
       ! local variable
       INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_value
+
+      CHARACTER(LEN=lc)                      :: cl_dimorder
 
       TYPE(TVAR)                             :: tl_var
@@ -1694,5 +1732,9 @@
       INTEGER(i4) :: ji
       INTEGER(i4) :: jj
-      !----------------------------------------------------------------
+      INTEGER(i4) :: jvar
+      !----------------------------------------------------------------
+
+      cl_dimorder='xyzt'
+      IF( PRESENT(cd_dimorder) ) cl_dimorder=TRIM(cd_dimorder)
 
       ! check if file opened
@@ -1726,4 +1768,13 @@
             ENDIF
 
+            ! change dimension order
+            IF( TRIM(cl_dimorder) /= 'xyzt' )THEN
+               CALL dim_reorder(td_file%t_dim(:),TRIM(cl_dimorder))
+               DO jvar=1,td_file%i_nvar
+                  CALL logger_debug("VAR REORDER: "//TRIM(td_file%t_var(jvar)%c_name))
+                  CALL var_reorder(td_file%t_var(jvar),TRIM(cl_dimorder))
+               ENDDO
+            ENDIF
+
             ! write dimension in file
             DO ji = 1, ip_maxdim
@@ -1776,5 +1827,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1798,5 +1849,5 @@
          ! Enter define mode
          il_status=NF90_REDEF(td_file%i_id)
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF WRITE FILE DIM: ")
 
          td_file%l_def=.TRUE.
@@ -1813,9 +1864,9 @@
             il_status=NF90_DEF_DIM(td_file%i_id, fct_upper(td_dim%c_sname), &
             &                      NF90_UNLIMITED, td_dim%i_id)
-            CALL iom_cdf__check(il_status)
+            CALL iom_cdf__check(il_status,"IOM CDF WRITE FILE DIM: ")
 
          ELSE
             ! write not unlimited dimension
-            CALL logger_trace( &
+            CALL logger_debug( &
             &  "IOM CDF WRITE FILE DIM: write dimension "//TRIM(td_dim%c_name)//&
             &  " in file "//TRIM(td_file%c_name))
@@ -1823,5 +1874,5 @@
             il_status=NF90_DEF_DIM(td_file%i_id, fct_upper(td_dim%c_sname), &
             &                      td_dim%i_len, td_dim%i_id)
-            CALL iom_cdf__check(il_status)
+            CALL iom_cdf__check(il_status,"IOM CDF WRITE FILE DIM: ")
 
          ENDIF
@@ -1834,5 +1885,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1859,5 +1910,5 @@
          ! Enter define mode
          il_status=NF90_REDEF(td_file%i_id)
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF WRITE FILE ATT: ")
 
          td_file%l_def=.TRUE.
@@ -1876,5 +1927,5 @@
             il_status = NF90_PUT_ATT(td_file%i_id, id_varid, &
             &  td_att%c_name, td_att%c_value )
-            CALL iom_cdf__check(il_status)
+            CALL iom_cdf__check(il_status,"IOM CDF WRITE FILE ATT: ")
 
          CASE(NF90_BYTE, NF90_SHORT, NF90_INT, NF90_FLOAT, NF90_DOUBLE)
@@ -1882,5 +1933,5 @@
             il_status = NF90_PUT_ATT(td_file%i_id, id_varid, &
             &  td_att%c_name, td_att%d_value )
-            CALL iom_cdf__check(il_status)
+            CALL iom_cdf__check(il_status,"IOM CDF WRITE FILE ATT: ")
 
       END SELECT
@@ -1891,5 +1942,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1917,10 +1968,10 @@
          ! Enter define mode
          il_status=NF90_REDEF(td_file%i_id)
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR: ")
 
          td_file%l_def=.TRUE.
 
       ENDIF
-      
+ 
       ! check if file and variable dimension conform
       IF( file_check_var_dim(td_file, td_var) )THEN
@@ -1938,10 +1989,15 @@
             ENDIF
          ENDDO
+         ! ugly patch until NEMO do not force to use 0. as FillValue 
          IF( ll_chg )THEN
             ! not a dimension variable
             ! change FillValue
-
-            ! ugly patch until NEMO do not force to use 0. as FillValue 
-            CALL var_chg_FillValue(td_var,0._dp)
+            SELECT CASE( TRIM(fct_lower(td_var%c_name)) )
+               CASE DEFAULT
+                  CALL var_chg_FillValue(td_var,0._dp)
+               CASE('nav_lon','nav_lat', &
+                  & 'glamt','glamu','glamv','glamf', &
+                  & 'gphit','gphiu','gphiv','gphif')
+            END SELECT
          ENDIF
 
@@ -1957,5 +2013,5 @@
             ! Leave define mode
             il_status=NF90_ENDDEF(td_file%i_id)
-            CALL iom_cdf__check(il_status)
+            CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR: ")
 
             td_file%l_def=.FALSE.
@@ -1975,5 +2031,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -2002,9 +2058,17 @@
       tl_var=var_copy(td_var)
 
+      ! forced to use float type
+      IF( tl_var%d_unf /= 1. .AND. tl_var%i_type==NF90_SHORT )THEN
+         tl_var%i_type=NF90_FLOAT
+      ENDIF
+
       IF( ALL( .NOT. tl_var%t_dim(:)%l_use ) )THEN
+         CALL logger_debug( &
+         &  "IOM CDF WRITE VAR DEF scalar: define variable "//&
+         &  TRIM(tl_var%c_name)//" in file "//TRIM(td_file%c_name))
          ! scalar value
          il_status = NF90_DEF_VAR(td_file%i_id, TRIM(tl_var%c_name), &
          &                        tl_var%i_type, varid=iom_cdf__write_var_def) 
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR DEF: ")
       ELSE
 
@@ -2020,16 +2084,17 @@
          ENDDO
 
-         CALL logger_trace( &
+         CALL logger_debug( &
          &  "IOM CDF WRITE VAR DEF: define dimension to be used for variable "//&
          &  TRIM(tl_var%c_name)//" in file "//TRIM(td_file%c_name))
 
          DO ji=1,jj
-            CALL logger_trace("IOM CDF WRITE VAR DEF: dimid "//TRIM(fct_str(il_dimid(ji))) )
+            CALL logger_debug("IOM CDF WRITE VAR DEF: dimid "//TRIM(fct_str(il_dimid(ji))) )
          ENDDO
+
          il_status = NF90_DEF_VAR(td_file%i_id, TRIM(tl_var%c_name),     &
          &                        tl_var%i_type,                         &
          &                        il_dimid(1:jj),                        &
          &                        varid=iom_cdf__write_var_def           )
-         CALL iom_cdf__check(il_status)
+         CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR DEF: ")
       ENDIF
 
@@ -2043,8 +2108,13 @@
 
       DO ji = 1, tl_var%i_natt
-         CALL logger_trace( &
+         CALL logger_debug( &
          &  " IOM CDF WRITE VAR DEF: put attribute "//TRIM(tl_var%t_att(ji)%c_name)//&
          &  " for variable "//TRIM(tl_var%c_name)//&
          &  " in file "//TRIM(td_file%c_name) )
+
+         ! forced FillValue to have same type than variable
+         IF( TRIM(tl_var%t_att(ji)%c_name) == '_FillValue' )THEN
+            tl_var%t_att(ji)%i_type=tl_var%i_type
+         ENDIF
 
          IF( tl_var%t_att(ji)%i_type == NF90_CHAR )THEN
@@ -2053,5 +2123,5 @@
                &                        TRIM(tl_var%t_att(ji)%c_name),        &
                &                        TRIM(tl_var%t_att(ji)%c_value)        )
-               CALL iom_cdf__check(il_status)
+               CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR DEF: ")
             ENDIF
          ELSE
@@ -2082,6 +2152,6 @@
                   &                        TRIM(tl_var%t_att(ji)%c_name),  &
                   &                        REAL(tl_var%t_att(ji)%d_value(:),dp))
-               END SELECT
-            CALL iom_cdf__check(il_status)
+            END SELECT
+            CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR DEF: ")
          ENDIF
       ENDDO
@@ -2097,5 +2167,7 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - reuse scale factor and offset, before writing variable
    !
    !> @param[in] td_file   file structure
@@ -2122,5 +2194,11 @@
       &  "IOM CDF WRITE VAR VALUE: get dimension to be used for variable "//&
       &  TRIM(td_var%c_name)//" in file "//TRIM(td_file%c_name))
-
+   
+      ! use scale factor and offset
+      WHERE( td_var%d_value(:,:,:,:) /= td_var%d_fill )
+         td_var%d_value(:,:,:,:) = &
+         &  (td_var%d_value(:,:,:,:)-td_var%d_ofs)/td_var%d_scf
+      END WHERE
+      
       jj=0
       DO ji = 1, ip_maxdim
@@ -2153,5 +2231,5 @@
 
       il_status = NF90_PUT_VAR( td_file%i_id, td_var%i_id, dl_value(:,:,:,:))
-      CALL iom_cdf__check(il_status)
+      CALL iom_cdf__check(il_status,"IOM CDF WRITE VAR VALUE: ")
 
       DEALLOCATE( dl_value )
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_dom.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_dom.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_dom.f90	(revision 9987)
@@ -71,5 +71,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[inout] td_mpp mpp structure
@@ -106,5 +106,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[in] td_mpp mpp structure
@@ -130,5 +130,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @param[in] td_mpp    mpp structure
@@ -194,5 +194,5 @@
    !
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
@@ -246,5 +246,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @todo
@@ -411,5 +411,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
@@ -465,5 +465,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @param[in] td_mpp    mpp structure
@@ -524,5 +524,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !>
    !> @param[in] td_mpp    mpp structure
@@ -636,5 +636,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
@@ -663,5 +663,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
@@ -691,5 +691,5 @@
    !>
    !> @author J.Paul
-   !> - October, 2014- Initial Version
+   !> @date October, 2014 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_mpp.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_mpp.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_mpp.f90	(revision 9987)
@@ -87,5 +87,5 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -137,5 +137,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_mpp mpp structure
@@ -161,4 +161,7 @@
 
       ELSE
+         ! 
+         td_mpp%i_id=1
+
          ! if no processor file selected
          ! force to open all files 
@@ -221,5 +224,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_mpp mpp structure
@@ -248,5 +251,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_mpp mpp structure
@@ -267,4 +270,7 @@
 
       ELSE
+         ! 
+         td_mpp%i_id=0         
+
          DO ji=1,td_mpp%i_nproc
             IF( td_mpp%t_proc(ji)%i_id /= 0 )THEN
@@ -285,5 +291,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - use start and count array instead of domain structure.
@@ -314,5 +320,11 @@
          &               " in mpp strcuture "//TRIM(td_mpp%c_name))
 
+      ELSEIF( td_mpp%i_id == 0 )THEN
+
+         CALL logger_error( " IOM MPP READ VAR: mpp structure not opened. "//&
+         &               " can not read variable in "//TRIM(td_mpp%c_name))   
+      
       ELSE
+
 
          IF( ANY(td_mpp%t_proc(:)%i_id /= 0) )THEN
@@ -355,5 +367,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - use start and count array instead of domain structure.
@@ -384,4 +396,9 @@
          &               " in mpp strcuture "//TRIM(td_mpp%c_name))
 
+      ELSEIF( td_mpp%i_id == 0 )THEN
+
+         CALL logger_error( " IOM MPP READ VAR: mpp structure not opened. "//&
+         &               " can not read variable in "//TRIM(td_mpp%c_name))   
+      
       ELSE
 
@@ -400,5 +417,5 @@
                CALL logger_error( &
                &  " IOM MPP READ VAR: there is no variable with "//&
-               &  "name or standard name"//TRIM(cd_name)//&
+               &  "name or standard name "//TRIM(cd_name)//&
                &  " in processor/file "//TRIM(td_mpp%t_proc(1)%c_name))
             ENDIF
@@ -416,5 +433,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - use start and count array instead of domain structure.
@@ -467,4 +484,15 @@
       IF( PRESENT(id_count) ) il_count(:)=id_count(:)
 
+      CALL logger_debug("IOM MPP READ VAR VALUE: start "//&
+               &  TRIM(fct_str(il_start(jp_I)))//","//&
+               &  TRIM(fct_str(il_start(jp_J)))//","//&
+               &  TRIM(fct_str(il_start(jp_K)))//","//&
+               &  TRIM(fct_str(il_start(jp_L))) )
+      CALL logger_debug("IOM MPP READ VAR VALUE: count "//&
+               &  TRIM(fct_str(il_count(jp_I)))//","//&
+               &  TRIM(fct_str(il_count(jp_J)))//","//&
+               &  TRIM(fct_str(il_count(jp_K)))//","//&
+               &  TRIM(fct_str(il_count(jp_L))) )
+
       DO jk=1,ip_maxdim
          IF( .NOT. td_var%t_dim(jk)%l_use )THEN
@@ -476,6 +504,15 @@
       ENDDO
 
-
       IF( ANY(il_end(:) > td_mpp%t_dim(:)%i_len) )THEN
+            CALL logger_debug("IOM MPP READ VAR VALUE: start + count "//&
+               &  TRIM(fct_str(il_end(jp_I)))//","//&
+               &  TRIM(fct_str(il_end(jp_J)))//","//&
+               &  TRIM(fct_str(il_end(jp_K)))//","//&
+               &  TRIM(fct_str(il_end(jp_L))) )
+            CALL logger_debug("IOM MPP READ VAR VALUE: dimension "//&
+               &  TRIM(fct_str(td_mpp%t_dim(jp_I)%i_len))//","//&
+               &  TRIM(fct_str(td_mpp%t_dim(jp_J)%i_len))//","//&
+               &  TRIM(fct_str(td_mpp%t_dim(jp_K)%i_len))//","//&
+               &  TRIM(fct_str(td_mpp%t_dim(jp_L)%i_len)) )
             CALL logger_fatal("IOM MPP READ VAR VALUE: start + count "//&
             &                 "exceed dimension bound.")
@@ -583,14 +620,18 @@
    !
    !> @details
+   !> optionally, you could specify the dimension order (default 'xyzt')
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 - add dimension order option 
    !
    !> @param[inout] td_mpp mpp structure
-   !-------------------------------------------------------------------
-   SUBROUTINE iom_mpp_write_file(td_mpp)
+   !> @param[In] cd_dimorder dimension order
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_mpp_write_file(td_mpp, cd_dimorder)
       IMPLICIT NONE
       ! Argument      
-      TYPE(TMPP), INTENT(INOUT) :: td_mpp
+      TYPE(TMPP)      , INTENT(INOUT) :: td_mpp
+      CHARACTER(LEN=*), INTENT(IN   ), OPTIONAL :: cd_dimorder
 
       ! local variable
@@ -610,5 +651,5 @@
                !CALL file_del_att(td_mpp%t_proc(ji), 'ew_overlap')
 
-               CALL iom_write_file(td_mpp%t_proc(ji))
+               CALL iom_write_file(td_mpp%t_proc(ji), cd_dimorder)
             ELSE
                CALL logger_debug( " MPP WRITE: no id associated to file "//&
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_rstdimg.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_rstdimg.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/iom_rstdimg.f90	(revision 9987)
@@ -131,5 +131,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -284,5 +284,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -328,5 +328,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -394,5 +394,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -544,5 +544,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -636,5 +636,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -688,5 +688,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -733,5 +733,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -778,5 +778,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -820,5 +820,5 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -863,5 +863,5 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -907,5 +907,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -972,5 +972,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1037,5 +1037,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file structure
@@ -1058,4 +1058,5 @@
       INTEGER(i4), DIMENSION(ip_maxdim)            :: il_start
       INTEGER(i4), DIMENSION(ip_maxdim)            :: il_count
+
       REAL(dp),    DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
 
@@ -1204,4 +1205,16 @@
       ENDIF
 
+      ! force to change _FillValue to avoid mistake 
+      ! with dummy zero _FillValue
+      IF( td_var%d_fill == 0._dp )THEN
+         CALL var_chg_FillValue(td_var)
+      ENDIF
+
+      ! use scale factor and offset
+      WHERE( td_var%d_value(:,:,:,:) /= td_var%d_fill )
+         td_var%d_value(:,:,:,:) = &
+         &  td_var%d_value(:,:,:,:)*td_var%d_scf + td_var%d_ofs
+      END WHERE
+
    END SUBROUTINE iom_rstdimg__read_var_value
    !-------------------------------------------------------------------
@@ -1212,5 +1225,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date September, 2014
    !> - use iom_rstdimg__get_rec
@@ -1308,5 +1321,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1413,5 +1426,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_file   file structure
@@ -1630,7 +1643,9 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015
+   !> - bug fix: do not use scale factor an offset for case no0d, no1d...
    !>
-   !> @param[in] id_fileid file id
+   !> @param[in] td_file file structure
    !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__write_var(td_file)
@@ -1667,4 +1682,14 @@
             CASE('no0d','no1d','no2d','no3d')
             CASE DEFAULT
+               
+               ! use scale factor and offset
+               WHERE( td_file%t_var(ji)%d_value(:,:,:,:) /= &
+               &      td_file%t_var(ji)%d_fill )
+                  td_file%t_var(ji)%d_value(:,:,:,:) = &
+                  &   ( td_file%t_var(ji)%d_value(:,:,:,:) - &
+                  &     td_file%t_var(ji)%d_ofs ) / &
+                  &   td_file%t_var(ji)%d_scf
+               END WHERE
+
                DO jk=1,td_file%t_var(ji)%t_dim(3)%i_len
                   SELECT CASE (td_file%t_var(ji)%i_ndim)
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/logger.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/logger.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/logger.f90	(revision 9987)
@@ -16,6 +16,7 @@
 !> but not necessarily "wrong". 
 !>    - error : Other runtime errors or unexpected conditions.
-!>    - fatal : Severe errors that cause premature termination.<br />
+!>    - fatal : Severe errors that cause premature termination.
 !>  default verbosity is warning
+!>    - none  : to not create and write any information in logger file.<br />
 !
 !> If total number of error exceeded maximum number 
@@ -24,5 +25,5 @@
 !> to open/create logger file:<br/>
 !> @code
-!>    CALL logger_open(cd_file, [cd_verbosity,] [id_loggerid,] [id_maxerror])
+!>    CALL logger_open(cd_file, [cd_verbosity,] [id_maxerror,] [id_loggerid])
 !> @endcode
 !> - cd_file is logger file name
@@ -120,5 +121,8 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date November, 2013- Initial Version
+!> @date November, 2013 - Initial Version
+!> @date February, 2015
+!> - check verbosity validity
+!> - add 'none' verbosity level to not used logger file
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -151,7 +155,9 @@
 
    PRIVATE :: logger__write     ! cut message to get maximum of 80 character by line in log file
+   PRIVATE :: logger__check_verb! check verbosity validity
 
    TYPE TLOGGER   !< logger structure
       INTEGER(i4)       :: i_id = 0                 !< log file id
+      LOGICAL           :: l_use=.TRUE.             !< use logger or not
       CHARACTER(LEN=lc) :: c_name                   !< log file name
       CHARACTER(LEN=lc) :: c_verbosity = "warning"  !< verbosity choose
@@ -163,5 +169,5 @@
 
    !  module variable
-   INTEGER(i4), PARAMETER :: im_nverbosity=6     !< number of log level
+   INTEGER(i4), PARAMETER :: im_nverbosity=7     !< number of log level
    CHARACTER(len=*), DIMENSION(im_nverbosity), PARAMETER :: cm_verbosity= & !< verbosity array 
    &               (/ 'trace   ',&
@@ -170,5 +176,6 @@
    &                  'warning ',&
    &                  'error   ',&
-   &                  'fatal   '/)
+   &                  'fatal   ',&
+   &                  'none    '/)
 
    TYPE(TLOGGER), SAVE :: tm_logger      !< logger structure
@@ -184,62 +191,74 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_file      log file name
    !> @param[in] cd_verbosity log file verbosity
+   !> @param[in] id_maxerror  maximum number of error
    !> @param[in] id_logid     log file id (use to flush)
-   !> @param[in] id_maxerror  maximum number of error
-   !-------------------------------------------------------------------
-   SUBROUTINE logger_open(cd_file, cd_verbosity, id_logid, id_maxerror)
+   !-------------------------------------------------------------------
+   SUBROUTINE logger_open(cd_file, cd_verbosity, id_maxerror, id_logid)
       IMPLICIT NONE
       ! Argument
       CHARACTER(len=*), INTENT(IN) :: cd_file                ! log file name
       CHARACTER(len=*), INTENT(IN), OPTIONAL :: cd_verbosity ! log file verbosity
+      INTEGER(i4),      INTENT(IN), OPTIONAL :: id_maxerror  ! log max error
       INTEGER(i4),      INTENT(IN), OPTIONAL :: id_logid     ! log file id
-      INTEGER(i4),      INTENT(IN), OPTIONAL :: id_maxerror  ! log max error
 
       ! local variable
       INTEGER(i4) :: il_status
 
+      LOGICAL     :: ll_valid
+
       ! loop
       INTEGER(i4) :: ji
       !----------------------------------------------------------------
-      ! get id if not already define
-      IF( PRESENT(id_logid) )THEN
-         tm_logger%i_id=id_logid
-      ELSE
-         tm_logger%i_id=fct_getunit()
-      ENDIF
-
-      ! open log file
-      OPEN( tm_logger%i_id, &
-      &     STATUS="unknown",    &
-      &     FILE=TRIM(ADJUSTL(cd_file)),  &
-      &     ACTION="write",      &
-      &     POSITION="append",   &
-      &     IOSTAT=il_status)
-      CALL fct_err(il_status)
-
-      ! keep filename
-      tm_logger%c_name=TRIM(ADJUSTL(cd_file))
 
       ! if present, change verbosity value
       IF( PRESENT(cd_verbosity) )THEN
-         tm_logger%c_verbosity=TRIM(ADJUSTL(cd_verbosity))
-      ENDIF
-
-      ! compute "tab" of verbosity to be used
-      IF( TRIM(ADJUSTL(tm_logger%c_verb)) == "" )THEN
-         DO ji=im_nverbosity,1,-1
-            tm_logger%c_verb = &
-            &  TRIM(tm_logger%c_verb)//" "//TRIM(ADJUSTL(cm_verbosity(ji)))
-            IF( TRIM(tm_logger%c_verbosity) == TRIM(cm_verbosity(ji)) )THEN
-               EXIT
-            ENDIF
-         ENDDO
-      ENDIF
-
-      IF( PRESENT(id_maxerror) )THEN
-         tm_logger%i_maxerror=id_maxerror
+         ll_valid=logger__check_verb(TRIM(ADJUSTL(cd_verbosity)))
+         IF( ll_valid )THEN
+            tm_logger%c_verbosity=TRIM(ADJUSTL(cd_verbosity))
+         ENDIF
+      ENDIF
+
+      IF( TRIM(tm_logger%c_verbosity) == 'none' ) tm_logger%l_use=.FALSE.
+      
+      IF( tm_logger%l_use )THEN
+
+         ! get id if not already define
+         IF( PRESENT(id_logid) )THEN
+            tm_logger%i_id=id_logid
+         ELSE
+            tm_logger%i_id=fct_getunit()
+         ENDIF
+
+         ! open log file
+         OPEN( tm_logger%i_id, &
+         &     STATUS="unknown",    &
+         &     FILE=TRIM(ADJUSTL(cd_file)),  &
+         &     ACTION="write",      &
+         &     POSITION="append",   &
+         &     IOSTAT=il_status)
+         CALL fct_err(il_status)
+
+         ! keep filename
+         tm_logger%c_name=TRIM(ADJUSTL(cd_file))
+
+         ! compute "tab" of verbosity to be used
+         IF( TRIM(ADJUSTL(tm_logger%c_verb)) == "" )THEN
+            DO ji=im_nverbosity,1,-1
+               tm_logger%c_verb = &
+               &  TRIM(tm_logger%c_verb)//" "//TRIM(ADJUSTL(cm_verbosity(ji)))
+               IF( TRIM(tm_logger%c_verbosity) == TRIM(cm_verbosity(ji)) )THEN
+                  EXIT
+               ENDIF
+            ENDDO
+         ENDIF
+
+         IF( PRESENT(id_maxerror) )THEN
+            tm_logger%i_maxerror=id_maxerror
+         ENDIF
+
       ENDIF
 
@@ -249,5 +268,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !-------------------------------------------------------------------
    SUBROUTINE logger_close()
@@ -256,13 +275,15 @@
       INTEGER(i4) :: il_status
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         tm_logger%i_id = 0
-         CLOSE( tm_logger%i_id, &
-         &      IOSTAT=il_status)      
-         CALL fct_err(il_status)
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_close')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            tm_logger%i_id = 0
+            CLOSE( tm_logger%i_id, &
+            &      IOSTAT=il_status)      
+            CALL fct_err(il_status)
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_close')
+         ENDIF
       ENDIF
 
@@ -272,17 +293,19 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !-------------------------------------------------------------------
    SUBROUTINE logger_flush()
       IMPLICIT NONE
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         CALL logger_close()
-         CALL logger_open( tm_logger%c_name, tm_logger%c_verbosity, tm_logger%i_id, &
-         &              tm_logger%i_maxerror )     
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_flush')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            CALL logger_close()
+            CALL logger_open( tm_logger%c_name, tm_logger%c_verbosity, &
+            &                 tm_logger%i_maxerror, tm_logger%i_id )     
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_flush')
+         ENDIF
       ENDIF
 
@@ -292,5 +315,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !-------------------------------------------------------------------
    RECURSIVE SUBROUTINE logger_header()
@@ -299,17 +322,19 @@
       INTEGER(i4)       :: il_status
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         WRITE( tm_logger%i_id,    &
-            &   FMT='(4(a/))',     &
-            &   IOSTAT=il_status ) &
-            &   "--------------------------------------------------",&
-            &   "INIT     : verbosity "//TRIM(tm_logger%c_verbosity),&
-            &   "INIT     : max error "//TRIM(fct_str(tm_logger%i_maxerror)), &
-            &   "--------------------------------------------------"
-         CALL fct_err(il_status)
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_header')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            WRITE( tm_logger%i_id,    &
+               &   FMT='(4(a/))',     &
+               &   IOSTAT=il_status ) &
+               &   "--------------------------------------------------",&
+               &   "INIT     : verbosity "//TRIM(tm_logger%c_verbosity),&
+               &   "INIT     : max error "//TRIM(fct_str(tm_logger%i_maxerror)), &
+               &   "--------------------------------------------------"
+            CALL fct_err(il_status)
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_header')
+         ENDIF
       ENDIF
 
@@ -319,5 +344,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !-------------------------------------------------------------------
    SUBROUTINE logger_footer()
@@ -326,20 +351,22 @@
       INTEGER(i4)       :: il_status
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         WRITE( tm_logger%i_id,    &
-            &   FMT='(4(/a))',     &
-            &   IOSTAT=il_status ) &
-            &   "--------------------------------------------------",&
-            &   "END      : log ended ",              &
-            &   "END      : "//TRIM(fct_str(tm_logger%i_nerror))//   &
-            &   " ERROR detected ",                                  &
-            &   "END      : "//TRIM(fct_str(tm_logger%i_nfatal))//   &
-            &   " FATAL detected ",                                  &
-            &   "--------------------------------------------------"
-         CALL fct_err(il_status)
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_footer')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            WRITE( tm_logger%i_id,    &
+               &   FMT='(4(/a))',     &
+               &   IOSTAT=il_status ) &
+               &   "--------------------------------------------------",&
+               &   "END      : log ended ",              &
+               &   "END      : "//TRIM(fct_str(tm_logger%i_nerror))//   &
+               &   " ERROR detected ",                                  &
+               &   "END      : "//TRIM(fct_str(tm_logger%i_nfatal))//   &
+               &   " FATAL detected ",                                  &
+               &   "--------------------------------------------------"
+            CALL fct_err(il_status)
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_footer')
+         ENDIF
       ENDIF
    END SUBROUTINE logger_footer
@@ -350,5 +377,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_msg    message to write
@@ -361,19 +388,21 @@
       LOGICAL,          INTENT(IN), OPTIONAL :: ld_flush
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         IF( INDEX(TRIM(tm_logger%c_verb),'trace')/=0 )THEN
-
-            CALL logger__write("TRACE   :",cd_msg)
-
-            IF( PRESENT(ld_flush) )THEN
-               IF( ld_flush )THEN
-                  CALL logger_flush()
-               ENDIF
-            ENDIF      
-         ENDIF
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_trace')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            IF( INDEX(TRIM(tm_logger%c_verb),'trace')/=0 )THEN
+
+               CALL logger__write("TRACE   :",cd_msg)
+
+               IF( PRESENT(ld_flush) )THEN
+                  IF( ld_flush )THEN
+                     CALL logger_flush()
+                  ENDIF
+               ENDIF      
+            ENDIF
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_trace')
+         ENDIF
       ENDIF
    END SUBROUTINE logger_trace
@@ -384,5 +413,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_msg    message to write
@@ -395,19 +424,21 @@
       LOGICAL,          INTENT(IN), OPTIONAL :: ld_flush
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         IF( INDEX(TRIM(tm_logger%c_verb),'debug')/=0 )THEN
-
-            CALL logger__write("DEBUG   :",cd_msg)
-
-            IF( PRESENT(ld_flush) )THEN
-               IF( ld_flush )THEN
-                  CALL logger_flush()
-               ENDIF
-            ENDIF      
-         ENDIF
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_debug')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            IF( INDEX(TRIM(tm_logger%c_verb),'debug')/=0 )THEN
+
+               CALL logger__write("DEBUG   :",cd_msg)
+
+               IF( PRESENT(ld_flush) )THEN
+                  IF( ld_flush )THEN
+                     CALL logger_flush()
+                  ENDIF
+               ENDIF      
+            ENDIF
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_debug')
+         ENDIF
       ENDIF
    END SUBROUTINE logger_debug
@@ -418,5 +449,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_msg    message to write
@@ -429,19 +460,21 @@
       LOGICAL,          INTENT(IN), OPTIONAL :: ld_flush
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         IF( INDEX(TRIM(tm_logger%c_verb),'info')/=0 )THEN
-
-            CALL logger__write("INFO    :",cd_msg)
-
-            IF( PRESENT(ld_flush) )THEN
-               IF( ld_flush )THEN
-                  CALL logger_flush()
-               ENDIF
-            ENDIF      
-         ENDIF
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_info')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            IF( INDEX(TRIM(tm_logger%c_verb),'info')/=0 )THEN
+
+               CALL logger__write("INFO    :",cd_msg)
+
+               IF( PRESENT(ld_flush) )THEN
+                  IF( ld_flush )THEN
+                     CALL logger_flush()
+                  ENDIF
+               ENDIF      
+            ENDIF
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_info')
+         ENDIF
       ENDIF
    END SUBROUTINE logger_info
@@ -452,5 +485,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_msg    message to write
@@ -463,19 +496,21 @@
       LOGICAL,          INTENT(IN), OPTIONAL :: ld_flush
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         IF( INDEX(TRIM(tm_logger%c_verb),'warn')/=0 )THEN
-
-            CALL logger__write("WARNING :",cd_msg)
-
-            IF( PRESENT(ld_flush) )THEN
-               IF( ld_flush )THEN
-                  CALL logger_flush()
-               ENDIF
-            ENDIF      
-         ENDIF
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_warn')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            IF( INDEX(TRIM(tm_logger%c_verb),'warn')/=0 )THEN
+
+               CALL logger__write("WARNING :",cd_msg)
+
+               IF( PRESENT(ld_flush) )THEN
+                  IF( ld_flush )THEN
+                     CALL logger_flush()
+                  ENDIF
+               ENDIF      
+            ENDIF
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_warn')
+         ENDIF
       ENDIF
    END SUBROUTINE logger_warn
@@ -486,5 +521,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_msg    message to write
@@ -500,30 +535,33 @@
       CHARACTER(LEN=lc) :: cl_nerror
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         ! increment the error number
-         tm_logger%i_nerror=tm_logger%i_nerror+1
-
-         IF( INDEX(TRIM(tm_logger%c_verb),'error')/=0 )THEN
-
-            CALL logger__write("ERROR   :",cd_msg)
-
-            IF( PRESENT(ld_flush) )THEN
-               IF( ld_flush )THEN
-                  CALL logger_flush()
-               ENDIF
-            ENDIF      
-         ENDIF
-
-         IF( tm_logger%i_nerror >= tm_logger%i_maxerror )THEN
-            WRITE(cl_nerror,*) tm_logger%i_maxerror
-            CALL logger_fatal(&
-            &  'Error count reached limit of '//TRIM(ADJUSTL(cl_nerror)) )
-         ENDIF
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_error')
-      ENDIF
-
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            IF( TRIM(tm_logger%c_verb) /= 'none' )THEN
+               ! increment the error number
+               tm_logger%i_nerror=tm_logger%i_nerror+1
+            ENDIF
+
+            IF( INDEX(TRIM(tm_logger%c_verb),'error')/=0 )THEN
+
+               CALL logger__write("ERROR   :",cd_msg)
+
+               IF( PRESENT(ld_flush) )THEN
+                  IF( ld_flush )THEN
+                     CALL logger_flush()
+                  ENDIF
+               ENDIF      
+            ENDIF
+
+            IF( tm_logger%i_nerror >= tm_logger%i_maxerror )THEN
+               WRITE(cl_nerror,*) tm_logger%i_maxerror
+               CALL logger_fatal(&
+               &  'Error count reached limit of '//TRIM(ADJUSTL(cl_nerror)) )
+            ENDIF
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_error')
+         ENDIF
+      ENDIF
    END SUBROUTINE logger_error
    !-------------------------------------------------------------------
@@ -532,5 +570,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_msg message to write
@@ -541,21 +579,23 @@
       CHARACTER(LEN=*),           INTENT(IN) :: cd_msg
       !----------------------------------------------------------------
-      IF( tm_logger%i_id /= 0 )THEN
-         IF( INDEX(TRIM(tm_logger%c_verb),'fatal')/=0 )THEN
-            ! increment the error number
-            tm_logger%i_nfatal=tm_logger%i_nfatal+1
-
-            CALL logger__write("FATAL   :",cd_msg)
-
-            CALL logger_footer()
-            CALL logger_close()
-
-            WRITE(*,*) 'FATAL ERROR'
-            STOP
-         ENDIF
-      ELSE
-          CALL logger_open('logger.log')
-          CALL logger_header()
-          CALL logger_fatal('you must have create logger to use logger_fatal')
+      IF( tm_logger%l_use )THEN
+         IF( tm_logger%i_id /= 0 )THEN
+            IF( INDEX(TRIM(tm_logger%c_verb),'fatal')/=0 )THEN
+               ! increment the error number
+               tm_logger%i_nfatal=tm_logger%i_nfatal+1
+
+               CALL logger__write("FATAL   :",cd_msg)
+
+               CALL logger_footer()
+               CALL logger_close()
+
+               WRITE(*,*) 'FATAL ERROR'
+               STOP
+            ENDIF
+         ELSE
+             CALL logger_open('logger.log')
+             CALL logger_header()
+             CALL logger_fatal('you must have create logger to use logger_fatal')
+         ENDIF
       ENDIF
    END SUBROUTINE logger_fatal
@@ -565,5 +605,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] cd_verb   verbosity of the message to write
@@ -615,4 +655,43 @@
 
    END SUBROUTINE logger__write
+   !-------------------------------------------------------------------
+   !> @brief This function check validity of verbosity.
+   !>
+   !> @author J.Paul
+   !> @date February, 2015 - Initial Version
+   !
+   !> @param[in] cd_verb   verbosity of the message to write
+   !> @return verbosity is valid or not
+   !-------------------------------------------------------------------
+   FUNCTION logger__check_verb(cd_verb)
+      IMPLICIT NONE
+      ! Argument
+      CHARACTER(LEN=*),           INTENT(IN) :: cd_verb
+
+      !function
+      LOGICAL           :: logger__check_verb
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+
+      !----------------------------------------------------------------
+      logger__check_verb=.FALSE.
+
+      DO ji=1,im_nverbosity
+         IF( TRIM(cd_verb) == TRIM(cm_verbosity(ji)) )THEN
+            logger__check_verb=.TRUE.
+            EXIT
+         ENDIF
+      ENDDO
+
+      IF( .NOT. logger__check_verb )THEN
+         CALL logger_open('logger.log')
+         CALL logger_header()
+         CALL logger_fatal('LOGGER : invalid verbosity, check namelist.'//&
+         &                 ' default one will be used.')
+         CALL logger_footer()
+      ENDIF
+   END FUNCTION logger__check_verb
 END MODULE logger
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/math.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/math.f90	(revision 9987)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/math.f90	(revision 9987)
@@ -0,0 +1,1285 @@
+!----------------------------------------------------------------------
+! NEMO system team, System and Interface for oceanic RElocable Nesting
+!----------------------------------------------------------------------
+!
+! MODULE: math
+!
+! DESCRIPTION:
+!> @brief
+!> This module groups some useful mathematical function.
+!>
+!> @details
+!> 
+!>    to compute the mean of an array:<br/>
+!> @code
+!>    dl_value=math_mean( dl_value, dd_fill )
+!> @endcode
+!>       - dl_value is 1D or 2D array
+!>       - dd_fill is FillValue
+!>
+!>    to compute the median of an array:<br/>
+!> @code
+!>    dl_value=math_median( dl_value, dd_fill )
+!> @endcode
+!>       - dl_value is 1D or 2D array
+!>       - dd_fill is FillValue
+!>
+!>    to compute the mean without extremum of an array:<br/>
+!> @code
+!>    dl_value=math_mwe( dl_value, id_next, dd_fill )
+!> @endcode
+!>       - dl_value is 1D or 2D array
+!>       - id_next is the number of extremum to be removed
+!>       - dd_fill is FillValue
+!>
+!>    to sort an 1D array:<br/>
+!> @code
+!>    CALL math_QsortC(dl_value)
+!> @endcode
+!>       - dl_value is 1D array
+!>
+!>    to correct phase angles to produce smoother phase:<br/>
+!> @code
+!>    CALL math_unwrap(dl_value, [dl_discont])
+!> @endcode
+!>       - dl_value is 1D array
+!>       - dl_discont maximum discontinuity between values, default pi
+!>
+!>    to compute simple operation
+!> @code
+!>    dl_res=math_compute(cl_var)
+!> @endcode
+!>       - cl_var operation to compute (string of character)
+!>       - dl_res result of the operation, real(dp)
+!>
+!>    to compute first derivative of 1D array:<br/>
+!> @code
+!>    dl_value(:)=math_deriv_1D( dd_value(:), dd_fill, [ld_discont] )
+!> @endcode
+!>       - dd_value is 1D array of variable
+!>       - dd_fill is FillValue of variable
+!>       - ld_discont is logical to take into account longitudinal 
+!>         East-West discontinuity [optional]
+!>
+!>    to compute first derivative of 2D array:<br/>
+!> @code
+!>    dl_value(:,:)=math_deriv_2D( dd_value(:,:), dd_fill, cd_dim, 
+!>                  [ld_discont] )
+!> @endcode
+!>       - dd_value is 2D array of variable
+!>       - dd_fill is FillValue of variable
+!>       - cd_dim is character to compute derivative on first (I) or
+!>         second (J) dimension
+!>       - ld_discont is logical to take into account longitudinal 
+!>         East-West discontinuity [optional]
+!>
+!>    to compute first derivative of 3D array:<br/>
+!> @code
+!>    dl_value(:,:,:)=math_deriv_3D( dd_value(:,:,:), dd_fill, cd_dim,
+!>                    [ld_discont] )
+!> @endcode
+!>       - dd_value is 3D array of variable
+!>       - dd_fill is FillValue of variable
+!>       - cd_dim is character to compute derivative on first (I), second (J),
+!>         or third (K) dimension
+!>       - ld_discont is logical to take into account longitudinal East-West 
+!>         discontinuity [optional]
+!>
+!>
+!> @author
+!> J.Paul
+! REVISION HISTORY:
+!> @date January, 2015 - Initial version
+!
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!----------------------------------------------------------------------
+MODULE math
+   USE kind                            ! F90 kind parameter
+   USE global                          ! global variable
+   USE phycst                          ! physical constant
+   USE fct                             ! basic useful function
+   IMPLICIT NONE
+   ! NOTE_avoid_public_variables_if_possible
+
+   ! function and subroutine
+   PUBLIC :: math_mean      !< return mean of an array
+   PUBLIC :: math_median    !< return median of an array
+   PUBLIC :: math_mwe       !< return mean without extremum of an array
+   PUBLIC :: math_QsortC    !< sort an 1D array
+   PUBLIC :: math_unwrap    !< correct phase angles to produce smoother phase
+   PUBLIC :: math_compute   !< compute simple operation
+   PUBLIC :: math_deriv_1D  !< compute first derivative of 1D array 
+   PUBLIC :: math_deriv_2D  !< compute first derivative of 2D array 
+   PUBLIC :: math_deriv_3D  !< compute first derivative of 3D array
+
+
+   PRIVATE :: math__Partition
+   PRIVATE :: math__mean_1d
+   PRIVATE :: math__mean_2d
+   PRIVATE :: math__median_1d
+   PRIVATE :: math__median_2d
+   PRIVATE :: math__mwe_1d
+   PRIVATE :: math__mwe_2d
+   PRIVATE :: math__parentheses
+
+
+   INTERFACE math_mean
+      MODULE PROCEDURE math__mean_1d ! return mean of an array 1D
+      MODULE PROCEDURE math__mean_2d ! return mean of an array 2D
+   END INTERFACE math_mean
+
+   INTERFACE math_median
+      MODULE PROCEDURE math__median_1d ! return median of an array 1D
+      MODULE PROCEDURE math__median_2d ! return median of an array 2D
+   END INTERFACE math_median
+
+   INTERFACE math_mwe
+      MODULE PROCEDURE math__mwe_1d ! return mean without extremum of an array 1D
+      MODULE PROCEDURE math__mwe_2d ! return mean without extremum of an array 2D
+   END INTERFACE math_mwe
+
+CONTAINS
+   !------------------------------------------------------------------- 
+   !> @brief This function compute the mean of a 1D array. 
+   ! 
+   !> @author J.Paul 
+   !> @date January, 2015 - Initial Version 
+   ! 
+   !> @param[in] dd_array  1D array 
+   !> @param[in] dd_fill   fillValue
+   !> @return mean value, real(dp)
+   !------------------------------------------------------------------- 
+   PURE REAL(dp) FUNCTION math__mean_1d(dd_array, dd_fill)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:), INTENT(IN) :: dd_array
+      REAL(dp),               INTENT(IN), OPTIONAL :: dd_fill
+
+      ! local variable
+      INTEGER(i4)  :: il_count
+      REAL(dp)     :: dl_sum
+      REAL(dp)     :: dl_count
+      !----------------------------------------------------------------
+      
+      IF( PRESENT(dd_fill) )THEN
+         il_count=COUNT(dd_array(:)/=dd_fill)
+         IF( il_count > 0 )THEN
+            dl_sum  =SUM ( dd_array(:), dd_array(:)/= dd_fill )
+            dl_count=REAL( il_count, dp)
+
+            math__mean_1d=dl_sum/dl_count
+         ELSE
+            math__mean_1d=dd_fill
+         ENDIF
+      ELSE
+         il_count=SIZE(dd_array(:))
+         IF( il_count > 0 )THEN
+            dl_sum  =SUM ( dd_array(:) )
+            dl_count=REAL( il_count, dp)
+
+            math__mean_1d=dl_sum/dl_count
+         ELSE
+            math__mean_1d=0
+         ENDIF
+      ENDIF
+
+   END FUNCTION math__mean_1d
+   !------------------------------------------------------------------- 
+   !> @brief This function compute the mean of a 2D array. 
+   ! 
+   !> @author J.Paul 
+   !> @date January, 2015 - Initial Version 
+   ! 
+   !> @param[in] dd_array  2D array 
+   !> @param[in] dd_fill   fillValue
+   !> @return mean value, real(dp)
+   !------------------------------------------------------------------- 
+   PURE REAL(dp) FUNCTION math__mean_2d(dd_array, dd_fill)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_array
+      REAL(dp),                 INTENT(IN), OPTIONAL :: dd_fill
+
+      ! local variable
+      INTEGER(i4)                         :: il_count
+
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_list
+      !----------------------------------------------------------------
+
+      IF( PRESENT(dd_fill)  )THEN
+         il_count=COUNT(dd_array(:,:)/=dd_fill)
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:,:),dd_array(:,:)/=dd_fill)
+         ELSE
+            math__mean_2d=dd_fill
+         ENDIF
+      ELSE
+         il_count=SIZE(dd_array)
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:,:), MASK=.TRUE.)
+         ELSE
+            math__mean_2d=0
+         ENDIF
+      ENDIF
+
+      IF( ALLOCATED(dl_list) )THEN
+         math__mean_2d=math_mean(dl_list(:))
+         DEALLOCATE( dl_list )
+      ENDIF
+
+   END FUNCTION math__mean_2d
+   !------------------------------------------------------------------- 
+   !> @brief This function compute the median of a 1D array. 
+   ! 
+   !> @author J.Paul 
+   !> @date January, 2015 - Initial Version 
+   ! 
+   !> @param[in] dd_array  1D array 
+   !> @param[in] dd_fill   fillValue
+   !> @return median value, real(dp)
+   !-------------------------------------------------------------------
+   PURE REAL(dp) FUNCTION math__median_1d(dd_array, dd_fill)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:), INTENT(IN) :: dd_array
+      REAL(dp),               INTENT(IN), OPTIONAL :: dd_fill
+
+      ! local variable
+      INTEGER(i4)                         :: il_count
+
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_list
+      !----------------------------------------------------------------
+      
+      IF( PRESENT(dd_fill)  )THEN
+         il_count=COUNT(dd_array(:)/=dd_fill)
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:),dd_array(:)/=dd_fill)
+         ELSE
+            math__median_1d=dd_fill
+         ENDIF
+      ELSE
+         il_count=SIZE(dd_array(:))
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=dd_array(:)
+         ELSE
+            math__median_1d=0
+         ENDIF
+      ENDIF
+
+      IF( ALLOCATED(dl_list) )THEN
+         CALL math_QsortC(dl_list(:))
+
+         IF( MOD(il_count,2) == 0 )THEN
+            math__median_1d=(dl_list(il_count/2+1)+dl_list(il_count/2))/2_dp
+         ELSE
+            math__median_1d=dl_list(il_count/2+1)
+         ENDIF
+
+         DEALLOCATE(dl_list)
+      ENDIF
+
+   END FUNCTION math__median_1d
+   !------------------------------------------------------------------- 
+   !> @brief This function compute the median of a 2D array. 
+   ! 
+   !> @author J.Paul 
+   !> @date January, 2015 - Initial Version 
+   ! 
+   !> @param[in] dd_array  2D array 
+   !> @param[in] dd_fill   fillValue
+   !> @return median value, real(dp)
+   !-------------------------------------------------------------------
+   PURE REAL(dp) FUNCTION math__median_2d(dd_array, dd_fill)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_array
+      REAL(dp),                 INTENT(IN), OPTIONAL :: dd_fill
+
+      ! local variable
+      INTEGER(i4)                         :: il_count
+
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_list
+      !----------------------------------------------------------------
+      
+      IF( PRESENT(dd_fill)  )THEN
+         il_count=COUNT(dd_array(:,:)/=dd_fill)
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:,:),dd_array(:,:)/=dd_fill)
+         ELSE
+            math__median_2d=dd_fill
+         ENDIF
+      ELSE
+         il_count=SIZE(dd_array(:,:))
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:,:), MASK=.TRUE.)
+         ELSE
+            math__median_2d=0
+         ENDIF
+      ENDIF
+
+      IF( ALLOCATED(dl_list) )THEN
+         math__median_2d=math_median(dl_list(:))
+         DEALLOCATE(dl_list)
+      ENDIF
+
+   END FUNCTION math__median_2d
+   !------------------------------------------------------------------- 
+   !> @brief This function compute the mean without extremum of a 1D array. 
+   ! 
+   !> @author J.Paul 
+   !> @date January, 2015 - Initial Version 
+   ! 
+   !> @param[in] dd_array  1D array 
+   !> @param[in] id_next   number of extremum to be removed
+   !> @param[in] dd_fill   fillValue
+   !> @return median value, real(dp)
+   !-------------------------------------------------------------------
+   PURE REAL(dp) FUNCTION math__mwe_1d(dd_array, id_next, dd_fill)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:), INTENT(IN) :: dd_array
+      INTEGER(i4)           , INTENT(IN), OPTIONAL :: id_next
+      REAL(dp),               INTENT(IN), OPTIONAL :: dd_fill
+
+      ! local variable
+      INTEGER(i4)                         :: il_next
+      INTEGER(i4)                         :: il_count
+      INTEGER(i4)                         :: il_size
+
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_list
+      !----------------------------------------------------------------
+
+      il_next=2
+      IF( PRESENT(id_next) ) il_next=id_next
+      
+      il_size=SIZE(dd_array(:))
+      IF( PRESENT(dd_fill)  )THEN
+         il_count=COUNT(dd_array(:)/=dd_fill)
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:),dd_array(:)/=dd_fill)
+         ELSE
+            math__mwe_1d=dd_fill
+         ENDIF
+      ELSE
+         il_count=SIZE(dd_array(:))
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=dd_array(:)
+         ELSE
+            math__mwe_1d=0
+         ENDIF
+      ENDIF
+
+      IF( ALLOCATED(dl_list) )THEN
+         CALL math_QsortC(dl_list(:))
+
+         IF( il_count == il_size )THEN
+            ! no fillValue
+            math__mwe_1d=math_mean(dl_list(il_next+1:il_size-il_next))
+         ELSEIF( il_count > il_size-2*il_next )THEN
+            ! remove one extremum each side
+            math__mwe_1d=math_mean(dl_list(2:il_size-1))
+         ELSE ! il_count <= il_size-2*il_next
+            ! more than 2*il_next fillValue
+            ! compute mean only
+            math__mwe_1d=math_mean(dl_list(:))
+         ENDIF
+
+         DEALLOCATE(dl_list)
+      ENDIF
+
+   END FUNCTION math__mwe_1d
+   !------------------------------------------------------------------- 
+   !> @brief This function compute the mean without extremum of a 2D array. 
+   ! 
+   !> @author J.Paul 
+   !> @date January, 2015 - Initial Version 
+   ! 
+   !> @param[in] dd_array  2D array 
+   !> @param[in] id_next   number of extremum to be removed
+   !> @param[in] dd_fill   fillValue
+   !> @return median value, real(dp)
+   !-------------------------------------------------------------------
+   PURE REAL(dp) FUNCTION math__mwe_2d(dd_array, id_next, dd_fill)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_array
+      INTEGER(i4)             , INTENT(IN), OPTIONAL :: id_next
+      REAL(dp),                 INTENT(IN), OPTIONAL :: dd_fill
+
+      ! local variable
+      INTEGER(i4)                         :: il_count
+
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_list
+      !----------------------------------------------------------------
+      
+      IF( PRESENT(dd_fill)  )THEN
+         il_count=COUNT(dd_array(:,:)/=dd_fill)
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:,:),dd_array(:,:)/=dd_fill)
+
+            math__mwe_2d=math_mwe(dl_list(:), id_next)
+         ELSE
+            math__mwe_2d=dd_fill
+         ENDIF
+      ELSE
+         il_count=SIZE(dd_array(:,:))
+         IF( il_count > 0 )THEN
+            ALLOCATE( dl_list(il_count) )
+            dl_list(:)=PACK(dd_array(:,:), MASK=.TRUE.)
+
+            math__mwe_2d=math_mwe(dl_list(:), id_next)
+         ELSE
+            math__mwe_2d=0
+         ENDIF
+      ENDIF
+
+      IF( ALLOCATED(dl_list) ) DEALLOCATE(dl_list)
+
+   END FUNCTION math__mwe_2d
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine sort a 1D array. 
+   !>
+   !> @details
+   !> Recursive Fortran 95 quicksort routine
+   !> sorts real numbers into ascending numerical order
+   !> Author: Juli Rew, SCD Consulting (juliana@ucar.edu), 9/03
+   !> Based on algorithm from Cormen et al., Introduction to Algorithms,
+   !> 1997 printing
+   !> 
+   !> @author J.Paul 
+   !> @date January, 2015 - Rewrite with SIREN coding rules 
+   ! 
+   !> @param[inout] dd_array  1D array 
+   !-------------------------------------------------------------------
+   PURE RECURSIVE SUBROUTINE math_QsortC(dd_array)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:), INTENT(INOUT) :: dd_array
+
+      ! local variable
+      INTEGER(i4) :: il_iq
+      !----------------------------------------------------------------
+     
+      IF( SIZE(dd_array(:)) > 1 )THEN
+         CALL math__Partition(dd_array, il_iq)
+         CALL math_QsortC(dd_array(:il_iq-1))
+         CALL math_QsortC(dd_array(il_iq:))
+      ENDIF
+
+   END SUBROUTINE math_QsortC
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine partition a 1D array. 
+   !>
+   !> @details
+   !> Author: Juli Rew, SCD Consulting (juliana@ucar.edu), 9/03
+   !> Based on algorithm from Cormen et al., Introduction to Algorithms,
+   !> 1997 printing
+   !> 
+   !> @author J.Paul 
+   !> @date January, 2015 - Rewrite with SIREN coding rules 
+   ! 
+   !> @param[inout] dd_array  1D array 
+   !> @param[in] id_marker 
+   !-------------------------------------------------------------------
+   PURE SUBROUTINE math__Partition(dd_array, id_marker)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:), INTENT(INOUT) :: dd_array
+      INTEGER(i4),               INTENT(  OUT) :: id_marker
+
+      ! local variable
+      REAL(dp)    :: dl_temp
+      REAL(dp)    :: dl_x     ! pivot point
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+
+      dl_x = dd_array(1)
+      ji= 0
+      jj= SIZE(dd_array(:)) + 1
+
+      DO 
+         jj=jj-1
+         DO
+            IF( dd_array(jj) <= dl_x ) EXIT
+            jj=jj-1
+         ENDDO
+         ji=ji+1
+         DO
+            IF( dd_array(jj) >= dl_x ) EXIT
+            ji=ji+1
+         ENDDO
+         IF( ji < jj )THEN
+            ! exchange dd_array(ji) and dd_array(jj)
+            dl_temp= dd_array(ji)
+            dd_array(ji) = dd_array(jj)
+            dd_array(jj) = dl_temp
+         ELSEIF( ji==jj )THEN
+            id_marker=ji+1
+            RETURN
+         ELSE
+            id_marker=ji
+            RETURN
+         ENDIF
+      ENDDO
+
+   END SUBROUTINE math__Partition
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine correct phase angles to produce smoother 
+   !> phase plots. 
+   !>
+   !> @details
+   !> This code is based on numpy unwrap function
+   !>
+   !> Unwrap by changing deltas between values to 2*pi complement.
+   !>
+   !> Unwrap radian phase `dd_array` by changing absolute jumps greater than
+   !> `dd_discont` to their 2*pi complement.
+   !>
+   !> @note If the discontinuity in `dd_array` is smaller than ``pi``, 
+   !> but larger than `dd_discont`, no unwrapping is done because taking
+   !> the 2*pi complement would only make the discontinuity larger.
+   !>
+   !> @author J.Paul 
+   !> @date Marsh, 2015 - Rewrite in fortran, with SIREN coding rules 
+   ! 
+   !> @param[inout] dd_array  1D array 
+   !> @param[in] dd_discont maximum discontinuity between values, default pi
+   !-------------------------------------------------------------------
+   PURE SUBROUTINE math_unwrap(dd_array, dd_discont)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:), INTENT(INOUT) :: dd_array
+      REAL(dp)   ,               INTENT(IN   ), OPTIONAL :: dd_discont
+
+      ! local variable
+      INTEGER(i4)                         :: il_size
+
+      REAL(dp)                            :: dl_discont
+
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_diff
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_mod
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_correct
+      REAL(dp), DIMENSION(:), ALLOCATABLE :: dl_tmp
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      dl_discont=dp_pi
+      IF( PRESENT(dd_discont) ) dl_discont=dd_discont
+
+      il_size=SIZE(dd_array)
+      ALLOCATE(dl_diff(il_size-1))
+      DO ji=1,il_size-1
+         dl_diff(ji)=dd_array(ji+1)-dd_array(ji)
+      ENDDO
+
+      ALLOCATE(dl_mod(il_size-1))
+      DO ji=1,il_size-1
+         dl_mod(ji) = MOD(dl_diff(ji) + dp_pi, 2*dp_pi) - dp_pi
+      ENDDO
+
+      WHERE( (dl_mod(:) == -dp_pi) .AND. (dl_diff(:) > 0._dp ) )
+         dl_mod(:)=dp_pi
+      END WHERE
+
+      ALLOCATE(dl_correct(il_size-1))
+      dl_correct(:)=dl_mod(:)-dl_diff(:)
+
+      DEALLOCATE(dl_mod)
+
+      WHERE( ABS(dl_diff(:)) < dl_discont )
+         dl_correct(:)=0._dp
+      END WHERE
+
+      DEALLOCATE(dl_diff)
+      
+      ALLOCATE(dl_tmp(il_size))
+      dl_tmp(:)=dd_array(:)
+
+      DO ji=1,il_size-1
+         dd_array(ji+1)=dl_tmp(ji+1)+SUM(dl_correct(1:ji))
+      ENDDO
+
+      DEALLOCATE(dl_correct)
+      DEALLOCATE(dl_tmp)
+
+   END SUBROUTINE math_unwrap
+   !------------------------------------------------------------------- 
+   !> @brief This function compute simple operation 
+   !>
+   !> @details
+   !> - operation should be write as a string of character.
+   !> - operators allowed are : +,-,*,/ 
+   !> - to ordered operation you should use parentheses
+   !>
+   !> exemples: '1e6/(16/122)', '(3/2)*(2+1)' 
+   !>
+   !> @author J.Paul 
+   !> @date June, 2015 - initial version
+   ! 
+   !> @param[in] cd_var operation to compute (string of character)  
+   !> @return result of the operation, real(dp)
+   !-------------------------------------------------------------------
+   REAL(dp) RECURSIVE FUNCTION math_compute(cd_var) RESULT(dd_res)
+      IMPLICIT NONE
+      ! Argument      
+      CHARACTER(LEN=*), INTENT(IN) :: cd_var
+   
+      ! local variables
+      CHARACTER(LEN=lc) :: cl_var
+      CHARACTER(LEN=lc) :: cl_str1
+      CHARACTER(LEN=lc) :: cl_str2
+   
+      INTEGER(i4)       :: il_ind
+      ! loop indices
+      !----------------------------------------------------------------
+   
+   
+      IF(fct_is_real(cd_var))THEN
+         READ(cd_var,*) dd_res
+      ELSE
+      
+   
+         CALL math__parentheses(cd_var, cl_var)
+         
+         IF(fct_is_real(cl_var))THEN
+            READ(cl_var,*) dd_res
+         ELSE
+            il_ind=SCAN(TRIM(cl_var),'*')
+            IF( il_ind /= 0 )THEN
+               cl_str1=cl_var(1:il_ind-1)
+               cl_str2=cl_var(il_ind+1:)
+               dd_res=math_compute(cl_str1)*math_compute(cl_str2)
+            ELSE
+               il_ind=SCAN(TRIM(cl_var),'/')
+               IF( il_ind /= 0 )THEN
+                  cl_str1=cl_var(1:il_ind-1)
+                  cl_str2=cl_var(il_ind+1:)
+                  dd_res=math_compute(cl_str1)/math_compute(cl_str2)
+               ELSE
+                  il_ind=SCAN(TRIM(cl_var),'+')
+                  IF( il_ind /= 0 )THEN
+                     cl_str1=cl_var(1:il_ind-1)
+                     cl_str2=cl_var(il_ind+1:)
+                     dd_res=math_compute(cl_str1)+math_compute(cl_str2)
+                  ELSE
+                     il_ind=SCAN(TRIM(cl_var),'-')
+                     IF( il_ind /= 0 )THEN
+                        cl_str1=cl_var(1:il_ind-1)
+                        cl_str2=cl_var(il_ind+1:)
+                        dd_res=math_compute(cl_str1)-math_compute(cl_str2)
+                     ELSE
+                        dd_res=dp_fill
+                     ENDIF
+                  ENDIF
+               ENDIF
+            ENDIF
+         ENDIF
+      ENDIF
+   
+   END FUNCTION math_compute
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine replace sub string inside parentheses
+   !> by the value of the operation inside.
+   !>
+   !> @details
+   !> exemple : 
+   !> - '2.6+(3/2)' => '2.6+1.5000'
+   !>
+   !> @author J.Paul 
+   !> @date June, 2015 - initial version
+   ! 
+   !> @param[in] cd_varin  string of character with operation inside
+   !> parentheses 
+   !> @param[out] cd_varout string of character with result of 
+   !> operation inside parentheses
+   !-------------------------------------------------------------------   
+   SUBROUTINE math__parentheses(cd_varin, cd_varout)
+      IMPLICIT NONE
+      ! Argument      
+      CHARACTER(LEN=*) , INTENT(IN)  :: cd_varin
+      CHARACTER(LEN=lc), INTENT(OUT) :: cd_varout
+      ! local variables
+      CHARACTER(LEN=lc)     :: cl_cpt
+      INTEGER(i4)           :: il_ind
+      INTEGER(i4)           :: il_count
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      il_ind=INDEX(cd_varin,'(')
+      IF( il_ind /= 0 )THEN
+         il_count=0
+         DO ji=il_ind+1,LEN(cd_varin)
+            IF( cd_varin(ji:ji) == '(' )THEN
+               il_count=il_count+1
+            ELSEIF( cd_varin(ji:ji) == ')' )THEN
+               IF( il_count == 0 )THEN
+                  WRITE(cl_cpt,*) math_compute(cd_varin(il_ind+1:ji-1))
+                  cd_varout=TRIM(cd_varin(1:il_ind-1))//TRIM(ADJUSTL(cl_cpt))//&
+                     &        TRIM(cd_varin(ji+1:))
+                  EXIT
+               ELSE
+                  il_count=il_count-1
+               ENDIF
+            ENDIF
+         ENDDO
+      ELSE
+         cd_varout=TRIM(cd_varin)
+      ENDIF
+   
+   END SUBROUTINE math__parentheses
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function compute derivative of 1D array.
+   !> 
+   !> @details 
+   !> optionaly you could specify to take into account east west discontinuity
+   !> (-180° 180° or 0° 360° for longitude variable)
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] dd_value     1D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] ld_discont   logical to take into account east west discontinuity 
+   !-------------------------------------------------------------------
+   PURE FUNCTION math_deriv_1D( dd_value, dd_fill, ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:), INTENT(IN) :: dd_value
+      REAL(dp)                 , INTENT(IN) :: dd_fill
+      LOGICAL                  , INTENT(IN), OPTIONAL :: ld_discont
+
+      ! function
+      REAL(dp), DIMENSION(SIZE(dd_value,DIM=1) ) :: math_deriv_1D
+
+      ! local variable
+      INTEGER(i4)                            :: il_imin
+      INTEGER(i4)                            :: il_imax
+      INTEGER(i4), DIMENSION(1)              :: il_shape
+
+      REAL(dp)                               :: dl_min
+      REAL(dp)                               :: dl_max
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_value
+
+      LOGICAL                                :: ll_discont
+
+      ! loop indices
+      INTEGER(i4) :: ji
+
+      INTEGER(i4) :: i1
+      INTEGER(i4) :: i2
+      !----------------------------------------------------------------
+      ! init
+      math_deriv_1D(:)=dd_fill
+
+      ll_discont=.FALSE.
+      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
+
+      il_shape(:)=SHAPE(dd_value(:))
+
+      ALLOCATE( dl_value(3))
+
+      ! compute derivative in i-direction
+      DO ji=1,il_shape(1)
+         
+            il_imin=MAX(ji-1,1)
+            il_imax=MIN(ji+1,il_shape(1))
+
+            IF( il_imin==ji-1 .AND. il_imax==ji+1 )THEN
+               i1=1  ; i2=3
+            ELSEIF( il_imin==ji .AND. il_imax==ji+1 )THEN
+               i1=1  ; i2=2
+            ELSEIF( il_imin==ji-1 .AND. il_imax==ji )THEN
+               i1=2  ; i2=3
+            ENDIF
+
+            dl_value(i1:i2)=dd_value(il_imin:il_imax)
+            IF( il_imin == 1 )THEN
+               dl_value(:)=EOSHIFT( dl_value(:), &
+               &                    DIM=1,         &
+               &                    SHIFT=-1,      &
+               &                    BOUNDARY=dl_value(1) )
+            ENDIF
+            IF( il_imax == il_shape(1) )THEN
+               dl_value(:)=EOSHIFT( dl_value(:), &
+               &                    DIM=1,         &
+               &                    SHIFT=1,       &
+               &                    BOUNDARY=dl_value(3))
+            ENDIF
+
+            IF( ll_discont )THEN
+               dl_min=MINVAL( dl_value(:), dl_value(:)/=dd_fill )
+               dl_max=MAXVAL( dl_value(:), dl_value(:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_value(:) < 0._dp ) 
+                     dl_value(:) = dl_value(:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_value(:) > 180._dp ) 
+                     dl_value(:) = dl_value(:)-180._dp
+                  END WHERE
+               ENDIF
+            ENDIF
+
+         IF( dl_value( 2) /= dd_fill .AND. & ! ji
+         &   dl_value( 3) /= dd_fill .AND. & ! ji+1
+         &   dl_value( 1) /= dd_fill )THEN   ! ji-1
+
+            math_deriv_1D(ji)=&
+            &  ( dl_value(3) - dl_value(1) ) / &
+            &  REAL( il_imax-il_imin ,dp)
+
+         ENDIF
+
+      ENDDO
+
+      DEALLOCATE( dl_value )
+
+   END FUNCTION math_deriv_1D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function compute derivative of 2D array.
+   !> you have to specify in which direction derivative have to be computed:
+   !> first (I) or second (J) dimension. 
+   !>
+   !> @details 
+   !> optionaly you could specify to take into account east west discontinuity
+   !> (-180° 180° or 0° 360° for longitude variable)
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] dd_value     2D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] cd_dim       compute derivative on first (I) or second (J) dimension 
+   !> @param[in] ld_discont   logical to take into account east west discontinuity 
+   !-------------------------------------------------------------------
+   FUNCTION math_deriv_2D( dd_value, dd_fill, cd_dim, ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:,:), INTENT(IN) :: dd_value
+      REAL(dp)                   , INTENT(IN) :: dd_fill
+      CHARACTER(LEN=*)           , INTENT(IN) :: cd_dim
+      LOGICAL                    , INTENT(IN), OPTIONAL :: ld_discont
+
+      ! function
+      REAL(dp), DIMENSION(SIZE(dd_value,DIM=1), &
+      &                   SIZE(dd_value,DIM=2) ) :: math_deriv_2D
+
+      ! local variable
+      INTEGER(i4)                              :: il_imin
+      INTEGER(i4)                              :: il_imax
+      INTEGER(i4)                              :: il_jmin
+      INTEGER(i4)                              :: il_jmax
+      INTEGER(i4), DIMENSION(2)                :: il_shape
+
+      REAL(dp)                                 :: dl_min
+      REAL(dp)                                 :: dl_max
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_value
+
+      LOGICAL                                  :: ll_discont
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+
+      INTEGER(i4) :: i1
+      INTEGER(i4) :: i2
+
+      INTEGER(i4) :: j1
+      INTEGER(i4) :: j2
+      !----------------------------------------------------------------
+      ! init
+      math_deriv_2D(:,:)=dd_fill
+
+      ll_discont=.FALSE.
+      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
+
+      il_shape(:)=SHAPE(dd_value(:,:))
+
+      SELECT CASE(TRIM(fct_upper(cd_dim)))
+
+      CASE('I')
+
+         ALLOCATE( dl_value(3,il_shape(2)) )
+         ! compute derivative in i-direction
+         DO ji=1,il_shape(1)
+
+            ! init
+            dl_value(:,:)=dd_fill
+            
+            il_imin=MAX(ji-1,1)
+            il_imax=MIN(ji+1,il_shape(1))
+
+            IF( il_imin==ji-1 .AND. il_imax==ji+1 )THEN
+               i1=1  ; i2=3
+            ELSEIF( il_imin==ji .AND. il_imax==ji+1 )THEN
+               i1=1  ; i2=2
+            ELSEIF( il_imin==ji-1 .AND. il_imax==ji )THEN
+               i1=2  ; i2=3
+            ENDIF
+
+            dl_value(i1:i2,:)=dd_value(il_imin:il_imax,:)
+            IF( il_imin == 1 )THEN
+               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
+               &                      DIM=1,         &
+               &                      SHIFT=-1,      &
+               &                      BOUNDARY=dl_value(1,:) )
+            ENDIF
+            IF( il_imax == il_shape(1) )THEN
+               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
+               &                      DIM=1,         &
+               &                      SHIFT=1,       &
+               &                      BOUNDARY=dl_value(3,:))
+            ENDIF
+
+            IF( ll_discont )THEN
+               dl_min=MINVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
+               dl_max=MAXVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_value(:,:) < 0_dp ) 
+                     dl_value(:,:) = dl_value(:,:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_value(:,:) > 180 ) 
+                     dl_value(:,:) = dl_value(:,:)-180._dp
+                  END WHERE
+               ENDIF
+            ENDIF
+            
+            WHERE( dl_value(2,:) /= dd_fill .AND. &  ! ji
+            &      dl_value(3,:) /= dd_fill .AND. &  ! ji+1
+            &      dl_value(1,:) /= dd_fill )        ! ji-1
+
+               math_deriv_2D(ji,:)=&
+               &  ( dl_value(3,:) - dl_value(1,:) ) / &
+               &    REAL( il_imax-il_imin,dp)
+
+            END WHERE
+
+         ENDDO
+
+      CASE('J')
+
+         ALLOCATE( dl_value(il_shape(1),3) )
+         ! compute derivative in j-direction
+         DO jj=1,il_shape(2)
+         
+            il_jmin=MAX(jj-1,1)
+            il_jmax=MIN(jj+1,il_shape(2))
+
+            IF( il_jmin==jj-1 .AND. il_jmax==jj+1 )THEN
+               j1=1  ; j2=3
+            ELSEIF( il_jmin==jj .AND. il_jmax==jj+1 )THEN
+               j1=1  ; j2=2
+            ELSEIF( il_jmin==jj-1 .AND. il_jmax==jj )THEN
+               j1=2  ; j2=3
+            ENDIF
+
+            dl_value(:,j1:j2)=dd_value(:,il_jmin:il_jmax)
+            IF( il_jmin == 1 )THEN
+               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
+               &                      DIM=2,         &
+               &                      SHIFT=-1,      &
+               &                      BOUNDARY=dl_value(:,1))
+            ENDIF
+            IF( il_jmax == il_shape(2) )THEN
+               dl_value(:,:)=EOSHIFT( dl_value(:,:), &
+               &                      DIM=2,         &
+               &                      SHIFT=1,       &
+               &                      BOUNDARY=dl_value(:,3))
+            ENDIF
+
+            IF( ll_discont )THEN
+               dl_min=MINVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
+               dl_max=MAXVAL( dl_value(:,:), dl_value(:,:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_value(:,:) < 0_dp ) 
+                     dl_value(:,:) = dl_value(:,:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_value(:,:) > 180 ) 
+                     dl_value(:,:) = dl_value(:,:)-180._dp
+                  END WHERE
+               ENDIF
+            ENDIF
+
+            WHERE( dl_value(:, 2) /= dd_fill .AND. & ! jj
+            &      dl_value(:, 3) /= dd_fill .AND. & ! jj+1
+            &      dl_value(:, 1) /= dd_fill )       ! jj-1
+
+               math_deriv_2D(:,jj)=&
+               &  ( dl_value(:,3) - dl_value(:,1) ) / &
+               &   REAL(il_jmax-il_jmin,dp)         
+
+            END WHERE
+
+         ENDDO
+         
+      END SELECT
+
+      DEALLOCATE( dl_value )
+
+   END FUNCTION math_deriv_2D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function compute derivative of 3D array.
+   !> you have to specify in which direction derivative have to be computed:
+   !> first (I), second (J) or third (K) dimension.
+   !> 
+   !> @details 
+   !> optionaly you could specify to take into account east west discontinuity
+   !> (-180° 180° or 0° 360° for longitude variable)
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] dd_value  3D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] cd_dim       compute derivative on first (I) second (J) or third (K) dimension   
+   !> @param[in] ld_discont   logical to take into account east west discontinuity
+   !-------------------------------------------------------------------
+   PURE FUNCTION math_deriv_3D( dd_value, dd_fill, cd_dim, ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:,:), INTENT(IN) :: dd_value
+      REAL(dp)                          , INTENT(IN) :: dd_fill
+      CHARACTER(LEN=*)                  , INTENT(IN) :: cd_dim
+      LOGICAL                           , INTENT(IN), OPTIONAL :: ld_discont
+
+      ! function
+      REAL(dp), DIMENSION(SIZE(dd_value,DIM=1), &
+      &                   SIZE(dd_value,DIM=2), &
+      &                   SIZE(dd_value,DIM=3)) :: math_deriv_3D
+
+      ! local variable
+      INTEGER(i4)                                :: il_imin
+      INTEGER(i4)                                :: il_imax
+      INTEGER(i4)                                :: il_jmin
+      INTEGER(i4)                                :: il_jmax
+      INTEGER(i4)                                :: il_kmin
+      INTEGER(i4)                                :: il_kmax
+      INTEGER(i4), DIMENSION(3)                  :: il_shape
+
+      REAL(dp)                                   :: dl_min
+      REAL(dp)                                   :: dl_max
+      REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_value
+
+      LOGICAL                                    :: ll_discont
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: jk
+
+      INTEGER(i4) :: i1
+      INTEGER(i4) :: i2
+
+      INTEGER(i4) :: j1
+      INTEGER(i4) :: j2
+      
+      INTEGER(i4) :: k1
+      INTEGER(i4) :: k2      
+      !----------------------------------------------------------------
+      ! init
+      math_deriv_3D(:,:,:)=dd_fill
+
+      ll_discont=.FALSE.
+      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
+
+      il_shape(:)=SHAPE(dd_value(:,:,:))
+
+
+      SELECT CASE(TRIM(fct_upper(cd_dim)))
+
+      CASE('I')
+
+         ALLOCATE( dl_value(3,il_shape(2),il_shape(3)) )
+         ! compute derivative in i-direction
+         DO ji=1,il_shape(1)
+            
+            il_imin=MAX(ji-1,1)
+            il_imax=MIN(ji+1,il_shape(1))
+
+            IF( il_imin==ji-1 .AND. il_imax==ji+1 )THEN
+               i1=1  ; i2=3
+            ELSEIF( il_imin==ji .AND. il_imax==ji+1 )THEN
+               i1=1  ; i2=2
+            ELSEIF( il_imin==ji-1 .AND. il_imax==ji )THEN
+               i1=2  ; i2=3
+            ENDIF
+
+            dl_value(i1:i2,:,:)=dd_value(il_imin:il_imax,:,:)
+            IF( il_imin == 1 )THEN
+               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
+               &                      DIM=1,         &
+               &                      SHIFT=-1,      &
+               &                      BOUNDARY=dl_value(1,:,:) )
+            ENDIF
+            IF( il_imax == il_shape(1) )THEN
+               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
+               &                      DIM=1,         &
+               &                      SHIFT=1,       &
+               &                      BOUNDARY=dl_value(3,:,:))
+            ENDIF
+
+            IF( ll_discont )THEN
+               dl_min=MINVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
+               dl_max=MAXVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_value(:,:,:) < 0_dp ) 
+                     dl_value(:,:,:) = dl_value(:,:,:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_value(:,:,:) > 180 ) 
+                     dl_value(:,:,:) = dl_value(:,:,:)-180._dp
+                  END WHERE
+               ENDIF
+            ENDIF
+
+            WHERE( dl_value(2,:,:) /= dd_fill .AND. & ! ji
+            &      dl_value(3,:,:) /= dd_fill .AND. & !ji+1 
+            &      dl_value(1,:,:) /= dd_fill )       !ji-1
+
+               math_deriv_3D(ji,:,:)= &
+               &  ( dl_value(3,:,:) - dl_value(1,:,:) ) / &
+               &  REAL( il_imax-il_imin ,dp)
+
+            END WHERE
+
+         ENDDO
+
+      CASE('J')
+
+         ALLOCATE( dl_value(il_shape(1),3,il_shape(3)) )
+         ! compute derivative in j-direction
+         DO jj=1,il_shape(2)
+         
+            il_jmin=MAX(jj-1,1)
+            il_jmax=MIN(jj+1,il_shape(2))
+
+            IF( il_jmin==jj-1 .AND. il_jmax==jj+1 )THEN
+               j1=1  ; j2=3
+            ELSEIF( il_jmin==jj .AND. il_jmax==jj+1 )THEN
+               j1=1  ; j2=2
+            ELSEIF( il_jmin==jj-1 .AND. il_jmax==jj )THEN
+               j1=2  ; j2=3
+            ENDIF
+
+            dl_value(:,j1:j2,:)=dd_value(:,il_jmin:il_jmax,:)
+            IF( il_jmin == 1 )THEN
+               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
+               &                      DIM=2,         &
+               &                      SHIFT=-1,      &
+               &                      BOUNDARY=dl_value(:,1,:) )
+            ENDIF
+            IF( il_jmax == il_shape(2) )THEN
+               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
+               &                      DIM=2,         &
+               &                      SHIFT=1,       &
+               &                      BOUNDARY=dl_value(:,3,:))
+            ENDIF
+
+            IF( ll_discont )THEN
+               dl_min=MINVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
+               dl_max=MAXVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_value(:,:,:) < 0_dp ) 
+                     dl_value(:,:,:) = dl_value(:,:,:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_value(:,:,:) > 180 ) 
+                     dl_value(:,:,:) = dl_value(:,:,:)-180._dp
+                  END WHERE
+               ENDIF
+            ENDIF
+
+            WHERE( dl_value(:, 2,:) /= dd_fill .AND. & ! jj
+               &   dl_value(:, 3,:) /= dd_fill .AND. & ! jj+1
+            &      dl_value(:, 1,:) /= dd_fill )       ! jj-1
+
+               math_deriv_3D(:,jj,:)=&
+               &  ( dl_value(:,3,:) - dl_value(:,1,:) ) / &
+               &  REAL( il_jmax - il_jmin ,dp)         
+
+            END WHERE
+
+         ENDDO
+         
+      CASE('K')
+         ! compute derivative in k-direction
+         DO jk=1,il_shape(3)
+
+            il_kmin=MAX(jk-1,1)
+            il_kmax=MIN(jk+1,il_shape(3))
+
+            IF( il_kmin==jk-1 .AND. il_kmax==jk+1 )THEN
+               k1=1  ; k2=3
+            ELSEIF( il_kmin==jk .AND. il_kmax==jk+1 )THEN
+               k1=1  ; k2=2
+            ELSEIF( il_kmin==jk-1 .AND. il_kmax==jk )THEN
+               k1=2  ; k2=3
+            ENDIF
+
+            dl_value(:,:,k1:k2)=dd_value(:,:,il_kmin:il_kmax)
+            IF( il_kmin == 1 )THEN
+               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
+               &                      DIM=3,         &
+               &                      SHIFT=-1,      &
+               &                      BOUNDARY=dl_value(:,:,1) )
+            ENDIF
+            IF( il_kmax == il_shape(3) )THEN
+               dl_value(:,:,:)=EOSHIFT( dl_value(:,:,:), &
+               &                        DIM=3,         &
+               &                        SHIFT=1,       &
+               &                        BOUNDARY=dl_value(:,:,3))
+            ENDIF
+
+            IF( ll_discont )THEN
+               dl_min=MINVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
+               dl_max=MAXVAL( dl_value(:,:,:), dl_value(:,:,:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_value(:,:,:) < 0_dp ) 
+                     dl_value(:,:,:) = dl_value(:,:,:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_value(:,:,:) > 180 ) 
+                     dl_value(:,:,:) = dl_value(:,:,:)-180._dp
+                  END WHERE
+               ENDIF
+            ENDIF         
+
+            WHERE( dl_value(:,:, 2) /= dd_fill .AND. & ! jk
+               &   dl_value(:,:, 3) /= dd_fill .AND. & ! jk+1
+               &   dl_value(:,:, 1) /= dd_fill )       ! jk-1
+
+               math_deriv_3D(:,:,jk)=&
+               &  ( dl_value(:,:,3) - dl_value(:,:,1) ) / &
+               &  REAL( il_kmax-il_kmin,dp)         
+
+            END WHERE
+
+         ENDDO
+
+      END SELECT
+
+      DEALLOCATE( dl_value )
+
+   END FUNCTION math_deriv_3D
+END MODULE math
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/merge_bathy.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/merge_bathy.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/merge_bathy.f90	(revision 9987)
@@ -28,4 +28,7 @@
 !> @endcode
 !>    
+!> @note 
+!>    you could find a template of the namelist in templates directory.
+!>
 !>    merge_bathy.nam comprise 8 namelists:
 !>       - logger namelist (namlog)
@@ -45,5 +48,5 @@
 !>       - cn_logfile   : logger filename
 !>       - cn_verbosity : verbosity ('trace','debug','info',
-!>  'warning','error','fatal')
+!>  'warning','error','fatal','none')
 !>       - in_maxerror  : maximum number of error allowed
 !>
@@ -62,10 +65,10 @@
 !>    * _variable namelist (namvar)_:
 !>       - cn_varinfo : list of variable and extra information about request(s) 
-!>       to be used.<br/>
+!>       to be used (separated by ',').<br/>
 !>          each elements of *cn_varinfo* is a string character.<br/>
 !>          it is composed of the variable name follow by ':', 
 !>          then request(s) to be used on this variable.<br/> 
 !>          request could be:
-!>             - interpolation method
+!>             - int = interpolation method
 !> 
 !>                requests must be separated by ';'.<br/>
@@ -74,5 +77,5 @@
 !>          informations about available method could be find in 
 !>          @ref interp modules.<br/>
-!>          Example: 'bathymetry: cubic'
+!>          Example: 'bathymetry: int=cubic'
 !>          @note 
 !>             If you do not specify a method which is required, 
@@ -95,9 +98,9 @@
 !>          segments are separated by '|'.<br/>
 !>          each segments of the boundary is composed of:
-!>             - orthogonal indice (.ie. for north boundary,
-!>             J-indice where boundary are). 
-!>             - first indice of boundary (I-indice for north boundary) 
-!>             - last  indice of boundary (I-indice for north boundary)<br/>
-!>                indices must be separated by ',' .<br/>
+!>             - indice of velocity (orthogonal to boundary .ie. 
+!>                for north boundary, J-indice). 
+!>             - indice of segment start (I-indice for north boundary) 
+!>             - indice of segment end   (I-indice for north boundary)<br/>
+!>                indices must be separated by ':' .<br/>
 !>             - optionally, boundary size could be added between '(' and ')' 
 !>             in the first segment defined.
@@ -106,6 +109,7 @@
 !>
 !>          Examples:
-!>             - cn_north='index1,first1,last1(width)'
-!>             - cn_north='index1(width),first1,last1|index2,first2,last2'
+!>             - cn_north='index1,first1:last1(width)'
+!>             - cn_north='index1(width),first1:last1|index2,first2:last2'
+!>
 !>       - cn_south : south boundary indices on fine grid<br/>
 !>       - cn_east  : east  boundary indices on fine grid<br/>
@@ -121,4 +125,7 @@
 !> @date Sepember, 2014 
 !> - add header for user
+!> @date July, 2015 
+!> - extrapolate all land points
+!> - add attributes with boundary string character (as in namelist)
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -153,4 +160,5 @@
    CHARACTER(LEN=lc)                                  :: cl_namelist
    CHARACTER(LEN=lc)                                  :: cl_date
+   CHARACTER(LEN=lc)                                  :: cl_tmp
 
    INTEGER(i4)                                        :: il_narg
@@ -162,4 +170,5 @@
    INTEGER(i4)                                        :: il_jmin0
    INTEGER(i4)                                        :: il_jmax0
+   INTEGER(i4)                                        :: il_shift
    INTEGER(i4)      , DIMENSION(ip_maxdim)            :: il_rho
    INTEGER(i4)      , DIMENSION(2,2)                  :: il_ind
@@ -231,5 +240,6 @@
    NAMELIST /namlog/ &  !< logger namelist
    &  cn_logfile,    &  !< log file
-   &  cn_verbosity      !< log verbosity
+   &  cn_verbosity,  &  !< log verbosity
+   &  in_maxerror       !< logger maximum error
 
    NAMELIST /namcfg/ &  !< config namelist
@@ -298,5 +308,5 @@
       READ( il_fileid, NML = namlog )
       ! define log file
-      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity), in_maxerror)
+      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity),in_maxerror)
       CALL logger_header()
 
@@ -510,4 +520,78 @@
    ENDIF
 
+
+   IF( tl_bdy(jp_north)%l_use )THEN
+      ! add shift on north boundary
+      ! boundary compute on T point but express on U or V point
+      il_shift=1
+
+      cl_tmp=TRIM(fct_str(tl_bdy(jp_north)%t_seg(1)%i_index-il_shift))//','//&
+         &   TRIM(fct_str(tl_bdy(jp_north)%t_seg(1)%i_first))//':'//&
+         &   TRIM(fct_str(tl_bdy(jp_north)%t_seg(1)%i_last))//&
+         &   '('//TRIM(fct_str(tl_bdy(jp_north)%t_seg(1)%i_width))//')'
+      DO ji=2,tl_bdy(jp_north)%i_nseg
+         cl_tmp=TRIM(cl_tmp)//'|'//&
+            &   TRIM(fct_str(tl_bdy(jp_north)%t_seg(ji)%i_index-il_shift))//','//&
+            &   TRIM(fct_str(tl_bdy(jp_north)%t_seg(ji)%i_first))//':'//&
+            &   TRIM(fct_str(tl_bdy(jp_north)%t_seg(ji)%i_last))
+      ENDDO
+      tl_att=att_init("bdy_north",TRIM(cl_tmp))
+      CALL file_add_att(tl_fileout, tl_att)
+   ENDIF
+
+   IF( tl_bdy(jp_south)%l_use )THEN
+      
+      cl_tmp=TRIM(fct_str(tl_bdy(jp_south)%t_seg(1)%i_index))//','//&
+         &   TRIM(fct_str(tl_bdy(jp_south)%t_seg(1)%i_first))//':'//&
+         &   TRIM(fct_str(tl_bdy(jp_south)%t_seg(1)%i_last))//&
+         &   '('//TRIM(fct_str(tl_bdy(jp_south)%t_seg(1)%i_width))//')'
+      DO ji=2,tl_bdy(jp_south)%i_nseg
+         cl_tmp=TRIM(cl_tmp)//'|'//&
+            &   TRIM(fct_str(tl_bdy(jp_south)%t_seg(ji)%i_index))//','//&
+            &   TRIM(fct_str(tl_bdy(jp_south)%t_seg(ji)%i_first))//':'//&
+            &   TRIM(fct_str(tl_bdy(jp_south)%t_seg(ji)%i_last))
+      ENDDO
+
+      tl_att=att_init("bdy_south",TRIM(cl_tmp))
+      CALL file_add_att(tl_fileout, tl_att)
+   ENDIF
+
+   IF( tl_bdy(jp_east)%l_use )THEN
+      ! add shift on east boundary
+      ! boundary compute on T point but express on U or V point
+      il_shift=1
+
+      cl_tmp=TRIM(fct_str(tl_bdy(jp_east)%t_seg(1)%i_index-il_shift))//','//&
+         &   TRIM(fct_str(tl_bdy(jp_east)%t_seg(1)%i_first))//':'//&
+         &   TRIM(fct_str(tl_bdy(jp_east)%t_seg(1)%i_last))//&
+         &   '('//TRIM(fct_str(tl_bdy(jp_east)%t_seg(1)%i_width))//')'
+      DO ji=2,tl_bdy(jp_east)%i_nseg
+         cl_tmp=TRIM(cl_tmp)//'|'//&
+            &   TRIM(fct_str(tl_bdy(jp_east)%t_seg(ji)%i_index-il_shift))//','//&
+            &   TRIM(fct_str(tl_bdy(jp_east)%t_seg(ji)%i_first))//':'//&
+            &   TRIM(fct_str(tl_bdy(jp_east)%t_seg(ji)%i_last))
+      ENDDO
+
+      tl_att=att_init("bdy_east",TRIM(cl_tmp))
+      CALL file_add_att(tl_fileout, tl_att)
+   ENDIF
+
+   IF( tl_bdy(jp_west)%l_use )THEN
+
+      cl_tmp=TRIM(fct_str(tl_bdy(jp_west)%t_seg(1)%i_index))//','//&
+         &   TRIM(fct_str(tl_bdy(jp_west)%t_seg(1)%i_first))//':'//&
+         &   TRIM(fct_str(tl_bdy(jp_west)%t_seg(1)%i_last))//&
+         &   '('//TRIM(fct_str(tl_bdy(jp_west)%t_seg(1)%i_width))//')'
+      DO ji=2,tl_bdy(jp_west)%i_nseg
+         cl_tmp=TRIM(cl_tmp)//'|'//&
+            &   TRIM(fct_str(tl_bdy(jp_west)%t_seg(ji)%i_index))//','//&
+            &   TRIM(fct_str(tl_bdy(jp_west)%t_seg(ji)%i_first))//':'//&
+            &   TRIM(fct_str(tl_bdy(jp_west)%t_seg(ji)%i_last))
+      ENDDO
+
+      tl_att=att_init("bdy_west",TRIM(cl_tmp))
+      CALL file_add_att(tl_fileout, tl_att)
+   ENDIF
+
    ! create file
    CALL iom_create(tl_fileout)
@@ -525,4 +609,5 @@
    CALL mpp_clean(tl_bathy0)
    DEALLOCATE(dl_weight)
+   CALL boundary_clean(tl_bdy(:))
 
    ! close log file
@@ -908,7 +993,5 @@
 
       ! extrapolate variable
-      CALL extrap_fill_value( td_var, id_offset=id_offset(:,:), &
-      &                               id_rho=id_rho(:),         &
-      &                               id_iext=il_iext, id_jext=il_jext )
+      CALL extrap_fill_value( td_var )
 
       ! interpolate Bathymetry
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/mpp.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/mpp.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/mpp.f90	(revision 9987)
@@ -165,13 +165,11 @@
 !>    to get processors to be used:<br/>
 !> @code
-!>    CALL mpp_get_use( td_mpp, id_imin, id_imax, id_idim, & 
-!>    &                         id_jmin, id_jmax, id_jdim )
+!>    CALL mpp_get_use( td_mpp, id_imin, id_imax, & 
+!>    &                         id_jmin, id_jmax )
 !> @endcode
 !>       - id_imin 
 !>       - id_imax 
-!>       - id_idim 
 !>       - id_jmin 
 !>       - id_jmax 
-!>       - id_jdim 
 !>
 !>    to get sub domains which form global domain contour:<br/>
@@ -352,5 +350,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
    !>    - use function instead of overload assignment operator 
@@ -379,4 +377,5 @@
       ! copy mpp variable
       mpp__copy_unit%c_name     = TRIM(td_mpp%c_name)
+      mpp__copy_unit%i_id       = td_mpp%i_id
       mpp__copy_unit%i_niproc   = td_mpp%i_niproc
       mpp__copy_unit%i_njproc   = td_mpp%i_njproc
@@ -425,5 +424,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
    !>    - use function instead of overload assignment operator 
@@ -454,5 +453,5 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_mpp mpp structure
@@ -495,5 +494,5 @@
       ! print dimension
       IF(  td_mpp%i_ndim /= 0 )THEN
-         WRITE(*,'(/a)') " File dimension"
+         WRITE(*,'(/a)') " MPP dimension"
          DO ji=1,ip_maxdim
             IF( td_mpp%t_dim(ji)%l_use )THEN
@@ -698,5 +697,5 @@
       CALL dim_clean(tl_dim)
 
-      IF( (       PRESENT(id_niproc)  .AND. (.NOT. PRESENT(id_niproc))) .OR. &
+      IF( (       PRESENT(id_niproc)  .AND. (.NOT. PRESENT(id_njproc))) .OR. &
           ((.NOT. PRESENT(id_niproc)) .AND.        PRESENT(id_njproc) ) )THEN
           CALL logger_warn( "MPP INIT: number of processors following I and J "//&
@@ -912,5 +911,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file strcuture
@@ -1028,29 +1027,29 @@
             ! create some attributes for domain decomposition (use with dimg file)
             tl_att=att_init( "DOMAIN_number_total", mpp__init_file%i_nproc )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_I_position_first", mpp__init_file%t_proc(:)%i_impp )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_J_position_first", mpp__init_file%t_proc(:)%i_jmpp )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_I_position_last", mpp__init_file%t_proc(:)%i_lci )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_J_position_last", mpp__init_file%t_proc(:)%i_lcj )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_I_halo_size_start", mpp__init_file%t_proc(:)%i_ldi )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_J_halo_size_start", mpp__init_file%t_proc(:)%i_ldj )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_I_halo_size_end", mpp__init_file%t_proc(:)%i_lei )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
 
             tl_att=att_init( "DOMAIN_J_halo_size_end", mpp__init_file%t_proc(:)%i_lej )
-            CALL mpp_add_att(mpp__init_file, tl_att)
+            CALL mpp_move_att(mpp__init_file, tl_att)
             
             ! clean
@@ -1122,5 +1121,4 @@
       CALL file_clean(tl_file)
 
-      CALL logger_debug("MPP INIT READ: fin init_read ")
    END FUNCTION mpp__init_file
    !-------------------------------------------------------------------
@@ -1131,5 +1129,6 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 - add only use dimension in MPP structure
    !>
    !> @param[in] td_file   file strcuture
@@ -1163,6 +1162,6 @@
          IF( td_file%i_id == 0 )THEN
             CALL logger_info(" id "//TRIM(fct_str(td_file%i_id))) 
-            CALL logger_error("MPP INIT READ: netcdf file "//TRIM(td_file%c_name)//&
-            &  " not opened")
+            CALL logger_error("MPP INIT READ: netcdf file "//&
+               &  TRIM(td_file%c_name)//" not opened")
          ELSE
 
@@ -1191,9 +1190,14 @@
                CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
             ENDIF
-            tl_dim=dim_init( td_file%t_dim(3)%c_name, td_file%t_dim(3)%i_len)
-            CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
-
-            tl_dim=dim_init( td_file%t_dim(4)%c_name, td_file%t_dim(4)%i_len)
-            CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+
+            IF( td_file%t_dim(3)%l_use )THEN
+               tl_dim=dim_init( td_file%t_dim(3)%c_name, td_file%t_dim(3)%i_len)
+               CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+            ENDIF
+
+            IF( td_file%t_dim(4)%l_use )THEN
+               tl_dim=dim_init( td_file%t_dim(4)%c_name, td_file%t_dim(4)%i_len)
+               CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+            ENDIF
 
             ! initialise file/processor
@@ -1312,5 +1316,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   file strcuture
@@ -1532,5 +1536,5 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
@@ -1624,8 +1628,4 @@
             IF( il_varid /= 0 )THEN
 
-               CALL logger_error( " MPP ADD VAR: variable "//TRIM(td_var%c_name)//&
-               &  ", standard name "//TRIM(td_var%c_stdname)//&
-               &  ", already in mpp "//TRIM(td_mpp%c_name) )
-
                DO ji=1,td_mpp%t_proc(1)%i_nvar
                   CALL logger_debug( " MPP ADD VAR: in mpp structure : &
@@ -1634,4 +1634,7 @@
                   &  TRIM(td_mpp%t_proc(1)%t_var(ji)%c_stdname) )
                ENDDO
+               CALL logger_error( " MPP ADD VAR: variable "//TRIM(td_var%c_name)//&
+               &  ", standard name "//TRIM(td_var%c_stdname)//&
+               &  ", already in mpp "//TRIM(td_mpp%c_name) )
 
             ELSE
@@ -1675,5 +1678,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_mpp    mpp structure
@@ -1840,4 +1843,6 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial version
+   !> @date February, 2015 
+   !> - define local variable structure to avoid mistake with pointer
    !
    !> @param[inout] td_mpp    mpp strcuture
@@ -1852,4 +1857,5 @@
       ! local variable
       INTEGER(i4)       :: il_varid
+      TYPE(TVAR)        :: tl_var
       !----------------------------------------------------------------
       ! check if mpp exist
@@ -1882,5 +1888,6 @@
             ELSE
 
-               CALL mpp_del_var(td_mpp, td_mpp%t_proc(1)%t_var(il_varid)) 
+               tl_var=var_copy(td_mpp%t_proc(1)%t_var(il_varid))
+               CALL mpp_del_var(td_mpp, tl_var)
 
             ENDIF
@@ -2193,5 +2200,7 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - rewrite the same as way var_add_dim
    !>
    !> @param[inout] td_mpp mpp structure
@@ -2208,51 +2217,33 @@
 
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
       IF( td_mpp%i_ndim <= ip_maxdim )THEN
 
-         ! check if dimension already in mpp structure
-         il_ind=dim_get_index(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
-         IF( il_ind /= 0 )THEN
-
-            IF( td_mpp%t_dim(il_ind)%l_use )THEN
-               CALL logger_error( &
-               &  "MPP ADD DIM: dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", already used in mpp "//TRIM(td_mpp%c_name) )
-            ELSE
-               ! replace dimension
-               td_mpp%t_dim(il_ind)=dim_copy(td_dim)
-               td_mpp%t_dim(il_ind)%i_id=il_ind
-               td_mpp%t_dim(il_ind)%l_use=.TRUE.
-            ENDIF
-
+         ! check if dimension already used in mpp structure
+         il_ind=SCAN(TRIM(cp_dimorder),TRIM(td_dim%c_sname))
+         IF( il_ind == 0 )THEN
+            CALL logger_warn( &
+            &  " MPP ADD DIM: dimension "//TRIM(td_dim%c_name)//&
+            &  ", short name "//TRIM(td_dim%c_sname)//&
+            &  ", will not be added in mpp "//TRIM(td_mpp%c_name) )
+         ELSEIF( td_mpp%t_dim(il_ind)%l_use )THEN
+            CALL logger_error( &
+            &  " MPP ADD DIM: dimension "//TRIM(td_dim%c_name)//&
+            &  ", short name "//TRIM(td_dim%c_sname)//&
+            &  ", already used in mpp "//TRIM(td_mpp%c_name) )
          ELSE
 
-            IF( td_mpp%i_ndim == ip_maxdim )THEN
-               CALL logger_error( &
-               &  "MPP ADD DIM: can not add dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", in mpp "//TRIM(td_mpp%c_name)//". Already "//&
-               &  TRIM(fct_str(ip_maxdim))//" dimensions." )
-            ELSE
-               ! search empty dimension
-               DO ji=1,ip_maxdim
-                  IF( td_mpp%t_dim(ji)%i_id == 0 )THEN
-                     il_ind=ji 
-                     EXIT
-                  ENDIF
-               ENDDO
- 
-               ! add new dimension    
-               td_mpp%t_dim(il_ind)=dim_copy(td_dim)
-               ! update number of attribute
-               td_mpp%i_ndim=COUNT(td_mpp%t_dim(:)%l_use)
-
-               td_mpp%t_dim(il_ind)%l_use=.TRUE.
-               td_mpp%t_dim(il_ind)%i_id=td_mpp%i_ndim
-            ENDIF
+            ! back to disorder dimension array 
+            CALL dim_disorder(td_mpp%t_dim(:))
+
+            ! add new dimension
+            td_mpp%t_dim(td_mpp%i_ndim+1)=dim_copy(td_dim)
+
+            ! update number of attribute
+            td_mpp%i_ndim=COUNT(td_mpp%t_dim(:)%l_use)
 
          ENDIF
+         ! reorder dimension to ('x','y','z','t')
+         CALL dim_reorder(td_mpp%t_dim(:))
 
       ELSE
@@ -2268,5 +2259,7 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - rewrite the same as way var_del_dim
    !>
    !> @param[inout] td_mpp mpp structure
@@ -2280,55 +2273,34 @@
 
       ! local variable
-      INTEGER(i4) :: il_status
       INTEGER(i4) :: il_ind
-      TYPE(TDIM), DIMENSION(:), ALLOCATABLE  :: tl_dim
+      TYPE(TDIM)  :: tl_dim
 
       ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-      ! check if dimension already in mpp structure
-      il_ind=dim_get_index(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
-      IF( il_ind == 0 )THEN
-
-         CALL logger_error( &
-         &  "MPP DEL DIM: no dimension "//TRIM(td_dim%c_name)//&
+      !----------------------------------------------------------------
+
+
+      IF( td_mpp%i_ndim <= ip_maxdim )THEN
+
+         CALL logger_trace( &
+         &  " MPP DEL DIM: delete dimension "//TRIM(td_dim%c_name)//&
          &  ", short name "//TRIM(td_dim%c_sname)//&
          &  ", in mpp "//TRIM(td_mpp%c_name) )
+         
+         ! check if dimension already in variable structure
+         il_ind=SCAN(TRIM(cp_dimorder),TRIM(td_dim%c_sname))
+
+         ! replace dimension by empty one
+         td_mpp%t_dim(il_ind)=dim_copy(tl_dim)
+
+         ! update number of dimension
+         td_mpp%i_ndim=COUNT(td_mpp%t_dim(:)%l_use)
+
+         ! reorder dimension to ('x','y','z','t')
+         CALL dim_reorder(td_mpp%t_dim)
 
       ELSE
-
-         ALLOCATE( tl_dim(td_mpp%i_ndim-1), stat=il_status )
-         IF(il_status /= 0 )THEN
-
-            CALL logger_error( &
-            &  "MPP DEL DIM: not enough space to put dimensions from "//&
-            &  TRIM(td_mpp%c_name)//" in temporary dimension structure")
-
-         ELSE
-
-            ! save temporary dimension's mpp structure
-            tl_dim( 1 : il_ind-1 ) = dim_copy(td_mpp%t_dim( 1 : il_ind-1 ))
-            tl_dim( il_ind : td_mpp%i_ndim-1 ) = &
-            &           dim_copy(td_mpp%t_dim( il_ind+1 : td_mpp%i_ndim ))
-
-            ! remove dimension from file
-            CALL dim_clean(td_mpp%t_dim(:))
-            ! copy dimension in file, except one
-            td_mpp%t_dim(1:td_mpp%i_ndim)=dim_copy(tl_dim(:))
-
-            ! update number of dimension
-            td_mpp%i_ndim=td_mpp%i_ndim-1
-
-            ! update dimension id
-            DO ji=1,td_mpp%i_ndim
-               td_mpp%t_dim(ji)%i_id=ji
-            ENDDO
-
-            ! clean
-            CALL dim_clean(tl_dim(:))
-            DEALLOCATE(tl_dim)
-
-         ENDIF
-
+         CALL logger_error( &
+         &  " MPP DEL DIM: too much dimension in mpp "//&
+         &  TRIM(td_mpp%c_name)//" ("//TRIM(fct_str(td_mpp%i_ndim))//")")
       ENDIF
 
@@ -2340,5 +2312,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_mpp mpp structure
@@ -2488,8 +2460,8 @@
             &  ", in mpp structure "//TRIM(td_mpp%c_name) )
 
-            IF( ASSOCIATED(td_mpp%t_proc(1)%t_var) )THEN
+            IF( ASSOCIATED(td_mpp%t_proc(1)%t_att) )THEN
                DO ji=1,td_mpp%t_proc(1)%i_natt
                   CALL logger_debug( "MPP DEL ATT: in mpp structure : &
-                  &  attribute : "//TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name) )
+                  &  attribute : "//TRIM(td_mpp%t_proc(1)%t_att(ji)%c_name) )
                ENDDO
             ENDIF
@@ -2516,4 +2488,6 @@
    !> @author J.Paul
    !> @date November, 2013 - Initial version
+   !> @date February, 2015 
+   !> - define local attribute structure to avoid mistake with pointer
    !
    !> @param[inout] td_mpp    mpp strcuture
@@ -2527,5 +2501,6 @@
 
       ! local variable
-      INTEGER(i4)       :: il_attid
+      INTEGER(i4) :: il_attid
+      TYPE(TATT)  :: tl_att
       !----------------------------------------------------------------
       ! check if mpp exist
@@ -2551,5 +2526,5 @@
             IF( il_attid == 0 )THEN
 
-               CALL logger_warn( &
+               CALL logger_debug( &
                &  "MPP DEL ATT : there is no attribute with "//&
                &  "name "//TRIM(cd_name)//" in mpp structure "//&
@@ -2558,5 +2533,6 @@
             ELSE
 
-               CALL mpp_del_att(td_mpp, td_mpp%t_proc(1)%t_att(il_attid)) 
+               tl_att=att_copy(td_mpp%t_proc(1)%t_att(il_attid))
+               CALL mpp_del_att(td_mpp, tl_att) 
 
             ENDIF
@@ -2863,8 +2839,13 @@
 
             CALL logger_info("MPP OPTIMIZ: number of processor "//&
-            &  TRIM(fct_str(tl_mpp%i_nproc)) )
+            &   TRIM(fct_str(ji))//"x"//TRIM(fct_str(jj))//"="//&
+            &   TRIM(fct_str(tl_mpp%i_nproc)) )
             IF( tl_mpp%i_nproc > td_mpp%i_nproc .AND. &
             &   tl_mpp%i_nproc <= il_maxproc )THEN
                ! save optimiz decomposition 
+
+               CALL logger_info("MPP OPTIMIZ:save this decomposition "//&
+               &   TRIM(fct_str(ji))//"x"//TRIM(fct_str(jj))//"="//&
+               &   TRIM(fct_str(tl_mpp%i_nproc)) )
 
                ! clean mpp
@@ -3146,5 +3127,5 @@
    !>
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !>
    !> @param[inout] td_mpp mpp strcuture
@@ -3184,5 +3165,5 @@
    !>
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !>
    !> @param[in] td_mpp    mpp strcuture
@@ -3249,5 +3230,5 @@
    !
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !
    !> @param[in] td_mpp    mpp strcuture
@@ -3311,5 +3292,5 @@
    !>
    !> @author J.Paul
-   !> @date November, 2013
+   !> @date November, 2013 - Initial version
    !>
    !> @param[inout] td_mpp mpp strcuture
@@ -3404,5 +3385,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[in] td_mpp mpp structure
@@ -3417,5 +3398,4 @@
 
       ! local variable
-      INTEGER(i4) :: il_ndim
 
       ! loop indices
@@ -3429,14 +3409,8 @@
          mpp__check_var_dim=.FALSE.
 
-         CALL logger_error( &
-         &  "MPP CHECK DIM: variable and mpp dimension differ"//&
-         &  " for variable "//TRIM(td_var%c_name)//&
-         &  " and mpp "//TRIM(td_mpp%c_name))
-
          CALL logger_debug( &
          &  " mpp dimension: "//TRIM(fct_str(td_mpp%i_ndim))//&
          &  " variable dimension: "//TRIM(fct_str(td_var%i_ndim)) )
-         il_ndim=MIN(td_var%i_ndim, td_mpp%i_ndim )
-         DO ji = 1, il_ndim
+         DO ji = 1, ip_maxdim
             CALL logger_debug( &
             &  "MPP CHECK DIM: for dimension "//&
@@ -3448,4 +3422,10 @@
             &  ", variable used "//TRIM(fct_str(td_var%t_dim(ji)%l_use)))
          ENDDO
+
+         CALL logger_error( &
+         &  "MPP CHECK DIM: variable and mpp dimension differ"//&
+         &  " for variable "//TRIM(td_var%c_name)//&
+         &  " and mpp "//TRIM(td_mpp%c_name))
+
       ENDIF
 
@@ -3456,5 +3436,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_file   array of file structure
@@ -3496,5 +3476,5 @@
    !
    !> @author J.Paul
-   !> - Ocotber, 2014- Initial Version
+   !> @date Ocotber, 2014 - Initial Version
    !
    !> @param[in] td_mpp   mpp file structure
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/multi.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/multi.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/multi.f90	(revision 9987)
@@ -61,5 +61,6 @@
 !> @date October, 2014
 !> - use mpp file structure instead of file
-!> @date November, 2014 - Fix memory leaks bug
+!> @date November, 2014 
+!> - Fix memory leaks bug
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -118,5 +119,5 @@
    !>   
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
    !>    - use function instead of overload assignment operator (to avoid memory leak)
@@ -169,5 +170,7 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - check if variable to be read is in file
    !>
    !> @param[in] cd_varfile   variable location information (from namelist) 
@@ -190,4 +193,5 @@
 
       INTEGER(i4)       :: il_nvar
+      INTEGER(i4)       :: il_varid
 
       LOGICAL           :: ll_dim
@@ -242,4 +246,12 @@
                   ! define variable
                   IF( TRIM(fct_lower(cl_lower)) /= 'all' )THEN
+
+                     ! check if variable is in file
+                     il_varid=var_get_index(tl_mpp%t_proc(1)%t_var(:),cl_lower)
+                     IF( il_varid == 0 )THEN
+                        CALL logger_fatal("MULTI INIT: variable "//&
+                           & TRIM(cl_name)//" not in file "//&
+                           & TRIM(cl_file) )
+                     ENDIF
 
                      ! clean var
@@ -317,5 +329,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_multi  multi file structure
@@ -348,5 +360,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_multi multi file structure
@@ -391,5 +403,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date October, 2014
    !> - use mpp file structure instead of file
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/phycst.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/phycst.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/phycst.f90	(revision 9987)
@@ -25,4 +25,5 @@
    PUBLIC :: dp_rearth  !< earth radius (km)
    PUBLIC :: dp_deg2rad !< degree to radian ratio 
+   PUBLIC :: dp_rad2deg !< radian to degree ratio 
    PUBLIC :: dp_delta   !<  
 
@@ -31,6 +32,7 @@
    REAL(dp), PARAMETER :: dp_rearth = 6871._dp
    REAL(dp), PARAMETER :: dp_deg2rad = dp_pi/180.0
+   REAL(dp), PARAMETER :: dp_rad2deg = 180.0/dp_pi
 
-   REAL(dp), PARAMETER :: dp_delta=1.e-2
+   REAL(dp), PARAMETER :: dp_delta=1.e-6
 END MODULE phycst
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/variable.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/variable.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/variable.f90	(revision 9987)
@@ -281,4 +281,8 @@
 !> @date November, 2014 
 !> - Fix memory leaks bug
+!> @date June, 2015
+!> - change way to get variable information in namelist
+!> @date July, 2015 
+!> - add subroutine var_chg_unit to change unit of output variable
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -293,4 +297,5 @@
    USE att                             ! attribute manager
    USE dim                             ! dimension manager
+   USE math                            ! mathematical function
    IMPLICIT NONE
    ! NOTE_avoid_public_variables_if_possible
@@ -318,4 +323,5 @@
    PUBLIC :: var_concat        !< concatenate two variables
    PUBLIC :: var_limit_value   !< forced min and max value
+   PUBLIC :: var_chg_unit      !< change variable unit and value
    PUBLIC :: var_max_dim       !< get array of maximum dimension use
    PUBLIC :: var_reorder       !< reorder table of value in variable structure
@@ -382,4 +388,6 @@
    PRIVATE :: var__get_max       ! get maximum value from namelist 
    PRIVATE :: var__get_min       ! get minimum value from namelist
+   PRIVATE :: var__get_unf       ! get scale factor value from namelist
+   PRIVATE :: var__get_unt       ! get unit from namelist
    PRIVATE :: var__get_interp    ! get interpolation method from namelist
    PRIVATE :: var__get_extrap    ! get extrapolation method from namelist
@@ -401,5 +409,5 @@
       TYPE(TATT), DIMENSION(:), POINTER :: t_att => NULL() !< variable attributes
       TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim           !< variable dimension
-      
+ 
       LOGICAL           :: l_file = .FALSE.  !< variable read in a file
 
@@ -414,5 +422,8 @@
       REAL(dp)          :: d_min = dp_fill      !< minimum value 
       REAL(dp)          :: d_max = dp_fill      !< maximum value 
-      
+ 
+      CHARACTER(LEN=lc) :: c_unt = ''           !< new variables units (linked to units factor)
+      REAL(dp)          :: d_unf = 1._dp        !< units factor
+
       !!! netcdf4
       LOGICAL           :: l_contiguous = .FALSE. !< use contiguous storage or not
@@ -518,5 +529,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
    !> - use function instead of overload assignment operator (to avoid memory leak)
@@ -548,4 +559,7 @@
       var__copy_unit%d_min      = td_var%d_min
       var__copy_unit%d_max      = td_var%d_max
+
+      var__copy_unit%c_unt      = TRIM(td_var%c_unt)
+      var__copy_unit%d_unf      = td_var%d_unf
 
       var__copy_unit%i_type     = td_var%i_type
@@ -577,4 +591,5 @@
       var__copy_unit%c_units    = TRIM(td_var%c_units)
       var__copy_unit%c_axis     = TRIM(td_var%c_axis)
+      var__copy_unit%d_unf      = td_var%d_unf
       var__copy_unit%d_scf      = td_var%d_scf
       var__copy_unit%d_ofs      = td_var%d_ofs
@@ -627,5 +642,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !> @date November, 2014
    !> - use function instead of overload assignment operator 
@@ -656,5 +671,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable strucutre
@@ -695,5 +710,5 @@
    !
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[inout] td_var array of variable strucutre
@@ -718,5 +733,5 @@
    !
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[inout] td_var array of variable strucutre
@@ -744,5 +759,5 @@
    !
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[inout] td_var array of variable strucutre
@@ -788,4 +803,5 @@
    !>   - id_id : variable id (read from a file).
    !>   - id_ew : number of point composing east west wrap band.
+   !>   - dd_unf : real(8) value for units factor attribute.
    !>   - dd_scf : real(8) value for scale factor attribute.
    !>   - dd_ofs : real(8) value for add offset attribute.
@@ -801,4 +817,6 @@
    !>   - cd_extrap  : a array of character defining extrapolation method.
    !>   - cd_filter  : a array of character defining filtering method.
+   !>   - cd_unt : a string character to define output unit
+   !>   - dd_unf : real(8) factor applied to change unit
    !>
    !>  @note most of these optionals arguments will be inform automatically,
@@ -806,5 +824,9 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - Bug fix: conversion of the FillValue type (float case)
+   !> @date June, 2015 
+   !> - add unit factor (to change unit)
    !>
    !> @param[in] cd_name         variable name
@@ -833,4 +855,6 @@
    !> @param[in] cd_extrap       extrapolation method
    !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -843,5 +867,6 @@
    &                              ld_contiguous, ld_shuffle,&
    &                              ld_fletcher32, id_deflvl, id_chunksz, &
-   &                              cd_interp, cd_extrap, cd_filter )
+   &                              cd_interp, cd_extrap, cd_filter, &
+   &                              cd_unt, dd_unf )
       IMPLICIT NONE
       ! Argument
@@ -871,4 +896,6 @@
       CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
       CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
 
@@ -933,7 +960,7 @@
                tl_att=att_init('_FillValue', INT(dd_fill,i4) )
             CASE(NF90_FLOAT)
-               tl_att=att_init('_FillValue', INT(dd_fill,sp) )
+               tl_att=att_init('_FillValue', REAL(dd_fill,sp) )
             CASE DEFAULT ! NF90_DOUBLE
-                     tl_att=att_init('_FillValue', dd_fill )
+               tl_att=att_init('_FillValue', dd_fill )
          END SELECT
          CALL var_move_att(var__init, tl_att)
@@ -1038,4 +1065,16 @@
       ENDIF
 
+      ! units factor
+      IF( PRESENT(dd_unf) )THEN
+         tl_att=att_init('units_factor',dd_unf)
+         CALL var_move_att(var__init, tl_att)
+      ENDIF
+
+      ! new units (linked to units factor)
+      IF( PRESENT(cd_unt) )THEN
+         tl_att=att_init('new_units',cd_units)
+         CALL var_move_att(var__init, tl_att)
+      ENDIF
+
       ! add extra information
       CALL var__get_extra(var__init)
@@ -1047,4 +1086,6 @@
       CALL var_del_att(var__init, 'filter')
       CALL var_del_att(var__init, 'src_file')
+      CALL var_del_att(var__init, 'src_i_indices')
+      CALL var_del_att(var__init, 'src_j_indices')
       CALL var_del_att(var__init, 'valid_min')
       CALL var_del_att(var__init, 'valid_max')
@@ -1072,6 +1113,10 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
+   !>
    !> @param[in] cd_name         variable name
    !> @param[in] dd_value        1D array of real(8) value
@@ -1100,4 +1145,9 @@
    !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -1110,5 +1160,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
       IMPLICIT NONE
       ! Argument
@@ -1138,4 +1190,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -1193,5 +1250,9 @@
       &                          ld_fletcher32=ld_fletcher32,        &
       &                          id_deflvl=id_deflvl,                &
-      &                          id_chunksz=id_chunksz(:))
+      &                          id_chunksz=id_chunksz(:),           &
+      &                          cd_interp=cd_interp(:),             &
+      &                          cd_extrap=cd_extrap(:),             &
+      &                          cd_filter=cd_filter(:),             &
+      &                          cd_unt=cd_unt, dd_unf=dd_unf )
    
       ! add value
@@ -1239,5 +1300,13 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - bug fix: array initialise with dimension
+   !> array not only one value
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> - Bux fix: dimension array initialise not only one value
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -1269,4 +1338,9 @@
    !> no deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -1279,5 +1353,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
       IMPLICIT NONE
       ! Argument
@@ -1307,4 +1383,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -1350,5 +1431,5 @@
       ENDIF
 
-      il_count(:)=tl_dim(1)%i_len
+      il_count(:)=tl_dim(:)%i_len
       IF( PRESENT(id_count) )THEN
          IF( SIZE(id_count(:)) /= 2 )THEN
@@ -1381,5 +1462,9 @@
       &                          ld_fletcher32=ld_fletcher32,        &
       &                          id_deflvl=id_deflvl,                &
-      &                          id_chunksz=id_chunksz(:))
+      &                          id_chunksz=id_chunksz(:),           &
+      &                          cd_interp=cd_interp(:),             &
+      &                          cd_extrap=cd_extrap(:),             &
+      &                          cd_filter=cd_filter(:),             &
+      &                          cd_unt=cd_unt, dd_unf=dd_unf )
    
       ! add value
@@ -1431,6 +1516,10 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
+   !>
    !> @param[in] cd_name         variable name
    !> @param[in] dd_value        1D array of real(8) value
@@ -1461,4 +1550,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -1471,5 +1565,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
       IMPLICIT NONE
       ! Argument
@@ -1499,4 +1595,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -1577,5 +1678,9 @@
       &                          ld_fletcher32=ld_fletcher32,        &
       &                          id_deflvl=id_deflvl,                &
-      &                          id_chunksz=id_chunksz(:))
+      &                          id_chunksz=id_chunksz(:),           &
+      &                          cd_interp=cd_interp(:),             &
+      &                          cd_extrap=cd_extrap(:),             &
+      &                          cd_filter=cd_filter(:),             &
+      &                          cd_unt=cd_unt, dd_unf=dd_unf )
    
       ! add value
@@ -1623,6 +1728,10 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
+   !>
    !> @param[in] cd_name         variable name
    !> @param[in] dd_value        4D array of real(8) value
@@ -1653,4 +1762,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -1663,5 +1777,7 @@
    &                                 dd_min, dd_max,           &
    &                                 ld_contiguous, ld_shuffle,&
-   &                                 ld_fletcher32, id_deflvl, id_chunksz)
+   &                                 ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                 cd_interp, cd_extrap, cd_filter, &
+   &                                 cd_unt, dd_unf )
       IMPLICIT NONE
       ! Argument
@@ -1691,4 +1807,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -1723,5 +1844,9 @@
       &                       ld_fletcher32=ld_fletcher32,        &
       &                       id_deflvl=id_deflvl,                &
-      &                       id_chunksz=id_chunksz(:))
+      &                       id_chunksz=id_chunksz(:),           &
+      &                       cd_interp=cd_interp(:),             &
+      &                       cd_extrap=cd_extrap(:),             &
+      &                       cd_filter=cd_filter(:),             &
+      &                       cd_unt=cd_unt, dd_unf=dd_unf )
  
       ! add value
@@ -1758,5 +1883,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -1788,4 +1917,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -1798,5 +1932,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -1827,4 +1963,10 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
+
 
       ! local variable
@@ -1870,5 +2012,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf )
  
       DEALLOCATE( dl_value )
@@ -1892,5 +2038,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         : variable name
@@ -1922,4 +2072,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      : chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -1932,5 +2087,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -1961,4 +2118,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2006,5 +2168,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf )
       
       DEALLOCATE( dl_value )
@@ -2028,5 +2194,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         : variable name
@@ -2058,4 +2228,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      : chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2068,5 +2243,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2097,4 +2274,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2143,5 +2325,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -2165,5 +2351,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -2195,4 +2385,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2205,5 +2400,7 @@
    &                                 dd_min, dd_max,           &
    &                                 ld_contiguous, ld_shuffle,&
-   &                                 ld_fletcher32, id_deflvl, id_chunksz)
+   &                                 ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                 cd_interp, cd_extrap, cd_filter, &
+   &                                 cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2234,4 +2431,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2281,5 +2483,9 @@
       &                      ld_fletcher32=ld_fletcher32,        &
       &                      id_deflvl=id_deflvl,                &
-      &                      id_chunksz=id_chunksz(:))
+      &                      id_chunksz=id_chunksz(:),           &
+      &                      cd_interp=cd_interp(:),             &
+      &                      cd_extrap=cd_extrap(:),             &
+      &                      cd_filter=cd_filter(:),             &
+      &                      cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -2303,5 +2509,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         : variable name
@@ -2333,4 +2543,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      : chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2343,5 +2558,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2372,4 +2589,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2415,5 +2637,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
  
       DEALLOCATE( dl_value )
@@ -2437,5 +2663,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -2465,4 +2695,9 @@
    !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2475,5 +2710,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2504,4 +2741,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2549,5 +2791,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -2571,5 +2817,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -2601,4 +2851,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2611,5 +2866,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2640,4 +2897,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2686,5 +2948,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -2708,5 +2974,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -2738,4 +3008,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2748,5 +3023,7 @@
    &                                 dd_min, dd_max,           &
    &                                 ld_contiguous, ld_shuffle,&
-   &                                 ld_fletcher32, id_deflvl, id_chunksz)
+   &                                 ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                 cd_interp, cd_extrap, cd_filter, &
+   &                                 cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2777,4 +3054,10 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
+
 
       ! local variable
@@ -2824,5 +3107,9 @@
       &                      ld_fletcher32=ld_fletcher32,        &
       &                      id_deflvl=id_deflvl,                &
-      &                      id_chunksz=id_chunksz(:))
+      &                      id_chunksz=id_chunksz(:),           &
+      &                      cd_interp=cd_interp(:),             &
+      &                      cd_extrap=cd_extrap(:),             &
+      &                      cd_filter=cd_filter(:),             &
+      &                      cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -2846,5 +3133,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -2876,4 +3167,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -2886,5 +3182,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -2915,4 +3213,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -2958,5 +3261,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
  
       DEALLOCATE( dl_value )
@@ -2980,5 +3287,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3010,4 +3321,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3020,5 +3336,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3049,4 +3367,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -3094,5 +3417,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -3116,5 +3443,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3146,4 +3477,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3156,5 +3492,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3185,4 +3523,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -3231,5 +3574,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -3253,5 +3600,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3283,4 +3634,10 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
+
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3293,5 +3650,7 @@
    &                                 dd_min, dd_max,           &
    &                                 ld_contiguous, ld_shuffle,&
-   &                                 ld_fletcher32, id_deflvl, id_chunksz)
+   &                                 ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                 cd_interp, cd_extrap, cd_filter, &
+   &                                 cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3322,4 +3681,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -3369,5 +3733,9 @@
       &                      ld_fletcher32=ld_fletcher32,        &
       &                      id_deflvl=id_deflvl,                &
-      &                      id_chunksz=id_chunksz(:))
+      &                      id_chunksz=id_chunksz(:),           &
+      &                      cd_interp=cd_interp(:),             &
+      &                      cd_extrap=cd_extrap(:),             &
+      &                      cd_filter=cd_filter(:),             &
+      &                      cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -3391,5 +3759,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3421,4 +3793,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3431,5 +3808,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3460,4 +3839,10 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
+
 
       ! local variable
@@ -3503,5 +3888,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
  
       DEALLOCATE( dl_value )
@@ -3525,5 +3914,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3555,4 +3948,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3565,5 +3963,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3594,4 +3994,10 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
+
 
       ! local variable
@@ -3639,5 +4045,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -3661,5 +4071,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3691,4 +4105,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3701,5 +4120,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3730,4 +4151,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -3776,5 +4202,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -3798,5 +4228,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3828,4 +4262,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3838,5 +4277,7 @@
    &                                 dd_min, dd_max,           &
    &                                 ld_contiguous, ld_shuffle,&
-   &                                 ld_fletcher32, id_deflvl, id_chunksz)
+   &                                 ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                 cd_interp, cd_extrap, cd_filter, &
+   &                                 cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -3867,4 +4308,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -3914,5 +4360,9 @@
       &                      ld_fletcher32=ld_fletcher32,        &
       &                      id_deflvl=id_deflvl,                &
-      &                      id_chunksz=id_chunksz(:))
+      &                      id_chunksz=id_chunksz(:),           &
+      &                      cd_interp=cd_interp(:),             &
+      &                      cd_extrap=cd_extrap(:),             &
+      &                      cd_filter=cd_filter(:),             &
+      &                      cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -3936,5 +4386,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -3966,4 +4420,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -3976,5 +4435,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -4005,4 +4466,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -4048,5 +4514,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
  
       DEALLOCATE( dl_value )
@@ -4070,5 +4540,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -4100,4 +4574,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -4110,5 +4589,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -4139,4 +4620,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -4184,5 +4670,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -4206,5 +4696,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -4236,4 +4730,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -4246,5 +4745,7 @@
    &                                    dd_min, dd_max,           &
    &                                    ld_contiguous, ld_shuffle,&
-   &                                    ld_fletcher32, id_deflvl, id_chunksz)
+   &                                    ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                    cd_interp, cd_extrap, cd_filter, &
+   &                                    cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -4275,4 +4776,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -4321,5 +4827,9 @@
       &                         ld_fletcher32=ld_fletcher32,        &
       &                         id_deflvl=id_deflvl,                &
-      &                         id_chunksz=id_chunksz(:))
+      &                         id_chunksz=id_chunksz(:),           &
+      &                         cd_interp=cd_interp(:),             &
+      &                         cd_extrap=cd_extrap(:),             &
+      &                         cd_filter=cd_filter(:),             &
+      &                         cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -4343,5 +4853,9 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015
+   !> - add interp, extrap, and filter argument
+   !> @date July, 2015
+   !> - add unit factor (to change unit)
    !
    !> @param[in] cd_name         variable name
@@ -4373,4 +4887,9 @@
    !> deflation is in use
    !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @param[in] cd_unt          new units (linked to units factor)
+   !> @param[in] dd_unf          units factor
    !> @return variable structure
    !-------------------------------------------------------------------
@@ -4383,5 +4902,7 @@
    &                                 dd_min, dd_max,           &
    &                                 ld_contiguous, ld_shuffle,&
-   &                                 ld_fletcher32, id_deflvl, id_chunksz)
+   &                                 ld_fletcher32, id_deflvl, id_chunksz, &
+   &                                 cd_interp, cd_extrap, cd_filter, &
+   &                                 cd_unt, dd_unf)
 
       IMPLICIT NONE
@@ -4412,4 +4933,9 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_deflvl
       INTEGER(i4)     , DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_chunksz
+      CHARACTER(LEN=*), DIMENSION(2)        , INTENT(IN), OPTIONAL :: cd_interp
+      CHARACTER(LEN=*), DIMENSION(1)        , INTENT(IN), OPTIONAL :: cd_extrap
+      CHARACTER(LEN=*), DIMENSION(5)        , INTENT(IN), OPTIONAL :: cd_filter
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_unt
+      REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_unf
 
       ! local variable
@@ -4459,5 +4985,9 @@
       &                      ld_fletcher32=ld_fletcher32,        &
       &                      id_deflvl=id_deflvl,                &
-      &                      id_chunksz=id_chunksz(:))
+      &                      id_chunksz=id_chunksz(:),           &
+      &                      cd_interp=cd_interp(:),             &
+      &                      cd_extrap=cd_extrap(:),             &
+      &                      cd_filter=cd_filter(:),             &
+      &                      cd_unt=cd_unt, dd_unf=dd_unf)
       
       DEALLOCATE( dl_value )
@@ -4473,5 +5003,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var1   variable structure
@@ -4523,5 +5053,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var1   variable structure
@@ -4595,5 +5125,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var1   variable structure
@@ -4670,5 +5200,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var1   variable structure
@@ -4745,5 +5275,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var1   variable structure
@@ -4820,5 +5350,7 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - add all element of the array in the same time
    !>
    !> @param[inout] td_var variable structure
@@ -4833,4 +5365,7 @@
       ! local variable
       INTEGER(i4) :: il_natt
+      INTEGER(i4) :: il_status
+      INTEGER(i4) :: il_ind
+      TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
 
       ! loop indices
@@ -4840,7 +5375,103 @@
       il_natt=SIZE(td_att(:))
 
+      IF( td_var%i_natt > 0 )THEN
+      ! already other attribute in variable structure
+         ALLOCATE( tl_att(td_var%i_natt), stat=il_status )
+         IF(il_status /= 0 )THEN
+
+            CALL logger_error( &
+            &  " VAR ADD ATT: not enough space to put attributes from "//&
+            &  TRIM(td_var%c_name)//" in temporary attribute structure")
+
+         ELSE
+
+            ! save temporary global attribute's variable structure
+            tl_att(:)=att_copy(td_var%t_att(:))
+
+            CALL att_clean(td_var%t_att(:))
+            DEALLOCATE( td_var%t_att )
+            ALLOCATE( td_var%t_att(td_var%i_natt+il_natt), stat=il_status )
+            IF(il_status /= 0 )THEN
+
+               CALL logger_error( &
+               &  " VAR ADD ATT: not enough space to put attributes "//&
+               &  "in variable structure "//TRIM(td_var%c_name) )
+
+            ENDIF
+
+            ! copy attribute in variable before
+            td_var%t_att(1:td_var%i_natt)=att_copy(tl_att(:))
+
+            ! clean
+            CALL att_clean(tl_att(:))
+            DEALLOCATE(tl_att)
+            
+         ENDIF
+      ELSE
+      ! no attribute in variable structure
+         IF( ASSOCIATED(td_var%t_att) )THEN
+            CALL att_clean(td_var%t_att(:))
+            DEALLOCATE(td_var%t_att)
+         ENDIF
+         ALLOCATE( td_var%t_att(td_var%i_natt+il_natt), stat=il_status )
+         IF(il_status /= 0 )THEN
+
+            CALL logger_error( &
+            &  " VAR ADD ATT: not enough space to put attributes "//&
+            &  "in variable structure "//TRIM(td_var%c_name) )
+
+         ENDIF
+      ENDIF
+
+      ALLOCATE( tl_att(il_natt) )
+      tl_att(:)=att_copy(td_att(:))
+
+      ! check if attribute already in variable structure
       DO ji=1,il_natt
-         CALL var_add_att(td_var, td_att(ji))
+         il_ind=0
+         il_ind=att_get_index( td_var%t_att(:), tl_att(ji)%c_name )
+         IF( il_ind /= 0 )THEN
+            CALL logger_error( &
+            &  " VAR ADD ATT: attribute "//TRIM(tl_att(ji)%c_name)//&
+            &  ", already in variable "//TRIM(td_var%c_name) )
+            CALL att_clean(tl_att(ji))
+         ENDIF
       ENDDO
+
+      ! add new attributes
+      td_var%t_att(td_var%i_natt+1:td_var%i_natt+il_natt)=att_copy(tl_att(:))
+
+      DEALLOCATE(tl_att)
+
+      DO ji=1,il_natt
+         ! highlight some attribute
+         IF( ASSOCIATED(td_var%t_att(td_var%i_natt+ji)%d_value) .OR. &
+           & td_var%t_att(td_var%i_natt+ji)%c_value /= 'none' )THEN
+            SELECT CASE(TRIM(td_var%t_att(td_var%i_natt+ji)%c_name))
+
+               CASE("add_offset")
+                  td_var%d_ofs = td_var%t_att(td_var%i_natt+ji)%d_value(1)
+               CASE("scale_factor")
+                  td_var%d_scf = td_var%t_att(td_var%i_natt+ji)%d_value(1)
+               CASE("_FillValue")
+                  td_var%d_fill = td_var%t_att(td_var%i_natt+ji)%d_value(1)
+               CASE("ew_overlap")
+                  td_var%i_ew = INT(td_var%t_att(td_var%i_natt+ji)%d_value(1),i4) 
+               CASE("standard_name")
+                  td_var%c_stdname = TRIM(td_var%t_att(td_var%i_natt+ji)%c_value)
+               CASE("long_name")
+                  td_var%c_longname = TRIM(td_var%t_att(td_var%i_natt+ji)%c_value)
+               CASE("units")
+                  td_var%c_units = TRIM(td_var%t_att(td_var%i_natt+ji)%c_value)
+               CASE("grid_point")
+                  td_var%c_point = TRIM(td_var%t_att(td_var%i_natt+ji)%c_value)
+
+            END SELECT
+         ENDIF
+      ENDDO
+
+      ! update number of attribute
+      td_var%i_natt=td_var%i_natt+il_natt
+
 
    END SUBROUTINE var__add_att_arr
@@ -4850,5 +5481,7 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - use var__add_att_arr subroutine
    !
    !> @param[inout] td_var variable structure
@@ -4862,117 +5495,14 @@
 
       ! local variable
-      INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_ind
-      TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
+      TYPE(TATT), DIMENSION(1) :: tl_att
 
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
-      ! check if attribute already in variable structure
-      il_ind=0
-      IF( ASSOCIATED(td_var%t_att) )THEN
-         il_ind=att_get_index( td_var%t_att(:), td_att%c_name )
-      ENDIF
-
-      IF( il_ind /= 0 )THEN
-
-         CALL logger_error( &
-         &  " VAR ADD ATT: attribute "//TRIM(td_att%c_name)//&
-         &  ", already in variable "//TRIM(td_var%c_name) )
-
-         DO ji=1,td_var%i_natt
-            CALL logger_debug( &
-            &  " VAR ADD ATT: in variable "//TRIM(td_var%t_att(ji)%c_name) )
-         ENDDO
-
-      ELSE
-         
-         CALL logger_trace( &
-         &  " VAR ADD ATT: add attribute "//TRIM(td_att%c_name)//&
-         &  ", in variable "//TRIM(td_var%c_name) )
-
-         IF( td_var%i_natt > 0 )THEN
-         ! already other attribute in variable structure
-            ALLOCATE( tl_att(td_var%i_natt), stat=il_status )
-            IF(il_status /= 0 )THEN
-
-               CALL logger_error( &
-               &  " VAR ADD ATT: not enough space to put attributes from "//&
-               &  TRIM(td_var%c_name)//" in temporary attribute structure")
-
-            ELSE
-
-               ! save temporary global attribute's variable structure
-               tl_att(:)=att_copy(td_var%t_att(:))
-
-               CALL att_clean(td_var%t_att(:))
-               DEALLOCATE( td_var%t_att )
-               ALLOCATE( td_var%t_att(td_var%i_natt+1), stat=il_status )
-               IF(il_status /= 0 )THEN
-
-                  CALL logger_error( &
-                  &  " VAR ADD ATT: not enough space to put attributes "//&
-                  &  "in variable structure "//TRIM(td_var%c_name) )
-
-               ENDIF
-
-               ! copy attribute in variable before
-               td_var%t_att(1:td_var%i_natt)=att_copy(tl_att(:))
-
-               ! clean
-               CALL att_clean(tl_att(:))
-               DEALLOCATE(tl_att)
-               
-            ENDIF
-         ELSE
-         ! no attribute in variable structure
-            IF( ASSOCIATED(td_var%t_att) )THEN
-               CALL att_clean(td_var%t_att(:))
-               DEALLOCATE(td_var%t_att)
-            ENDIF
-            ALLOCATE( td_var%t_att(td_var%i_natt+1), stat=il_status )
-            IF(il_status /= 0 )THEN
-
-               CALL logger_error( &
-               &  " VAR ADD ATT: not enough space to put attributes "//&
-               &  "in variable structure "//TRIM(td_var%c_name) )
-
-            ENDIF
-         ENDIF
-         ! update number of attribute
-         td_var%i_natt=td_var%i_natt+1
-
-         ! add new attribute
-         td_var%t_att(td_var%i_natt)=att_copy(td_att)
-
-         !! add new attribute id
-         !td_var%t_att(td_var%i_natt)%i_id=att_get_unit(td_var%t_att(:))
-
-         ! highlight some attribute
-         IF( ASSOCIATED(td_var%t_att(td_var%i_natt)%d_value) .OR. &
-           & td_var%t_att(td_var%i_natt)%c_value /= "none" )THEN
-            SELECT CASE(TRIM(td_var%t_att(td_var%i_natt)%c_name))
-
-               CASE("add_offset")
-                  td_var%d_ofs = td_var%t_att(td_var%i_natt)%d_value(1)
-               CASE("scale_factor")
-                  td_var%d_scf = td_var%t_att(td_var%i_natt)%d_value(1)
-               CASE("_FillValue")
-                  td_var%d_fill = td_var%t_att(td_var%i_natt)%d_value(1)
-               CASE("ew_overlap")
-                  td_var%i_ew = INT(td_var%t_att(td_var%i_natt)%d_value(1),i4) 
-               CASE("standard_name")
-                  td_var%c_stdname = TRIM(td_var%t_att(td_var%i_natt)%c_value)
-               CASE("long_name")
-                  td_var%c_longname = TRIM(td_var%t_att(td_var%i_natt)%c_value)
-               CASE("units")
-                  td_var%c_units = TRIM(td_var%t_att(td_var%i_natt)%c_value)
-               CASE("grid_point")
-                  td_var%c_point = TRIM(td_var%t_att(td_var%i_natt)%c_value)
-
-            END SELECT
-         ENDIF
-      ENDIF
+      ! copy structure in an array
+      tl_att(1)=att_copy(td_att)
+
+      ! 
+      CALL var_add_att( td_var, tl_att(:) )
 
    END SUBROUTINE var__add_att_unit
@@ -4982,5 +5512,8 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date February, 2015 
+   !> - define local attribute structure to avoid mistake 
+   !> with pointer
    !
    !> @param[inout] td_var variable structure
@@ -4996,4 +5529,5 @@
       INTEGER(i4) :: il_ind
 
+      TYPE(TATT)  :: tl_att
       ! loop indices
       !----------------------------------------------------------------
@@ -5007,5 +5541,5 @@
       IF( il_ind == 0 )THEN
 
-         CALL logger_warn( &
+         CALL logger_debug( &
          &  " VAR DEL ATT: no attribute "//TRIM(cd_name)//&
          &  ", in variable "//TRIM(td_var%c_name) )
@@ -5013,5 +5547,6 @@
       ELSE
          
-         CALL var_del_att(td_var, td_var%t_att(il_ind))
+         tl_att=att_copy(td_var%t_att(il_ind))
+         CALL var_del_att(td_var, tl_att)
 
       ENDIF
@@ -5023,5 +5558,8 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013- Initial Version
+   !> @date February, 2015 
+   !> - delete highlight attribute too, when attribute 
+   !> is deleted
    !
    !> @param[inout] td_var variable structure
@@ -5040,5 +5578,4 @@
 
       ! loop indices
-      !INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
@@ -5051,5 +5588,5 @@
       IF( il_ind == 0 )THEN
 
-         CALL logger_warn( &
+         CALL logger_debug( &
          &  " VAR DEL ATT: no attribute "//TRIM(td_att%c_name)//&
          &  ", in variable "//TRIM(td_var%c_name) )
@@ -5103,9 +5640,4 @@
                td_var%t_att(1:td_var%i_natt)=att_copy(tl_att(:))
 
-               !! change attribute id
-               !DO ji=1,td_var%i_natt
-               !   td_var%t_att(ji)%i_id=ji
-               !ENDDO
-
                ! clean
                CALL att_clean(tl_att(:))
@@ -5113,4 +5645,27 @@
             ENDIF 
          ENDIF
+
+         ! highlight attribute
+         SELECT CASE( TRIM(td_att%c_name) )
+
+            CASE("add_offset")
+               td_var%d_ofs = 0._dp
+            CASE("scale_factor")
+               td_var%d_scf = 1._dp
+            CASE("_FillValue")
+               td_var%d_fill = 0._dp
+            CASE("ew_overlap")
+               td_var%i_ew = -1 
+            CASE("standard_name")
+               td_var%c_stdname = ''
+            CASE("long_name")
+               td_var%c_longname = ''
+            CASE("units")
+               td_var%c_units = ''
+            CASE("grid_point")
+               td_var%c_point = ''
+
+         END SELECT
+
       ENDIF
 
@@ -5121,5 +5676,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -5156,5 +5711,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -5195,5 +5750,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -5211,5 +5766,5 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_ndim <= 4 )THEN
+      IF( td_var%i_ndim <= ip_maxdim )THEN
 
          ! check if dimension already used in variable structure
@@ -5227,6 +5782,7 @@
          ELSE
 
-         ! back to unorder dimension array 
-         CALL dim_unorder(td_var%t_dim(:))
+            ! back to disorder dimension array 
+            CALL dim_disorder(td_var%t_dim(:))
+
             ! add new dimension
             td_var%t_dim(td_var%i_ndim+1)=dim_copy(td_dim)
@@ -5253,5 +5809,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -5272,5 +5828,5 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_ndim <= 4 )THEN
+      IF( td_var%i_ndim <= ip_maxdim )THEN
 
          CALL logger_trace( &
@@ -5317,5 +5873,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -5360,5 +5916,5 @@
    !>
    !> @author J.Paul
-   !> - June, 2014- Initial Version
+   !> @date June, 2014 - Initial Version
    !
    !> @param[in] td_var array of variables structure
@@ -5386,5 +5942,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var    variable structure
@@ -5493,5 +6049,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure
@@ -5631,5 +6187,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure
@@ -5685,5 +6241,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -5761,5 +6317,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variabele structure
@@ -5837,5 +6393,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variabele structure
@@ -5913,5 +6469,5 @@
    !
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variabele structure
@@ -5987,5 +6543,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -6057,5 +6613,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure
@@ -6080,5 +6636,5 @@
    !>
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !>
    !> @param[in] td_var       array of variable structure
@@ -6145,5 +6701,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var       array of variable structure
@@ -6200,5 +6756,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var array of variable structure
@@ -6239,5 +6795,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var array of variable structure
@@ -6322,5 +6878,7 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - new namelist format to get extra information (interpolation,...)
    !
    !> @param[in] cd_file   configuration file of variable
@@ -6357,5 +6915,4 @@
 
          il_fileid=fct_getunit()
-         CALL logger_trace("VAR DEF EXTRA: open "//TRIM(cd_file))
          OPEN( il_fileid, FILE=TRIM(cd_file), &
          &                FORM='FORMATTED',   &
@@ -6366,5 +6923,6 @@
          CALL fct_err(il_status)
          IF( il_status /= 0 )THEN
-            CALL logger_error("VAR DEF EXTRA: opening file "//TRIM(cd_file))
+            CALL logger_fatal("VAR DEF EXTRA: can not open file "//&
+            &                 TRIM(cd_file))
          ENDIF
 
@@ -6375,5 +6933,5 @@
          DO WHILE( il_status == 0 )
 
-         ! search line do not beginning with comment character
+         ! search line not beginning with comment character
             IF( SCAN( TRIM(fct_concat(cp_com(:))) ,cl_line(1:1)) == 0 )THEN
                il_nvar=il_nvar+1
@@ -6419,13 +6977,14 @@
                   tg_varextra(ji)%c_axis    =TRIM(fct_split(cl_line,3))
                   tg_varextra(ji)%c_point   =TRIM(fct_split(cl_line,4))
-                  tg_varextra(ji)%c_stdname =TRIM(fct_split(cl_line,5))
-                  tg_varextra(ji)%c_longname=TRIM(fct_split(cl_line,6))
-
-                  cl_interp=TRIM(fct_split(cl_line,7))
+
+                  cl_interp='int='//TRIM(fct_split(cl_line,5))
                   tg_varextra(ji)%c_interp(:) = &
                   &  var__get_interp(TRIM(tg_varextra(ji)%c_name), cl_interp)
                   CALL logger_debug("VAR DEF EXTRA: "//&
                   &  TRIM(tg_varextra(ji)%c_name)//&
-                  &  " "//TRIM(cl_interp))
+                  &  " "//TRIM(tg_varextra(ji)%c_interp(1)))
+
+                  tg_varextra(ji)%c_longname=TRIM(fct_split(cl_line,6))
+                  tg_varextra(ji)%c_stdname =TRIM(fct_split(cl_line,7))
                ELSE
                   ji=ji-1
@@ -6458,5 +7017,5 @@
    !> @details 
    !> string character format must be : <br/>
-   !> "varname:interp; filter; extrap; > min; < max"<br/>
+   !> "varname:int=interp; flt=filter; ext=extrap; min=min; max=max"<br/>
    !> you could specify only interpolation, filter or extrapolation method, 
    !> whatever the order. you could find more
@@ -6464,6 +7023,10 @@
    !> \ref extrap module.<br/>
    !> Examples: 
-   !> cn_varinfo='Bathymetry:2*hamming(2,3); > 10.'
-   !> cn_varinfo='votemper:cubic; dist_weight; <40.'
+   !> cn_varinfo='Bathymetry:flt=2*hamming(2,3); min=10.'
+   !> cn_varinfo='votemper:int=cubic; ext=dist_weight; max=40.'
+   !>
+   !>
+   !> @warning variable should be define in tg_varextra (ie in configuration
+   !> file, to be able to add information from namelist
    !>
    !> @note If you do not specify a method which is required, default one is
@@ -6471,5 +7034,7 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date July, 2015 
+   !> - get unit and unit factor (to change unit) 
    !
    !> @param[in] cd_varinfo   variable information from namelist
@@ -6486,4 +7051,5 @@
       CHARACTER(LEN=lc), DIMENSION(1)              :: cl_extrap
       CHARACTER(LEN=lc), DIMENSION(5)              :: cl_filter
+      CHARACTER(LEN=lc)                            :: cl_unt
 
       INTEGER(i4)                                  :: il_ind
@@ -6492,4 +7058,5 @@
       REAL(dp)                                     :: dl_min
       REAL(dp)                                     :: dl_max
+      REAL(dp)                                     :: dl_unf
 
       TYPE(TVAR)       , DIMENSION(:), ALLOCATABLE :: tl_varextra
@@ -6508,7 +7075,10 @@
             dl_min=var__get_min(cl_name, cl_method)
             dl_max=var__get_max(cl_name, cl_method)
+            dl_unf=var__get_unf(cl_name, cl_method)
             cl_interp(:)=var__get_interp(cl_name, cl_method)
             cl_extrap(:)=var__get_extrap(cl_name, cl_method)
             cl_filter(:)=var__get_filter(cl_name, cl_method)
+            cl_unt=var__get_unt(cl_name, cl_method)
+
 
             il_ind=var_get_index(tg_varextra(:), TRIM(cl_name))
@@ -6516,4 +7086,6 @@
                IF( dl_min /= dp_fill ) tg_varextra(il_ind)%d_min=dl_min
                IF( dl_max /= dp_fill ) tg_varextra(il_ind)%d_max=dl_max
+               IF( dl_unf /= dp_fill ) tg_varextra(il_ind)%d_unf=dl_unf
+               IF(cl_unt      /='') tg_varextra(il_ind)%c_unt      =cl_unt
                IF(cl_interp(1)/='') tg_varextra(il_ind)%c_interp(:)=cl_interp(:)
                IF(cl_extrap(1)/='') tg_varextra(il_ind)%c_extrap(:)=cl_extrap(:)
@@ -6551,24 +7123,34 @@
                &                               cd_filter=cl_filter(:), &
                &                               dd_min = dl_min, &
-               &                               dd_max = dl_max )
+               &                               dd_max = dl_max, &
+               &                               cd_unt = cl_unt, &
+               &                               dd_unf = dl_unf )
 
             ENDIF
 
             ji=ji+1
-            CALL logger_trace( "VAR CHG EXTRA: name       "//&
+            CALL logger_debug( "VAR CHG EXTRA: name       "//&
             &                  TRIM(tg_varextra(il_ind)%c_name) )
-            CALL logger_trace( "VAR CHG EXTRA: interp     "//&
+            CALL logger_debug( "VAR CHG EXTRA: interp     "//&
             &                  TRIM(tg_varextra(il_ind)%c_interp(1)) )         
-            CALL logger_trace( "VAR CHG EXTRA: filter     "//&
+            CALL logger_debug( "VAR CHG EXTRA: filter     "//&
             &                  TRIM(tg_varextra(il_ind)%c_filter(1)) )         
-            CALL logger_trace( "VAR CHG EXTRA: extrap     "//&
+            CALL logger_debug( "VAR CHG EXTRA: extrap     "//&
             &                  TRIM(tg_varextra(il_ind)%c_extrap(1)) )
             IF( tg_varextra(il_ind)%d_min /= dp_fill )THEN
-               CALL logger_trace( "VAR CHG EXTRA: min value  "//&
+               CALL logger_debug( "VAR CHG EXTRA: min value  "//&
                &                  TRIM(fct_str(tg_varextra(il_ind)%d_min)) )
             ENDIF
             IF( tg_varextra(il_ind)%d_max /= dp_fill )THEN
-               CALL logger_trace( "VAR CHG EXTRA: max value  "//&
+               CALL logger_debug( "VAR CHG EXTRA: max value  "//&
                &                  TRIM(fct_str(tg_varextra(il_ind)%d_max)) )
+            ENDIF
+            IF( TRIM(tg_varextra(il_ind)%c_unt) /= '' )THEN
+               CALL logger_debug( "VAR CHG EXTRA: new unit  "//&
+               &                  TRIM(tg_varextra(il_ind)%c_unt) )
+            ENDIF
+            IF( tg_varextra(il_ind)%d_unf /= 1. )THEN
+               CALL logger_debug( "VAR CHG EXTRA: new unit factor  "//&
+               &                  TRIM(fct_str(tg_varextra(il_ind)%d_unf)) )
             ENDIF
          ENDDO
@@ -6593,5 +7175,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -6687,5 +7269,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
    !> @param[inout] td_var variable structure
@@ -6808,13 +7390,16 @@
             ENDIF
 
-         CALL logger_trace("VAR GET EXTRA: name       "//TRIM(td_var%c_name))
-         CALL logger_trace("VAR GET EXTRA: stdname    "//TRIM(td_var%c_stdname))
-         CALL logger_trace("VAR GET EXTRA: longname   "//TRIM(td_var%c_longname))
-         CALL logger_trace("VAR GET EXTRA: units      "//TRIM(td_var%c_units))
-         CALL logger_trace("VAR GET EXTRA: point      "//TRIM(td_var%c_point))
-         CALL logger_trace("VAR GET EXTRA: interp     "//TRIM(td_var%c_interp(1)))
-         CALL logger_trace("VAR GET EXTRA: filter     "//TRIM(td_var%c_filter(1)))
-         CALL logger_trace("VAR GET EXTRA: min value  "//TRIM(fct_str(td_var%d_min)))
-         CALL logger_trace("VAR GET EXTRA: max value  "//TRIM(fct_str(td_var%d_max)))
+            ! unt
+            IF( TRIM(td_var%c_unt) == '' .AND. &
+            &   TRIM(tg_varextra(il_ind)%c_unt) /= '' )THEN
+               td_var%c_unt=TRIM(tg_varextra(il_ind)%c_unt)
+            ENDIF
+
+            ! units factor
+            IF( td_var%d_unf == 1._dp .AND. &
+            &   tg_varextra(il_ind)%d_unf /= 1._dp )THEN
+               td_var%d_unf=tg_varextra(il_ind)%d_unf
+            ENDIF
+
          ENDIF
 
@@ -6833,8 +7418,11 @@
    !> 
    !> @details
-   !> minimum value is assume to follow sign '>'
+   !> minimum value is assume to follow string "min ="
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - change way to get information in namelist, 
+   !> value follows string "min ="
    !
    !> @param[in] cd_name      variable name
@@ -6867,7 +7455,7 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
-         il_ind=SCAN(TRIM(cl_tmp),'>')
+         il_ind=INDEX(TRIM(cl_tmp),'min')
          IF( il_ind /= 0 )THEN
-            cl_min=TRIM(ADJUSTL(cl_tmp(il_ind+1:)))
+            cl_min=fct_split(cl_tmp,2,'=')
             EXIT
          ENDIF
@@ -6877,5 +7465,5 @@
 
       IF( TRIM(cl_min) /= '' )THEN
-         IF( fct_is_num(cl_min) )THEN
+         IF( fct_is_real(cl_min) )THEN
             READ(cl_min,*) var__get_min
             CALL logger_debug("VAR GET MIN: will use minimum value of "//&
@@ -6894,8 +7482,11 @@
    !> 
    !> @details
-   !> maximum value is assume to follow sign '<'
+   !> maximum value is assume to follow string "max ="
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - change way to get information in namelist, 
+   !> value follows string "max ="
    !
    !> @param[in] cd_name      variable name
@@ -6928,7 +7519,7 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
-         il_ind=SCAN(TRIM(cl_tmp),'<')
+         il_ind=INDEX(TRIM(cl_tmp),'max')
          IF( il_ind /= 0 )THEN
-            cl_max=TRIM(ADJUSTL(cl_tmp(il_ind+1:)))
+            cl_max=fct_split(cl_tmp,2,'=')
             EXIT
          ENDIF
@@ -6938,5 +7529,5 @@
 
       IF( TRIM(cl_max) /= '' )THEN
-         IF( fct_is_num(cl_max) )THEN
+         IF( fct_is_real(cl_max) )THEN
             READ(cl_max,*) var__get_max
             CALL logger_debug("VAR GET MAX: will use maximum value of "//&
@@ -6952,18 +7543,87 @@
    !> @brief
    !> This function check if variable information read in namelist contains 
+   !> units factor value and return it if true. 
+   !> 
+   !> @details
+   !> units factor value is assume to follow string "unf ="
+   !>
+   !> @author J.Paul
+   !> @date June, 2015 - Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist 
+   !> @return untis factor value to be used (FillValue if none)
+   !-------------------------------------------------------------------
+   FUNCTION var__get_unf( cd_name, cd_varinfo )
+      IMPLICIT NONE
+      ! Argument
+      CHARACTER(LEN=*), INTENT(IN   ) :: cd_name
+      CHARACTER(LEN=*), INTENT(IN   ) :: cd_varinfo
+
+      ! function
+      REAL(dp) :: var__get_unf
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_tmp
+      CHARACTER(LEN=lc) :: cl_unf
+      
+      INTEGER(i4)       :: il_ind
+
+      REAL(dp)          :: rl_unf
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! init
+      cl_unf=''
+      var__get_unf=dp_fill
+
+      ji=1
+      cl_tmp=fct_split(cd_varinfo,ji,';')
+      DO WHILE( TRIM(cl_tmp) /= '' )
+         il_ind=INDEX(TRIM(cl_tmp),'unf')
+         IF( il_ind /= 0 )THEN
+            cl_unf=fct_split(cl_tmp,2,'=')
+            EXIT
+         ENDIF
+         ji=ji+1
+         cl_tmp=fct_split(cd_varinfo,ji,';')         
+      ENDDO
+
+      IF( TRIM(cl_unf) /= '' )THEN
+         rl_unf=math_compute(cl_unf)
+         IF( rl_unf /= dp_fill )THEN
+            var__get_unf = rl_unf
+            CALL logger_debug("VAR GET UNITS FACTOR: will use units factor "//&
+               &  "value of "//TRIM(fct_str(var__get_unf))//" for variable "//&
+               &   TRIM(cd_name) )
+         ELSE
+            CALL logger_error("VAR GET UNITS FACTOR: invalid units factor "//&
+               &  "value for variable "//TRIM(cd_name)//". check namelist." )
+         ENDIF
+      ENDIF
+
+   END FUNCTION var__get_unf
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function check if variable information read in namelist contains 
    !> interpolation method and return it if true. 
    !> 
    !> @details 
-   !> split namelist information, using ';' as separator.
+   !> interpolation method is assume to follow string "int ="
+   !>
    !> compare method name with the list of interpolation method available (see
    !> module global).
    !> check if factor (*rhoi, /rhoj..) are present.<br/>
    !> Example:<br/> 
-   !> - cubic/rhoi ; dist_weight
-   !> - bilin
+   !> - int=cubic/rhoi ; ext=dist_weight
+   !> - int=bilin
    !> see @ref interp module for more information.
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - change way to get information in namelist, 
+   !> value follows string "int ="
    !
    !> @param[in] cd_name      variable name
@@ -6982,4 +7642,5 @@
       ! local variable
       CHARACTER(LEN=lc) :: cl_tmp
+      CHARACTER(LEN=lc) :: cl_int
       CHARACTER(LEN=lc) :: cl_factor
       
@@ -7000,6 +7661,16 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
+         il_ind=INDEX(TRIM(cl_tmp),'int')
+         IF( il_ind /= 0 )THEN
+            cl_int=fct_split(cl_tmp,2,'=')
+            EXIT
+         ENDIF
+         ji=ji+1
+         cl_tmp=fct_split(cd_varinfo,ji,';')         
+      ENDDO
+
+      IF( TRIM(cl_int) /= '' )THEN
          DO jj=1,ip_ninterp
-            il_ind= INDEX(fct_lower(cl_tmp),TRIM(cp_interp_list(jj)))
+            il_ind= INDEX(fct_lower(cl_int),TRIM(cp_interp_list(jj)))
             IF( il_ind /= 0 )THEN
 
@@ -7009,7 +7680,7 @@
                ! look for factor
                IF( il_ind==1 )THEN
-                  cl_factor=cl_tmp(il_len+1:)
+                  cl_factor=cl_int(il_len+1:)
                ELSE
-                  cl_factor=cl_tmp(1:il_ind-1)
+                  cl_factor=cl_int(1:il_ind-1)
                ENDIF
                il_mul=SCAN(TRIM(cl_factor),'*')
@@ -7052,8 +7723,5 @@
             ENDIF
          ENDDO
-         IF( jj /= ip_ninterp + 1 ) EXIT
-         ji=ji+1
-         cl_tmp=fct_split(cd_varinfo,ji,';')         
-      ENDDO
+      ENDIF
 
    END FUNCTION var__get_interp
@@ -7064,14 +7732,18 @@
    !> 
    !> @details 
-   !> split namelist information, using ';' as separator.
+   !> extrapolation method is assume to follow string "ext ="
+   !> 
    !> compare method name with the list of extrapolation method available (see
    !> module global).<br/>
    !> Example:<br/>
-   !> - cubic ; dist_weight
-   !> - min_error
+   !> - int=cubic ; ext=dist_weight
+   !> - ext=min_error
    !> see @ref extrap module for more information.
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - change way to get information in namelist, 
+   !> value follows string "ext ="
    !
    !> @param[in] cd_name      variable name
@@ -7090,4 +7762,7 @@
       ! local variable
       CHARACTER(LEN=lc) :: cl_tmp
+      CHARACTER(LEN=lc) :: cl_ext
+
+      INTEGER(i4)       :: il_ind
 
       ! loop indices
@@ -7101,6 +7776,16 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
+         il_ind=INDEX(TRIM(cl_tmp),'ext')
+         IF( il_ind /= 0 )THEN
+            cl_ext=fct_split(cl_tmp,2,'=')
+            EXIT
+         ENDIF
+         ji=ji+1
+         cl_tmp=fct_split(cd_varinfo,ji,';')         
+      ENDDO
+
+      IF( TRIM(cl_ext) /= '' )THEN
          DO jj=1,ip_nextrap
-            IF( TRIM(fct_lower(cl_tmp)) == TRIM(cp_extrap_list(jj)) )THEN
+            IF( TRIM(fct_lower(cl_ext)) == TRIM(cp_extrap_list(jj)) )THEN
                var__get_extrap(1)=TRIM(cp_extrap_list(jj))
 
@@ -7111,8 +7796,5 @@
             ENDIF
          ENDDO
-         IF( jj /= ip_nextrap + 1 ) EXIT
-         ji=ji+1
-         cl_tmp=fct_split(cd_varinfo,ji,';')         
-      ENDDO
+      ENDIF
 
 
@@ -7124,17 +7806,21 @@
    !> 
    !> @details 
-   !> split namelist information, using ';' as separator.
+   !> filter method is assume to follow string "flt ="
+   !>
    !> compare method name with the list of filter method available (see
    !> module global).
-   !> look for the number of turn, using '*' separator, and method parameters inside
+   !> look for the number of run, using '*' separator, and method parameters inside
    !> bracket.<br/>
    !> Example:<br/>
-   !> - cubic ; 2*hamming(2,3)
-   !> - hann
+   !> - int=cubic ; flt=2*hamming(2,3)
+   !> - flt=hann
    !> see @ref filter module for more information.
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
-   !
+   !> @date November, 2013 - Initial Version
+   !> @date June, 2015 
+   !> - change way to get information in namelist, 
+   !> value follows string "flt ="
+   !>
    !> @param[in] cd_name      variable name
    !> @param[in] cd_varinfo   variable information read in namelist 
@@ -7151,4 +7837,5 @@
       ! local variable
       CHARACTER(LEN=lc) :: cl_tmp
+      CHARACTER(LEN=lc) :: cl_flt
       INTEGER(i4)       :: il_ind
 
@@ -7163,16 +7850,26 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
+         il_ind=INDEX(TRIM(cl_tmp),'flt')
+         IF( il_ind /= 0 )THEN
+            cl_flt=fct_split(cl_tmp,2,'=')
+            EXIT
+         ENDIF
+         ji=ji+1
+         cl_tmp=fct_split(cd_varinfo,ji,';')         
+      ENDDO
+      
+      IF( TRIM(cl_flt) /= '' )THEN
          DO jj=1,ip_nfilter
-            il_ind=INDEX(fct_lower(cl_tmp),TRIM(cp_filter_list(jj)))
+            il_ind=INDEX(fct_lower(cl_flt),TRIM(cp_filter_list(jj)))
             IF( il_ind /= 0 )THEN
                var__get_filter(1)=TRIM(cp_filter_list(jj))
 
-               ! look for number of turn
-               il_ind=SCAN(fct_lower(cl_tmp),'*')
+               ! look for number of run
+               il_ind=SCAN(fct_lower(cl_flt),'*')
                IF( il_ind /=0 )THEN
-                  IF( fct_is_num(cl_tmp(1:il_ind-1)) )THEN
-                     var__get_filter(2)=TRIM(cl_tmp(1:il_ind-1))
-                  ELSE IF( fct_is_num(cl_tmp(il_ind+1:)) )THEN
-                     var__get_filter(2)=TRIM(cl_tmp(il_ind+1:))
+                  IF( fct_is_num(cl_flt(1:il_ind-1)) )THEN
+                     var__get_filter(2)=TRIM(cl_flt(1:il_ind-1))
+                  ELSE IF( fct_is_num(cl_flt(il_ind+1:)) )THEN
+                     var__get_filter(2)=TRIM(cl_flt(il_ind+1:))
                   ELSE
                      var__get_filter(2)='1'
@@ -7183,16 +7880,16 @@
 
                ! look for filter parameter
-               il_ind=SCAN(fct_lower(cl_tmp),'(')
+               il_ind=SCAN(fct_lower(cl_flt),'(')
                IF( il_ind /=0 )THEN
-                  cl_tmp=TRIM(cl_tmp(il_ind+1:))
-                  il_ind=SCAN(fct_lower(cl_tmp),')')
+                  cl_flt=TRIM(cl_flt(il_ind+1:))
+                  il_ind=SCAN(fct_lower(cl_flt),')')
                   IF( il_ind /=0 )THEN
-                     cl_tmp=TRIM(cl_tmp(1:il_ind-1))
+                     cl_flt=TRIM(cl_flt(1:il_ind-1))
                      ! look for cut-off frequency
-                     var__get_filter(3)=fct_split(cl_tmp,1,',')
+                     var__get_filter(3)=fct_split(cl_flt,1,',')
                      ! look for halo size
-                     var__get_filter(4)=fct_split(cl_tmp,2,',')
+                     var__get_filter(4)=fct_split(cl_flt,2,',')
                      ! look for alpha parameter
-                     var__get_filter(5)=fct_split(cl_tmp,3,',')
+                     var__get_filter(5)=fct_split(cl_flt,3,',')
                   ELSE
                      CALL logger_error("VAR GET FILTER: variable "//&
@@ -7215,10 +7912,61 @@
             ENDIF
          ENDDO
-         IF( jj /= ip_nfilter + 1 ) EXIT
+      ENDIF
+
+   END FUNCTION var__get_filter
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function check if variable information read in namelist contains 
+   !> unit and return it if true. 
+   !> 
+   !> @details 
+   !> unit is assume to follow string "unt ="
+   !>
+   !> @author J.Paul
+   !> @date June, 2015 - Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist
+   !> @return unit string character 
+   !-------------------------------------------------------------------
+   FUNCTION var__get_unt( cd_name, cd_varinfo )
+      IMPLICIT NONE
+      ! Argument
+      CHARACTER(LEN=*), INTENT(IN   ) :: cd_name
+      CHARACTER(LEN=*), INTENT(IN   ) :: cd_varinfo
+
+      ! function
+      CHARACTER(LEN=lc)               :: var__get_unt
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_tmp
+      
+      INTEGER(i4)       :: il_ind
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      var__get_unt=''
+
+      ji=1
+      cl_tmp=fct_split(cd_varinfo,ji,';')
+      DO WHILE( TRIM(cl_tmp) /= '' )
+         il_ind=INDEX(TRIM(cl_tmp),'unt')
+         IF( il_ind /= 0 )THEN
+            var__get_unt=fct_split(cl_tmp,2,'=')
+            EXIT
+         ENDIF
          ji=ji+1
          cl_tmp=fct_split(cd_varinfo,ji,';')         
       ENDDO
 
-   END FUNCTION var__get_filter
+      IF( TRIM(var__get_unt) /= '' )THEN
+         CALL logger_debug("VAR GET UNIT: will use units "//&
+            &  TRIM(var__get_unt)//" for variable "//&
+            &  TRIM(cd_name) )
+      ENDIF
+
+   END FUNCTION var__get_unt
    !-------------------------------------------------------------------
    !> @brief 
@@ -7227,5 +7975,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_var array of variable structure
@@ -7285,5 +8033,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var variable structure
@@ -7321,4 +8069,55 @@
    !-------------------------------------------------------------------
    !> @brief
+   !> This subroutine replace unit name of the variable,
+   !> and apply unit factor to the value of this variable.
+   !> 
+   !> @details
+   !> new unit name (unt) and unit factor (unf) are read from the namelist.
+   !>
+   !> @note the variable value should be already read.
+   !>
+   !> @author J.Paul
+   !> @date June, 2015 - Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var_chg_unit( td_var )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), INTENT(INOUT) :: td_var
+
+      ! local variable
+      TYPE(TATT)                :: tl_att
+
+      ! loop indices
+      !----------------------------------------------------------------
+
+      IF( ASSOCIATED(td_var%d_value) )THEN
+         !- change value
+         IF( td_var%d_unf /= 1._dp )THEN
+            WHERE( td_var%d_value(:,:,:,:) /= td_var%d_fill )
+               td_var%d_value(:,:,:,:)=td_var%d_value(:,:,:,:)*td_var%d_unf
+            END WHERE
+
+            !- change scale factor and offset to avoid mistake
+            tl_att=att_init('scale_factor',1)
+            CALL var_move_att(td_var, tl_att)
+
+            tl_att=att_init('add_offset',0)
+            CALL var_move_att(td_var, tl_att)
+         ENDIF
+
+         !- change unit name 
+         IF( TRIM(td_var%c_unt) /= TRIM(td_var%c_units) .AND. &
+         &   TRIM(td_var%c_unt) /= '' )THEN
+            tl_att=att_init('units',TRIM(td_var%c_unt))
+            CALL var_move_att(td_var,tl_att)
+         ENDIF
+
+      ENDIF
+
+   END SUBROUTINE var_chg_unit
+   !-------------------------------------------------------------------
+   !> @brief
    !> This subroutine check variable dimension expected, as defined in
    !> file 'variable.cfg'.
@@ -7329,5 +8128,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[inout] td_var    variable structure
@@ -7414,5 +8213,7 @@
    !> 
    !> @author J.Paul
-   !> - August, 2014- Initial Version
+   !> @date August, 2014 - Initial Version
+   !> @date July 2015 
+   !> - do not use dim_disorder anymore
    !
    !> @param[inout] td_var       variable structure
@@ -7438,7 +8239,9 @@
       IF( PRESENT(cd_dimorder) ) cl_dimorder=TRIM(ADJUSTL(cd_dimorder))
 
+      CALL logger_debug("VAR REORDER: work on "//TRIM(td_var%c_name)//&
+         &  " new dimension order "//TRIM(cl_dimorder))
+
       tl_dim(:)=dim_copy(td_var%t_dim(:))
 
-      CALL dim_unorder(tl_dim(:))
       CALL dim_reorder(tl_dim(:),TRIM(cl_dimorder))
 
@@ -7467,5 +8270,5 @@
    !> 
    !> @author J.Paul
-   !> - September, 2014- Initial Version
+   !> @date September, 2014 - Initial Version
    !
    !> @param[in] td_var array of variable structure 
@@ -7492,5 +8295,5 @@
    !> 
    !> @author J.Paul
-   !> - November, 2014- Initial Version
+   !> @date November, 2014 - Initial Version
    !
    !> @param[in] td_var time variable structure 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/vgrid.f90
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/vgrid.f90	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/src/vgrid.f90	(revision 9987)
@@ -70,4 +70,5 @@
 !> @date Spetember, 2014
 !> - add header
+!> @date June, 2015 - update subroutine with NEMO 3.6
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -118,5 +119,5 @@
    !>
    !> @author G. Madec
-   !> - 03,08-  G. Madec: F90: Free form and module
+   !> @date Marsh,2008 - F90: Free form and module
    !
    !> @note Reference : Marti, Madec & Delecluse, 1992, JGR, 97, No8, 12,763-12,766.
@@ -139,4 +140,5 @@
    !-------------------------------------------------------------------
    SUBROUTINE vgrid_zgr_z( dd_gdepw, dd_gdept, dd_e3w, dd_e3t,          &
+   &                       dd_e3w_1d, dd_e3t_1d, &
    &                       dd_ppkth, dd_ppkth2, dd_ppacr, dd_ppacr2,    &
    &                       dd_ppdzmin, dd_pphmax, dd_pp_to_be_computed, &
@@ -148,4 +150,6 @@
       REAL(dp), DIMENSION(:), INTENT(INOUT) :: dd_e3w
       REAL(dp), DIMENSION(:), INTENT(INOUT) :: dd_e3t
+      REAL(dp), DIMENSION(:), INTENT(INOUT) :: dd_e3w_1d
+      REAL(dp), DIMENSION(:), INTENT(INOUT) :: dd_e3t_1d
 
       REAL(dp)              , INTENT(IN   ) :: dd_ppkth
@@ -226,5 +230,5 @@
          DO jk = 1, il_jpk
             dl_zw = REAL(jk,dp)
-            dl_zt = REAL(jk,dp) + 0.5
+            dl_zt = REAL(jk,dp) + 0.5_dp
             dd_gdepw(jk) = ( dl_zw - 1.0 ) * dl_za1
             dd_gdept(jk) = ( dl_zt - 1.0 ) * dl_za1
@@ -237,5 +241,5 @@
          DO jk = 1, il_jpk
             dl_zw = REAL( jk,dp)
-            dl_zt = REAL( jk,dp) + 0.5
+            dl_zt = REAL( jk,dp) + 0.5_dp
             dd_gdepw(jk) = ( dl_zsur + dl_za0 * dl_zw + &
             &                dl_za1 * dl_zacr * LOG( COSH( (dl_zw-dl_zkth)/dl_zacr ) ) + &
@@ -255,4 +259,17 @@
       ENDIF
 
+   ! need to be like this to compute the pressure gradient with ISF.
+   ! If not, level beneath the ISF are not aligned (sum(e3t) /= depth)
+   ! define e3t_0 and e3w_0 as the differences between gdept and gdepw respectively
+      DO jk = 1, il_jpk-1
+         dd_e3t_1d(jk) = dd_gdepw(jk+1)-dd_gdepw(jk) 
+      END DO
+      dd_e3t_1d(il_jpk) = dd_e3t_1d(il_jpk-1) ! we don't care because this level is masked in NEMO
+
+      DO jk = 2, il_jpk
+         dd_e3w_1d(jk) = dd_gdept(jk) - dd_gdept(jk-1) 
+      END DO
+      dd_e3w_1d(1  ) = 2._dp * (dd_gdept(1) - dd_gdepw(1))
+
       ! Control and  print
       ! ==================
@@ -260,6 +277,10 @@
       DO jk = 1, il_jpk
          IF( dd_e3w(jk)  <= 0. .OR. dd_e3t(jk)  <= 0. )then
-            CALL logger_debug("VGRID ZGR Z: e3w or e3t =< 0 ")
+            CALL logger_debug("VGRID ZGR Z: e3w or e3t <= 0 ")
          ENDIF   
+
+         IF( dd_e3w_1d(jk)  <= 0. .OR. dd_e3t_1d(jk)  <= 0. )then
+            CALL logger_debug("VGRID ZGR Z: e3w_1d or e3t_1d <= 0 ")
+         ENDIF
 
          IF( dd_gdepw(jk) < 0. .OR. dd_gdept(jk) < 0. )then
@@ -269,4 +290,43 @@
 
    END SUBROUTINE vgrid_zgr_z
+   !-------------------------------------------------------------------
+   !-------------------------------------------------------------------
+   SUBROUTINE vgrid_zgr_bat( dd_bathy, dd_gdepw, dd_hmin, dd_fill )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:,:), INTENT(INOUT) :: dd_bathy 
+      REAL(dp), DIMENSION(:)  , INTENT(IN   ) :: dd_gdepw 
+      REAL(dp)                , INTENT(IN   ) :: dd_hmin
+      REAL(dp)                , INTENT(IN   ), OPTIONAL :: dd_fill
+
+      ! local
+      INTEGER(i4) :: il_jpk
+      
+      REAL(dp)    :: dl_hmin
+      REAL(dp)    :: dl_fill
+
+      ! loop indices
+      INTEGER(i4) :: jk
+      !----------------------------------------------------------------
+      il_jpk = SIZE(dd_gdepw(:))
+
+      dl_fill=0._dp
+      IF( PRESENT(dd_fill) ) dl_fill=dd_fill
+
+      IF( dd_hmin < 0._dp ) THEN
+         jk = - INT( dd_hmin )     ! from a nb of level
+      ELSE
+         jk = MINLOC( dd_gdepw, mask = dd_gdepw > dd_hmin, dim = 1 )  ! from a depth
+      ENDIF
+      
+      dl_hmin = dd_gdepw(jk+1) ! minimum depth = ik+1 w-levels 
+      WHERE( dd_bathy(:,:) <= 0._wp .OR. dd_bathy(:,:) == dl_fill )
+         dd_bathy(:,:) = dl_fill                         ! min=0     over the lands
+      ELSE WHERE
+         dd_bathy(:,:) = MAX(  dl_hmin , dd_bathy(:,:)  )   ! min=dl_hmin over the oceans
+      END WHERE
+      WRITE(*,*) 'Minimum ocean depth: ', dl_hmin, ' minimum number of ocean levels : ', jk      
+
+   END SUBROUTINE vgrid_zgr_bat
    !-------------------------------------------------------------------
    !> @brief This subroutine set the depth and vertical scale factor in partial step
@@ -313,6 +373,7 @@
    !
    !> @author A. Bozec, G. Madec
-   !> - 02-09 (A. Bozec, G. Madec) F90: Free form and module
-   !> - 02-09 (A. de Miranda)  rigid-lid + islands
+   !> @date February, 2009 - F90: Free form and module
+   !> @date February, 2009 
+   !> - A. de Miranda : rigid-lid + islands
    !>
    !> @note Reference : Pacanowsky & Gnanadesikan 1997, Mon. Wea. Rev., 126, 3248-3270.
@@ -327,6 +388,7 @@
    !-------------------------------------------------------------------
    SUBROUTINE vgrid_zgr_zps( id_mbathy, dd_bathy, id_jpkmax, &
-   &                         dd_gdepw, dd_e3t,               &
-   &                         dd_e3zps_min, dd_e3zps_rat )
+   &                          dd_gdepw, dd_e3t,               &
+   &                          dd_e3zps_min, dd_e3zps_rat,     &
+   &                          dd_fill )
       IMPLICIT NONE
       ! Argument      
@@ -336,11 +398,13 @@
       REAL(dp)   , DIMENSION(:)  , INTENT(IN   ) :: dd_gdepw
       REAL(dp)   , DIMENSION(:)  , INTENT(IN   ) :: dd_e3t
-      REAL(dp)                                   :: dd_e3zps_min
-      REAL(dp)                                   :: dd_e3zps_rat
+      REAL(dp)                   , INTENT(IN   ) :: dd_e3zps_min
+      REAL(dp)                   , INTENT(IN   ) :: dd_e3zps_rat
+      REAL(dp)                   , INTENT(IN   ), OPTIONAL :: dd_fill
 
       ! local variable
       REAL(dp) :: dl_zmax     ! Maximum depth
-      REAL(dp) :: dl_zmin     ! Minimum depth
+      !REAL(dp) :: dl_zmin     ! Minimum depth
       REAL(dp) :: dl_zdepth   ! Ajusted ocean depth to avoid too small e3t 
+      REAL(dp) :: dl_fill     
 
       INTEGER(i4) :: il_jpk
@@ -359,7 +423,14 @@
       il_jpjglo=SIZE(id_mbathy(:,:),DIM=2)
 
+      dl_fill=0._dp
+      IF( PRESENT(dd_fill) ) dl_fill=dd_fill
+
       ! Initialization of constant
-      dl_zmax = dd_gdepw(il_jpk) + dd_e3t(il_jpk)
-      dl_zmin = dd_gdepw(4)
+      dl_zmax = dd_gdepw(il_jpk) + dd_e3t(il_jpk) ! maximum depth (i.e. the last ocean level thickness <= 2*e3t_1d(jpkm1) )
+
+      ! bounded value of bathy (min already set at the end of zgr_bat)
+      WHERE( dd_bathy(:,:) /= dl_fill )
+         dd_bathy(:,:) = MIN( dl_zmax ,  dd_bathy(:,:) )
+      END WHERE
 
       ! bathymetry in level (from bathy_meter)
@@ -372,19 +443,8 @@
       DO jj = 1, il_jpjglo
          DO ji= 1, il_jpiglo
-            IF( dd_bathy(ji,jj) <= 0. )   id_mbathy(ji,jj) = INT(dd_bathy(ji,jj),i4)
-         END DO
-      END DO
-
-      ! bounded value of bathy
-      ! minimum depth == 3 levels
-      ! maximum depth == gdepw(jpk)+e3t(jpk) 
-      ! i.e. the last ocean level thickness cannot exceed e3t(jpkm1)+e3t(jpk)
-      DO jj = 1, il_jpjglo
-         DO ji= 1, il_jpiglo
-            IF( dd_bathy(ji,jj) <= 0. ) THEN
-               dd_bathy(ji,jj) = 0.e0
-            ELSE
-               dd_bathy(ji,jj) = MAX( dd_bathy(ji,jj), dl_zmin )
-               dd_bathy(ji,jj) = MIN( dd_bathy(ji,jj), dl_zmax )
+            IF( dd_bathy(ji,jj) <= 0._dp )THEN
+               id_mbathy(ji,jj) = INT(dd_bathy(ji,jj),i4)
+            ELSEIF( dd_bathy(ji,jj) == dl_fill )THEN
+               id_mbathy(ji,jj) = 0_i4
             ENDIF
          END DO
@@ -401,5 +461,8 @@
          DO jj = 1, il_jpjglo
             DO ji = 1, il_jpiglo
-               IF( 0. < dd_bathy(ji,jj) .AND. dd_bathy(ji,jj) <= dl_zdepth ) id_mbathy(ji,jj) = jk-1
+               IF( dd_bathy(ji,jj) /= dl_fill )THEN
+                  IF( 0. < dd_bathy(ji,jj) .AND. &
+                  &       dd_bathy(ji,jj) <= dl_zdepth ) id_mbathy(ji,jj) = jk-1
+               ENDIF
             END DO
          END DO
@@ -434,5 +497,5 @@
 
    !> @author G.Madec
-   !> - 03-08 Original code
+   !> @date Marsh, 2008 - Original code
    !
    !> @param[in] id_mbathy 
@@ -543,5 +606,5 @@
    !>
    !> @author J.Paul
-   !> - November, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
    !> @param[in] td_bathy     Bathymetry file structure 
@@ -567,4 +630,6 @@
       REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_e3w 
       REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_e3t
+      REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_e3w_1d 
+      REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_e3t_1d
 
       INTEGER(i4)                                  :: il_status
@@ -710,5 +775,7 @@
       ALLOCATE( dl_gdepw(in_nlevel), dl_gdept(in_nlevel) ) 
       ALLOCATE(   dl_e3w(in_nlevel),   dl_e3t(in_nlevel) ) 
+      ALLOCATE(   dl_e3w_1d(in_nlevel),   dl_e3t_1d(in_nlevel) ) 
       CALL vgrid_zgr_z( dl_gdepw(:), dl_gdept(:), dl_e3w(:), dl_e3t(:), &
+      &                 dl_e3w_1d, dl_e3t_1d, &
       &                 dn_ppkth, dn_ppkth2, dn_ppacr, dn_ppacr2,       &
       &                 dn_ppdzmin, dn_pphmax, dn_pp_to_be_computed,    &
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_bathy.nam
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_bathy.nam	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_bathy.nam	(revision 9987)
@@ -19,6 +19,6 @@
 
 &namvar
+   cn_varfile=
    cn_varinfo=
-   cn_varfile=
 /
 
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_boundary.nam
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_boundary.nam	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_boundary.nam	(revision 9987)
@@ -60,8 +60,9 @@
    cn_west  = 
    ln_oneseg= 
-   in_extrap= 
 /
 
 &namout
    cn_fileout="boundary_out.nc"      
+   dn_dayofs=
+   ln_extrap=
 /
Index: /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_restart.nam
===================================================================
--- /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_restart.nam	(revision 9986)
+++ /branches/UKMO/dev_r5518_obs_oper_update_icethick/NEMOGCM/TOOLS/SIREN/templates/create_restart.nam	(revision 9987)
@@ -12,4 +12,10 @@
    cn_coord0=
    in_perio0=
+/
+
+&namfin
+   cn_coord1=
+   cn_bathy1=
+   in_perio1=
 /
 
@@ -34,11 +40,4 @@
 /
 
-&namfin
-   cn_coord1=
-   cn_bathy1=
-   in_perio1=
-   in_extrap=
-/
-
 &namvar
    cn_varinfo=
@@ -53,3 +52,8 @@
 &namout
    cn_fileout="restart_out.nc"      
+   ln_extrap=
+   in_nipro=
+   in_njproc=
+   in_nproc=
+   cn_type=
 /
