Index: issm/trunk/configure.ac
===================================================================
--- issm/trunk/configure.ac	(revision 27035)
+++ issm/trunk/configure.ac	(revision 27232)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([Ice-sheet and Sea-level System Model (ISSM)],[4.20],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([Ice-sheet and Sea-level System Model (ISSM)],[4.21],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
 AC_CONFIG_AUX_DIR([./aux-config])	# Put config files in aux-config
 AC_CONFIG_MACRO_DIR([m4])			# m4 macros are located in m4
Index: issm/trunk/etc/environment.sh
===================================================================
--- issm/trunk/etc/environment.sh	(revision 27035)
+++ issm/trunk/etc/environment.sh	(revision 27232)
@@ -299,4 +299,13 @@
 fi
 
+HDF5_ROOT="${ISSM_EXT_DIR}/hdf5/install"
+if [ -d "${HDF5_ROOT}" ]; then
+	export HDF5_ROOT # Used in installation of NetCDF, GDAL
+	cpath_append "${HDF5_ROOT}/include"
+	library_path_append "${HDF5_ROOT}/lib"
+	dyld_library_path_append "${HDF5_ROOT}/lib"
+	ld_library_path_append "${HDF5_ROOT}/lib"
+fi
+
 LAPACK_ROOT="${ISSM_EXT_DIR}/lapack/install"
 if [ -d "${LAPACK_ROOT}" ]; then
@@ -308,4 +317,8 @@
 		path_append "${LAPACK_ROOT}/lib" # Allows dynamic loader to find DLLs
 	fi
+
+	if ls ${LAPACK_ROOT}/lib/libblas.* 1> /dev/null 2>&1; then
+		export BLAS_ROOT="${LAPACK_ROOT}"
+	fi
 fi
 
@@ -340,4 +353,11 @@
 		path_append "${PARMETIS_ROOT}/lib" # Allows dynamic loader to find DLLs
 	fi
+fi
+
+QD_ROOT="${ISSM_EXT_DIR}/qd/install"
+if [ -d "${QD_ROOT}" ]; then
+	export QD_ROOT # Used in installation of MPLAPACK
+	library_path_prepend "${QD_ROOT}/lib"
+	ld_library_path_prepend "${QD_ROOT}/lib"
 fi
 
@@ -430,23 +450,4 @@
 ld_library_path_append "${TAO_ROOT}/lib"
 
-DAKOTA_ROOT="${ISSM_EXT_DIR}/dakota/install"
-if [ -d "${DAKOTA_ROOT}" ]; then
-	path_append "${DAKOTA_ROOT}/bin"
-	ld_library_path_append "${DAKOTA_ROOT}/lib"
-	dyld_library_path_prepend "${DAKOTA_ROOT}/lib"
-fi
-
-NCO_ROOT="${ISSM_EXT_DIR}/nco/install/bin"
-path_prepend "${NCO_ROOT}/bin"
-
-CPPCHECK_ROOT="${ISSM_EXT_DIR}/cppcheck/install"
-path_append "${CPPCHECK_ROOT}/bin"
-
-MERCURIAL_ROOT="${ISSM_EXT_DIR}/mercurial/install"
-if [ -d "${MERCURIAL_ROOT}" ]; then
-	export PYTHONPATH="${PYTHONPATH}:${MERCURIAL_ROOT}/mercurial/pure/"
-	path_append "${MERCURIAL_ROOT}"
-fi
-
 BOOST_ROOT="${ISSM_EXT_DIR}/boost/install"
 if [ -d "${BOOST_ROOT}" ]; then
@@ -454,8 +455,27 @@
 	export BOOST_DIR=${BOOST_ROOT}
 	export BOOSTROOT=${BOOST_ROOT}
-	library_path_append "${BOOST_ROOT}/lib"
-	ld_library_path_append "${BOOST_ROOT}/lib"
-	dyld_library_path_append "${BOOST_ROOT}/lib"
 	path_append "${BOOST_ROOT}/bin"
+	library_path_prepend "${BOOST_ROOT}/lib"
+	ld_library_path_prepend "${BOOST_ROOT}/lib"
+	dyld_library_path_prepend "${BOOST_ROOT}/lib"
+fi
+
+DAKOTA_ROOT="${ISSM_EXT_DIR}/dakota/install"
+if [ -d "${DAKOTA_ROOT}" ]; then
+	path_append "${DAKOTA_ROOT}/bin"
+	ld_library_path_prepend "${DAKOTA_ROOT}/lib"
+	dyld_library_path_prepend "${DAKOTA_ROOT}/lib"
+fi
+
+NCO_ROOT="${ISSM_EXT_DIR}/nco/install/bin"
+path_prepend "${NCO_ROOT}/bin"
+
+CPPCHECK_ROOT="${ISSM_EXT_DIR}/cppcheck/install"
+path_append "${CPPCHECK_ROOT}/bin"
+
+MERCURIAL_ROOT="${ISSM_EXT_DIR}/mercurial/install"
+if [ -d "${MERCURIAL_ROOT}" ]; then
+	export PYTHONPATH="${PYTHONPATH}:${MERCURIAL_ROOT}/mercurial/pure/"
+	path_append "${MERCURIAL_ROOT}"
 fi
 
@@ -469,9 +489,9 @@
 if [ -d "${NETCDF_ROOT}" ]; then
 	export NETCDF_ROOT # Used in installation of GDAL, GMT
-	path_append "${NETCDF_ROOT}/bin"
-	cpath_append "${NETCDF_ROOT}/include"
-	library_path_append "${NETCDF_ROOT}/lib"
-	dyld_library_path_append "${NETCDF_ROOT}/lib"
-	ld_library_path_append "${NETCDF_ROOT}/lib"
+	path_prepend "${NETCDF_ROOT}/bin"
+	cpath_prepend "${NETCDF_ROOT}/include"
+	library_path_prepend "${NETCDF_ROOT}/lib"
+	dyld_library_path_prepend "${NETCDF_ROOT}/lib"
+	ld_library_path_prepend "${NETCDF_ROOT}/lib"
 fi
 
@@ -491,16 +511,8 @@
 if [ -d "${CURL_ROOT}" ]; then
 	export CURL_ROOT # Used in installation of NetCDF, GDAL, GMT
-	ld_library_path_append "${CURL_ROOT}/lib"
-	dyld_library_path_append "${CURL_ROOT}/lib"
+	cpath_prepend "${CURL_ROOT}/include"
+	ld_library_path_prepend "${CURL_ROOT}/lib"
+	dyld_library_path_prepend "${CURL_ROOT}/lib"
 	path_append "${CURL_ROOT}/bin"
-fi
-
-HDF5_ROOT="${ISSM_EXT_DIR}/hdf5/install"
-if [ -d "${HDF5_ROOT}" ]; then
-	export HDF5_ROOT # Used in installation of NetCDF, GDAL
-	cpath_append "${HDF5_ROOT}/include"
-	library_path_append "${HDF5_ROOT}/lib"
-	dyld_library_path_append "${HDF5_ROOT}/lib"
-	ld_library_path_append "${HDF5_ROOT}/lib"
 fi
 
Index: issm/trunk/examples/Greenland/runme.m
===================================================================
--- issm/trunk/examples/Greenland/runme.m	(revision 27035)
+++ issm/trunk/examples/Greenland/runme.m	(revision 27232)
@@ -21,5 +21,5 @@
 
 	%Mesh Greenland
-	md=bamg(md,'hmax',400000,'hmin',5000,'gradation',1.7,'field',vel,'err',8);
+	md=bamg(md,'hmax',400000,'hmin',5000,'gradation',1.4,'field',vel,'err',8);
 
 	%convert x,y coordinates (Polar stereo) to lat/lon
@@ -56,5 +56,5 @@
 	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,3);
 	md.inversion.cost_functions_coefficients(:,1)=350;
-	md.inversion.cost_functions_coefficients(:,2)=0.6;
+	md.inversion.cost_functions_coefficients(:,2)=0.2;
 	md.inversion.cost_functions_coefficients(:,3)=2e-6;
 
Index: issm/trunk/examples/Greenland/runme.py
===================================================================
--- issm/trunk/examples/Greenland/runme.py	(revision 27035)
+++ issm/trunk/examples/Greenland/runme.py	(revision 27232)
@@ -42,5 +42,5 @@
 
     #Mesh Greenland
-    md = bamg(md, 'hmax', 400000, 'hmin', 5000, 'gradation', 1.7, 'field', vel, 'err', 8)
+    md = bamg(md, 'hmax', 400000, 'hmin', 5000, 'gradation', 1.4, 'field', vel, 'err', 8)
 
     #convert x, y coordinates (Polar stereo) to lat / lon
@@ -77,5 +77,5 @@
     md.inversion.cost_functions_coefficients = np.ones((md.mesh.numberofvertices, 3))
     md.inversion.cost_functions_coefficients[:, 0] = 350
-    md.inversion.cost_functions_coefficients[:, 1] = 0.6
+    md.inversion.cost_functions_coefficients[:, 1] = 0.2
     md.inversion.cost_functions_coefficients[:, 2] = 2e-6
 
Index: issm/trunk/examples/Inversion/runme.m
===================================================================
--- issm/trunk/examples/Inversion/runme.m	(revision 27035)
+++ issm/trunk/examples/Inversion/runme.m	(revision 27232)
@@ -1,3 +1,3 @@
-steps=[4];
+steps=[1];
 
 if any(steps==1) 
Index: issm/trunk/examples/UncertaintyQuantification/runme.m
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/runme.m	(revision 27035)
+++ issm/trunk/examples/UncertaintyQuantification/runme.m	(revision 27232)
@@ -5,4 +5,5 @@
 	disp('   Step 1: plot flux gates');
 
+	% NOTE: Need to run all steps of ../Pig/runme.m first!
 	md = loadmodel('../Pig/Models/PIG_Control_drag');
 
Index: issm/trunk/externalpackages/autotools/install-linux.sh
===================================================================
--- issm/trunk/externalpackages/autotools/install-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/autotools/install-linux.sh	(revision 27232)
@@ -60,4 +60,5 @@
 fi
 cd ..
+
 # Install Automake
 echo " === INSTALLING AUTOMAKE ==="
Index: issm/trunk/externalpackages/boost/install-1.7-mac.sh
===================================================================
--- issm/trunk/externalpackages/boost/install-1.7-mac.sh	(revision 27035)
+++ issm/trunk/externalpackages/boost/install-1.7-mac.sh	(revision 27232)
@@ -54,2 +54,10 @@
 	install_name_tool -id ${PREFIX}/lib/${name} ${name} 2>/dev/null
 done
+
+if [ "${VER}" == "1_79_0" ]; then
+	## Patch install names for certain libraries
+	#
+	# TODO: Figure out how to reconfigure source to apply these install names at compile time
+	#
+	install_name_tool -change @rpath/libboost_atomic.dylib ${PREFIX}/lib/libboost_atomic.dylib libboost_filesystem.dylib
+fi
Index: issm/trunk/externalpackages/chaco/install.sh
===================================================================
--- issm/trunk/externalpackages/chaco/install.sh	(revision 27035)
+++ issm/trunk/externalpackages/chaco/install.sh	(revision 27232)
@@ -8,4 +8,8 @@
 
 PREFIX="${ISSM_DIR}/externalpackages/chaco/install" # Set to location where external package should be installed
+
+## Environment
+#
+export CFLAGS="-Wno-error=implicit-function-declaration"
 
 # Cleanup
Index: issm/trunk/externalpackages/curl/install-7-linux-static.sh
===================================================================
--- issm/trunk/externalpackages/curl/install-7-linux-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/curl/install-7-linux-static.sh	(revision 27232)
@@ -34,4 +34,5 @@
 	--disable-ldaps \
 	--with-zlib="${ZLIB_ROOT}" \
+	--without-zstd \
 	--without-libidn2 \
 	--without-nghttp2 \
Index: issm/trunk/externalpackages/curl/install-7-mac-static.sh
===================================================================
--- issm/trunk/externalpackages/curl/install-7-mac-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/curl/install-7-mac-static.sh	(revision 27232)
@@ -38,4 +38,5 @@
 	--disable-ldaps \
 	--with-zlib="${ZLIB_ROOT}" \
+	--without-zstd \
 	--without-libidn2 \
 	--without-nghttp2 \
Index: issm/trunk/externalpackages/dakota/install-6.2-linux-static.sh
===================================================================
--- issm/trunk/externalpackages/dakota/install-6.2-linux-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/dakota/install-6.2-linux-static.sh	(revision 27232)
@@ -9,12 +9,20 @@
 PREFIX="${ISSM_DIR}/externalpackages/dakota/install" # Set to location where external package should be installed
 
+# Find libgfortran and libgcc so we do not have to hardcode them
+#
+# TODO:
+# - Move this to etc/environment.sh
+#
+LIBGFORTRAN=$(find /usr -name libgfortran* | egrep -n libgfortran.a | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
+LIBGCC=$(find ${LIBGFORTRAN_ROOT} -name libgcc* | egrep -n libgcc.a | sed "s/[0-9]*://g" | head -1
+
 ## Environment
 #
-export BLAS_LIBS="-L${BLAS_ROOT}/lib -lfblas -L/usr/lib/x86_64-linux-gnu -lgfortran" # Need to export BLAS_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
-export CXXFLAGS='-std=c++98' # Setting CXXFLAGS to deal with C++11 incompatibility with MATLAB's Boost (absolutely necessary for this version)
+export BLAS_LIBS="-L${BLAS_ROOT}/lib -lfblas ${LIBGFORTRAN_ROOT}/libgfortran.a ${LIBGFORTRAN_ROOT}/libquadmath.a ${LIBGCC}" # Need to export BLAS_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
 export DAK_BUILD=${ISSM_DIR}/externalpackages/dakota/build # DO NOT CHANGE THIS
 export DAK_INSTALL=${PREFIX} # DO NOT CHANGE THIS
 export DAK_SRC=${ISSM_DIR}/externalpackages/dakota/src # DO NOT CHANGE THIS
-export LAPACK_LIBS="-L${LAPACK_ROOT}/lib -lflapack -L/usr/lib/x86_64-linux-gnu -lgfortran" # Need to export LAPACK_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
+export LAPACK_LIBS="-L${LAPACK_ROOT}/lib -lflapack -L/usr/lib/x86_64-linux-gnu ${LIBGFORTRAN_ROOT}/libgfortran.a ${LIBGFORTRAN_ROOT}/libquadmath.a ${LIBGCC}" # Need to export LAPACK_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
 
 # Cleanup
@@ -45,4 +53,7 @@
 cp configs/${VER}/linux/cmake/DakotaDev.cmake ${DAK_SRC}/cmake
 
+# Disable requirement of Python 2 for TriBITS
+sed -i'' -e 's|SET(PythonInterp_FIND_VERSION|#SET(PythonInterp_FIND_VERSION|' ${DAK_SRC}/packages/teuchos/cmake/tribits/package_arch/TribitsFindPythonInterp.cmake
+
 # Configure
 cd ${DAK_BUILD}
@@ -54,4 +65,5 @@
 	-DCMAKE_CXX_COMPILER=${MPI_HOME}/bin/mpicxx \
 	-DCMAKE_CXX_FLAGS="-fPIC" \
+	-DCMAKE_CXX_STANDARD="11" \
 	-DCMAKE_Fortran_COMPILER=${MPI_HOME}/bin/mpif77 \
 	-DBoost_NO_BOOST_CMAKE=TRUE \
Index: issm/trunk/externalpackages/dakota/install-6.2-linux.sh
===================================================================
--- issm/trunk/externalpackages/dakota/install-6.2-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/dakota/install-6.2-linux.sh	(revision 27232)
@@ -12,6 +12,4 @@
 #
 export BLAS_LIBS="-L${BLAS_ROOT}/lib -lfblas -L/usr/lib/x86_64-linux-gnu -lgfortran" # Need to export BLAS_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
-export CXXFLAGS='-std=c++98' # Setting CXXFLAGS to deal with C++11 incompatibility with MATLAB's Boost (absolutely necessary for this version)
-#export CXXFLAGS='-std=c++11'
 export DAK_BUILD=${ISSM_DIR}/externalpackages/dakota/build # DO NOT CHANGE THIS
 export DAK_INSTALL=${PREFIX} # DO NOT CHANGE THIS
@@ -46,4 +44,7 @@
 cp configs/${VER}/linux/cmake/DakotaDev.cmake ${DAK_SRC}/cmake
 
+# Disable requirement of Python 2 for TriBITS
+sed -i'' -e 's|SET(PythonInterp_FIND_VERSION|#SET(PythonInterp_FIND_VERSION|' ${DAK_SRC}/packages/teuchos/cmake/tribits/package_arch/TribitsFindPythonInterp.cmake
+
 # Configure
 cd ${DAK_BUILD}
@@ -54,4 +55,5 @@
 	-DCMAKE_C_FLAGS="-Wno-error=implicit-function-declaration" \
 	-DCMAKE_CXX_COMPILER=${MPI_HOME}/bin/mpicxx \
+	-DCMAKE_CXX_STANDARD="11" \
 	-DCMAKE_Fortran_COMPILER=${MPI_HOME}/bin/mpif77 \
 	-DBoost_NO_BOOST_CMAKE=TRUE \
Index: issm/trunk/externalpackages/dakota/install-6.2-mac-static.sh
===================================================================
--- issm/trunk/externalpackages/dakota/install-6.2-mac-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/dakota/install-6.2-mac-static.sh	(revision 27232)
@@ -8,7 +8,4 @@
 
 PREFIX="${ISSM_DIR}/externalpackages/dakota/install" # Set to location where external package should be installed
-
-## Environment
-#
 
 # Find libgfortran and libgcc so we do not have to hardcode them.
@@ -22,8 +19,10 @@
 # - Otherwise, refactor this to work with other gfortran installations
 #
-LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | grep -n libgfortran.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | egrep -n libgfortran.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
 LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
-LIBGCC=$(mdfind -onlyin ${LIBGFORTRAN_ROOT} -name libgcc | grep -n libgcc.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGCC=$(mdfind -onlyin ${LIBGFORTRAN_ROOT} -name libgcc | egrep -n libgcc.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
 
+## Environment
+#
 export BLAS_LIBS="-L${BLAS_ROOT}/lib -lfblas ${LIBGFORTRAN_ROOT}/libgfortran.a ${LIBGFORTRAN_ROOT}/libquadmath.a ${LIBGCC}" # Need to export BLAS_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
 export DAK_BUILD=${ISSM_DIR}/externalpackages/dakota/build # DO NOT CHANGE THIS
@@ -72,4 +71,7 @@
 # cp configs/${VER}/mac/static/packages/nidr/nidr-scanner.c ${DAK_SRC}/packages/nidr
 
+# Disable requirement of Python 2 for TriBITS
+sed -i'' -e 's|SET(PythonInterp_FIND_VERSION|#SET(PythonInterp_FIND_VERSION|' ${DAK_SRC}/packages/teuchos/cmake/tribits/package_arch/TribitsFindPythonInterp.cmake
+
 # Configure
 cd ${DAK_BUILD}
@@ -81,4 +83,5 @@
 	-DCMAKE_CXX_COMPILER=${MPI_HOME}/bin/mpicxx \
 	-DCMAKE_CXX_FLAGS="-fPIC -fdelayed-template-parsing" \
+	-DCMAKE_CXX_STANDARD="11" \
 	-DCMAKE_Fortran_COMPILER=${MPI_HOME}/bin/mpif77 \
 	-DCMAKE_Fortran_FLAGS="-fPIC -fallow-argument-mismatch" \
Index: issm/trunk/externalpackages/dakota/install-6.2-mac.sh
===================================================================
--- issm/trunk/externalpackages/dakota/install-6.2-mac.sh	(revision 27035)
+++ issm/trunk/externalpackages/dakota/install-6.2-mac.sh	(revision 27232)
@@ -9,7 +9,4 @@
 PREFIX="${ISSM_DIR}/externalpackages/dakota/install" # Set to location where external package should be installed
 
-## Environment
-#
-
 # Find libgfortran so that we do not have to hardcode it.
 #
@@ -20,7 +17,9 @@
 # - Move this to etc/environment.sh
 #
-LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | grep -n libgfortran.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | egrep -n libgfortran.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
 LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
 
+## Environment
+#
 export BLAS_LIBS="-L${BLAS_ROOT}/lib -lfblas -L${LIBGFORTRAN_ROOT} -lgfortran" # Need to export BLAS_LIBS *and* pass it as an option to CMake to ensure that external packages also find it
 export DAK_BUILD=${ISSM_DIR}/externalpackages/dakota/build # DO NOT CHANGE THIS
@@ -57,4 +56,7 @@
 cp configs/${VER}/mac/cmake/InstallDarwinDylibs.cmake ${DAK_SRC}/cmake
 
+# Disable requirement of Python 2 for TriBITS
+sed -i'' -e 's|SET(PythonInterp_FIND_VERSION|#SET(PythonInterp_FIND_VERSION|' ${DAK_SRC}/packages/teuchos/cmake/tribits/package_arch/TribitsFindPythonInterp.cmake
+
 # Configure
 cd ${DAK_BUILD}
@@ -65,6 +67,6 @@
 	-DCMAKE_CXX_COMPILER=${MPI_HOME}/bin/mpicxx \
 	-DCMAKE_CXX_FLAGS="-fdelayed-template-parsing" \
+	-DCMAKE_CXX_STANDARD="11" \
 	-DCMAKE_Fortran_COMPILER=${MPI_HOME}/bin/mpif77 \
-	-DCMAKE_Fortran_FLAGS="-fallow-argument-mismatch" \
 	-DBoost_NO_BOOST_CMAKE=TRUE \
 	-DHAVE_ACRO=OFF \
Index: issm/trunk/externalpackages/gdal/install-3-python-static.sh
===================================================================
--- issm/trunk/externalpackages/gdal/install-3-python-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/gdal/install-3-python-static.sh	(revision 27232)
@@ -9,5 +9,5 @@
 ## Constants
 #
-VER="3.1.1"
+VER="3.5.1"
 
 ## Environment
@@ -42,10 +42,15 @@
 	--enable-static \
 	--with-pic \
-	--with-python \
+	--with-python=python3 \
+	--with-curl="${CURL_ROOT}/bin/curl-config" \
+	--with-hdf5="${HDF5_ROOT}" \
+	--with-jpeg=internal \
 	--with-libz="${ZLIB_ROOT}" \
-	--with-hdf5="${HDF5_ROOT}" \
 	--with-netcdf="${NETCDF_ROOT}" \
+	--with-pcre=no \
+	--with-pg=no \
+	--with-png=internal \
 	--with-proj="${PROJ_ROOT}" \
-	--with-pg=no
+	--with-zstd=no
 
 # Compile and install
Index: issm/trunk/externalpackages/gdal/install-3-python.sh
===================================================================
--- issm/trunk/externalpackages/gdal/install-3-python.sh	(revision 27035)
+++ issm/trunk/externalpackages/gdal/install-3-python.sh	(revision 27232)
@@ -9,5 +9,5 @@
 ## Constants
 #
-VER="3.1.1"
+VER="3.5.1"
 
 ## Environment
@@ -34,7 +34,7 @@
 	--prefix="${PREFIX}" \
 	--enable-fast-install \
-	--with-python \
+	--with-python=python3 \
+	--with-hdf5="${HDF5_ROOT}" \
 	--with-libz="${ZLIB_ROOT}" \
-	--with-hdf5="${HDF5_ROOT}" \
 	--with-netcdf="${NETCDF_ROOT}" \
 	--with-proj="${PROJ_ROOT}"
Index: issm/trunk/externalpackages/gdal/install-3-static.sh
===================================================================
--- issm/trunk/externalpackages/gdal/install-3-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/gdal/install-3-static.sh	(revision 27232)
@@ -9,5 +9,5 @@
 ## Constants
 #
-VER="3.1.1"
+VER="3.5.1"
 
 ## Environment
@@ -42,9 +42,14 @@
 	--enable-static \
 	--with-pic \
+	--with-curl="${CURL_ROOT}/bin/curl-config" \
+	--with-hdf5="${HDF5_ROOT}" \
+	--with-jpeg=internal \
 	--with-libz="${ZLIB_ROOT}" \
-	--with-hdf5="${HDF5_ROOT}" \
 	--with-netcdf="${NETCDF_ROOT}" \
+	--with-pcre=no \
+	--with-pg=no \
+	--with-png=internal \
 	--with-proj="${PROJ_ROOT}" \
-	--with-pg=no
+	--with-zstd=no
 
 # Compile and install
Index: issm/trunk/externalpackages/gdal/install-3.sh
===================================================================
--- issm/trunk/externalpackages/gdal/install-3.sh	(revision 27035)
+++ issm/trunk/externalpackages/gdal/install-3.sh	(revision 27232)
@@ -5,5 +5,5 @@
 ## Constants
 #
-VER="3.1.1"
+VER="3.5.1"
 
 ## Environment
@@ -30,6 +30,6 @@
 	--prefix="${PREFIX}" \
 	--enable-fast-install \
+	--with-hdf5="${HDF5_ROOT}" \
 	--with-libz="${ZLIB_ROOT}" \
-	--with-hdf5="${HDF5_ROOT}" \
 	--with-netcdf="${NETCDF_ROOT}" \
 	--with-proj="${PROJ_ROOT}"
Index: issm/trunk/externalpackages/gmsh/install-4-linux-static.sh
===================================================================
--- issm/trunk/externalpackages/gmsh/install-4-linux-static.sh	(revision 27232)
+++ issm/trunk/externalpackages/gmsh/install-4-linux-static.sh	(revision 27232)
@@ -0,0 +1,83 @@
+#!/bin/bash
+set -eu
+
+
+# TODO:
+# - Add support for,
+#	- MUMPS
+#	- PETSc
+# 
+# See Also:
+# - configs/4/static/CMakeLists.txt
+# - http://gmsh.info/doc/texinfo/gmsh.html#Compiling-the-source-code
+#
+
+## Constants
+#
+VER="4.10.5"
+
+PREFIX="${ISSM_DIR}/externalpackages/gmsh/install" # Set to location where external package should be installed
+
+# Find libgfortran and libgcc so we do not have to hardcode them
+#
+# TODO:
+# - Move this to etc/environment.sh
+#
+LIBGFORTRAN=$(find /usr -name libgfortran* | egrep -n libgfortran.a | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
+LIBGCC=$(find ${LIBGFORTRAN_ROOT} -name libgcc* | egrep -n libgcc.a | sed "s/[0-9]*://g" | head -1)
+
+# Cleanup
+rm -rf ${PREFIX} src
+mkdir -p ${PREFIX} src
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmsh-${VER}-source.tgz" "gmsh-${VER}-source.tgz"
+
+# Unpack source
+tar -xvzf gmsh-${VER}-source.tgz
+
+# Move source to 'src' directory
+mv gmsh-${VER}-source/* src
+rm -rf gmsh-${VER}-source
+
+# Configure
+#
+# NOTE:
+# - Option -DENABLE_FLTK=0 is used because we do not need GUI.
+# - Option -DENABLE_MPEG_ENCODE=0 is used because we do not need to record MPEG 
+#	movies.
+# - Option -DENABLE_OCC=0 is used because we do not need CAD kernel and are not 
+#	importing STEP/IGES files.
+# - Option -DENABLE_TOUCHBAR=0 is used because we do not have GUI, therefore we 
+#	do not need to support Apple Touch bar (does not affect compilation on 
+#	Linux).
+#
+cd src
+cmake \
+	-DCMAKE_INSTALL_PREFIX="${PREFIX}" \
+	-DENABLE_BUILD_LIB=1 \
+	-DBLAS_LAPACK_LIBRARIES="-L${LAPACK_ROOT}/lib -lflapack -L${BLAS_ROOT}/lib -lfblas ${LIBGFORTRAN_ROOT}/libgfortran.a ${LIBGFORTRAN_ROOT}/libquadmath.a ${LIBGCC}" \
+	-DENABLE_BLAS_LAPACK=1 \
+	-DENABLE_EIGEN=0 \
+	-DENABLE_FLTK=0 \
+	-DENABLE_MPEG_ENCODE=0 \
+	-DENABLE_MPI=1 \
+	-DENABLE_OCC=0 \
+	-DENABLE_TOUCHBAR=0 \
+	-DMETIS_ROOT="${METIS_ROOT}"
+
+# Compile and install
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+
+# Make necessary link on RHEL
+if [[ -d ${PREFIX}/lib64 && ! -d ${PREFIX}/lib ]]; then
+	cd ${PREFIX}
+	ln -s ./lib64 ./lib
+fi
Index: issm/trunk/externalpackages/gmsh/install-4-linux.sh
===================================================================
--- issm/trunk/externalpackages/gmsh/install-4-linux.sh	(revision 27232)
+++ issm/trunk/externalpackages/gmsh/install-4-linux.sh	(revision 27232)
@@ -0,0 +1,83 @@
+#!/bin/bash
+set -eu
+
+
+# TODO:
+# - Add support for,
+#	- MUMPS
+#	- PETSc
+# 
+# See Also:
+# - configs/4/static/CMakeLists.txt
+# - http://gmsh.info/doc/texinfo/gmsh.html#Compiling-the-source-code
+#
+
+## Constants
+#
+VER="4.10.5"
+
+PREFIX="${ISSM_DIR}/externalpackages/gmsh/install" # Set to location where external package should be installed
+
+# Find libgfortran so that we do not have to hardcode it.
+#
+# TODO:
+# - Move this to etc/environment.sh
+#
+LIBGFORTRAN=$(find /usr -name libgfortran* | egrep -n libgfortran.a | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
+
+# Cleanup
+rm -rf ${PREFIX} src
+mkdir -p ${PREFIX} src
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmsh-${VER}-source.tgz" "gmsh-${VER}-source.tgz"
+
+# Unpack source
+tar -xvzf gmsh-${VER}-source.tgz
+
+# Move source to 'src' directory
+mv gmsh-${VER}-source/* src
+rm -rf gmsh-${VER}-source
+
+# Configure
+#
+# NOTE:
+# - Option -DENABLE_FLTK=0 is used because we do not need GUI.
+# - Option -DENABLE_MPEG_ENCODE=0 is used because we do not need to record MPEG 
+#	movies.
+# - Option -DENABLE_OCC=0 is used because we do not need CAD kernel and are not 
+#	importing STEP/IGES files.
+# - Option -DENABLE_TOUCHBAR=0 is used because we do not have GUI, therefore we 
+#	do not need to support Apple Touch bar (does not affect compilation on 
+#	Linux).
+#
+cd src
+cmake \
+	-DCMAKE_INSTALL_PREFIX="${PREFIX}" \
+	-DENABLE_BUILD_DYNAMIC=1 \
+	-DENABLE_BUILD_SHARED=1 \
+	-DBLAS_LAPACK_LIBRARIES="-L${LAPACK_ROOT}/lib -lflapack -L${BLAS_ROOT}/lib -lfblas -L${LIBGFORTRAN_ROOT} -lgfortran" \
+	-DENABLE_BLAS_LAPACK=1 \
+	-DENABLE_EIGEN=0 \
+	-DENABLE_FLTK=0 \
+	-DENABLE_MPEG_ENCODE=0 \
+	-DENABLE_MPI=1 \
+	-DENABLE_OCC=0 \
+	-DENABLE_TOUCHBAR=0 \
+	-DMETIS_ROOT="${METIS_ROOT}"
+
+# Compile and install
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+
+# Make necessary link on RHEL
+if [[ -d ${PREFIX}/lib64 && ! -d ${PREFIX}/lib ]]; then
+	cd ${PREFIX}
+	ln -s ./lib64 ./lib
+fi
Index: issm/trunk/externalpackages/gmsh/install-4-mac-static.sh
===================================================================
--- issm/trunk/externalpackages/gmsh/install-4-mac-static.sh	(revision 27232)
+++ issm/trunk/externalpackages/gmsh/install-4-mac-static.sh	(revision 27232)
@@ -0,0 +1,91 @@
+#!/bin/bash
+set -eu
+
+
+# TODO:
+# - Add support for,
+#	- MUMPS
+#	- PETSc
+# 
+# See Also:
+# - configs/4/static/CMakeLists.txt
+# - http://gmsh.info/doc/texinfo/gmsh.html#Compiling-the-source-code
+#
+
+## Constants
+#
+VER="4.10.5"
+
+PREFIX="${ISSM_DIR}/externalpackages/gmsh/install" # Set to location where external package should be installed
+
+
+# Find libgfortran and libgcc so we do not have to hardcode them
+#
+# Should retrieve a copy of gfortran that is compiled from source before returning one that is installed via package manager
+#
+# TODO:
+# - Move this to etc/environment.sh
+# - Test if -static-libgfortran flag will avoid all of this.
+# - Otherwise, refactor this to work with other gfortran installations.
+#
+LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | egrep -n libgfortran.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
+LIBGCC=$(mdfind -onlyin ${LIBGFORTRAN_ROOT} -name libgcc | egrep -n libgcc.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
+
+# Cleanup
+rm -rf ${PREFIX} src
+mkdir -p ${PREFIX} src
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmsh-${VER}-source.tgz" "gmsh-${VER}-source.tgz"
+
+# Unpack source
+tar -xvzf gmsh-${VER}-source.tgz
+
+# Move source to 'src' directory
+mv gmsh-${VER}-source/* src
+rm -rf gmsh-${VER}-source
+
+# Copy customized source and config files to 'src' directory
+cp configs/${VER}/static/CMakeLists.txt src
+
+# Configure
+#
+# NOTE:
+# - Option -DENABLE_FLTK=0 is used because we do not need GUI.
+# - Option -DENABLE_MPEG_ENCODE=0 is used because we do not need to record MPEG 
+#	movies.
+# - Option -DENABLE_OCC=0 is used because we do not need CAD kernel and are not 
+#	importing STEP/IGES files.
+# - Option -DENABLE_TOUCHBAR=0 is used because we do not have GUI, therefore we 
+#	do not need to support Apple Touch bar (does not affect compilation on 
+#	Linux).
+#
+cd src
+cmake \
+	-DCMAKE_INSTALL_PREFIX="${PREFIX}" \
+	-DENABLE_BUILD_LIB=1 \
+	-DBLAS_LAPACK_LIBRARIES="-L${LAPACK_ROOT}/lib -lflapack -L${BLAS_ROOT}/lib -lfblas ${LIBGFORTRAN_ROOT}/libgfortran.a ${LIBGFORTRAN_ROOT}/libquadmath.a ${LIBGCC}" \
+	-DENABLE_BLAS_LAPACK=1 \
+	-DENABLE_EIGEN=0 \
+	-DENABLE_FLTK=0 \
+	-DENABLE_MPEG_ENCODE=0 \
+	-DENABLE_MPI=1 \
+	-DENABLE_OCC=0 \
+	-DENABLE_TOUCHBAR=0 \
+	-DMETIS_ROOT="${METIS_ROOT}"
+
+# Compile and install
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+
+# Make necessary link on RHEL
+if [[ -d ${PREFIX}/lib64 && ! -d ${PREFIX}/lib ]]; then
+	cd ${PREFIX}
+	ln -s ./lib64 ./lib
+fi
Index: issm/trunk/externalpackages/gmsh/install-4-mac.sh
===================================================================
--- issm/trunk/externalpackages/gmsh/install-4-mac.sh	(revision 27232)
+++ issm/trunk/externalpackages/gmsh/install-4-mac.sh	(revision 27232)
@@ -0,0 +1,86 @@
+#!/bin/bash
+set -eu
+
+
+# TODO:
+# - Add support for,
+#	- MUMPS
+#	- PETSc
+# 
+# See Also:
+# - configs/4/static/CMakeLists.txt
+# - http://gmsh.info/doc/texinfo/gmsh.html#Compiling-the-source-code
+#
+
+## Constants
+#
+VER="4.10.5"
+
+PREFIX="${ISSM_DIR}/externalpackages/gmsh/install" # Set to location where external package should be installed
+
+# Find libgfortran so that we do not have to hardcode it.
+#
+# Should retrieve a copy of gfortran that is compiled from source before 
+# returning one that is installed via package manager.
+#
+# TODO:
+# - Move this to etc/environment.sh
+#
+LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | egrep -n libgfortran.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
+
+# Cleanup
+rm -rf ${PREFIX} src
+mkdir -p ${PREFIX} src
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmsh-${VER}-source.tgz" "gmsh-${VER}-source.tgz"
+
+# Unpack source
+tar -xvzf gmsh-${VER}-source.tgz
+
+# Move source to 'src' directory
+mv gmsh-${VER}-source/* src
+rm -rf gmsh-${VER}-source
+
+# Configure
+#
+# NOTE:
+# - Option -DENABLE_FLTK=0 is used because we do not need GUI.
+# - Option -DENABLE_MPEG_ENCODE=0 is used because we do not need to record MPEG 
+#	movies.
+# - Option -DENABLE_OCC=0 is used because we do not need CAD kernel and are not 
+#	importing STEP/IGES files.
+# - Option -DENABLE_TOUCHBAR=0 is used because we do not have GUI, therefore we 
+#	do not need to support Apple Touch bar (does not affect compilation on 
+#	Linux).
+#
+cd src
+cmake \
+	-DCMAKE_INSTALL_PREFIX="${PREFIX}" \
+	-DENABLE_BUILD_DYNAMIC=1 \
+	-DENABLE_BUILD_SHARED=1 \
+	-DBLAS_LAPACK_LIBRARIES="-L${LAPACK_ROOT}/lib -lflapack -L${BLAS_ROOT}/lib -lfblas -L${LIBGFORTRAN_ROOT} -lgfortran" \
+	-DENABLE_BLAS_LAPACK=1 \
+	-DENABLE_EIGEN=0 \
+	-DENABLE_FLTK=0 \
+	-DENABLE_MPEG_ENCODE=0 \
+	-DENABLE_MPI=1 \
+	-DENABLE_OCC=0 \
+	-DENABLE_TOUCHBAR=0 \
+	-DMETIS_ROOT="${METIS_ROOT}"
+
+# Compile and install
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+
+# Make necessary link on RHEL
+if [[ -d ${PREFIX}/lib64 && ! -d ${PREFIX}/lib ]]; then
+	cd ${PREFIX}
+	ln -s ./lib64 ./lib
+fi
Index: issm/trunk/externalpackages/gmsh/install-4-static.sh
===================================================================
--- issm/trunk/externalpackages/gmsh/install-4-static.sh	(revision 27035)
+++ 	(revision )
@@ -1,72 +1,0 @@
-#!/bin/bash
-set -eu
-
-
-# TODO:
-# - Add support for,
-#	- BLAS_LAPACK
-#	- MUMPS
-#	- PETSC
-# (see configs/4/static/CMakeLists.txt)
-#
-
-## Constants
-#
-VER="4.5.6"
-
-PREFIX="${ISSM_DIR}/externalpackages/gmsh/install" # Set to location where external package should be installed
-
-# Cleanup
-rm -rf ${PREFIX} src
-mkdir -p ${PREFIX} src
-
-# Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmsh-${VER}-source.tgz" "gmsh-${VER}-source.tgz"
-
-# Unpack source
-tar -xvzf gmsh-${VER}-source.tgz
-
-# Move source to 'src' directory
-mv gmsh-${VER}-source/* src
-rm -rf gmsh-${VER}-source
-
-# Copy customized source and config files to 'src' directory
-cp configs/${VER}/static/CMakeLists.txt src
-
-# Configure
-#
-# NOTE:
-# - Option -DENABLE_FLTK=0 is used because we do not need GUI.
-# - Option -DENABLE_MPEG_ENCODE=0 is used because we do not need to record MPEG 
-#	movies.
-# - Option -DENABLE_OCC=0 is used because we do not need CAD kernel and are not 
-#	importing STEP/IGES files.
-# - Option -DENABLE_TOUCHBAR=0 is used because we do not have GUI, therefore we 
-#	do not need to support Apple Touch bar (does not affect compilation on 
-#	Linux).
-#
-cd src
-cmake \
-	-DCMAKE_INSTALL_PREFIX="${PREFIX}" \
-	-DENABLE_BUILD_LIB=1 \
-	-DENABLE_FLTK=0 \
-	-DENABLE_MPEG_ENCODE=0 \
-	-DENABLE_MPI=1 \
-	-DENABLE_OCC=0 \
-	-DENABLE_TOUCHBAR=0 \
-	-DMETIS_ROOT="${METIS_ROOT}"
-
-# Compile and install
-if [ $# -eq 0 ]; then
-	make
-	make install
-else
-	make -j $1
-	make -j $1 install
-fi
-
-# Make necessary link on RHEL
-if [[ -d ${PREFIX}/lib64 && ! -d ${PREFIX}/lib ]]; then
-	cd ${PREFIX}
-	ln -s ./lib64 ./lib
-fi
Index: issm/trunk/externalpackages/gmsh/install-4.sh
===================================================================
--- issm/trunk/externalpackages/gmsh/install-4.sh	(revision 27035)
+++ 	(revision )
@@ -1,70 +1,0 @@
-#!/bin/bash
-set -eu
-
-
-# TODO:
-# - Add support for,
-#	- BLAS_LAPACK
-#	- MUMPS
-#	- PETSC
-# (see configs/4/static/CMakeLists.txt)
-#
-
-## Constants
-#
-VER="4.5.6"
-
-PREFIX="${ISSM_DIR}/externalpackages/gmsh/install" # Set to location where external package should be installed
-
-# Cleanup
-rm -rf ${PREFIX} src
-mkdir -p ${PREFIX} src
-
-# Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmsh-${VER}-source.tgz" "gmsh-${VER}-source.tgz"
-
-# Unpack source
-tar -xvzf gmsh-${VER}-source.tgz
-
-# Move source to 'src' directory
-mv gmsh-${VER}-source/* src
-rm -rf gmsh-${VER}-source
-
-# Configure
-#
-# NOTE:
-# - Option -DENABLE_FLTK=0 is used because we do not need GUI.
-# - Option -DENABLE_MPEG_ENCODE=0 is used because we do not need to record MPEG 
-#	movies.
-# - Option -DENABLE_OCC=0 is used because we do not need CAD kernel and are not 
-#	importing STEP/IGES files.
-# - Option -DENABLE_TOUCHBAR=0 is used because we do not have GUI, therefore we 
-#	do not need to support Apple Touch bar (does not affect compilation on 
-#	Linux).
-#
-cd src
-cmake \
-	-DCMAKE_INSTALL_PREFIX="${PREFIX}" \
-	-DENABLE_BUILD_DYNAMIC=1 \
-	-DENABLE_BUILD_SHARED=1 \
-	-DENABLE_FLTK=0 \
-	-DENABLE_MPEG_ENCODE=0 \
-	-DENABLE_MPI=1 \
-	-DENABLE_OCC=0 \
-	-DENABLE_TOUCHBAR=0 \
-	-DMETIS_ROOT="${METIS_ROOT}"
-
-# Compile and install
-if [ $# -eq 0 ]; then
-	make
-	make install
-else
-	make -j $1
-	make -j $1 install
-fi
-
-# Make necessary link on RHEL
-if [[ -d ${PREFIX}/lib64 && ! -d ${PREFIX}/lib ]]; then
-	cd ${PREFIX}
-	ln -s ./lib64 ./lib
-fi
Index: issm/trunk/externalpackages/gmt/configs/6/static/cmake/modules/FindGDAL.cmake
===================================================================
--- issm/trunk/externalpackages/gmt/configs/6/static/cmake/modules/FindGDAL.cmake	(revision 27035)
+++ issm/trunk/externalpackages/gmt/configs/6/static/cmake/modules/FindGDAL.cmake	(revision 27232)
@@ -148,4 +148,6 @@
 		NAMES ${_extralib}
 		HINTS
+		${NETCDF_ROOT}
+		$ENV{NETCDF_ROOT}
 		${HDF5_ROOT}
 		$ENV{HDF5_ROOT}
Index: issm/trunk/externalpackages/gmt/configs/6/static/cmake/modules/FindNETCDF.cmake
===================================================================
--- issm/trunk/externalpackages/gmt/configs/6/static/cmake/modules/FindNETCDF.cmake	(revision 27035)
+++ issm/trunk/externalpackages/gmt/configs/6/static/cmake/modules/FindNETCDF.cmake	(revision 27232)
@@ -130,5 +130,5 @@
 # find all manually-supplied libs
 if (NETCDF_EXTRA_LIBS)
-	# Ensure -l is precedeced by whitespace to not match
+	# Ensure -l is preceded by whitespace to not match
 	# '-l' in '-L/usr/lib/x86_64-linux-gnu/hdf5/serial'
 	string (REGEX MATCHALL "(^| )-l[^ ]+" _netcdf_extra_lib_dashl ${NETCDF_EXTRA_LIBS})
Index: issm/trunk/externalpackages/gmt/configs/6/static/linux/cmake/ConfigUser.static.cmake
===================================================================
--- issm/trunk/externalpackages/gmt/configs/6/static/linux/cmake/ConfigUser.static.cmake	(revision 27035)
+++ issm/trunk/externalpackages/gmt/configs/6/static/linux/cmake/ConfigUser.static.cmake	(revision 27232)
@@ -58,6 +58,6 @@
 # Exclude optional GDAL, PCRE, PCRE2, FFTW3, LAPACK, BLAS, ZLIB dependencies even if you have them installed [FALSE]
 #set (GMT_EXCLUDE_GDAL TRUE)
-#set (GMT_EXCLUDE_PCRE TRUE)
-#set (GMT_EXCLUDE_PCRE2 TRUE)
+set (GMT_EXCLUDE_PCRE TRUE)
+set (GMT_EXCLUDE_PCRE2 TRUE)
 #set (GMT_EXCLUDE_FFTW3 TRUE)
 #set (GMT_EXCLUDE_LAPACK TRUE)
@@ -112,5 +112,5 @@
 
 # Copy GSHHG files to ${GMT_DATADIR}/coast [FALSE]:
-#set (COPY_GSHHG TRUE)
+set (COPY_GSHHG TRUE)
 
 # Set path to DCW Digital Chart of the World for GMT [auto]:
Index: issm/trunk/externalpackages/gmt/configs/6/static/mac/cmake/ConfigUser.static.cmake
===================================================================
--- issm/trunk/externalpackages/gmt/configs/6/static/mac/cmake/ConfigUser.static.cmake	(revision 27035)
+++ issm/trunk/externalpackages/gmt/configs/6/static/mac/cmake/ConfigUser.static.cmake	(revision 27232)
@@ -58,6 +58,6 @@
 # Exclude optional GDAL, PCRE, PCRE2, FFTW3, LAPACK, BLAS, ZLIB dependencies even if you have them installed [FALSE]
 #set (GMT_EXCLUDE_GDAL TRUE)
-#set (GMT_EXCLUDE_PCRE TRUE)
-#set (GMT_EXCLUDE_PCRE2 TRUE)
+set (GMT_EXCLUDE_PCRE TRUE)
+set (GMT_EXCLUDE_PCRE2 TRUE)
 #set (GMT_EXCLUDE_FFTW3 TRUE)
 #set (GMT_EXCLUDE_LAPACK TRUE)
@@ -112,5 +112,5 @@
 
 # Copy GSHHG files to ${GMT_DATADIR}/coast [FALSE]:
-#set (COPY_GSHHG TRUE)
+set (COPY_GSHHG TRUE)
 
 # Set path to DCW Digital Chart of the World for GMT [auto]:
Index: issm/trunk/externalpackages/gmt/install-6-linux-static.sh
===================================================================
--- issm/trunk/externalpackages/gmt/install-6-linux-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/gmt/install-6-linux-static.sh	(revision 27232)
@@ -5,18 +5,14 @@
 ## Constants
 #
-VER="6.0.0"
+VER="6.4.0"
 
 # Find libgfortran and libgcc so we do not have to hardcode them
 #
-# NOTE: For now, paths are hardcoded.
-#
 # TODO:
 # - Move this to etc/environment.sh
-# - Figure out how to find and grep for single result like we do with mdfind 
-#	under macOS.
 #
-LIBGFORTRAN="/usr/lib/gcc/x86_64-linux-gnu/8/libgfortran.a"
+LIBGFORTRAN=$(find /usr -name libgfortran* | egrep -n libgfortran.a | sed "s/[0-9]*://g" | head -1)
 LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
-LIBGCC="/usr/lib/gcc/x86_64-linux-gnu/8/libgcc.a"
+LIBGCC=$(find ${LIBGFORTRAN_ROOT} -name libgcc* | egrep -n libgcc.a | sed "s/[0-9]*://g" | head -1)
 
 GDAL_EXTRA_LIBS="-lstdc++" # Determined by running `$GDAL_ROOT/bin/gdal-config --dep-libs` then removing duplicate libs
@@ -65,4 +61,6 @@
 cmake \
 	-DBLAS_LIBRARIES="${BLAS_ROOT}/lib/libfblas.a;${LIBGFORTRAN_ROOT}/libgfortran.a;${LIBGFORTRAN_ROOT}/libquadmath.a;${LIBGCC}" \
+	-DCURL_INCLUDE_DIR="${CURL_ROOT}/include" \
+	-DCURL_LIBRARY="${CURL_ROOT}/lib/libcurl.a" \
 	-DGDAL_EXTRA_LIBS="${GDAL_EXTRA_LIBS}" \
 	-DHDF5_ROOT="${HDF5_ROOT}" \
Index: issm/trunk/externalpackages/gmt/install-6-linux.sh
===================================================================
--- issm/trunk/externalpackages/gmt/install-6-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/gmt/install-6-linux.sh	(revision 27232)
@@ -5,5 +5,13 @@
 ## Constants
 #
-VER="6.0.0"
+VER="6.4.0"
+
+# Find libgfortran so that we do not have to hardcode it.
+#
+# TODO:
+# - Move this to etc/environment.sh
+#
+LIBGFORTRAN=$(find /usr -name libgfortran* | egrep -n libgfortran.a | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
 
 # Environment
@@ -42,6 +50,8 @@
 #
 cmake \
-	-DCURL_LIBRARY="${CURL_ROOT}/lib" \
+	-DBLAS_LIBRARIES="-L${BLAS_ROOT}/lib;-lfblas;-L${LIBGFORTRAN_ROOT};-lgfortran" \
 	-DCURL_INCLUDE_DIR="${CURL_ROOT}/include" \
+	-DCURL_LIBRARY="-L${CURL_ROOT}/lib;-lcurl" \
+	-DLAPACK_LIBRARIES="-L${LAPACK_ROOT}/lib;-lflapack;-L${LIBGFORTRAN_ROOT};-lgfortran" \
 	..
 
Index: issm/trunk/externalpackages/gmt/install-6-mac-static.sh
===================================================================
--- issm/trunk/externalpackages/gmt/install-6-mac-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/gmt/install-6-mac-static.sh	(revision 27232)
@@ -5,5 +5,5 @@
 ## Constants
 #
-VER="6.0.0"
+VER="6.4.0"
 
 # Find libgfortran and libgcc so we do not have to hardcode them
@@ -16,10 +16,10 @@
 # - Otherwise, refactor this to work with other gfortran installations.
 #
-LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | grep -n libgfortran.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | egrep -n libgfortran.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
 LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
-LIBGCC=$(mdfind -onlyin ${LIBGFORTRAN_ROOT} -name libgcc | grep -n libgcc.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGCC=$(mdfind -onlyin ${LIBGFORTRAN_ROOT} -name libgcc | egrep -n libgcc.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
 
-GDAL_EXTRA_LIBS="-lc++" # `$GDAL_ROOT/bin/gdal-config --dep-libs` does not report need to link to libc++ (see also customized configuration file ./configs/6.0/static/cmake/modules/FindGDAL.cmake)
-NETCDF_EXTRA_LIBS="-lsqlite3 -lpthread -ldl -liconv" # `$NETCDF_ROOT/bin/nc-config --libs` does not report certain dependencies of certain static libraries (see also customized configuration file ./configs/6.0/static/cmake/modules/FindNETCDF.cmake)
+GDAL_EXTRA_LIBS="-lc++" # `$GDAL_ROOT/bin/gdal-config --dep-libs` does not report need to link to libc++ (see also customized configuration file ./configs/6/static/cmake/modules/FindGDAL.cmake)
+NETCDF_EXTRA_LIBS="-lsqlite3 -lpthread -ldl -liconv" # `$NETCDF_ROOT/bin/nc-config --libs` does not report certain dependencies of certain static libraries (see also customized configuration file ./configs/6/static/cmake/modules/FindNETCDF.cmake)
 
 # Environment
@@ -65,4 +65,6 @@
 cmake \
 	-DBLAS_LIBRARIES="${BLAS_ROOT}/lib/libfblas.a;${LIBGFORTRAN_ROOT}/libgfortran.a;${LIBGFORTRAN_ROOT}/libquadmath.a;${LIBGCC}" \
+	-DCURL_INCLUDE_DIR="${CURL_ROOT}/include" \
+	-DCURL_LIBRARY="${CURL_ROOT}/lib/libcurl.a" \
 	-DGDAL_EXTRA_LIBS="${GDAL_EXTRA_LIBS}" \
 	-DHDF5_ROOT="${HDF5_ROOT}" \
Index: issm/trunk/externalpackages/gmt/install-6-mac.sh
===================================================================
--- issm/trunk/externalpackages/gmt/install-6-mac.sh	(revision 27035)
+++ issm/trunk/externalpackages/gmt/install-6-mac.sh	(revision 27232)
@@ -5,5 +5,16 @@
 ## Constants
 #
-VER="6.0.0"
+VER="6.4.0"
+
+# Find libgfortran so that we do not have to hardcode it.
+#
+# Should retrieve a copy of gfortran that is compiled from source before 
+# returning one that is installed via package manager.
+#
+# TODO:
+# - Move this to etc/environment.sh
+#
+LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | egrep -n libgfortran.a | egrep -v i386 | sed "s/[0-9]*://g" | head -1)
+LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
 
 # Environment
@@ -42,6 +53,8 @@
 #
 cmake \
-	-DCURL_LIBRARY="${CURL_ROOT}/lib" \
+	-DBLAS_LIBRARIES="-L${BLAS_ROOT}/lib;-lfblas;-L${LIBGFORTRAN_ROOT};-lgfortran" \
 	-DCURL_INCLUDE_DIR="${CURL_ROOT}/include" \
+	-DCURL_LIBRARY="-L${CURL_ROOT}/lib;-lcurl" \
+	-DLAPACK_LIBRARIES="-L${LAPACK_ROOT}/lib;-lflapack;-L${LIBGFORTRAN_ROOT};-lgfortran" \
 	..
 
Index: issm/trunk/externalpackages/gsl/install-javascript.sh
===================================================================
--- issm/trunk/externalpackages/gsl/install-javascript.sh	(revision 27035)
+++ issm/trunk/externalpackages/gsl/install-javascript.sh	(revision 27232)
@@ -3,12 +3,7 @@
 
 
-## TODO:
-# - Revisit enviroment variables (especially EMCC_CFLAGS) once support for
-#	Fortran has been accomplished.
-#
-
 ## Constants
 #
-VER="1.15"
+VER="2.7"
 
 PREFIX="${ISSM_DIR}/externalpackages/gsl/install" # Set to location where external package should be installed
@@ -21,5 +16,4 @@
 export RANLIB=emranlib
 #export EMCC_DEBUG=1 # Uncomment to enable debugging
-export EMCC_CFLAGS="-s ERROR_ON_UNDEFINED_SYMBOLS=0" # Required after v1.38.14 to avoid undefined symbol warnings from our Fortran object files being treated as errors
 
 # Source Emscripten environment
Index: issm/trunk/externalpackages/gsl/install-static.sh
===================================================================
--- issm/trunk/externalpackages/gsl/install-static.sh	(revision 27035)
+++ issm/trunk/externalpackages/gsl/install-static.sh	(revision 27232)
@@ -5,5 +5,5 @@
 ## Constants
 #
-VER="1.15"
+VER="2.7"
 
 PREFIX="${ISSM_DIR}/externalpackages/gsl/install" # Set to location where external package should be installed
Index: issm/trunk/externalpackages/gsl/install.sh
===================================================================
--- issm/trunk/externalpackages/gsl/install.sh	(revision 27035)
+++ issm/trunk/externalpackages/gsl/install.sh	(revision 27232)
@@ -3,7 +3,7 @@
 
 
-# Constants
+## Constants
 #
-VER="1.15"
+VER="2.7"
 
 PREFIX="${ISSM_DIR}/externalpackages/gsl/install" # Set to location where external package should be installed
Index: issm/trunk/externalpackages/mplapack/install-1-linux.sh
===================================================================
--- issm/trunk/externalpackages/mplapack/install-1-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/mplapack/install-1-linux.sh	(revision 27232)
@@ -56,4 +56,5 @@
 	--enable-fast-install=yes \
 	--disable-dependency-tracking \
+	--enable-optimization=yes \
 	--enable-fortranwrapper=yes \
 	--enable-gmp=yes \
Index: issm/trunk/externalpackages/mplapack/install-2-linux.sh
===================================================================
--- issm/trunk/externalpackages/mplapack/install-2-linux.sh	(revision 27232)
+++ issm/trunk/externalpackages/mplapack/install-2-linux.sh	(revision 27232)
@@ -0,0 +1,75 @@
+#!/bin/bash
+set -eu
+
+##
+# Source code and installation guidelines available at,
+#
+#	https://github.com/nakatamaho/mplapack
+#
+# Note that original website (for MPACK) at,
+#
+#	http://mplapack.sourceforge.net
+#
+# is not maintained.
+#
+
+## Constants
+#
+VER="2.0"
+
+PREFIX="${ISSM_DIR}/externalpackages/mplapack/install" # Set to location where external package should be installed
+
+## Environment
+#
+export CC=gcc
+export CXX=g++
+export FC=gfortran
+export F77=gfortran
+
+# Cleanup
+rm -rf ${PREFIX} src
+mkdir -p ${PREFIX} src
+
+# Download source
+${ISSM_DIR}/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/mplapack-${VER}.tar.gz" "mplapack-${VER}.tar.gz"
+
+# Unpack source
+tar -zxvf mplapack-${VER}.tar.gz
+
+# Move source to 'src' directory
+mv mplapack-${VER}/* src
+rm -rf mplapack-${VER}
+
+# Configure
+cd src
+pushd mplapack/test/compare
+bash gen.Makefile.am.sh
+popd
+autoreconf --force --install
+aclocal
+autoconf
+automake --add-missing
+autoreconf --force --install
+./configure \
+	--prefix="${PREFIX}" \
+	--disable-static \
+	--enable-fast-install=yes \
+	--disable-dependency-tracking \
+	--enable-optimization=yes \
+	--enable-fortranwrapper=yes \
+	--enable-gmp=yes \
+	--enable-mpfr=yes \
+	--enable-qd=yes \
+	--enable-dd=yes \
+	--enable-double=yes \
+	--enable-_Float128=yes \
+	--enable-_Float64x=yes
+
+# Compile and install
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
Index: issm/trunk/externalpackages/petsc/install-3.12-linux.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.12-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.12-linux.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.12-lonestar.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.12-lonestar.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.12-lonestar.sh	(revision 27232)
@@ -1,8 +1,12 @@
 #!/bin/bash
 set -eu
+
 
 ## Constants
 #
 VER="3.12.3"
+
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
 
 # Download source
@@ -13,16 +17,16 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
-# Move source to 'src' directory
-mv petsc-${VER}/* src/
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
-#configure
-cd src
+# Configure
+cd ${PETSC_DIR}
 ./config/configure.py \
-	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	--with-mpi-dir="/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/" \
 	--with-blas-lapack-dir="$TACC_MKL_LIB" \
Index: issm/trunk/externalpackages/petsc/install-3.12-mac.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.12-mac.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.12-mac.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.12-win-msys2-gcc-msmpi.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.12-win-msys2-gcc-msmpi.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.12-win-msys2-gcc-msmpi.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.13-pleiades.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.13-pleiades.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.13-pleiades.sh	(revision 27232)
@@ -20,5 +20,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.14-discover.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-discover.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-discover.sh	(revision 27232)
@@ -3,15 +3,13 @@
 
 
-# NOTE: There is a single difference between the Linux and macOS 
-#		configurations, which is the addition of the -static-libgfortran 
-#		option to FFLAGS on the macOS static configurations. For the sake of 
-#		consistency, we maintain separate files for each, respective Linux and 
-#		macOS configuration.
-
-# Constants
+## Constants
+#
 VER="3.14.6"
 
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
 # Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
 
 # Unpack source
@@ -19,17 +17,17 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
-# Move source to 'src' directory
-mv petsc-${VER}/* src/
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
 # Configure
-cd src
+cd ${PETSC_DIR}
 ./config/configure.py \
 	COPTFLAGS="-g -O3" CXXOPTFLAGS="-g -O3" FOPTFLAGS="-g -O3" \
-	--prefix="${ISSM_DIR}/externalpackages/petsc/install" \
-	--PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	--with-debugging=0 \
 	--with-valgrind=0 \
Index: issm/trunk/externalpackages/petsc/install-3.14-greenplanet.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-greenplanet.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-greenplanet.sh	(revision 27232)
@@ -2,24 +2,34 @@
 set -eu
 
-#WARNING: make sure you have the right mpi
 
-#Some cleanup
-rm -rf install petsc-3.14.0 src
-mkdir install src
+# WARNING: Make sure you have the right MPI
 
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.sh 'https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-lite-3.14.0.tar.gz' 'petsc-3.14.0.tar.gz'
+## Constants
+#
+VER="3.14.0"
 
-#Untar and move petsc to install directory
-tar -zxvf  petsc-3.14.0.tar.gz
-mv petsc-3.14.0/* src/
-rm -rf petsc-3.14.0
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+
+# Unpack source
+tar -zxvf petsc-${VER}.tar.gz
+
+# Cleanup
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
+
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
+rm -rf petsc-${VER}
 
 #configure
-cd src
+cd ${PETSC_DIR}
 ./config/configure.py \
 	COPTFLAGS="-g -O3" CXXOPTFLAGS="-g -O3" FOPTFLAGS="-g -O3" \
-	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	--with-blas-lapack-dir="/sopt/INTEL/compilers_and_libraries_2018.3.222/linux/mkl/" \
 	--with-mpi-dir="/sopt/OpenMPI/3.1.2/intel-2018.3-slim/" \
Index: issm/trunk/externalpackages/petsc/install-3.14-linux.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-linux.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.14-mac-nohdf5.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-mac-nohdf5.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-mac-nohdf5.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.14-mac.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-mac.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-mac.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.14-pleiades.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-pleiades.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-pleiades.sh	(revision 27232)
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.14-tetralith.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-tetralith.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-tetralith.sh	(revision 27232)
@@ -3,12 +3,10 @@
 
 
-# NOTE: There is a single difference between the Linux and macOS 
-#		configurations, which is the addition of the -static-libgfortran 
-#		option to FFLAGS on the macOS static configurations. For the sake of 
-#		consistency, we maintain separate files for each, respective Linux and 
-#		macOS configuration.
+## Constants
+#
+VER="3.14.6"
 
-# Constants
-VER="3.14.6"
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
 
 # Download source
@@ -19,17 +17,17 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
-# Move source to 'src' directory
-mv petsc-${VER}/* src/
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
 # Configure
-cd src
+cd ${PETSC_DIR}
 ./config/configure.py \
 	COPTFLAGS="-g -O2" CXXOPTFLAGS="-g -O2" FOPTFLAGS="-g -O2" \
-	--prefix="${ISSM_DIR}/externalpackages/petsc/install" \
-	--PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	--with-debugging=0 \
 	--with-valgrind=0 \
Index: issm/trunk/externalpackages/petsc/install-3.14-win-msys2-mingw-msmpi.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.14-win-msys2-mingw-msmpi.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.14-win-msys2-mingw-msmpi.sh	(revision 27232)
@@ -32,5 +32,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.15-babylon.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.15-babylon.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.15-babylon.sh	(revision 27232)
@@ -11,5 +11,5 @@
 
 # Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
 
 # Unpack source
@@ -18,5 +18,5 @@
 # Cleanup
 rm -rf ${PREFIX} ${PETSC_DIR}
-mkdir ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
Index: issm/trunk/externalpackages/petsc/install-3.15-discovery.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.15-discovery.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.15-discovery.sh	(revision 27232)
@@ -3,8 +3,12 @@
 
 ## Constants
+#
 VER="3.15.3"
 
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
 # Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
 
 # Unpack source
@@ -12,16 +16,17 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
-# Move source to 'src' directory
-mv petsc-${VER}/* src/
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
-cd src
+# Configure
+cd ${PETSC_DIR}
 ./config/configure.py \
 	COPTFLAGS="-g -O3" CXXOPTFLAGS="-g -O3" FOPTFLAGS="-g -O3" \
-	--prefix="${ISSM_DIR}/externalpackages/petsc/install" \
-	--PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	--with-make-np=20 \
 	--with-blas-lapack-dir=$MKL_ROOT \
Index: issm/trunk/externalpackages/petsc/install-3.15-pleiades.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.15-pleiades.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.15-pleiades.sh	(revision 27232)
@@ -14,20 +14,21 @@
 
 # Unpack source
-tar -zxvf petsc-3.15.0.tar.gz
+tar -zxvf petsc-${VER}.tar.gz
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
-mv petsc-3.15.0/* src/
-rm -rf petsc-3.15.0
-
+mv petsc-${VER}/* ${PETSC_DIR}
+rm -rf petsc-${VER}
 
 # Configure
 #
-# NOTE: Based on /nasa/petsc/3.7.5/intel_mpt/lib/petsc/conf/petscvariables; look for CONFIGURE_OPTIONS
+# NOTE:
+# - Based on /nasa/petsc/3.7.5/intel_mpt/lib/petsc/conf/petscvariables (look 
+#	for CONFIGURE_OPTIONS)
 #
-cd src
+cd ${PETSC_DIR}
 ./config/configure.py \
 	--prefix="${PREFIX}" \
Index: issm/trunk/externalpackages/petsc/install-3.16-linux.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.16-linux.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.16-linux.sh	(revision 27232)
@@ -3,4 +3,5 @@
 
 ## Constants
+#
 VER="3.16.0"
 
@@ -9,5 +10,5 @@
 
 # Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
 
 # Unpack source
@@ -15,16 +16,16 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
-mv petsc-${VER}/* src/
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
 # Configure
-cd src
+cd ${PETSC_DIR}
 ./config/configure.py \
-	--prefix="${ISSM_DIR}/externalpackages/petsc/install" \
-	--PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	-COPTFLAGS="-g -O2" -CXXOPTFLAGS="-g -O2" -FOPTFLAGS="-g -O2" \
 	--with-debugging=0 \
Index: issm/trunk/externalpackages/petsc/install-3.16-mac.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.16-mac.sh	(revision 27232)
+++ issm/trunk/externalpackages/petsc/install-3.16-mac.sh	(revision 27232)
@@ -0,0 +1,60 @@
+#!/bin/bash
+set -eu
+
+
+## Constants
+#
+VER="3.16.6"
+
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+
+# Unpack source
+tar -zxvf petsc-${VER}.tar.gz
+
+# Cleanup
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
+
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
+rm -rf petsc-${VER}
+
+# Configure
+#
+# NOTE:
+# - Added -Wno-error=implicit-function-declaration to CFLAGS for Clang >= 12. 
+#	(may need to remove it for earlier versions not using the C99 standard).
+# - Added -fallow-argument-mismatch to FFLAGS in order to clear,
+#
+#		error: The Fortran compiler gfortran will not compile files that call 
+#		the same routine with arguments of different types.
+#
+#	for gfortran 10 or later (may need to remove it for earlier versions).
+#
+cd ${PETSC_DIR}
+./config/configure.py \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
+	--CFLAGS="-Wno-error=implicit-function-declaration" \
+	--FFLAGS="-fallow-argument-mismatch" \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--with-pic=1 \
+	--download-fblaslapack=1 \
+	--download-mpich=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-scalapack=1 \
+	--download-mumps=1 \
+	--download-zlib=1 \
+	--download-hdf5=1
+
+# Compile and install
+make
+make install
Index: issm/trunk/externalpackages/petsc/install-3.16-pleiades.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.16-pleiades.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.16-pleiades.sh	(revision 27232)
@@ -17,9 +17,9 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
 # Move source to $PETSC_DIR
-mv petsc-${VER}/* src/
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
@@ -27,7 +27,9 @@
 # Configure
 #
-# NOTE: Based on /nasa/petsc/3.7.5/intel_mpt/lib/petsc/conf/petscvariables; look for CONFIGURE_OPTIONS
+# NOTE:
+# - Based on /nasa/petsc/3.7.5/intel_mpt/lib/petsc/conf/petscvariables (look 
+#	for CONFIGURE_OPTIONS)
 #
-cd src
+cd ${PETSC_DIR}
 ./config/configure.py \
 	--prefix="${PREFIX}" \
Index: issm/trunk/externalpackages/petsc/install-3.17-mac-intel.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.17-mac-intel.sh	(revision 27232)
+++ issm/trunk/externalpackages/petsc/install-3.17-mac-intel.sh	(revision 27232)
@@ -0,0 +1,48 @@
+#!/bin/bash
+set -eu
+
+
+## Constants
+#
+VER="3.17.4"
+
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+
+# Unpack source
+tar -zxvf petsc-${VER}.tar.gz
+
+# Cleanup
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
+
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
+rm -rf petsc-${VER}
+
+# Configure
+cd ${PETSC_DIR}
+./configure \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--with-pic=1 \
+	--download-fblaslapack=1 \
+	--download-mpich=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-scalapack=1 \
+	--download-mumps=1 \
+	--download-zlib=1 \
+	--download-hdf5=1
+
+# Compile and install
+make
+make install
+
Index: issm/trunk/externalpackages/petsc/install-3.17-mac-m1-static.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.17-mac-m1-static.sh	(revision 27232)
+++ issm/trunk/externalpackages/petsc/install-3.17-mac-m1-static.sh	(revision 27232)
@@ -0,0 +1,64 @@
+#!/bin/bash
+set -eu
+
+
+## Constants
+#
+VER="3.17.4"
+
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+
+# Unpack source
+tar -zxvf petsc-${VER}.tar.gz
+
+# Cleanup
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
+
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
+rm -rf petsc-${VER}
+
+# Configure
+#
+# NOTE:
+# - Cannot use --with-fpic option when compiling static libs,
+#
+#		Cannot determine compiler PIC flags if shared libraries is turned off
+#		Either run using --with-shared-libraries or --with-pic=0 and supply the
+#		compiler PIC flag via CFLAGS, CXXXFLAGS, and FCFLAGS
+#
+# - Added -fallow-argument-mismatch to FFLAGS in order to clear,
+#
+#		error: The Fortran compiler gfortran will not compile files that call 
+#		the same routine with arguments of different types.
+#
+#	for gfortran 10 or later (may need to remove it for earlier versions).
+cd ${PETSC_DIR}
+./config/configure.py \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
+	--LDFLAGS="-Wl,-no_compact_unwind" \
+	--with-shared-libraries=0 \
+	--CFLAGS="-fPIC" \
+	--CXXFLAGS="-fPIC" \
+	--FFLAGS="-fPIC" \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--download-fblaslapack=1 \
+	--download-mpich=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-scalapack=1 \
+	--download-mumps=1 \
+	--download-zlib=1 
+
+# Compile and install
+make
+make install
Index: issm/trunk/externalpackages/petsc/install-3.17-mac-m1.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.17-mac-m1.sh	(revision 27035)
+++ issm/trunk/externalpackages/petsc/install-3.17-mac-m1.sh	(revision 27232)
@@ -4,8 +4,12 @@
 
 ## Constants
-VER="3.17.0"
+#
+VER="3.17.4"
+
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
 
 # Download source
-$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
 
 # Unpack source
@@ -13,15 +17,16 @@
 
 # Cleanup
-rm -rf install src
-mkdir install src
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
 
-# Move source to 'src' directory
-mv petsc-${VER}/* src/
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
 rm -rf petsc-${VER}
 
-cd src
+# Configure
+cd ${PETSC_DIR}
 ./config/configure.py \
-	--prefix="${ISSM_DIR}/externalpackages/petsc/install" \
-	--PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
 	--LDFLAGS="-Wl,-no_compact_unwind" \
 	--with-debugging=0 \
Index: issm/trunk/externalpackages/petsc/install-3.17-pleiades.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.17-pleiades.sh	(revision 27232)
+++ issm/trunk/externalpackages/petsc/install-3.17-pleiades.sh	(revision 27232)
@@ -0,0 +1,58 @@
+#!/bin/bash
+set -eu
+
+
+## Constants
+#
+VER="3.17.4"
+
+PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
+PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed
+
+# Download source
+$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/petsc-lite-${VER}.tar.gz" "petsc-${VER}.tar.gz"
+
+# Unpack source
+tar -zxvf petsc-${VER}.tar.gz
+
+# Cleanup
+rm -rf ${PREFIX} ${PETSC_DIR}
+mkdir -p ${PETSC_DIR}
+
+# Move source to $PETSC_DIR
+mv petsc-${VER}/* ${PETSC_DIR}
+rm -rf petsc-${VER}
+
+# Configure
+#
+# NOTE:
+# - Options from,
+#
+# 		cat /nasa/petsc/3.14.5_toss3/lib/petsc/conf/petscvariables | grep CONF
+#
+cd ${PETSC_DIR}
+./configure \
+	--prefix="${PREFIX}" \
+	--PETSC_DIR="${PETSC_DIR}" \
+	--with-blas-lapack-dir="/nasa/intel/Compiler/2018.3.222/compilers_and_libraries_2018.3.222/linux/mkl" \
+	--with-scalapack-include="/nasa/intel/Compiler/2018.3.222/mkl/include" \
+	--with-scalapack-lib="/nasa/intel/Compiler/2018.3.222/mkl/lib/intel64/libmkl_scalapack_lp64.so /nasa/intel/Compiler/2018.3.222/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.so" \
+	--CFLAGS="-g -O3" \
+	--CXXFLAGS="-g -O3" \
+	--FFLAGS="-g -O3" \
+	--with-make-np=10 \
+	--with-batch=1 \
+	--with-pic=1 \
+	--with-shared-libraries=1 \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--download-make=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 
+
+# Compile and install
+make
+make install
Index: issm/trunk/externalpackages/sqlite/install.sh
===================================================================
--- issm/trunk/externalpackages/sqlite/install.sh	(revision 27035)
+++ issm/trunk/externalpackages/sqlite/install.sh	(revision 27232)
@@ -8,4 +8,8 @@
 
 PREFIX="${ISSM_DIR}/externalpackages/sqlite/install" # Set to location where external package should be installed
+
+# Environment
+#
+export CFLAGS="-DSQLITE_ENABLE_COLUMN_METADATA=1"
 
 # Cleanup
Index: issm/trunk/externalpackages/triangle/install-linux-javascript.sh
===================================================================
--- issm/trunk/externalpackages/triangle/install-linux-javascript.sh	(revision 27035)
+++ issm/trunk/externalpackages/triangle/install-linux-javascript.sh	(revision 27232)
@@ -2,9 +2,4 @@
 set -eu
 
-
-# TODO:
-# - Revisit enviroment variables (especially EMCC_CFLAGS) once support for
-#	Fortran has been accomplished.
-#
 
 # Constants
@@ -19,5 +14,4 @@
 export RANLIB=emranlib
 #export EMCC_DEBUG=1 # Uncomment to enable debugging
-export EMCC_CFLAGS="-s ERROR_ON_UNDEFINED_SYMBOLS=0" # Required after v1.38.14 to avoid undefined symbol warnings from our Fortran object files being treated as errors
 
 # Source Emscripten environment
@@ -26,5 +20,5 @@
 # Cleanup
 rm -rf ${PREFIX} src
-mkdir ${PREFIX} ${PREFIX}/include ${PREFIX}/share src
+mkdir -p ${PREFIX} ${PREFIX}/include ${PREFIX}/share src
 
 # Download source
Index: issm/trunk/jenkins/aws-amazon_linux-solid_earth
===================================================================
--- issm/trunk/jenkins/aws-amazon_linux-solid_earth	(revision 27035)
+++ issm/trunk/jenkins/aws-amazon_linux-solid_earth	(revision 27232)
@@ -46,5 +46,5 @@
 	gshhg			install.sh
 	gmt				install-6-linux.sh
-	gmsh			install-4.sh
+	gmsh			install-4-linux.sh
 	shell2junit		install.sh
 "
Index: issm/trunk/jenkins/examples_tests.sh
===================================================================
--- issm/trunk/jenkins/examples_tests.sh	(revision 27035)
+++ issm/trunk/jenkins/examples_tests.sh	(revision 27232)
@@ -40,4 +40,10 @@
 for dir in ./* ; do
 	if [ -d "${dir}" ]; then
+		# # Temporary short circuit to check single example
+		# example="./AMR"
+		# if [ "${dir}" != "${example}" ]; then
+		# 	continue
+		# fi
+
 		# Some of the examples are incomplete (on purpose). As such, we will 
 		# have to populate the missing steps in order to make sure that 
@@ -45,5 +51,4 @@
 
 		cd ${dir}
-
 		if [ "${dir}" == "./AMR" ]; then
 			sed -i.bak -e '1 s|^.*$|try\n\n&|' $RUNME_FILE
Index: issm/trunk/jenkins/jenkins.sh
===================================================================
--- issm/trunk/jenkins/jenkins.sh	(revision 27035)
+++ issm/trunk/jenkins/jenkins.sh	(revision 27232)
@@ -178,28 +178,40 @@
 		cd ${ISSM_DIR}/externalpackages/$PACKAGENAME
 
-		echo "======================================================";
-		echo "       Installing $PACKAGENAME                        ";
-		echo "======================================================";
-
-		./$PACKAGEINST $NUMCPUS_INSTALL &> compil.log
-		if [ $? -ne 0 ] && [ "${PACKAGENAME}" != "boost" ]; then
-			cat compil.log
+		# Do not install package if it already exists
+		#
+		# NOTE: Assumes PREFIX is defined in package installation script
+		#
+		PREFIX=$(egrep "PREFIX=" ./$PACKAGEINST | cut -d'"' -f 2 | envsubst)
+		if [ ! -d "${PREFIX}" ]; then
 			echo "======================================================";
-			echo "    ERROR: installation of $PACKAGENAME failed        ";
+			echo "       Installing $PACKAGENAME                        ";
 			echo "======================================================";
-			echo "<testcase classname=\"externalpackages\" name=\"$PACKAGENAME\">" >> $EXTERNAL_TEST_FILE
-			echo '<failure message="failure">External packages did not install right. Check it.' >> $EXTERNAL_TEST_FILE
-			cat compil.log >> $EXTERNAL_TEST_FILE
-			echo '</failure>' >> $EXTERNAL_TEST_FILE
-			echo '</testcase>' >> $EXTERNAL_TEST_FILE
-			EXTERNALPACKAGES_FAILED=1;
+
+			./$PACKAGEINST $NUMCPUS_INSTALL &> compil.log
+			if [ $? -ne 0 ] && [ "${PACKAGENAME}" != "boost" ]; then
+				cat compil.log
+				echo "======================================================";
+				echo "    ERROR: installation of $PACKAGENAME failed        ";
+				echo "======================================================";
+				echo "<testcase classname=\"externalpackages\" name=\"$PACKAGENAME\">" >> $EXTERNAL_TEST_FILE
+				echo '<failure message="failure">External packages did not install right. Check it.' >> $EXTERNAL_TEST_FILE
+				cat compil.log >> $EXTERNAL_TEST_FILE
+				echo '</failure>' >> $EXTERNAL_TEST_FILE
+				echo '</testcase>' >> $EXTERNAL_TEST_FILE
+				EXTERNALPACKAGES_FAILED=1;
+			else
+				echo "<testcase classname=\"externalpackages\" name=\"$PACKAGENAME\"/>" >> $EXTERNAL_TEST_FILE
+			fi
+			source ${ISSM_DIR}/etc/environment.sh
+
+			#If external package is rebuilt, we also need to recompile
+			ISSM_RECONFIGURE="yes"
+			ISSM_COMPILATION="yes"
 		else
+			echo "======================================================";
+			echo "       Skipping $PACKAGENAME                          ";
+			echo "======================================================";
 			echo "<testcase classname=\"externalpackages\" name=\"$PACKAGENAME\"/>" >> $EXTERNAL_TEST_FILE
 		fi
-		source ${ISSM_DIR}/etc/environment.sh
-
-		#If external package is rebuilt, we also need to recompile
-		ISSM_RECONFIGURE="yes"
-		ISSM_COMPILATION="yes"
 	else
 		echo "======================================================";
Index: issm/trunk/jenkins/pine_island-mac-binaries-matlab
===================================================================
--- issm/trunk/jenkins/pine_island-mac-binaries-matlab	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-binaries-matlab	(revision 27232)
@@ -56,5 +56,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac-static.sh
-	gmsh		install-4-static.sh
+	gmsh		install-4-mac-static.sh
 	triangle	install-mac-static.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-binaries-python-2
===================================================================
--- issm/trunk/jenkins/pine_island-mac-binaries-python-2	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-binaries-python-2	(revision 27232)
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac-static.sh
-	gmsh		install-4-static.sh
+	gmsh		install-4-mac-static.sh
 	triangle	install-mac-static.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-binaries-python-3
===================================================================
--- issm/trunk/jenkins/pine_island-mac-binaries-python-3	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-binaries-python-3	(revision 27232)
@@ -55,5 +55,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac-static.sh
-	gmsh		install-4-static.sh
+	gmsh		install-4-mac-static.sh
 	triangle	install-mac-static.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-dakota
===================================================================
--- issm/trunk/jenkins/pine_island-mac-dakota	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-dakota	(revision 27232)
@@ -56,5 +56,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac.sh
-	gmsh		install-4.sh
+	gmsh		install-4-mac.sh
 	triangle	install-mac.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-examples
===================================================================
--- issm/trunk/jenkins/pine_island-mac-examples	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-examples	(revision 27232)
@@ -57,5 +57,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac.sh
-	gmsh		install-4.sh
+	gmsh		install-4-mac.sh
 	triangle	install-mac.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-full
===================================================================
--- issm/trunk/jenkins/pine_island-mac-full	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-full	(revision 27232)
@@ -44,5 +44,5 @@
 	autotools	install-mac.sh
 	cmake		install.sh
-	petsc		install-3.12-mac.sh
+	petsc		install-3.17-mac-intel.sh
 	gsl			install.sh
 	boost		install-1.7-mac.sh
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac.sh
-	gmsh		install-4.sh
+	gmsh		install-4-mac.sh
 	triangle	install-mac.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-full-valgrind
===================================================================
--- issm/trunk/jenkins/pine_island-mac-full-valgrind	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-full-valgrind	(revision 27232)
@@ -44,5 +44,5 @@
 	autotools	install-mac.sh
 	cmake		install.sh
-	petsc		install-3.12-mac.sh
+	petsc		install-3.16-mac.sh
 	gsl			install.sh
 	boost		install-1.7-mac.sh
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac.sh
-	gmsh		install-4.sh
+	gmsh		install-4-mac.sh
 	triangle	install-mac.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-solid_earth
===================================================================
--- issm/trunk/jenkins/pine_island-mac-solid_earth	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-solid_earth	(revision 27232)
@@ -56,5 +56,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac.sh
-	gmsh		install-4.sh
+	gmsh		install-4-mac.sh
 	triangle	install-mac.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pine_island-mac-solid_earth-lambert
===================================================================
--- issm/trunk/jenkins/pine_island-mac-solid_earth-lambert	(revision 27035)
+++ issm/trunk/jenkins/pine_island-mac-solid_earth-lambert	(revision 27232)
@@ -56,5 +56,5 @@
 	gshhg		install.sh
 	gmt			install-6-mac.sh
-	gmsh		install-4.sh
+	gmsh		install-4-mac.sh
 	triangle	install-mac.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/pleiades-solid_earth
===================================================================
--- issm/trunk/jenkins/pleiades-solid_earth	(revision 27035)
+++ issm/trunk/jenkins/pleiades-solid_earth	(revision 27232)
@@ -49,5 +49,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux.sh
-	gmsh		install-4.sh
+	gmsh		install-4-linux.sh
 	triangle	install-linux.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-binaries-matlab
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-binaries-matlab	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-binaries-matlab	(revision 27232)
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux-static.sh
-	gmsh		install-4-static.sh
+	gmsh		install-4-linux-static.sh
 	triangle	install-linux-static.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-binaries-python-2
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-binaries-python-2	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-binaries-python-2	(revision 27232)
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux-static.sh
-	gmsh		install-4-static.sh
+	gmsh		install-4-linux-static.sh
 	triangle	install-linux-static.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-binaries-python-3
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-binaries-python-3	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-binaries-python-3	(revision 27232)
@@ -55,5 +55,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux-static.sh
-	gmsh		install-4-static.sh
+	gmsh		install-4-linux-static.sh
 	triangle	install-linux-static.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-dakota
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-dakota	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-dakota	(revision 27232)
@@ -53,5 +53,5 @@
 	gshhg			install.sh
 	gmt				install-6-linux.sh
-	gmsh			install-4.sh
+	gmsh			install-4-linux.sh
 	triangle		install-linux.sh
 	chaco			install.sh
Index: issm/trunk/jenkins/ross-debian_linux-full
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-full	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-full	(revision 27232)
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux.sh
-	gmsh		install-4.sh
+	gmsh		install-4-linux.sh
 	triangle	install-linux.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-full-mplapack
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-full-mplapack	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-full-mplapack	(revision 27232)
@@ -47,5 +47,5 @@
 	cmake		install.sh
 	petsc		install-3.12-linux.sh
-	mplapack	install-1-linux.sh
+	mplapack	install-2-linux.sh
 	gsl			install.sh
 	boost		install-1.7-linux.sh
@@ -57,5 +57,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux.sh
-	gmsh		install-4.sh
+	gmsh		install-4-linux.sh
 	triangle	install-linux.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-full-valgrind
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-full-valgrind	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-full-valgrind	(revision 27232)
@@ -54,5 +54,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux.sh
-	gmsh		install-4.sh
+	gmsh		install-4-linux.sh
 	triangle	install-linux.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-gia
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-gia	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-gia	(revision 27232)
@@ -37,5 +37,5 @@
 	triangle	install-linux.sh
 	math77		install.sh
-	gmsh		install-4.sh
+	gmsh		install-4-linux.sh
 	shell2junit	install.sh
 "
Index: issm/trunk/jenkins/ross-debian_linux-javascript
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-javascript	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-javascript	(revision 27232)
@@ -8,4 +8,5 @@
 	--enable-development \
 	--enable-debugging \
+	--with-cxxoptflags="-g -O2 -fPIC -std=c++11" \
 	--with-javascript \
 	--without-fortran \
Index: issm/trunk/jenkins/ross-debian_linux-python
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-python	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-python	(revision 27232)
@@ -49,5 +49,5 @@
 	gshhg		install.sh
 	gmt			install-6-linux.sh
-	gmsh		install-4.sh
+	gmsh		install-4-linux.sh
 	triangle	install-linux.sh
 	chaco		install.sh
Index: issm/trunk/jenkins/ross-debian_linux-solid_earth
===================================================================
--- issm/trunk/jenkins/ross-debian_linux-solid_earth	(revision 27035)
+++ issm/trunk/jenkins/ross-debian_linux-solid_earth	(revision 27232)
@@ -51,5 +51,5 @@
 	gshhg			install.sh
 	gmt				install-6-linux.sh
-	gmsh			install-4.sh
+	gmsh			install-4-linux.sh
 	triangle		install-linux.sh
 	chaco			install.sh
Index: issm/trunk/m4/analyses.m4
===================================================================
--- issm/trunk/m4/analyses.m4	(revision 27035)
+++ issm/trunk/m4/analyses.m4	(revision 27232)
@@ -11,1068 +11,590 @@
 
 dnl with-HydrologyTws{{{
-
 AC_ARG_WITH([HydrologyTws],
-
 	AS_HELP_STRING([--with-HydrologyTws = YES], [compile with HydrologyTws capabilities (default is yes)]),
-
 	[HYDROLOGYTWS=$withval],[HYDROLOGYTWS=yes])
-
 AC_MSG_CHECKING(for HydrologyTws capability compilation)
 
-
 HAVE_HYDROLOGYTWS=no 
-
 if test "x$HYDROLOGYTWS" = "xyes"; then
-
 	HAVE_HYDROLOGYTWS=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYTWS_],[1],[with HydrologyTws capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYTWS], [test x$HAVE_HYDROLOGYTWS = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYTWS)
-
 dnl }}}
 dnl with-AdjointBalancethickness2{{{
-
 AC_ARG_WITH([AdjointBalancethickness2],
-
 	AS_HELP_STRING([--with-AdjointBalancethickness2 = YES], [compile with AdjointBalancethickness2 capabilities (default is yes)]),
-
 	[ADJOINTBALANCETHICKNESS2=$withval],[ADJOINTBALANCETHICKNESS2=yes])
-
 AC_MSG_CHECKING(for AdjointBalancethickness2 capability compilation)
 
-
 HAVE_ADJOINTBALANCETHICKNESS2=no 
-
 if test "x$ADJOINTBALANCETHICKNESS2" = "xyes"; then
-
 	HAVE_ADJOINTBALANCETHICKNESS2=yes
-
 	AC_DEFINE([_HAVE_ADJOINTBALANCETHICKNESS2_],[1],[with AdjointBalancethickness2 capability])
-
-fi
-
+fi
 AM_CONDITIONAL([ADJOINTBALANCETHICKNESS2], [test x$HAVE_ADJOINTBALANCETHICKNESS2 = xyes])
-
 AC_MSG_RESULT($HAVE_ADJOINTBALANCETHICKNESS2)
-
 dnl }}}
 dnl with-AdjointBalancethickness{{{
-
 AC_ARG_WITH([AdjointBalancethickness],
-
 	AS_HELP_STRING([--with-AdjointBalancethickness = YES], [compile with AdjointBalancethickness capabilities (default is yes)]),
-
 	[ADJOINTBALANCETHICKNESS=$withval],[ADJOINTBALANCETHICKNESS=yes])
-
 AC_MSG_CHECKING(for AdjointBalancethickness capability compilation)
 
-
 HAVE_ADJOINTBALANCETHICKNESS=no 
-
 if test "x$ADJOINTBALANCETHICKNESS" = "xyes"; then
-
 	HAVE_ADJOINTBALANCETHICKNESS=yes
-
 	AC_DEFINE([_HAVE_ADJOINTBALANCETHICKNESS_],[1],[with AdjointBalancethickness capability])
-
-fi
-
+fi
 AM_CONDITIONAL([ADJOINTBALANCETHICKNESS], [test x$HAVE_ADJOINTBALANCETHICKNESS = xyes])
-
 AC_MSG_RESULT($HAVE_ADJOINTBALANCETHICKNESS)
-
 dnl }}}
 dnl with-AdjointHoriz{{{
-
 AC_ARG_WITH([AdjointHoriz],
-
 	AS_HELP_STRING([--with-AdjointHoriz = YES], [compile with AdjointHoriz capabilities (default is yes)]),
-
 	[ADJOINTHORIZ=$withval],[ADJOINTHORIZ=yes])
-
 AC_MSG_CHECKING(for AdjointHoriz capability compilation)
 
-
 HAVE_ADJOINTHORIZ=no 
-
 if test "x$ADJOINTHORIZ" = "xyes"; then
-
 	HAVE_ADJOINTHORIZ=yes
-
 	AC_DEFINE([_HAVE_ADJOINTHORIZ_],[1],[with AdjointHoriz capability])
-
-fi
-
+fi
 AM_CONDITIONAL([ADJOINTHORIZ], [test x$HAVE_ADJOINTHORIZ = xyes])
-
 AC_MSG_RESULT($HAVE_ADJOINTHORIZ)
-
+dnl }}}
+dnl with-Age{{{
+AC_ARG_WITH([Age],
+	AS_HELP_STRING([--with-Age = YES], [compile with Age capabilities (default is yes)]),
+	[AGE=$withval],[AGE=yes])
+AC_MSG_CHECKING(for Age capability compilation)
+
+HAVE_AGE=no 
+if test "x$AGE" = "xyes"; then
+	HAVE_AGE=yes
+	AC_DEFINE([_HAVE_AGE_],[1],[with Age capability])
+fi
+AM_CONDITIONAL([AGE], [test x$HAVE_AGE = xyes])
+AC_MSG_RESULT($HAVE_AGE)
 dnl }}}
 dnl with-Balancethickness2{{{
-
 AC_ARG_WITH([Balancethickness2],
-
 	AS_HELP_STRING([--with-Balancethickness2 = YES], [compile with Balancethickness2 capabilities (default is yes)]),
-
 	[BALANCETHICKNESS2=$withval],[BALANCETHICKNESS2=yes])
-
 AC_MSG_CHECKING(for Balancethickness2 capability compilation)
 
-
 HAVE_BALANCETHICKNESS2=no 
-
 if test "x$BALANCETHICKNESS2" = "xyes"; then
-
 	HAVE_BALANCETHICKNESS2=yes
-
 	AC_DEFINE([_HAVE_BALANCETHICKNESS2_],[1],[with Balancethickness2 capability])
-
-fi
-
+fi
 AM_CONDITIONAL([BALANCETHICKNESS2], [test x$HAVE_BALANCETHICKNESS2 = xyes])
-
 AC_MSG_RESULT($HAVE_BALANCETHICKNESS2)
-
 dnl }}}
 dnl with-Balancethickness{{{
-
 AC_ARG_WITH([Balancethickness],
-
 	AS_HELP_STRING([--with-Balancethickness = YES], [compile with Balancethickness capabilities (default is yes)]),
-
 	[BALANCETHICKNESS=$withval],[BALANCETHICKNESS=yes])
-
 AC_MSG_CHECKING(for Balancethickness capability compilation)
 
-
 HAVE_BALANCETHICKNESS=no 
-
 if test "x$BALANCETHICKNESS" = "xyes"; then
-
 	HAVE_BALANCETHICKNESS=yes
-
 	AC_DEFINE([_HAVE_BALANCETHICKNESS_],[1],[with Balancethickness capability])
-
-fi
-
+fi
 AM_CONDITIONAL([BALANCETHICKNESS], [test x$HAVE_BALANCETHICKNESS = xyes])
-
 AC_MSG_RESULT($HAVE_BALANCETHICKNESS)
-
 dnl }}}
 dnl with-BalancethicknessSoft{{{
-
 AC_ARG_WITH([BalancethicknessSoft],
-
 	AS_HELP_STRING([--with-BalancethicknessSoft = YES], [compile with BalancethicknessSoft capabilities (default is yes)]),
-
 	[BALANCETHICKNESSSOFT=$withval],[BALANCETHICKNESSSOFT=yes])
-
 AC_MSG_CHECKING(for BalancethicknessSoft capability compilation)
 
-
 HAVE_BALANCETHICKNESSSOFT=no 
-
 if test "x$BALANCETHICKNESSSOFT" = "xyes"; then
-
 	HAVE_BALANCETHICKNESSSOFT=yes
-
 	AC_DEFINE([_HAVE_BALANCETHICKNESSSOFT_],[1],[with BalancethicknessSoft capability])
-
-fi
-
+fi
 AM_CONDITIONAL([BALANCETHICKNESSSOFT], [test x$HAVE_BALANCETHICKNESSSOFT = xyes])
-
 AC_MSG_RESULT($HAVE_BALANCETHICKNESSSOFT)
-
 dnl }}}
 dnl with-Balancevelocity{{{
-
 AC_ARG_WITH([Balancevelocity],
-
 	AS_HELP_STRING([--with-Balancevelocity = YES], [compile with Balancevelocity capabilities (default is yes)]),
-
 	[BALANCEVELOCITY=$withval],[BALANCEVELOCITY=yes])
-
 AC_MSG_CHECKING(for Balancevelocity capability compilation)
 
-
 HAVE_BALANCEVELOCITY=no 
-
 if test "x$BALANCEVELOCITY" = "xyes"; then
-
 	HAVE_BALANCEVELOCITY=yes
-
 	AC_DEFINE([_HAVE_BALANCEVELOCITY_],[1],[with Balancevelocity capability])
-
-fi
-
+fi
 AM_CONDITIONAL([BALANCEVELOCITY], [test x$HAVE_BALANCEVELOCITY = xyes])
-
 AC_MSG_RESULT($HAVE_BALANCEVELOCITY)
-
 dnl }}}
 dnl with-DamageEvolution{{{
-
 AC_ARG_WITH([DamageEvolution],
-
 	AS_HELP_STRING([--with-DamageEvolution = YES], [compile with DamageEvolution capabilities (default is yes)]),
-
 	[DAMAGEEVOLUTION=$withval],[DAMAGEEVOLUTION=yes])
-
 AC_MSG_CHECKING(for DamageEvolution capability compilation)
 
-
 HAVE_DAMAGEEVOLUTION=no 
-
 if test "x$DAMAGEEVOLUTION" = "xyes"; then
-
 	HAVE_DAMAGEEVOLUTION=yes
-
 	AC_DEFINE([_HAVE_DAMAGEEVOLUTION_],[1],[with DamageEvolution capability])
-
-fi
-
+fi
 AM_CONDITIONAL([DAMAGEEVOLUTION], [test x$HAVE_DAMAGEEVOLUTION = xyes])
-
 AC_MSG_RESULT($HAVE_DAMAGEEVOLUTION)
-
 dnl }}}
 dnl with-DepthAverage{{{
-
 AC_ARG_WITH([DepthAverage],
-
 	AS_HELP_STRING([--with-DepthAverage = YES], [compile with DepthAverage capabilities (default is yes)]),
-
 	[DEPTHAVERAGE=$withval],[DEPTHAVERAGE=yes])
-
 AC_MSG_CHECKING(for DepthAverage capability compilation)
 
-
 HAVE_DEPTHAVERAGE=no 
-
 if test "x$DEPTHAVERAGE" = "xyes"; then
-
 	HAVE_DEPTHAVERAGE=yes
-
 	AC_DEFINE([_HAVE_DEPTHAVERAGE_],[1],[with DepthAverage capability])
-
-fi
-
+fi
 AM_CONDITIONAL([DEPTHAVERAGE], [test x$HAVE_DEPTHAVERAGE = xyes])
-
 AC_MSG_RESULT($HAVE_DEPTHAVERAGE)
-
 dnl }}}
 dnl with-Enthalpy{{{
-
 AC_ARG_WITH([Enthalpy],
-
 	AS_HELP_STRING([--with-Enthalpy = YES], [compile with Enthalpy capabilities (default is yes)]),
-
 	[ENTHALPY=$withval],[ENTHALPY=yes])
-
 AC_MSG_CHECKING(for Enthalpy capability compilation)
 
-
 HAVE_ENTHALPY=no 
-
 if test "x$ENTHALPY" = "xyes"; then
-
 	HAVE_ENTHALPY=yes
-
 	AC_DEFINE([_HAVE_ENTHALPY_],[1],[with Enthalpy capability])
-
-fi
-
+fi
 AM_CONDITIONAL([ENTHALPY], [test x$HAVE_ENTHALPY = xyes])
-
 AC_MSG_RESULT($HAVE_ENTHALPY)
-
 dnl }}}
 dnl with-Esa{{{
-
 AC_ARG_WITH([Esa],
-
 	AS_HELP_STRING([--with-Esa = YES], [compile with Esa capabilities (default is yes)]),
-
 	[ESA=$withval],[ESA=yes])
-
 AC_MSG_CHECKING(for Esa capability compilation)
 
-
 HAVE_ESA=no 
-
 if test "x$ESA" = "xyes"; then
-
 	HAVE_ESA=yes
-
 	AC_DEFINE([_HAVE_ESA_],[1],[with Esa capability])
-
-fi
-
+fi
 AM_CONDITIONAL([ESA], [test x$HAVE_ESA = xyes])
-
 AC_MSG_RESULT($HAVE_ESA)
-
 dnl }}}
 dnl with-Extrapolation{{{
-
 AC_ARG_WITH([Extrapolation],
-
 	AS_HELP_STRING([--with-Extrapolation = YES], [compile with Extrapolation capabilities (default is yes)]),
-
 	[EXTRAPOLATION=$withval],[EXTRAPOLATION=yes])
-
 AC_MSG_CHECKING(for Extrapolation capability compilation)
 
-
 HAVE_EXTRAPOLATION=no 
-
 if test "x$EXTRAPOLATION" = "xyes"; then
-
 	HAVE_EXTRAPOLATION=yes
-
 	AC_DEFINE([_HAVE_EXTRAPOLATION_],[1],[with Extrapolation capability])
-
-fi
-
+fi
 AM_CONDITIONAL([EXTRAPOLATION], [test x$HAVE_EXTRAPOLATION = xyes])
-
 AC_MSG_RESULT($HAVE_EXTRAPOLATION)
-
 dnl }}}
 dnl with-ExtrudeFromBase{{{
-
 AC_ARG_WITH([ExtrudeFromBase],
-
 	AS_HELP_STRING([--with-ExtrudeFromBase = YES], [compile with ExtrudeFromBase capabilities (default is yes)]),
-
 	[EXTRUDEFROMBASE=$withval],[EXTRUDEFROMBASE=yes])
-
 AC_MSG_CHECKING(for ExtrudeFromBase capability compilation)
 
-
 HAVE_EXTRUDEFROMBASE=no 
-
 if test "x$EXTRUDEFROMBASE" = "xyes"; then
-
 	HAVE_EXTRUDEFROMBASE=yes
-
 	AC_DEFINE([_HAVE_EXTRUDEFROMBASE_],[1],[with ExtrudeFromBase capability])
-
-fi
-
+fi
 AM_CONDITIONAL([EXTRUDEFROMBASE], [test x$HAVE_EXTRUDEFROMBASE = xyes])
-
 AC_MSG_RESULT($HAVE_EXTRUDEFROMBASE)
-
 dnl }}}
 dnl with-ExtrudeFromTop{{{
-
 AC_ARG_WITH([ExtrudeFromTop],
-
 	AS_HELP_STRING([--with-ExtrudeFromTop = YES], [compile with ExtrudeFromTop capabilities (default is yes)]),
-
 	[EXTRUDEFROMTOP=$withval],[EXTRUDEFROMTOP=yes])
-
 AC_MSG_CHECKING(for ExtrudeFromTop capability compilation)
 
-
 HAVE_EXTRUDEFROMTOP=no 
-
 if test "x$EXTRUDEFROMTOP" = "xyes"; then
-
 	HAVE_EXTRUDEFROMTOP=yes
-
 	AC_DEFINE([_HAVE_EXTRUDEFROMTOP_],[1],[with ExtrudeFromTop capability])
-
-fi
-
+fi
 AM_CONDITIONAL([EXTRUDEFROMTOP], [test x$HAVE_EXTRUDEFROMTOP = xyes])
-
 AC_MSG_RESULT($HAVE_EXTRUDEFROMTOP)
-
 dnl }}}
 dnl with-FreeSurfaceBase{{{
-
 AC_ARG_WITH([FreeSurfaceBase],
-
 	AS_HELP_STRING([--with-FreeSurfaceBase = YES], [compile with FreeSurfaceBase capabilities (default is yes)]),
-
 	[FREESURFACEBASE=$withval],[FREESURFACEBASE=yes])
-
 AC_MSG_CHECKING(for FreeSurfaceBase capability compilation)
 
-
 HAVE_FREESURFACEBASE=no 
-
 if test "x$FREESURFACEBASE" = "xyes"; then
-
 	HAVE_FREESURFACEBASE=yes
-
 	AC_DEFINE([_HAVE_FREESURFACEBASE_],[1],[with FreeSurfaceBase capability])
-
-fi
-
+fi
 AM_CONDITIONAL([FREESURFACEBASE], [test x$HAVE_FREESURFACEBASE = xyes])
-
 AC_MSG_RESULT($HAVE_FREESURFACEBASE)
-
 dnl }}}
 dnl with-FreeSurfaceTop{{{
-
 AC_ARG_WITH([FreeSurfaceTop],
-
 	AS_HELP_STRING([--with-FreeSurfaceTop = YES], [compile with FreeSurfaceTop capabilities (default is yes)]),
-
 	[FREESURFACETOP=$withval],[FREESURFACETOP=yes])
-
 AC_MSG_CHECKING(for FreeSurfaceTop capability compilation)
 
-
 HAVE_FREESURFACETOP=no 
-
 if test "x$FREESURFACETOP" = "xyes"; then
-
 	HAVE_FREESURFACETOP=yes
-
 	AC_DEFINE([_HAVE_FREESURFACETOP_],[1],[with FreeSurfaceTop capability])
-
-fi
-
+fi
 AM_CONDITIONAL([FREESURFACETOP], [test x$HAVE_FREESURFACETOP = xyes])
-
 AC_MSG_RESULT($HAVE_FREESURFACETOP)
-
 dnl }}}
 dnl with-GLheightadvection{{{
-
 AC_ARG_WITH([GLheightadvection],
-
 	AS_HELP_STRING([--with-GLheightadvection = YES], [compile with GLheightadvection capabilities (default is yes)]),
-
 	[GLHEIGHTADVECTION=$withval],[GLHEIGHTADVECTION=yes])
-
 AC_MSG_CHECKING(for GLheightadvection capability compilation)
 
-
 HAVE_GLHEIGHTADVECTION=no 
-
 if test "x$GLHEIGHTADVECTION" = "xyes"; then
-
 	HAVE_GLHEIGHTADVECTION=yes
-
 	AC_DEFINE([_HAVE_GLHEIGHTADVECTION_],[1],[with GLheightadvection capability])
-
-fi
-
+fi
 AM_CONDITIONAL([GLHEIGHTADVECTION], [test x$HAVE_GLHEIGHTADVECTION = xyes])
-
 AC_MSG_RESULT($HAVE_GLHEIGHTADVECTION)
-
 dnl }}}
 dnl with-HydrologyDCEfficient{{{
-
 AC_ARG_WITH([HydrologyDCEfficient],
-
 	AS_HELP_STRING([--with-HydrologyDCEfficient = YES], [compile with HydrologyDCEfficient capabilities (default is yes)]),
-
 	[HYDROLOGYDCEFFICIENT=$withval],[HYDROLOGYDCEFFICIENT=yes])
-
 AC_MSG_CHECKING(for HydrologyDCEfficient capability compilation)
 
-
 HAVE_HYDROLOGYDCEFFICIENT=no 
-
 if test "x$HYDROLOGYDCEFFICIENT" = "xyes"; then
-
 	HAVE_HYDROLOGYDCEFFICIENT=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYDCEFFICIENT_],[1],[with HydrologyDCEfficient capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYDCEFFICIENT], [test x$HAVE_HYDROLOGYDCEFFICIENT = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYDCEFFICIENT)
-
 dnl }}}
 dnl with-HydrologyDCInefficient{{{
-
 AC_ARG_WITH([HydrologyDCInefficient],
-
 	AS_HELP_STRING([--with-HydrologyDCInefficient = YES], [compile with HydrologyDCInefficient capabilities (default is yes)]),
-
 	[HYDROLOGYDCINEFFICIENT=$withval],[HYDROLOGYDCINEFFICIENT=yes])
-
 AC_MSG_CHECKING(for HydrologyDCInefficient capability compilation)
 
-
 HAVE_HYDROLOGYDCINEFFICIENT=no 
-
 if test "x$HYDROLOGYDCINEFFICIENT" = "xyes"; then
-
 	HAVE_HYDROLOGYDCINEFFICIENT=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYDCINEFFICIENT_],[1],[with HydrologyDCInefficient capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYDCINEFFICIENT], [test x$HAVE_HYDROLOGYDCINEFFICIENT = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYDCINEFFICIENT)
-
 dnl }}}
 dnl with-HydrologyGlaDS{{{
-
 AC_ARG_WITH([HydrologyGlaDS],
-
 	AS_HELP_STRING([--with-HydrologyGlaDS = YES], [compile with HydrologyGlaDS capabilities (default is yes)]),
-
 	[HYDROLOGYGLADS=$withval],[HYDROLOGYGLADS=yes])
-
 AC_MSG_CHECKING(for HydrologyGlaDS capability compilation)
 
-
 HAVE_HYDROLOGYGLADS=no 
-
 if test "x$HYDROLOGYGLADS" = "xyes"; then
-
 	HAVE_HYDROLOGYGLADS=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYGLADS_],[1],[with HydrologyGlaDS capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYGLADS], [test x$HAVE_HYDROLOGYGLADS = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYGLADS)
-
 dnl }}}
 dnl with-HydrologyPism{{{
-
 AC_ARG_WITH([HydrologyPism],
-
 	AS_HELP_STRING([--with-HydrologyPism = YES], [compile with HydrologyPism capabilities (default is yes)]),
-
 	[HYDROLOGYPISM=$withval],[HYDROLOGYPISM=yes])
-
 AC_MSG_CHECKING(for HydrologyPism capability compilation)
 
-
 HAVE_HYDROLOGYPISM=no 
-
 if test "x$HYDROLOGYPISM" = "xyes"; then
-
 	HAVE_HYDROLOGYPISM=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYPISM_],[1],[with HydrologyPism capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYPISM], [test x$HAVE_HYDROLOGYPISM = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYPISM)
-
 dnl }}}
 dnl with-HydrologyShakti{{{
-
 AC_ARG_WITH([HydrologyShakti],
-
 	AS_HELP_STRING([--with-HydrologyShakti = YES], [compile with HydrologyShakti capabilities (default is yes)]),
-
 	[HYDROLOGYSHAKTI=$withval],[HYDROLOGYSHAKTI=yes])
-
 AC_MSG_CHECKING(for HydrologyShakti capability compilation)
 
-
 HAVE_HYDROLOGYSHAKTI=no 
-
 if test "x$HYDROLOGYSHAKTI" = "xyes"; then
-
 	HAVE_HYDROLOGYSHAKTI=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYSHAKTI_],[1],[with HydrologyShakti capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYSHAKTI], [test x$HAVE_HYDROLOGYSHAKTI = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYSHAKTI)
-
 dnl }}}
 dnl with-HydrologyShreve{{{
-
 AC_ARG_WITH([HydrologyShreve],
-
 	AS_HELP_STRING([--with-HydrologyShreve = YES], [compile with HydrologyShreve capabilities (default is yes)]),
-
 	[HYDROLOGYSHREVE=$withval],[HYDROLOGYSHREVE=yes])
-
 AC_MSG_CHECKING(for HydrologyShreve capability compilation)
 
-
 HAVE_HYDROLOGYSHREVE=no 
-
 if test "x$HYDROLOGYSHREVE" = "xyes"; then
-
 	HAVE_HYDROLOGYSHREVE=yes
-
 	AC_DEFINE([_HAVE_HYDROLOGYSHREVE_],[1],[with HydrologyShreve capability])
-
-fi
-
+fi
 AM_CONDITIONAL([HYDROLOGYSHREVE], [test x$HAVE_HYDROLOGYSHREVE = xyes])
-
 AC_MSG_RESULT($HAVE_HYDROLOGYSHREVE)
-
 dnl }}}
 dnl with-L2ProjectionBase{{{
-
 AC_ARG_WITH([L2ProjectionBase],
-
 	AS_HELP_STRING([--with-L2ProjectionBase = YES], [compile with L2ProjectionBase capabilities (default is yes)]),
-
 	[L2PROJECTIONBASE=$withval],[L2PROJECTIONBASE=yes])
-
 AC_MSG_CHECKING(for L2ProjectionBase capability compilation)
 
-
 HAVE_L2PROJECTIONBASE=no 
-
 if test "x$L2PROJECTIONBASE" = "xyes"; then
-
 	HAVE_L2PROJECTIONBASE=yes
-
 	AC_DEFINE([_HAVE_L2PROJECTIONBASE_],[1],[with L2ProjectionBase capability])
-
-fi
-
+fi
 AM_CONDITIONAL([L2PROJECTIONBASE], [test x$HAVE_L2PROJECTIONBASE = xyes])
-
 AC_MSG_RESULT($HAVE_L2PROJECTIONBASE)
-
 dnl }}}
 dnl with-L2ProjectionEPL{{{
-
 AC_ARG_WITH([L2ProjectionEPL],
-
 	AS_HELP_STRING([--with-L2ProjectionEPL = YES], [compile with L2ProjectionEPL capabilities (default is yes)]),
-
 	[L2PROJECTIONEPL=$withval],[L2PROJECTIONEPL=yes])
-
 AC_MSG_CHECKING(for L2ProjectionEPL capability compilation)
 
-
 HAVE_L2PROJECTIONEPL=no 
-
 if test "x$L2PROJECTIONEPL" = "xyes"; then
-
 	HAVE_L2PROJECTIONEPL=yes
-
 	AC_DEFINE([_HAVE_L2PROJECTIONEPL_],[1],[with L2ProjectionEPL capability])
-
-fi
-
+fi
 AM_CONDITIONAL([L2PROJECTIONEPL], [test x$HAVE_L2PROJECTIONEPL = xyes])
-
 AC_MSG_RESULT($HAVE_L2PROJECTIONEPL)
-
 dnl }}}
 dnl with-Levelset{{{
-
 AC_ARG_WITH([Levelset],
-
 	AS_HELP_STRING([--with-Levelset = YES], [compile with Levelset capabilities (default is yes)]),
-
 	[LEVELSET=$withval],[LEVELSET=yes])
-
 AC_MSG_CHECKING(for Levelset capability compilation)
 
-
 HAVE_LEVELSET=no 
-
 if test "x$LEVELSET" = "xyes"; then
-
 	HAVE_LEVELSET=yes
-
 	AC_DEFINE([_HAVE_LEVELSET_],[1],[with Levelset capability])
-
-fi
-
+fi
 AM_CONDITIONAL([LEVELSET], [test x$HAVE_LEVELSET = xyes])
-
 AC_MSG_RESULT($HAVE_LEVELSET)
-
 dnl }}}
 dnl with-Love{{{
-
 AC_ARG_WITH([Love],
-
 	AS_HELP_STRING([--with-Love = YES], [compile with Love capabilities (default is yes)]),
-
 	[LOVE=$withval],[LOVE=yes])
-
 AC_MSG_CHECKING(for Love capability compilation)
 
-
 HAVE_LOVE=no 
-
 if test "x$LOVE" = "xyes"; then
-
 	HAVE_LOVE=yes
-
 	AC_DEFINE([_HAVE_LOVE_],[1],[with Love capability])
-
-fi
-
+fi
 AM_CONDITIONAL([LOVE], [test x$HAVE_LOVE = xyes])
-
 AC_MSG_RESULT($HAVE_LOVE)
-
 dnl }}}
 dnl with-Masstransport{{{
-
 AC_ARG_WITH([Masstransport],
-
 	AS_HELP_STRING([--with-Masstransport = YES], [compile with Masstransport capabilities (default is yes)]),
-
 	[MASSTRANSPORT=$withval],[MASSTRANSPORT=yes])
-
 AC_MSG_CHECKING(for Masstransport capability compilation)
 
-
 HAVE_MASSTRANSPORT=no 
-
 if test "x$MASSTRANSPORT" = "xyes"; then
-
 	HAVE_MASSTRANSPORT=yes
-
 	AC_DEFINE([_HAVE_MASSTRANSPORT_],[1],[with Masstransport capability])
-
-fi
-
+fi
 AM_CONDITIONAL([MASSTRANSPORT], [test x$HAVE_MASSTRANSPORT = xyes])
-
 AC_MSG_RESULT($HAVE_MASSTRANSPORT)
-
 dnl }}}
 dnl with-Melting{{{
-
 AC_ARG_WITH([Melting],
-
 	AS_HELP_STRING([--with-Melting = YES], [compile with Melting capabilities (default is yes)]),
-
 	[MELTING=$withval],[MELTING=yes])
-
 AC_MSG_CHECKING(for Melting capability compilation)
 
-
 HAVE_MELTING=no 
-
 if test "x$MELTING" = "xyes"; then
-
 	HAVE_MELTING=yes
-
 	AC_DEFINE([_HAVE_MELTING_],[1],[with Melting capability])
-
-fi
-
+fi
 AM_CONDITIONAL([MELTING], [test x$HAVE_MELTING = xyes])
-
 AC_MSG_RESULT($HAVE_MELTING)
-
 dnl }}}
 dnl with-Oceantransport{{{
-
 AC_ARG_WITH([Oceantransport],
-
 	AS_HELP_STRING([--with-Oceantransport = YES], [compile with Oceantransport capabilities (default is yes)]),
-
 	[OCEANTRANSPORT=$withval],[OCEANTRANSPORT=yes])
-
 AC_MSG_CHECKING(for Oceantransport capability compilation)
 
-
 HAVE_OCEANTRANSPORT=no 
-
 if test "x$OCEANTRANSPORT" = "xyes"; then
-
 	HAVE_OCEANTRANSPORT=yes
-
 	AC_DEFINE([_HAVE_OCEANTRANSPORT_],[1],[with Oceantransport capability])
-
-fi
-
+fi
 AM_CONDITIONAL([OCEANTRANSPORT], [test x$HAVE_OCEANTRANSPORT = xyes])
-
 AC_MSG_RESULT($HAVE_OCEANTRANSPORT)
-
 dnl }}}
 dnl with-Recovery{{{
-
 AC_ARG_WITH([Recovery],
-
 	AS_HELP_STRING([--with-Recovery = YES], [compile with Recovery capabilities (default is yes)]),
-
 	[RECOVERY=$withval],[RECOVERY=yes])
-
 AC_MSG_CHECKING(for Recovery capability compilation)
 
-
 HAVE_RECOVERY=no 
-
 if test "x$RECOVERY" = "xyes"; then
-
 	HAVE_RECOVERY=yes
-
 	AC_DEFINE([_HAVE_RECOVERY_],[1],[with Recovery capability])
-
-fi
-
+fi
 AM_CONDITIONAL([RECOVERY], [test x$HAVE_RECOVERY = xyes])
-
 AC_MSG_RESULT($HAVE_RECOVERY)
-
 dnl }}}
 dnl with-Sampling{{{
-
 AC_ARG_WITH([Sampling],
-
 	AS_HELP_STRING([--with-Sampling = YES], [compile with Sampling capabilities (default is yes)]),
-
 	[SAMPLING=$withval],[SAMPLING=yes])
-
 AC_MSG_CHECKING(for Sampling capability compilation)
 
-
 HAVE_SAMPLING=no 
-
 if test "x$SAMPLING" = "xyes"; then
-
 	HAVE_SAMPLING=yes
-
 	AC_DEFINE([_HAVE_SAMPLING_],[1],[with Sampling capability])
-
-fi
-
+fi
 AM_CONDITIONAL([SAMPLING], [test x$HAVE_SAMPLING = xyes])
-
 AC_MSG_RESULT($HAVE_SAMPLING)
-
 dnl }}}
 dnl with-Sealevelchange{{{
-
 AC_ARG_WITH([Sealevelchange],
-
 	AS_HELP_STRING([--with-Sealevelchange = YES], [compile with Sealevelchange capabilities (default is yes)]),
-
 	[SEALEVELCHANGE=$withval],[SEALEVELCHANGE=yes])
-
 AC_MSG_CHECKING(for Sealevelchange capability compilation)
 
-
 HAVE_SEALEVELCHANGE=no 
-
 if test "x$SEALEVELCHANGE" = "xyes"; then
-
 	HAVE_SEALEVELCHANGE=yes
-
 	AC_DEFINE([_HAVE_SEALEVELCHANGE_],[1],[with Sealevelchange capability])
-
-fi
-
+fi
 AM_CONDITIONAL([SEALEVELCHANGE], [test x$HAVE_SEALEVELCHANGE = xyes])
-
 AC_MSG_RESULT($HAVE_SEALEVELCHANGE)
-
 dnl }}}
 dnl with-Smb{{{
-
 AC_ARG_WITH([Smb],
-
 	AS_HELP_STRING([--with-Smb = YES], [compile with Smb capabilities (default is yes)]),
-
 	[SMB=$withval],[SMB=yes])
-
 AC_MSG_CHECKING(for Smb capability compilation)
 
-
 HAVE_SMB=no 
-
 if test "x$SMB" = "xyes"; then
-
 	HAVE_SMB=yes
-
 	AC_DEFINE([_HAVE_SMB_],[1],[with Smb capability])
-
-fi
-
+fi
 AM_CONDITIONAL([SMB], [test x$HAVE_SMB = xyes])
-
 AC_MSG_RESULT($HAVE_SMB)
-
 dnl }}}
 dnl with-Smooth{{{
-
 AC_ARG_WITH([Smooth],
-
 	AS_HELP_STRING([--with-Smooth = YES], [compile with Smooth capabilities (default is yes)]),
-
 	[SMOOTH=$withval],[SMOOTH=yes])
-
 AC_MSG_CHECKING(for Smooth capability compilation)
 
-
 HAVE_SMOOTH=no 
-
 if test "x$SMOOTH" = "xyes"; then
-
 	HAVE_SMOOTH=yes
-
 	AC_DEFINE([_HAVE_SMOOTH_],[1],[with Smooth capability])
-
-fi
-
+fi
 AM_CONDITIONAL([SMOOTH], [test x$HAVE_SMOOTH = xyes])
-
 AC_MSG_RESULT($HAVE_SMOOTH)
-
 dnl }}}
 dnl with-Stressbalance{{{
-
 AC_ARG_WITH([Stressbalance],
-
 	AS_HELP_STRING([--with-Stressbalance = YES], [compile with Stressbalance capabilities (default is yes)]),
-
 	[STRESSBALANCE=$withval],[STRESSBALANCE=yes])
-
 AC_MSG_CHECKING(for Stressbalance capability compilation)
 
-
 HAVE_STRESSBALANCE=no 
-
 if test "x$STRESSBALANCE" = "xyes"; then
-
 	HAVE_STRESSBALANCE=yes
-
 	AC_DEFINE([_HAVE_STRESSBALANCE_],[1],[with Stressbalance capability])
-
-fi
-
+fi
 AM_CONDITIONAL([STRESSBALANCE], [test x$HAVE_STRESSBALANCE = xyes])
-
 AC_MSG_RESULT($HAVE_STRESSBALANCE)
-
 dnl }}}
 dnl with-StressbalanceSIA{{{
-
 AC_ARG_WITH([StressbalanceSIA],
-
 	AS_HELP_STRING([--with-StressbalanceSIA = YES], [compile with StressbalanceSIA capabilities (default is yes)]),
-
 	[STRESSBALANCESIA=$withval],[STRESSBALANCESIA=yes])
-
 AC_MSG_CHECKING(for StressbalanceSIA capability compilation)
 
-
 HAVE_STRESSBALANCESIA=no 
-
 if test "x$STRESSBALANCESIA" = "xyes"; then
-
 	HAVE_STRESSBALANCESIA=yes
-
 	AC_DEFINE([_HAVE_STRESSBALANCESIA_],[1],[with StressbalanceSIA capability])
-
-fi
-
+fi
 AM_CONDITIONAL([STRESSBALANCESIA], [test x$HAVE_STRESSBALANCESIA = xyes])
-
 AC_MSG_RESULT($HAVE_STRESSBALANCESIA)
-
 dnl }}}
 dnl with-StressbalanceVertical{{{
-
 AC_ARG_WITH([StressbalanceVertical],
-
 	AS_HELP_STRING([--with-StressbalanceVertical = YES], [compile with StressbalanceVertical capabilities (default is yes)]),
-
 	[STRESSBALANCEVERTICAL=$withval],[STRESSBALANCEVERTICAL=yes])
-
 AC_MSG_CHECKING(for StressbalanceVertical capability compilation)
 
-
 HAVE_STRESSBALANCEVERTICAL=no 
-
 if test "x$STRESSBALANCEVERTICAL" = "xyes"; then
-
 	HAVE_STRESSBALANCEVERTICAL=yes
-
 	AC_DEFINE([_HAVE_STRESSBALANCEVERTICAL_],[1],[with StressbalanceVertical capability])
-
-fi
-
+fi
 AM_CONDITIONAL([STRESSBALANCEVERTICAL], [test x$HAVE_STRESSBALANCEVERTICAL = xyes])
-
 AC_MSG_RESULT($HAVE_STRESSBALANCEVERTICAL)
-
 dnl }}}
 dnl with-Thermal{{{
-
 AC_ARG_WITH([Thermal],
-
 	AS_HELP_STRING([--with-Thermal = YES], [compile with Thermal capabilities (default is yes)]),
-
 	[THERMAL=$withval],[THERMAL=yes])
-
 AC_MSG_CHECKING(for Thermal capability compilation)
 
-
 HAVE_THERMAL=no 
-
 if test "x$THERMAL" = "xyes"; then
-
 	HAVE_THERMAL=yes
-
 	AC_DEFINE([_HAVE_THERMAL_],[1],[with Thermal capability])
-
-fi
-
+fi
 AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
-
 AC_MSG_RESULT($HAVE_THERMAL)
-
 dnl }}}
 dnl with-UzawaPressure{{{
-
 AC_ARG_WITH([UzawaPressure],
-
 	AS_HELP_STRING([--with-UzawaPressure = YES], [compile with UzawaPressure capabilities (default is yes)]),
-
 	[UZAWAPRESSURE=$withval],[UZAWAPRESSURE=yes])
-
 AC_MSG_CHECKING(for UzawaPressure capability compilation)
 
-
 HAVE_UZAWAPRESSURE=no 
-
 if test "x$UZAWAPRESSURE" = "xyes"; then
-
 	HAVE_UZAWAPRESSURE=yes
-
 	AC_DEFINE([_HAVE_UZAWAPRESSURE_],[1],[with UzawaPressure capability])
-
-fi
-
+fi
 AM_CONDITIONAL([UZAWAPRESSURE], [test x$HAVE_UZAWAPRESSURE = xyes])
-
 AC_MSG_RESULT($HAVE_UZAWAPRESSURE)
-
 dnl }}}
 
Index: issm/trunk/m4/issm_options.m4
===================================================================
--- issm/trunk/m4/issm_options.m4	(revision 27035)
+++ issm/trunk/m4/issm_options.m4	(revision 27232)
@@ -196,4 +196,8 @@
 			IS_MAC=yes
 			AC_DEFINE([_MAC_], [1], [is macOS])
+			dnl When standard Dakota installation has been updated to new 
+			dnl version, remove the following
+			export CFLAGS="-Wno-deprecated-register -Wno-return-type"
+			export CXXFLAGS="-Wno-deprecated-register -Wno-return-type"
 		;;
 		*)
@@ -644,4 +648,5 @@
 		dnl TODO:
 		dnl - Should we also be checking if HAVE_BOOST before adding boost libs?
+		dnl - Clean up the following conditionals
 		dnl
 		case "${host_os}" in
@@ -668,5 +673,38 @@
 				elif test "${DAKOTA_VERSION}" == "6.1" || test "${DAKOTA_VERSION}" == "6.2"; then
 					if test "${BOOST_VERSION_MAJOR}" == "1"; then
-						DAKOTAFLAGS="-DHAVE_CONFIG_H -DHAVE_CONFIG_H -DDISABLE_DAKOTA_CONFIG_H -DBOOST_DISABLE_ASSERTS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DHAVE_ADAPTIVE_SAMPLING -DHAVE_ESM -DHAVE_QUESO -DHAVE_QUESO_GPMSA -DHAVE_CONMIN -DHAVE_DDACE -DHAVE_DREAM -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_NOMAD -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+						DAKOTAFLAGS="-DHAVE_CONFIG_H -DDISABLE_DAKOTA_CONFIG_H -DBOOST_DISABLE_ASSERTS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DHAVE_ADAPTIVE_SAMPLING -DHAVE_ESM -DHAVE_QUESO -DHAVE_QUESO_GPMSA -DHAVE_CONMIN -DHAVE_DDACE -DHAVE_DREAM -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_NOMAD -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+						DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -llhs_mods -llhs_mod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack -lsurfpack_fortran -lqueso -lconmin -lddace -ldream -lfsudace -lhopspack -lncsuopt -lcport -lnomad -loptpp -lpsuade -lamplsolver"
+						DAKOTALIB+=" -L${BOOST_ROOT}/lib -lboost_filesystem -lboost_program_options -lboost_regex -lboost_serialization -lboost_system"
+						DAKOTALIB+=" ${BLASLAPACKLIB}"
+					fi
+					AC_DEFINE([DISABLE_DAKOTA_CONFIG_H], [1], [enabling DAKOTA_CONFIG_H])
+					AC_DEFINE([DAKOTA_HAVE_MPI], [1], [enabling Dakota with MPI])
+				elif test "${DAKOTA_VERSION}" == "6.11"; then
+					if test "${BOOST_VERSION_MAJOR}" == "1"; then
+						if test "${BOOST_VERSION_MINOR}" == "55"; then
+							DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+							DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldream -lfsudace -lddace -lnomad -lpecos_src -llhs -llhs_mods -loptpp -lsurfpack -lconmin -ldakota_src_fortran -llhs_mod -lncsuopt -lsurfpack_fortran -lteuchos -lamplsolver -lcport -ldfftpack -lfsudace -lhopspack -lnidr -lpecos -lpsuade -lsparsegrid -L$BOOST_ROOT/lib -lboost_serialization -lboost_signals -lboost_regex -lboost_filesystem -lboost_system ${BLASLAPACKLIB}"
+						elif test "${BOOST_VERSION_MINOR}" == "72"; then
+							DAKOTAFLAGS="-DHAVE_CONFIG_H -DDISABLE_DAKOTA_CONFIG_H -DBOOST_DISABLE_ASSERTS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DHAVE_ADAPTIVE_SAMPLING -DHAVE_ESM -DHAVE_CONMIN -DHAVE_DDACE -DHAVE_DREAM -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_NOMAD -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+							DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchosremainder -lteuchosnumerics -lteuchoscomm -lteuchosparameterlist -lteuchosparser -lteuchoscore -lpecos_util -lpecos_src -llhs -llhs_mods -llhs_mod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack -lsurfpack_fortran -lapproxnn -lconmin -lddace -ldream -lfsudace -lhopspack -lncsuopt -lcport -lnomad -loptpp -lpsuade -lamplsolver -L${BOOST_ROOT}/lib -lboost_filesystem -lboost_program_options -lboost_regex -lboost_serialization -lboost_system ${BLASLAPACKLIB}"
+						fi
+					fi
+					AC_DEFINE([DISABLE_DAKOTA_CONFIG_H], [1], [enabling DAKOTA_CONFIG_H])
+					AC_DEFINE([DAKOTA_HAVE_MPI], [1], [enabling Dakota with MPI])
+				else
+					AC_MSG_ERROR([Dakota version not found or version (${DAKOTA_VERSION}) not supported!]);
+				fi
+			;;
+			*linux*)
+				if test "${DAKOTA_VERSION}" == "5.1" || test "${DAKOTA_VERSION}" == "5.2"; then
+					DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system -ldl"
+				elif test "${DAKOTA_VERSION}" == "5.3" || test "${DAKOTA_VERSION}" == "5.3.1"; then
+					DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_COLINY -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_JEGA -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+					DAKOTALIB="-L${DAKOTA_ROOT}/lib -L${BOOST_ROOT}/lib -ldakota_src -lpecos_src -lscolib -ljega_fe -llhs -lpebbl -lcolin -linterfaces -lmods -lmoga -loptpp -lsampling -lsoga -lsurfpack -lutilib -lconmin -ldakota_src_fortran -lmod -lncsuopt -lsurfpack_fortran -lteuchos -l3po -lamplsolver -lanalyzer -lbose -lcport -ldace -ldfftpack -leutils -lfsudace -lhopspack -ljega -lnidr -lpecos -lpsuade -lrandom -ltinyxml -lutilities -lsparsegrid -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
+					AC_DEFINE([DISABLE_DAKOTA_CONFIG_H], [1], [enabling DAKOTA_CONFIG_H])
+					AC_DEFINE([DAKOTA_HAVE_MPI], [1], [enabling Dakota with MPI])
+				elif test "${DAKOTA_VERSION}" == "6.1" || test "${DAKOTA_VERSION}" == "6.2"; then
+					if test "${BOOST_VERSION_MAJOR}" == "1"; then
+						DAKOTAFLAGS="-DHAVE_CONFIG_H -DDISABLE_DAKOTA_CONFIG_H -DBOOST_DISABLE_ASSERTS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DHAVE_ADAPTIVE_SAMPLING -DHAVE_ESM -DHAVE_QUESO -DHAVE_QUESO_GPMSA -DHAVE_CONMIN -DHAVE_DDACE -DHAVE_DREAM -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_NOMAD -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
 						DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -llhs_mods -llhs_mod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack -lsurfpack_fortran -lqueso -lconmin -lddace -ldream -lfsudace -lhopspack -lncsuopt -lcport -lnomad -loptpp -lpsuade -lamplsolver"
 						DAKOTALIB+=" -L${BOOST_ROOT}/lib -lboost_filesystem -lboost_program_options -lboost_regex -lboost_serialization -lboost_system"
@@ -691,37 +729,4 @@
 				fi
 			;;
-			*linux*)
-				if test "${DAKOTA_VERSION}" == "5.1" || test "${DAKOTA_VERSION}" == "5.2"; then
-					DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system -ldl"
-				elif test "${DAKOTA_VERSION}" == "5.3" || test "${DAKOTA_VERSION}" == "5.3.1"; then
-					DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_COLINY -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_JEGA -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
-					DAKOTALIB="-L${DAKOTA_ROOT}/lib -L${BOOST_ROOT}/lib -ldakota_src -lpecos_src -lscolib -ljega_fe -llhs -lpebbl -lcolin -linterfaces -lmods -lmoga -loptpp -lsampling -lsoga -lsurfpack -lutilib -lconmin -ldakota_src_fortran -lmod -lncsuopt -lsurfpack_fortran -lteuchos -l3po -lamplsolver -lanalyzer -lbose -lcport -ldace -ldfftpack -leutils -lfsudace -lhopspack -ljega -lnidr -lpecos -lpsuade -lrandom -ltinyxml -lutilities -lsparsegrid -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
-					AC_DEFINE([DISABLE_DAKOTA_CONFIG_H], [1], [enabling DAKOTA_CONFIG_H])
-					AC_DEFINE([DAKOTA_HAVE_MPI], [1], [enabling Dakota with MPI])
-				elif test "${DAKOTA_VERSION}" == "6.1" || test "${DAKOTA_VERSION}" == "6.2"; then
-					if test "${BOOST_VERSION_MAJOR}" == "1"; then
-						DAKOTAFLAGS="-DHAVE_CONFIG_H -DHAVE_CONFIG_H -DDISABLE_DAKOTA_CONFIG_H -DBOOST_DISABLE_ASSERTS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DHAVE_ADAPTIVE_SAMPLING -DHAVE_ESM -DHAVE_QUESO -DHAVE_QUESO_GPMSA -DHAVE_CONMIN -DHAVE_DDACE -DHAVE_DREAM -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_NOMAD -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
-						DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -llhs_mods -llhs_mod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack -lsurfpack_fortran -lqueso -lconmin -lddace -ldream -lfsudace -lhopspack -lncsuopt -lcport -lnomad -loptpp -lpsuade -lamplsolver"
-						DAKOTALIB+=" -L${BOOST_ROOT}/lib -lboost_filesystem -lboost_program_options -lboost_regex -lboost_serialization -lboost_system"
-						DAKOTALIB+=" ${BLASLAPACKLIB}"
-					fi
-					AC_DEFINE([DISABLE_DAKOTA_CONFIG_H], [1], [enabling DAKOTA_CONFIG_H])
-					AC_DEFINE([DAKOTA_HAVE_MPI], [1], [enabling Dakota with MPI])
-				elif test "${DAKOTA_VERSION}" == "6.11"; then
-					if test "${BOOST_VERSION_MAJOR}" == "1"; then
-						if test "${BOOST_VERSION_MINOR}" == "55"; then
-							DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
-							DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldream -lfsudace -lddace -lnomad -lpecos_src -llhs -llhs_mods -loptpp -lsurfpack -lconmin -ldakota_src_fortran -llhs_mod -lncsuopt -lsurfpack_fortran -lteuchos -lamplsolver -lcport -ldfftpack -lfsudace -lhopspack -lnidr -lpecos -lpsuade -lsparsegrid -L$BOOST_ROOT/lib -lboost_serialization -lboost_signals -lboost_regex -lboost_filesystem -lboost_system ${BLASLAPACKLIB}"
-						elif test "${BOOST_VERSION_MINOR}" == "72"; then
-							DAKOTAFLAGS="-DHAVE_CONFIG_H -DHAVE_CONFIG_H -DDISABLE_DAKOTA_CONFIG_H -DBOOST_DISABLE_ASSERTS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DHAVE_ADAPTIVE_SAMPLING -DHAVE_ESM -DHAVE_CONMIN -DHAVE_DDACE -DHAVE_DREAM -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_NOMAD -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
-							DAKOTALIB="-L${DAKOTA_ROOT}/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchosremainder -lteuchosnumerics -lteuchoscomm -lteuchosparameterlist -lteuchosparser -lteuchoscore -lpecos_util -lpecos_src -llhs -llhs_mods -llhs_mod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack -lsurfpack_fortran -lapproxnn -lconmin -lddace -ldream -lfsudace -lhopspack -lncsuopt -lcport -lnomad -loptpp -lpsuade -lamplsolver -L${BOOST_ROOT}/lib -lboost_filesystem -lboost_program_options -lboost_regex -lboost_serialization -lboost_system ${BLASLAPACKLIB}"
-						fi
-					fi
-					AC_DEFINE([DISABLE_DAKOTA_CONFIG_H], [1], [enabling DAKOTA_CONFIG_H])
-					AC_DEFINE([DAKOTA_HAVE_MPI], [1], [enabling Dakota with MPI])
-				else
-					AC_MSG_ERROR([Dakota version not found or version (${DAKOTA_VERSION}) not supported!]);
-				fi
-			;;
 		esac
 
@@ -826,8 +831,10 @@
 		elif ls ${PYTHON_ROOT}/lib/libpython${PYTHON_VERSION}m.* 1> /dev/null 2>&1; then
 			PYTHONLIB="-L${PYTHON_ROOT}/lib -lpython${PYTHON_VERSION}m"
+		elif ls ${PYTHON_ROOT}/lib/libpython${PYTHON_VERSION}.* 1> /dev/null 2>&1; then
+			PYTHONLIB="-L${PYTHON_ROOT}/lib -lpython${PYTHON_VERSION}"
 		elif ls ${PYTHON_ROOT}/lib64/libpython${PYTHON_VERSION}m.* 1> /dev/null 2>&1; then
 			PYTHONLIB="-L${PYTHON_ROOT}/lib64 -lpython${PYTHON_VERSION}m"
-		elif ls ${PYTHON_ROOT}/lib/libpython${PYTHON_VERSION}.* 1> /dev/null 2>&1; then
-			PYTHONLIB="-L${PYTHON_ROOT}/lib -lpython${PYTHON_VERSION}"
+		elif ls ${PYTHON_ROOT}/lib64/libpython${PYTHON_VERSION}.* 1> /dev/null 2>&1; then
+			PYTHONLIB="-L${PYTHON_ROOT}/lib64 -lpython${PYTHON_VERSION}"
 		else
 			AC_MSG_ERROR([libpython not found! Please locate this file and contact ISSM developers via forum or email.]);
@@ -2748,5 +2755,5 @@
 		AS_HELP_STRING([--with-cxxoptflags=CXXOPTFLAGS], [C++ optimization flags (i.e. --with-cxxoptflags="-march=opteron -O3 -std=c++11"]),
 		[CXXOPTFLAGS=${withval}],
-		[CXXOPTFLAGS="-g -O2 -fPIC -std=c++11"]
+		[CXXOPTFLAGS="-g -O2 -fPIC -std=c++11 -D_DO_NOT_LOAD_GLOBALS_"]
 	)
 	AC_SUBST([CXXOPTFLAGS])
Index: issm/trunk/packagers/linux/complete-issm-linux-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/linux/complete-issm-linux-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/linux/complete-issm-linux-binaries-matlab.sh	(revision 27232)
@@ -6,5 +6,5 @@
 #
 # Normally, we would put this directly into the project configuration under 
-# 'Build' -> 'Excute shell', but becasue it is a bit more involved, it is a 
+# 'Build' -> 'Execute shell', but because it is a bit more involved, it is a 
 # good idea to version it.
 #
Index: issm/trunk/packagers/linux/complete-issm-linux-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/linux/complete-issm-linux-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/linux/complete-issm-linux-binaries-python-2.sh	(revision 27232)
@@ -6,5 +6,5 @@
 #
 # Normally, we would put this directly into the project configuration under 
-# 'Build' -> 'Excute shell', but becasue it is a bit more involved, it is a 
+# 'Build' -> 'Execute shell', but because it is a bit more involved, it is a 
 # good idea to version it.
 #
Index: issm/trunk/packagers/linux/complete-issm-linux-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/linux/complete-issm-linux-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/linux/complete-issm-linux-binaries-python-3.sh	(revision 27232)
@@ -6,5 +6,5 @@
 #
 # Normally, we would put this directly into the project configuration under 
-# 'Build' -> 'Excute shell', but becasue it is a bit more involved, it is a 
+# 'Build' -> 'Execute shell', but because it is a bit more involved, it is a 
 # good idea to version it.
 #
Index: issm/trunk/packagers/linux/package-issm-linux-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/linux/package-issm-linux-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/linux/package-issm-linux-binaries-matlab.sh	(revision 27232)
@@ -112,4 +112,22 @@
 cp ${LIBGFORTRAN} ${LIBGFORTRAN_DIST} 2> /dev/null
 
+echo "Moving GSHHG assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/gmt/install/share/coast ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/gmt/install/share/coast ${ISSM_DIR}/share
+else
+	echo "GSHHG not found"
+	exit 1
+fi
+
+echo "Moving PROJ assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/proj/install/share/proj ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/proj/install/share/proj ${ISSM_DIR}/share
+else
+	echo "PROJ not found"
+	exit 1
+fi
+
 # Run tests
 if [ ${skip_tests} -eq 0 ]; then
@@ -119,8 +137,8 @@
 
 	# Run tests, redirecting output to logfile and suppressing output to console
-	${MATLAB_PATH}/bin/matlab -nojvm -nosplash -nojvm -r "try, addpath ${ISSM_DIR}/bin ${ISSM_DIR}/lib; runme(${MATLAB_NROPTIONS}); exit; catch me,fprintf('%s',getReport(me)); exit; end" &> matlab.log
+	${MATLAB_PATH}/bin/matlab -nojvm -nosplash -nojvm -r "try, addpath ${ISSM_DIR}/bin ${ISSM_DIR}/lib ${ISSM_DIR}/share; runme(${MATLAB_NROPTIONS}); exit; catch me,fprintf('%s',getReport(me)); exit; end" &> matlab.log
 
 	# Check that MATLAB did not exit in error
-	matlabExitedInError=`grep -E "Activation cannot proceed|Error in matlab_run|Illegal use of reserved keyword" matlab.log | wc -l`
+	matlabExitedInError=`grep -c -E "Activation cannot proceed|Error in matlab_run|Illegal use of reserved keyword|Invalid MEX-file" matlab.log`
 
 	if [ ${matlabExitedInError} -ne 0 ]; then
@@ -136,8 +154,10 @@
 
 	# Check that all tests passed
-	numTestsFailed=`cat matlab.log | grep -c -e "FAILED|ERROR"`
+	sed -i "/FAILED TO establish the default connection to the WindowServer/d" matlab.log # First, need to remove WindowServer error message
+	numTestsFailed=`grep -c -E "FAILED|ERROR" matlab.log`
 
 	if [ ${numTestsFailed} -ne 0 ]; then
 		echo "One or more tests FAILED"
+		cat matlab.log
 		exit 1
 	else
@@ -152,5 +172,5 @@
 svn cleanup --remove-ignored --remove-unversioned test # Clean up test directory (before copying to package)
 echo "Copying assets to package: ${PKG}"
-cp -rf bin examples lib scripts test ${PKG}
+cp -rf bin examples lib scripts share test ${PKG}
 mkdir ${PKG}/execution
 echo "Cleaning up unneeded/unwanted files"
Index: issm/trunk/packagers/linux/package-issm-linux-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/linux/package-issm-linux-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/linux/package-issm-linux-binaries-python-2.sh	(revision 27232)
@@ -105,4 +105,21 @@
 cp ${LIBGFORTRAN} ${LIBGFORTRAN_DIST} 2> /dev/null
 
+echo "Moving GSHHG assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/gmt/install/share/coast ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/gmt/install/share/coast ${ISSM_DIR}/share
+else
+	echo "GSHHG not found"
+	exit 1
+fi
+
+echo "Moving PROJ assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/proj/install/share/proj ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/proj/install/share/proj ${ISSM_DIR}/share
+else
+	echo "PROJ not found"
+	exit 1
+fi
 
 # Run tests
@@ -122,5 +139,5 @@
 	# Check that Python did not exit in error
 	pythonExitCode=`echo $?`
-	pythonExitedInError=`grep -E "Error|Standard exception|Traceback|bad interpreter" python.log | wc -l`
+	pythonExitedInError=`grep -c -E "Error|Standard exception|Traceback|bad interpreter" python.log`
 
 	if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
@@ -136,8 +153,10 @@
 
 	# Check that all tests passed
-	numTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`
+	sed -i "/FAILED TO establish the default connection to the WindowServer/d" python.log # First, need to remove WindowServer error message
+	numTestsFailed=`grep -c -E "FAILED|ERROR" python.log`
 
 	if [[ ${numTestsFailed} -ne 0 ]]; then
 		echo "One or more tests FAILED"
+		cat python.log
 		exit 1
 	else
@@ -152,5 +171,5 @@
 svn cleanup --remove-ignored --remove-unversioned test # Clean up test directory (before copying to package)
 echo "Copying assets to package: ${PKG}"
-cp -rf bin examples lib scripts test ${PKG}
+cp -rf bin examples lib scripts share test ${PKG}
 mkdir ${PKG}/execution
 ${ISSM_DIR}/scripts/py_to_pyc.sh ${PKG}/bin # Compile Python source files
Index: issm/trunk/packagers/linux/package-issm-linux-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/linux/package-issm-linux-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/linux/package-issm-linux-binaries-python-3.sh	(revision 27232)
@@ -105,4 +105,21 @@
 cp ${LIBGFORTRAN} ${LIBGFORTRAN_DIST} 2> /dev/null
 
+echo "Moving GSHHG assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/gmt/install/share/coast ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/gmt/install/share/coast ${ISSM_DIR}/share
+else
+	echo "GSHHG not found"
+	exit 1
+fi
+
+echo "Moving PROJ assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/proj/install/share/proj ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/proj/install/share/proj ${ISSM_DIR}/share
+else
+	echo "PROJ not found"
+	exit 1
+fi
 
 # Run tests
@@ -125,5 +142,5 @@
 	# Check that Python did not exit in error
 	pythonExitCode=`echo $?`
-	pythonExitedInError=`grep -E "Error|Standard exception|Traceback|bad interpreter" python.log | wc -l`
+	pythonExitedInError=`grep -c -E "Error|Standard exception|Traceback|bad interpreter" python.log`
 
 	if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
@@ -139,8 +156,10 @@
 
 	# Check that all tests passed
-	numTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`
+	sed -i "/FAILED TO establish the default connection to the WindowServer/d" python.log # First, need to remove WindowServer error message
+	numTestsFailed=`grep -c -E "FAILED|ERROR" python.log`
 
 	if [[ ${numTestsFailed} -ne 0 ]]; then
 		echo "One or more tests FAILED"
+		cat python.log
 		exit 1
 	else
@@ -155,5 +174,5 @@
 svn cleanup --remove-ignored --remove-unversioned test # Clean up test directory (before copying to package)
 echo "Copying assets to package: ${PKG}"
-cp -rf bin examples lib scripts test ${PKG}
+cp -rf bin examples lib scripts share test ${PKG}
 mkdir ${PKG}/execution
 ${ISSM_DIR}/scripts/py_to_pyc.sh ${PKG}/bin # Compile Python source files
Index: issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-matlab.sh	(revision 27232)
@@ -138,4 +138,6 @@
 	echo "Removing lock file from repository for signed packages"
 	svn update \
+		--trust-server-cert \
+		--non-interactive \
 		--username ${ISSM_BINARIES_REPO_USER} \
 		--password ${ISSM_BINARIES_REPO_PASS} \
@@ -156,4 +158,6 @@
 # If lock file exists, a signing build is still in process by JPL Cybersecurity
 svn update \
+	--trust-server-cert \
+	--non-interactive \
 	--username ${ISSM_BINARIES_REPO_USER} \
 	--password ${ISSM_BINARIES_REPO_PASS} \
@@ -214,4 +218,6 @@
 	sleep ${SIGNING_CHECK_PERIOD}
 	svn update \
+		--trust-server-cert \
+		--non-interactive \
 		--username ${ISSM_BINARIES_REPO_USER} \
 		--password ${ISSM_BINARIES_REPO_PASS} \
@@ -221,4 +227,6 @@
 		# Retrieve notarization lock file
 		svn update \
+			--trust-server-cert \
+			--non-interactive \
 			--username ${ISSM_BINARIES_REPO_USER} \
 			--password ${ISSM_BINARIES_REPO_PASS} \
Index: issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-python-2.sh	(revision 27232)
@@ -138,4 +138,6 @@
 	echo "Removing lock file from repository for signed packages"
 	svn update \
+		--trust-server-cert \
+		--non-interactive \
 		--username ${ISSM_BINARIES_REPO_USER} \
 		--password ${ISSM_BINARIES_REPO_PASS} \
@@ -156,4 +158,6 @@
 # If lock file exists, a signing build is still in process by JPL Cybersecurity
 svn update \
+	--trust-server-cert \
+	--non-interactive \
 	--username ${ISSM_BINARIES_REPO_USER} \
 	--password ${ISSM_BINARIES_REPO_PASS} \
@@ -214,4 +218,6 @@
 	sleep ${SIGNING_CHECK_PERIOD}
 	svn update \
+		--trust-server-cert \
+		--non-interactive \
 		--username ${ISSM_BINARIES_REPO_USER} \
 		--password ${ISSM_BINARIES_REPO_PASS} \
@@ -221,4 +227,6 @@
 		# Retrieve notarization lock file
 		svn update \
+			--trust-server-cert \
+			--non-interactive \
 			--username ${ISSM_BINARIES_REPO_USER} \
 			--password ${ISSM_BINARIES_REPO_PASS} \
Index: issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/mac/commit_for_signing-issm-mac-binaries-python-3.sh	(revision 27232)
@@ -138,4 +138,6 @@
 	echo "Removing lock file from repository for signed packages"
 	svn update \
+		--trust-server-cert \
+		--non-interactive \
 		--username ${ISSM_BINARIES_REPO_USER} \
 		--password ${ISSM_BINARIES_REPO_PASS} \
@@ -156,4 +158,6 @@
 # If lock file exists, a signing build is still in process by JPL Cybersecurity
 svn update \
+	--trust-server-cert \
+	--non-interactive \
 	--username ${ISSM_BINARIES_REPO_USER} \
 	--password ${ISSM_BINARIES_REPO_PASS} \
@@ -214,4 +218,6 @@
 	sleep ${SIGNING_CHECK_PERIOD}
 	svn update \
+		--trust-server-cert \
+		--non-interactive \
 		--username ${ISSM_BINARIES_REPO_USER} \
 		--password ${ISSM_BINARIES_REPO_PASS} \
@@ -221,4 +227,6 @@
 		# Retrieve notarization lock file
 		svn update \
+			--trust-server-cert \
+			--non-interactive \
 			--username ${ISSM_BINARIES_REPO_USER} \
 			--password ${ISSM_BINARIES_REPO_PASS} \
Index: issm/trunk/packagers/mac/complete-issm-mac-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/mac/complete-issm-mac-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/mac/complete-issm-mac-binaries-matlab.sh	(revision 27232)
@@ -6,5 +6,5 @@
 #
 # Normally, we would put this directly into the project configuration under 
-# 'Build' -> 'Excute shell', but becasue it is a bit more involved, it is a 
+# 'Build' -> 'Execute shell', but because it is a bit more involved, it is a 
 # good idea to version it.
 #
@@ -33,10 +33,11 @@
 # Debugging:
 # - Relies on a very tight handshake with project on remote JPL Cybersecurity 
-#	Jenkins server. Debugging may be perfomed locally by running,
+#	Jenkins server. Debugging may be performed locally by running,
 #
 #		packagers/mac/sign-issm-mac-binaries-matlab.sh
 #
-#	with "ISSM_BINARIES_USER" and "ISSM_BINARIES_PASS" hardcoded to Apple 
-#	Developer credentials.
+#	with "AD_IDENTITY", "AD_USERNAME", and "ASC_PROVIDER" hardcoded to Apple 
+#	Developer credentials (make sure to also set keychain password in 
+#	"ALTOOL_PASSWORD").
 # - Removing stdout/stderr redirections to null device (> /dev/null 2>&1) can 
 #	help debug potential SVN issues.
Index: issm/trunk/packagers/mac/complete-issm-mac-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/mac/complete-issm-mac-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/mac/complete-issm-mac-binaries-python-2.sh	(revision 27232)
@@ -6,5 +6,5 @@
 #
 # Normally, we would put this directly into the project configuration under 
-# 'Build' -> 'Excute shell', but becasue it is a bit more involved, it is a 
+# 'Build' -> 'Execute shell', but because it is a bit more involved, it is a 
 # good idea to version it.
 #
@@ -33,10 +33,11 @@
 # Debugging:
 # - Relies on a very tight handshake with project on remote JPL Cybersecurity 
-#	Jenkins server. Debugging may be perfomed locally by running,
+#	Jenkins server. Debugging may be performed locally by running,
 #
 #		packagers/mac/sign-issm-mac-binaries-python-2.sh
 #
-#	with "ISSM_BINARIES_USER" and "ISSM_BINARIES_PASS" hardcoded to Apple 
-#	Developer credentials.
+#	with "AD_IDENTITY", "AD_USERNAME", and "ASC_PROVIDER" hardcoded to Apple 
+#	Developer credentials (make sure to also set keychain password in 
+#	"ALTOOL_PASSWORD").
 # - Removing stdout/stderr redirections to null device (> /dev/null 2>&1) can 
 #	help debug potential SVN issues.
Index: issm/trunk/packagers/mac/complete-issm-mac-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/mac/complete-issm-mac-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/mac/complete-issm-mac-binaries-python-3.sh	(revision 27232)
@@ -6,5 +6,5 @@
 #
 # Normally, we would put this directly into the project configuration under 
-# 'Build' -> 'Excute shell', but becasue it is a bit more involved, it is a 
+# 'Build' -> 'Execute shell', but because it is a bit more involved, it is a 
 # good idea to version it.
 #
@@ -33,10 +33,11 @@
 # Debugging:
 # - Relies on a very tight handshake with project on remote JPL Cybersecurity 
-#	Jenkins server. Debugging may be perfomed locally by running,
+#	Jenkins server. Debugging may be performed locally by running,
 #
 #		packagers/mac/sign-issm-mac-binaries-python-3.sh
 #
-#	with "ISSM_BINARIES_USER" and "ISSM_BINARIES_PASS" hardcoded to Apple 
-#	Developer credentials.
+#	with "AD_IDENTITY", "AD_USERNAME", and "ASC_PROVIDER" hardcoded to Apple 
+#	Developer credentials (make sure to also set keychain password in 
+#	"ALTOOL_PASSWORD").
 # - Removing stdout/stderr redirections to null device (> /dev/null 2>&1) can 
 #	help debug potential SVN issues.
Index: issm/trunk/packagers/mac/package-issm-mac-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/mac/package-issm-mac-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/mac/package-issm-mac-binaries-matlab.sh	(revision 27232)
@@ -109,4 +109,12 @@
 fi
 
+echo "Moving Gmsh binaries to bin/"
+if [ -f ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh ]; then
+	cp ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh .
+else
+	echo "Gmsh not found"
+	exit 1
+fi
+
 echo "Moving GMT binaries to bin/"
 if [ -f ${ISSM_DIR}/externalpackages/gmt/install/bin/gmt-config ]; then
@@ -118,9 +126,19 @@
 fi
 
-echo "Moving Gmsh binaries to bin/"
-if [ -f ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh ]; then
-	cp ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh .
+echo "Moving GSHHG assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/gmt/install/share/coast ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/gmt/install/share/coast ${ISSM_DIR}/share
 else
-	echo "Gmsh not found"
+	echo "GSHHG not found"
+	exit 1
+fi
+
+echo "Moving PROJ assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/proj/install/share/proj ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/proj/install/share/proj ${ISSM_DIR}/share
+else
+	echo "PROJ not found"
 	exit 1
 fi
@@ -133,8 +151,8 @@
 
 	# Run tests, redirecting output to logfile and suppressing output to console
-	${MATLAB_PATH}/bin/matlab -nojvm -nosplash -nojvm -r "try, addpath ${ISSM_DIR}/bin ${ISSM_DIR}/lib; runme(${MATLAB_NROPTIONS}); exit; catch me,fprintf('%s',getReport(me)); exit; end" &> matlab.log
+	${MATLAB_PATH}/bin/matlab -nojvm -nosplash -nojvm -r "try, addpath ${ISSM_DIR}/bin ${ISSM_DIR}/lib ${ISSM_DIR}/share; runme(${MATLAB_NROPTIONS}); exit; catch me,fprintf('%s',getReport(me)); exit; end" &> matlab.log
 
 	# Check that MATLAB did not exit in error
-	matlabExitedInError=`grep -E "Activation cannot proceed|Error in matlab_run|Illegal use of reserved keyword" matlab.log | wc -l`
+	matlabExitedInError=`grep -c -E "Activation cannot proceed|Error in matlab_run|Illegal use of reserved keyword" matlab.log`
 
 	if [ ${matlabExitedInError} -ne 0 ]; then
@@ -150,8 +168,10 @@
 
 	# Check that all tests passed
-	numTestsFailed=`cat matlab.log | grep -c -e "FAILED|ERROR"`
+	sed -i '' "/FAILED TO establish the default connection to the WindowServer/d" matlab.log # First, need to remove WindowServer error message
+	numTestsFailed=`grep -c -E "FAILED|ERROR" matlab.log`
 
 	if [ ${numTestsFailed} -ne 0 ]; then
 		echo "One or more tests FAILED"
+		cat matlab.log
 		exit 1
 	else
@@ -166,5 +186,5 @@
 svn cleanup --remove-ignored --remove-unversioned test # Clean up test directory (before copying to package)
 echo "Copying assets to package: ${PKG}"
-cp -rf bin examples lib scripts test ${PKG}
+cp -rf bin examples lib scripts share test ${PKG}
 mkdir ${PKG}/execution
 cp packagers/mac/issm-executable_entitlements.plist ${PKG}/bin/entitlements.plist
Index: issm/trunk/packagers/mac/package-issm-mac-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/mac/package-issm-mac-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/mac/package-issm-mac-binaries-python-2.sh	(revision 27232)
@@ -101,4 +101,12 @@
 fi
 
+echo "Moving Gmsh binaries to bin/"
+if [ -f ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh ]; then
+	cp ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh .
+else
+	echo "Gmsh not found"
+	exit 1
+fi
+
 echo "Moving GMT binaries to bin/"
 if [ -f ${ISSM_DIR}/externalpackages/gmt/install/bin/gmt-config ]; then
@@ -110,9 +118,19 @@
 fi
 
-echo "Moving Gmsh binaries to bin/"
-if [ -f ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh ]; then
-	cp ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh .
+echo "Moving GSHHG assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/gmt/install/share/coast ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/gmt/install/share/coast ${ISSM_DIR}/share
 else
-	echo "Gmsh not found"
+	echo "GSHHG not found"
+	exit 1
+fi
+
+echo "Moving PROJ assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/proj/install/share/proj ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/proj/install/share/proj ${ISSM_DIR}/share
+else
+	echo "PROJ not found"
 	exit 1
 fi
@@ -134,5 +152,5 @@
 	# Check that Python did not exit in error
 	pythonExitCode=`echo $?`
-	pythonExitedInError=`grep -E "Error|Standard exception|Traceback|bad interpreter" python.log | wc -l`
+	pythonExitedInError=`grep -c -E "Error|Standard exception|Traceback|bad interpreter" python.log`
 
 	if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
@@ -148,8 +166,10 @@
 
 	# Check that all tests passed
-	numTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`
+	sed -i '' "/FAILED TO establish the default connection to the WindowServer/d" python.log # First, need to remove WindowServer error message
+	numTestsFailed=`grep -c -E "FAILED|ERROR" python.log`
 
 	if [ ${numTestsFailed} -ne 0 ]; then
 		echo "One or more tests FAILED"
+		cat python.log
 		exit 1
 	else
@@ -164,5 +184,5 @@
 svn cleanup --remove-ignored --remove-unversioned test # Clean up test directory (before copying to package)
 echo "Copying assets to package: ${PKG}"
-cp -rf bin examples lib scripts test ${PKG}
+cp -rf bin examples lib scripts share test ${PKG}
 mkdir ${PKG}/execution
 cp packagers/mac/issm-executable_entitlements.plist ${PKG}/bin/entitlements.plist
Index: issm/trunk/packagers/mac/package-issm-mac-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/mac/package-issm-mac-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/mac/package-issm-mac-binaries-python-3.sh	(revision 27232)
@@ -101,4 +101,12 @@
 fi
 
+echo "Moving Gmsh binaries to bin/"
+if [ -f ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh ]; then
+	cp ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh .
+else
+	echo "Gmsh not found"
+	exit 1
+fi
+
 echo "Moving GMT binaries to bin/"
 if [ -f ${ISSM_DIR}/externalpackages/gmt/install/bin/gmt-config ]; then
@@ -110,9 +118,19 @@
 fi
 
-echo "Moving Gmsh binaries to bin/"
-if [ -f ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh ]; then
-	cp ${ISSM_DIR}/externalpackages/gmsh/install/bin/gmsh .
-else
-	echo "Gmsh not found"
+echo "Moving GSHHG assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/gmt/install/share/coast ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/gmt/install/share/coast ${ISSM_DIR}/share
+else
+	echo "GSHHG not found"
+	exit 1
+fi
+
+echo "Moving PROJ assets to share/"
+if [ -d ${ISSM_DIR}/externalpackages/proj/install/share/proj ]; then
+	mkdir ${ISSM_DIR}/share 2> /dev/null
+	cp -R ${ISSM_DIR}/externalpackages/proj/install/share/proj ${ISSM_DIR}/share
+else
+	echo "PROJ not found"
 	exit 1
 fi
@@ -137,5 +155,5 @@
 	# Check that Python did not exit in error
 	pythonExitCode=`echo $?`
-	pythonExitedInError=`grep -E "Error|Standard exception|Traceback|bad interpreter" python.log | wc -l`
+	pythonExitedInError=`grep -c -E "Error|Standard exception|Traceback|bad interpreter" python.log`
 
 	if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
@@ -151,8 +169,10 @@
 
 	# Check that all tests passed
-	numTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`
+	sed -i '' "/FAILED TO establish the default connection to the WindowServer/d" python.log # First, need to remove WindowServer error message
+	numTestsFailed=`grep -c -E "FAILED|ERROR" python.log`
 
 	if [ ${numTestsFailed} -ne 0 ]; then
 		echo "One or more tests FAILED"
+		cat python.log
 		exit 1
 	else
@@ -167,5 +187,5 @@
 svn cleanup --remove-ignored --remove-unversioned test # Clean up test directory (before copying to package)
 echo "Copying assets to package: ${PKG}"
-cp -rf bin examples lib scripts test ${PKG}
+cp -rf bin examples lib scripts share test ${PKG}
 mkdir ${PKG}/execution
 cp packagers/mac/issm-executable_entitlements.plist ${PKG}/bin/entitlements.plist
Index: issm/trunk/packagers/mac/sign-issm-mac-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/mac/sign-issm-mac-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/mac/sign-issm-mac-binaries-matlab.sh	(revision 27232)
@@ -45,5 +45,5 @@
 #	the 'Bindings' section under a 'Username and password (separated)' binding 
 #	(requires 'Credentials Binding Plugin').
-# - For local debugging, the aformentioned credentials can be hardcoded into 
+# - For local debugging, the aforementioned credentials can be hardcoded into 
 #	the 'USERNAME' and 'PASSWORD' constants below.
 ################################################################################
@@ -109,5 +109,5 @@
 
 # # Check out copy of repository for unsigned packages
-# echo "Checking out copy of respository for unsigned packages"
+# echo "Checking out copy of repository for unsigned packages"
 # svn checkout \
 # 	--trust-server-cert \
@@ -160,10 +160,10 @@
 
 # Sleep until notarization request response is received
-echo "Waiting for notarizaion request response"
+echo "Waiting for notarization request response"
 while [[ ! -f ${NOTARIZATION_LOGFILE_PATH}/${NOTARIZATION_LOGFILE} || ! -z $(find ${NOTARIZATION_LOGFILE_PATH} -empty -name ${NOTARIZATION_LOGFILE}) ]]; do
 	sleep 30
 done
 
-echo "Notarizaion request response received"
+echo "Notarization request response received"
 
 # Check if UUID exists in response
@@ -249,5 +249,5 @@
 
 # Check out copy of repository for signed packages
-echo "Checking out copy of respository for signed packages"
+echo "Checking out copy of repository for signed packages"
 SVN_ATTEMPT=0
 SVN_SUCCESS=0
@@ -271,5 +271,5 @@
 
 if [ ${SVN_SUCCESS} -eq 0 ]; then
-	echo "Checkout of respository for signed packages failed"
+	echo "Checkout of repository for signed packages failed"
 	exit 1
 fi
@@ -308,5 +308,5 @@
 
 	if [ ${SVN_SUCCESS} -eq 0 ]; then
-		echo "Commit to respository for signed packages failed"
+		echo "Commit to repository for signed packages failed"
 		exit 1
 	fi
@@ -331,5 +331,5 @@
 
 	if [ ${SVN_SUCCESS} -eq 0 ]; then
-		echo "Commit to respository for signed packages failed"
+		echo "Commit to repository for signed packages failed"
 		exit 1
 	fi
Index: issm/trunk/packagers/mac/sign-issm-mac-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/mac/sign-issm-mac-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/mac/sign-issm-mac-binaries-python-2.sh	(revision 27232)
@@ -45,5 +45,5 @@
 #	the 'Bindings' section under a 'Username and password (separated)' binding 
 #	(requires 'Credentials Binding Plugin').
-# - For local debugging, the aformentioned credentials can be hardcoded into 
+# - For local debugging, the aforementioned credentials can be hardcoded into 
 #	the 'USERNAME' and 'PASSWORD' constants below.
 ################################################################################
@@ -109,5 +109,5 @@
 
 # # Check out copy of repository for unsigned packages
-# echo "Checking out copy of respository for unsigned packages"
+# echo "Checking out copy of repository for unsigned packages"
 # svn checkout \
 # 	--trust-server-cert \
@@ -170,10 +170,10 @@
 
 # Sleep until notarization request response is received
-echo "Waiting for notarizaion request response"
+echo "Waiting for notarization request response"
 while [[ ! -f ${NOTARIZATION_LOGFILE_PATH}/${NOTARIZATION_LOGFILE} || ! -z $(find ${NOTARIZATION_LOGFILE_PATH} -empty -name ${NOTARIZATION_LOGFILE}) ]]; do
 	sleep 30
 done
 
-echo "Notarizaion request response received"
+echo "Notarization request response received"
 
 # Check if UUID exists in response
@@ -259,5 +259,5 @@
 
 # Check out copy of repository for signed packages
-echo "Checking out copy of respository for signed packages"
+echo "Checking out copy of repository for signed packages"
 SVN_ATTEMPT=0
 SVN_SUCCESS=0
@@ -281,5 +281,5 @@
 
 if [ ${SVN_SUCCESS} -eq 0 ]; then
-	echo "Checkout of respository for signed packages failed"
+	echo "Checkout of repository for signed packages failed"
 	exit 1
 fi
@@ -318,5 +318,5 @@
 
 	if [ ${SVN_SUCCESS} -eq 0 ]; then
-		echo "Commit to respository for signed packages failed"
+		echo "Commit to repository for signed packages failed"
 		exit 1
 	fi
@@ -341,5 +341,5 @@
 
 	if [ ${SVN_SUCCESS} -eq 0 ]; then
-		echo "Commit to respository for signed packages failed"
+		echo "Commit to repository for signed packages failed"
 		exit 1
 	fi
Index: issm/trunk/packagers/mac/sign-issm-mac-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/mac/sign-issm-mac-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/mac/sign-issm-mac-binaries-python-3.sh	(revision 27232)
@@ -45,5 +45,5 @@
 #	the 'Bindings' section under a 'Username and password (separated)' binding 
 #	(requires 'Credentials Binding Plugin').
-# - For local debugging, the aformentioned credentials can be hardcoded into 
+# - For local debugging, the aforementioned credentials can be hardcoded into 
 #	the 'USERNAME' and 'PASSWORD' constants below.
 ################################################################################
@@ -109,5 +109,5 @@
 
 # # Check out copy of repository for unsigned packages
-# echo "Checking out copy of respository for unsigned packages"
+# echo "Checking out copy of repository for unsigned packages"
 # svn checkout \
 # 	--trust-server-cert \
@@ -170,10 +170,10 @@
 
 # Sleep until notarization request response is received
-echo "Waiting for notarizaion request response"
+echo "Waiting for notarization request response"
 while [[ ! -f ${NOTARIZATION_LOGFILE_PATH}/${NOTARIZATION_LOGFILE} || ! -z $(find ${NOTARIZATION_LOGFILE_PATH} -empty -name ${NOTARIZATION_LOGFILE}) ]]; do
 	sleep 30
 done
 
-echo "Notarizaion request response received"
+echo "Notarization request response received"
 
 # Check if UUID exists in response
@@ -259,5 +259,5 @@
 
 # Check out copy of repository for signed packages
-echo "Checking out copy of respository for signed packages"
+echo "Checking out copy of repository for signed packages"
 SVN_ATTEMPT=0
 SVN_SUCCESS=0
@@ -281,5 +281,5 @@
 
 if [ ${SVN_SUCCESS} -eq 0 ]; then
-	echo "Checkout of respository for signed packages failed"
+	echo "Checkout of repository for signed packages failed"
 	exit 1
 fi
@@ -318,5 +318,5 @@
 
 	if [ ${SVN_SUCCESS} -eq 0 ]; then
-		echo "Commit to respository for signed packages failed"
+		echo "Commit to repository for signed packages failed"
 		exit 1
 	fi
@@ -341,5 +341,5 @@
 
 	if [ ${SVN_SUCCESS} -eq 0 ]; then
-		echo "Commit to respository for signed packages failed"
+		echo "Commit to repository for signed packages failed"
 		exit 1
 	fi
Index: issm/trunk/packagers/mac/test-issm-mac-binaries-matlab.sh
===================================================================
--- issm/trunk/packagers/mac/test-issm-mac-binaries-matlab.sh	(revision 27035)
+++ issm/trunk/packagers/mac/test-issm-mac-binaries-matlab.sh	(revision 27232)
@@ -34,5 +34,5 @@
 # Check that MATLAB did not exit in error
 matlabExitCode=`echo $?`
-matlabExitedInError=`grep -E "Activation cannot proceed|license|Error|Warning: Name is nonexistent or not a directory" matlab.log | wc -l`
+matlabExitedInError=`grep -c -E "Activation cannot proceed|license|Error|Warning: Name is nonexistent or not a directory" matlab.log`
 
 if [[ ${matlabExitCode} -ne 0 || ${matlabExitedInError} -ne 0 ]]; then
@@ -45,8 +45,9 @@
 
 # Check that all tests passed
-numTestsFailed=`cat matlab.log | grep -c -e "FAILED|ERROR"`
+numTestsFailed=`grep -c -E "FAILED|ERROR" matlab.log`
 
 if [[ ${numTestsFailed} -ne 0 ]]; then
 	echo "One or more tests FAILED"
+	cat matlab.log
 	exit 1
 else
Index: issm/trunk/packagers/mac/test-issm-mac-binaries-python-2.sh
===================================================================
--- issm/trunk/packagers/mac/test-issm-mac-binaries-python-2.sh	(revision 27035)
+++ issm/trunk/packagers/mac/test-issm-mac-binaries-python-2.sh	(revision 27232)
@@ -34,5 +34,5 @@
 # Check that Python did not exit in error
 pythonExitCode=`echo $?`
-pythonExitedInError=`grep -E "runme.py: error" python.log | wc -l`
+pythonExitedInError=`grep -c -E "runme.py: error" python.log`
 
 if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
@@ -44,8 +44,9 @@
 
 # Check that all tests passed
-numTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`
+numTestsFailed=`grep -c -E "FAILED|ERROR" python.log`
 
 if [[ ${numTestsFailed} -ne 0 ]]; then
 	echo "One or more tests FAILED"
+	cat python.log
 	exit 1
 else
Index: issm/trunk/packagers/mac/test-issm-mac-binaries-python-3.sh
===================================================================
--- issm/trunk/packagers/mac/test-issm-mac-binaries-python-3.sh	(revision 27035)
+++ issm/trunk/packagers/mac/test-issm-mac-binaries-python-3.sh	(revision 27232)
@@ -34,5 +34,5 @@
 # Check that Python did not exit in error
 pythonExitCode=`echo $?`
-pythonExitedInError=`grep -E "runme.py: error" python.log | wc -l`
+pythonExitedInError=`grep -c -E "runme.py: error" python.log`
 
 if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
@@ -44,8 +44,9 @@
 
 # Check that all tests passed
-numTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`
+numTestsFailed=`grep -c -E "FAILED|ERROR" python.log`
 
 if [[ ${numTestsFailed} -ne 0 ]]; then
 	echo "One or more tests FAILED"
+	cat python.log
 	exit 1
 else
Index: issm/trunk/packagers/mac/transfer-issm-mac-binaries.sh
===================================================================
--- issm/trunk/packagers/mac/transfer-issm-mac-binaries.sh	(revision 27035)
+++ issm/trunk/packagers/mac/transfer-issm-mac-binaries.sh	(revision 27232)
@@ -76,4 +76,6 @@
 # Retrieve signed and notarized package
 svn update \
+	--trust-server-cert \
+	--non-interactive \
 	--username ${ISSM_BINARIES_REPO_USER} \
 	--password ${ISSM_BINARIES_REPO_PASS} \
Index: issm/trunk/src/c/Makefile.am
===================================================================
--- issm/trunk/src/c/Makefile.am	(revision 27035)
+++ issm/trunk/src/c/Makefile.am	(revision 27232)
@@ -346,5 +346,6 @@
 	./classes/Inputs/ControlInput.cpp \
 	./classes/Inputs/TransientInput.cpp \
-	./classes/Inputs/ArrayInput.cpp
+	./classes/Inputs/ArrayInput.cpp \
+	./classes/Inputs/IntArrayInput.cpp
 #}}}
 # ADJOINTMPI/MeDiPack sources {{{
@@ -400,5 +401,5 @@
 endif
 #}}}
-#GSL sources {{{
+# GSL sources {{{
 if GSL
 issm_sources += ./toolkits/gsl/DenseGslSolve.cpp
@@ -419,4 +420,7 @@
 if ADJOINTHORIZ
 issm_sources += ./analyses/AdjointHorizAnalysis.cpp
+endif
+if AGE
+issm_sources += ./analyses/AgeAnalysis.cpp
 endif
 if BALANCETHICKNESS
@@ -530,11 +534,5 @@
 issm_sources += \
 	./cores/love_core.cpp \
-	./analyses/LoveAnalysis.cpp \
-	./modules/FourierLoveCorex/FourierLoveCorex.cpp \
-	./modules/FourierLoveCorex/lnb_param.f90 \
-	./modules/FourierLoveCorex/model.f90 \
-	./modules/FourierLoveCorex/util.f90 \
-	./modules/FourierLoveCorex/lovenb_sub.f90 \
-	./modules/FourierLoveCorex/love_numbers.f90
+	./analyses/LoveAnalysis.cpp
 endif
 endif
@@ -831,5 +829,5 @@
 
 # External packages
-LDADD += $(CHACOLIB) $(DAKOTALIB) $(PETSCLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLASLAPACKLIB) $(PARMETISLIB) $(METISLIB) $(NEOPZLIB) $(TAOLIB) $(M1QN3LIB) $(SEMICLIB) $(PLAPACKLIB) $(MPLAPACKLIB) $(SUPERLULIB) $(SPOOLESLIB) $(BLACSLIB) $(HDF5LIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(SCOTCHLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(AMPILIB) $(ADJOINTMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJLIB) $(ESMFLIB) $(OSLIBS)
+LDADD += $(SEMICLIB) $(M1QN3LIB) $(CHACOLIB) $(PETSCLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLASLAPACKLIB) $(PARMETISLIB) $(METISLIB) $(NEOPZLIB) $(TAOLIB) $(PLAPACKLIB) $(MPLAPACKLIB) $(SUPERLULIB) $(SPOOLESLIB) $(BLACSLIB) $(HDF5LIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(SCOTCHLIB) $(MKLLIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(AMPILIB) $(ADJOINTMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJLIB) $(ESMFLIB) $(OSLIBS)
 
 if FORTRAN
@@ -842,4 +840,5 @@
 issm_slc_SOURCES = main/issm_slc.cpp
 issm_slc_CXXFLAGS= $(CXXFLAGS) $(CXXOPTFLAGS)
+issm_slc_LDADD = $(DAKOTALIB) $(LDADD)
 
 if OCEAN
@@ -859,5 +858,5 @@
 issm_dakota_SOURCES = main/issm_dakota.cpp
 issm_dakota_CXXFLAGS= $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS)
-issm_dakota_LDADD= $(LDADD)
+issm_dakota_LDADD = $(DAKOTALIB) $(LDADD)
 bin_PROGRAMS += issm_post
 issm_post_SOURCES = main/issm_post.cpp
Index: issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 27232)
@@ -3362,5 +3362,5 @@
 	 element->AddInput(AdjointpEnum,lambdap,element->PressureInterpolation());	
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(vdoflist);
 	xDelete<int>(pdoflist);
@@ -3414,5 +3414,5 @@
 	element->AddInput(AdjointyEnum,lambday,element->GetElementType());
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(lambdax);
@@ -3483,5 +3483,5 @@
 	element->AddInput(AdjointyEnum,lambday,element->GetElementType());
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(lambdax);
Index: issm/trunk/src/c/analyses/AgeAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/AgeAnalysis.cpp	(revision 27232)
+++ issm/trunk/src/c/analyses/AgeAnalysis.cpp	(revision 27232)
@@ -0,0 +1,537 @@
+#include "./AgeAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+void AgeAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	IoModelToConstraintsx(constraints,iomodel,"md.age.spcage",AgeAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void AgeAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain2DhorizontalEnum) _error_("2d meshes not supported yet");
+
+}/*}}}*/
+void AgeAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel,bool isamr){/*{{{*/
+
+	int finiteelement = P1Enum;
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,"md.mesh.vertexonbase","md.mesh.vertexonsurface");
+	::CreateNodes(nodes,iomodel,AgeAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,"md.mesh.vertexonbase","md.mesh.vertexonsurface");
+}/*}}}*/
+int  AgeAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void AgeAnalysis::UpdateElements(Elements* elements,Inputs* inputs,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	/*Update elements: */
+	int finiteelement = P1Enum;
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(inputs,i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	bool dakota_analysis, ismovingfront;
+	iomodel->FetchDataToInput(inputs,elements,"md.geometry.thickness",ThicknessEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.geometry.surface",SurfaceEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.geometry.base",BaseEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.mask.ocean_levelset",MaskOceanLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(inputs,elements,"md.mesh.vertexonbase",MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(inputs,elements,"md.mesh.vertexonsurface",MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(inputs,elements,"md.mesh.vertexonbase",MeshVertexonbaseEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.mesh.vertexonsurface",MeshVertexonsurfaceEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.initialization.age",AgeEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.initialization.vx",VxEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.initialization.vy",VyEnum);
+	iomodel->FetchDataToInput(inputs,elements,"md.initialization.vz",VzEnum);
+	InputUpdateFromConstantx(inputs,elements,0.,VxMeshEnum);
+	InputUpdateFromConstantx(inputs,elements,0.,VyMeshEnum);
+	InputUpdateFromConstantx(inputs,elements,0.,VzMeshEnum);
+}/*}}}*/
+void AgeAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject("md.age.stabilization",AgeStabilizationEnum));
+
+	iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.age.requested_outputs");
+	parameters->AddObject(new IntParam(AgeNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(AgeRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,"md.age.requested_outputs");
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           AgeAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void           AgeAnalysis::PreCore(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* AgeAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* AgeAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* AgeAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	_error_("STOP");
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixVolume(element);
+	ElementMatrix* Ke2=CreateKMatrixShelf(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* AgeAnalysis::CreateKMatrixShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!element->IsOnBase() || !element->IsAllFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,D;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsAllFloating()) return NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	IssmDouble gravity             = element->FindParam(ConstantsGEnum);
+	IssmDouble rho_water           = element->FindParam(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice             = element->FindParam(MaterialsRhoIceEnum);
+	IssmDouble heatcapacity        = element->FindParam(MaterialsHeatcapacityEnum);
+	IssmDouble mixed_layer_capacity= element->FindParam(MaterialsMixedLayerCapacityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	while(gauss->next()){
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		D=gauss->weight*Jdet*rho_water*mixed_layer_capacity/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) D=dt*D;
+		for(int i=0;i<numnodes;i++) for(int j=0;j<numnodes;j++) Ke->values[i*numnodes+j] += D*basis[i]*basis[j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return Ke;
+}/*}}}*/
+ElementMatrix* AgeAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         stabilization;
+	IssmDouble  Jdet,dt,u,v,w,um,vm,wm,vel;
+	IssmDouble  h,hx,hy,hz,vx,vy,vz,D_scalar;
+	IssmDouble  tau_parameter,diameter;
+	IssmDouble  tau_parameter_anisotropic[2],tau_parameter_hor,tau_parameter_ver;	
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
+	IssmDouble     K[3][3];
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,AgeStabilizationEnum);
+	IssmDouble  rho_water           = element->FindParam(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->FindParam(MaterialsRhoIceEnum);
+	IssmDouble  gravity             = element->FindParam(ConstantsGEnum);
+	IssmDouble  heatcapacity        = element->FindParam(MaterialsHeatcapacityEnum);
+	IssmDouble  thermalconductivity = 1.;
+	IssmDouble  kappa = thermalconductivity/(rho_ice*heatcapacity);
+	Input* vx_input  = element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input  = element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input  = element->GetInput(VzEnum);     _assert_(vz_input);
+	Input* vxm_input = element->GetInput(VxMeshEnum); _assert_(vxm_input);
+	Input* vym_input = element->GetInput(VyMeshEnum); _assert_(vym_input);
+	Input* vzm_input = element->GetInput(VzMeshEnum); _assert_(vzm_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	while(gauss->next()){
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+		if(dt!=0.) D_scalar=D_scalar*dt;
+
+		/*Conduction: */
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += D_scalar*kappa*(
+							dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + dbasis[1*numnodes+j]*dbasis[1*numnodes+i] + dbasis[2*numnodes+j]*dbasis[2*numnodes+i]
+							);
+			}
+		}
+
+		/*Advection: */
+		vx_input->GetInputValue(&u,gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
+		vy_input->GetInputValue(&v,gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
+		vz_input->GetInputValue(&w,gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += D_scalar*(
+							vx*dbasis[0*numnodes+j]*basis[i] + vy*dbasis[1*numnodes+j]*basis[i] +vz*dbasis[2*numnodes+j]*basis[i]
+							);
+			}
+		}
+
+		/*Transient: */
+		if(dt!=0.){
+			D_scalar=gauss->weight*Jdet;
+			for(int i=0;i<numnodes;i++) for(int j=0;j<numnodes;j++) Ke->values[i*numnodes+j] += D_scalar*basis[j]*basis[i];
+			D_scalar=D_scalar*dt;
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			element->ElementSizes(&hx,&hy,&hz);
+			vel=sqrt(vx*vx + vy*vy + vz*vz)+1.e-14;
+			h=sqrt( pow(hx*vx/vel,2) + pow(hy*vy/vel,2) + pow(hz*vz/vel,2));
+			K[0][0]=h/(2.*vel)*fabs(vx*vx);  K[0][1]=h/(2.*vel)*fabs(vx*vy); K[0][2]=h/(2.*vel)*fabs(vx*vz);
+			K[1][0]=h/(2.*vel)*fabs(vy*vx);  K[1][1]=h/(2.*vel)*fabs(vy*vy); K[1][2]=h/(2.*vel)*fabs(vy*vz);
+			K[2][0]=h/(2.*vel)*fabs(vz*vx);  K[2][1]=h/(2.*vel)*fabs(vz*vy); K[2][2]=h/(2.*vel)*fabs(vz*vz);
+			for(int i=0;i<3;i++) for(int j=0;j<3;j++) K[i][j] = D_scalar*K[i][j];
+
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += (
+								dbasis[0*numnodes+i] *(K[0][0]*dbasis[0*numnodes+j] + K[0][1]*dbasis[1*numnodes+j]+ K[0][2]*dbasis[2*numnodes+j]) +
+								dbasis[1*numnodes+i] *(K[1][0]*dbasis[0*numnodes+j] + K[1][1]*dbasis[1*numnodes+j]+ K[1][2]*dbasis[2*numnodes+j]) +
+								dbasis[2*numnodes+i] *(K[2][0]*dbasis[0*numnodes+j] + K[2][1]*dbasis[1*numnodes+j]+ K[2][2]*dbasis[2*numnodes+j]) 
+								);
+				}
+			}
+		}
+		else if(stabilization==2){
+			diameter=element->MinEdgeLength(xyz_list);
+			tau_parameter=element->StabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j]+=tau_parameter*D_scalar*
+					  ((u-um)*dbasis[0*numnodes+i]+(v-vm)*dbasis[1*numnodes+i]+(w-wm)*dbasis[2*numnodes+i])*
+					  ((u-um)*dbasis[0*numnodes+j]+(v-vm)*dbasis[1*numnodes+j]+(w-wm)*dbasis[2*numnodes+j]);
+				}
+			}
+			if(dt!=0.){
+				D_scalar=gauss->weight*Jdet;
+				for(int i=0;i<numnodes;i++){
+					for(int j=0;j<numnodes;j++){
+						Ke->values[i*numnodes+j]+=tau_parameter*D_scalar*basis[j]*((u-um)*dbasis[0*numnodes+i]+(v-vm)*dbasis[1*numnodes+i]+(w-wm)*dbasis[2*numnodes+i]);
+					}
+				}
+			}
+		}
+		/*anisotropic SUPG*/
+		else if(stabilization==3){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			element->ElementSizes(&hx,&hy,&hz);
+			element->StabilizationParameterAnisotropic(&tau_parameter_anisotropic[0],u-um,v-vm,w-wm,hx,hy,hz,kappa);
+			tau_parameter_hor=tau_parameter_anisotropic[0];
+			tau_parameter_ver=tau_parameter_anisotropic[1];
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j]+=D_scalar*
+						(sqrt(tau_parameter_hor)*(u-um)*dbasis[0*numnodes+i]+sqrt(tau_parameter_hor)*(v-vm)*dbasis[1*numnodes+i]+sqrt(tau_parameter_ver)*(w-wm)*dbasis[2*numnodes+i])*
+						(sqrt(tau_parameter_hor)*(u-um)*dbasis[0*numnodes+j]+sqrt(tau_parameter_hor)*(v-vm)*dbasis[1*numnodes+j]+sqrt(tau_parameter_ver)*(w-wm)*dbasis[2*numnodes+j]);
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* AgeAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	_error_("STOP");
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorVolume(element);
+	ElementVector* pe2=CreatePVectorSheet(element);
+	ElementVector* pe3=CreatePVectorShelf(element);
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}/*}}}*/
+ElementVector* AgeAnalysis::CreatePVectorSheet(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/* Geothermal flux on ice sheet base and basal friction */
+	if(!element->IsOnBase() || element->IsAllFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,geothermalflux,vx,vy,vz;
+	IssmDouble  alpha2,scalar,basalfriction,heatflux;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vx_input             = element->GetInput(VxEnum);                          _assert_(vx_input);
+	Input* vy_input             = element->GetInput(VyEnum);                          _assert_(vy_input);
+	Input* vz_input             = element->GetInput(VzEnum);                          _assert_(vz_input);
+	Input* geothermalflux_input = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+	IssmDouble  rho_ice             = element->FindParam(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->FindParam(MaterialsHeatcapacityEnum);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss   = element->NewGaussBase(4);
+	while(gauss->next()){
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		geothermalflux_input->GetInputValue(&geothermalflux,gauss);
+		friction->GetAlpha2(&alpha2,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		vz = 0.;//FIXME
+		basalfriction = alpha2*(vx*vx + vy*vy + vz*vz);
+		heatflux      = (basalfriction+geothermalflux)/(rho_ice*heatcapacity);
+
+		scalar = gauss->weight*Jdet*heatflux;
+		if(dt!=0.) scalar=dt*scalar;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+ElementVector* AgeAnalysis::CreatePVectorShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	IssmDouble  t_pmp,dt,Jdet,scalar_ocean,pressure;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsAllFloating()) return NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input*      pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	IssmDouble  gravity             = element->FindParam(ConstantsGEnum);
+	IssmDouble  rho_water           = element->FindParam(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->FindParam(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->FindParam(MaterialsHeatcapacityEnum);
+	IssmDouble  mixed_layer_capacity= element->FindParam(MaterialsMixedLayerCapacityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	while(gauss->next()){
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		t_pmp=element->TMeltingPoint(pressure);
+
+		scalar_ocean=gauss->weight*Jdet*rho_water*mixed_layer_capacity*(t_pmp)/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+ElementVector* AgeAnalysis::CreatePVectorVolume(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int         stabilization;
+	IssmDouble  Jdet,phi,dt;
+	IssmDouble  temperature;
+	IssmDouble  tau_parameter,diameter,hx,hy,hz;
+	IssmDouble  tau_parameter_anisotropic[2],tau_parameter_hor,tau_parameter_ver;
+	IssmDouble  u,v,w;
+	IssmDouble  scalar_def,scalar_transient;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe     = element->NewElementVector();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	IssmDouble  rho_ice             = element->FindParam(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->FindParam(MaterialsHeatcapacityEnum);
+	IssmDouble  thermalconductivity = 1.;
+	IssmDouble  kappa = thermalconductivity/(rho_ice*heatcapacity);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,AgeStabilizationEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=element->GetInput(VzEnum); _assert_(vz_input);
+	Input* temperature_input = NULL;
+	if(reCast<bool,IssmDouble>(dt)){temperature_input = element->GetInput(TemperatureEnum); _assert_(temperature_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	while(gauss->next()){
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->ViscousHeating(&phi,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_def*basis[i];
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			temperature_input->GetInputValue(&temperature, gauss);
+			scalar_transient=temperature*Jdet*gauss->weight;
+			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_transient*basis[i];
+		}
+
+		if(stabilization==2){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			diameter=element->MinEdgeLength(xyz_list);
+			vx_input->GetInputValue(&u,gauss);
+			vy_input->GetInputValue(&v,gauss);
+			vz_input->GetInputValue(&w,gauss);
+
+			tau_parameter=element->StabilizationParameter(u,v,w,diameter,kappa);
+
+			for(int i=0;i<numnodes;i++) pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0*numnodes+i]+v*dbasis[1*numnodes+i]+w*dbasis[2*numnodes+i]);
+			if(reCast<bool,IssmDouble>(dt)){
+				for(int i=0;i<numnodes;i++) pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0*numnodes+i]+v*dbasis[1*numnodes+i]+w*dbasis[2*numnodes+i]);
+			}
+		}
+		/* anisotropic SUPG */
+		else if(stabilization==3){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			element->ElementSizes(&hx,&hy,&hz);
+			vx_input->GetInputValue(&u,gauss);
+			vy_input->GetInputValue(&v,gauss);
+			vz_input->GetInputValue(&w,gauss);
+			element->StabilizationParameterAnisotropic(&tau_parameter_anisotropic[0],u,v,w,hx,hy,hz,kappa);
+			tau_parameter_hor=tau_parameter_anisotropic[0];
+			tau_parameter_ver=tau_parameter_anisotropic[1];
+
+			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_def*(tau_parameter_hor*u*dbasis[0*numnodes+i]+tau_parameter_hor*v*dbasis[1*numnodes+i]+tau_parameter_ver*w*dbasis[2*numnodes+i]);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+
+}/*}}}*/
+void           AgeAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,AgeEnum);
+}/*}}}*/
+void           AgeAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element*  element,int control_type,int control_interp,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void           AgeAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	element->InputUpdateFromSolutionOneDof(solution,AgeEnum);
+
+}/*}}}*/
+void           AgeAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	SetActiveNodesLSMx(femmodel);
+
+	_error_("Should also automatically constrain surface/basal nodes where we have inflow");
+}/*}}}*/
Index: issm/trunk/src/c/analyses/AgeAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/AgeAnalysis.h	(revision 27232)
+++ issm/trunk/src/c/analyses/AgeAnalysis.h	(revision 27232)
@@ -0,0 +1,39 @@
+/*! \file AgeAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _AGEANALYSIS_
+#define _AGEANALYSIS_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class AgeAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel,bool isamr=false);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,Inputs* inputs,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		void           PreCore(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixShelf(Element* element);
+		ElementMatrix* CreateKMatrixVolume(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorSheet(Element* element);
+		ElementVector* CreatePVectorShelf(Element* element);
+		ElementVector* CreatePVectorVolume(Element* element);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element*  element,int control_type,int control_interp,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 27232)
@@ -714,5 +714,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(newdamage);
 	xDelete<int>(doflist);
Index: issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 27232)
@@ -76,5 +76,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	iomodel->DeleteData(spcvector,"md.thermal.spctemperature");
 	iomodel->DeleteData(spcvectorstatic,"md.thermal.spctemperature");
@@ -348,5 +348,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(indices);
 	delete gauss;
@@ -1358,5 +1358,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(indices);
 	xDelete<int>(indicesup);
@@ -1432,5 +1432,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(indices);
 	xDelete<int>(indicesup);
@@ -1614,5 +1614,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(pressure);
Index: issm/trunk/src/c/analyses/EnumToAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 27232)
@@ -25,4 +25,7 @@
 		#ifdef _HAVE_ADJOINTHORIZ_
 		case AdjointHorizAnalysisEnum : return new AdjointHorizAnalysis();
+		#endif
+		#ifdef _HAVE_AGE_
+		case AgeAnalysisEnum : return new AgeAnalysis();
 		#endif
 		#ifdef _HAVE_BALANCETHICKNESS2_
Index: issm/trunk/src/c/analyses/EsaAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/EsaAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/EsaAnalysis.cpp	(revision 27232)
@@ -144,5 +144,5 @@
 	ISSM_MPI_Allgatherv(U_elastic_local, m, ISSM_MPI_DOUBLE, U_elastic, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
 	ISSM_MPI_Allgatherv(H_elastic_local, m, ISSM_MPI_DOUBLE, H_elastic, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<int>(recvcounts);
 	xDelete<int>(displs);
@@ -156,5 +156,5 @@
 	parameters->AddObject(new DoubleVecParam(EsaHElasticEnum,H_elastic,M));
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<IssmDouble>(love_h);
 	xDelete<IssmDouble>(love_l);
Index: issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 27232)
@@ -42,5 +42,5 @@
 	}
 
-	/*free ressources: */
+	/*Free resources: */
 	iomodel->DeleteData(vertex_pairing,"md.masstransport.vertex_pairing");
 	iomodel->DeleteData(nodeonbase,"md.mesh.vertexonbase");
Index: issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 27232)
@@ -42,5 +42,5 @@
 	}
 
-	/*free ressources: */
+	/*Free resources: */
 	iomodel->DeleteData(vertex_pairing,"md.masstransport.vertex_pairing");
 	iomodel->DeleteData(nodeonsurface,"md.mesh.vertexonsurface");
Index: issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 27232)
@@ -11,8 +11,13 @@
 void HydrologyDCEfficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 
+	bool        isefficientlayer;
 	int         hydrology_model;
 	int         eplflip_lock;
 	int         eplthickcomp;
-	bool        isefficientlayer;
+	IssmDouble  eplinitthick;
+	IssmDouble  eplcolapsethick;
+	IssmDouble  eplmaxthick;
+	IssmDouble  eplcond;
+
 	/*retrieve some parameters: */
 	iomodel->FindConstant(&hydrology_model,"md.hydrology.model");
@@ -27,10 +32,20 @@
 	if(!isefficientlayer) return;
 
-	/*If yes, initialize a flip flop counter*/
+	/*If yes, get the parameters*/
 	iomodel->FetchData(&eplflip_lock,"md.hydrology.eplflip_lock");
+	iomodel->FetchData(&eplthickcomp,"md.hydrology.epl_thick_comp");
+
 	parameters->AddObject(new IntParam(HydrologydcEplflipLockEnum,eplflip_lock));
-
-	iomodel->FetchData(&eplthickcomp,"md.hydrology.epl_thick_comp");
 	parameters->AddObject(new IntParam(HydrologydcEplThickCompEnum,eplthickcomp));
+
+	iomodel->FetchData(&eplinitthick,"md.hydrology.epl_initial_thickness");
+	iomodel->FetchData(&eplcolapsethick,"md.hydrology.epl_colapse_thickness");
+	iomodel->FetchData(&eplmaxthick,"md.hydrology.epl_max_thickness");
+	iomodel->FetchData(&eplcond,"md.hydrology.epl_conductivity");
+	parameters->AddObject(new DoubleParam(HydrologydcEplInitialThicknessEnum,eplinitthick));
+	parameters->AddObject(new DoubleParam(HydrologydcEplColapseThicknessEnum,eplcolapsethick));
+	parameters->AddObject(new DoubleParam(HydrologydcEplMaxThicknessEnum,eplmaxthick));
+	parameters->AddObject(new DoubleParam(HydrologydcEplConductivityEnum,eplcond));
+
 }/*}}}*/
 void HydrologyDCEfficientAnalysis::UpdateElements(Elements* elements,Inputs* inputs,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -419,5 +434,5 @@
 	element->AddBasalInput(EplHeadSubstepEnum,eplHeads,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(eplHeads);
 	xDelete<int>(doflist);
Index: issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 27232)
@@ -23,8 +23,11 @@
 	int         numoutputs;
 	bool        isefficientlayer;
+	bool        sliceadapt;
 	IssmDouble  penalty_factor;
 	IssmDouble  rel_tol;
 	IssmDouble  leakagefactor;
 	IssmDouble  sedimentlimit;
+	IssmDouble  sed_poro;
+	IssmDouble  sed_thick;
 	char**      requestedoutputs = NULL;
 
@@ -43,4 +46,5 @@
 	iomodel->FetchData(&hydro_maxiter,      "md.hydrology.max_iter" );
 	iomodel->FetchData(&hydroslices,        "md.hydrology.steps_per_step");
+	iomodel->FetchData(&sliceadapt,         "md.hydrology.step_adapt");
 	iomodel->FetchData(&averaging_method,   "md.hydrology.averaging");
 	iomodel->FetchData(&isefficientlayer,   "md.hydrology.isefficientlayer");
@@ -55,9 +59,16 @@
 	parameters->AddObject(new IntParam(HydrologydcMaxIterEnum,hydro_maxiter));
 	parameters->AddObject(new IntParam(HydrologyStepsPerStepEnum,hydroslices));
+	parameters->AddObject(new BoolParam(HydrologyStepAdaptEnum,sliceadapt));
 	parameters->AddObject(new IntParam(HydrologyAveragingEnum,averaging_method));
-
 	parameters->AddObject(new BoolParam(HydrologydcIsefficientlayerEnum,isefficientlayer));
 	parameters->AddObject(new DoubleParam(HydrologydcPenaltyFactorEnum,penalty_factor));
 	parameters->AddObject(new DoubleParam(HydrologydcRelTolEnum,rel_tol));
+
+	iomodel->FetchData(&sed_poro,  "md.hydrology.sediment_porosity" );
+	iomodel->FetchData(&sed_thick, "md.hydrology.sediment_thickness" );
+
+	parameters->AddObject(new DoubleParam(HydrologydcSedimentPorosityEnum,sed_poro));
+	parameters->AddObject(new DoubleParam(HydrologydcSedimentThicknessEnum,sed_thick));
+
 	if(transfer_flag==1){
 		iomodel->FetchData(&leakagefactor,"md.hydrology.leakage_factor");
@@ -110,4 +121,6 @@
 	iomodel->FetchDataToInput(inputs,elements,"md.hydrology.sediment_transmitivity",HydrologydcSedimentTransmitivityEnum);
 	iomodel->FetchDataToInput(inputs,elements,"md.hydrology.mask_thawed_node",HydrologydcMaskThawedNodeEnum);
+
+
 	if(iomodel->domaintype!=Domain2DhorizontalEnum){
 		iomodel->FetchDataToInput(inputs,elements,"md.mesh.vertexonbase",MeshVertexonbaseEnum);
@@ -518,5 +531,5 @@
 	element->AddBasalInput(SedimentHeadResidualEnum,residual,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(residual);
Index: issm/trunk/src/c/analyses/HydrologyShaktiAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyShaktiAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/HydrologyShaktiAnalysis.cpp	(revision 27232)
@@ -242,5 +242,4 @@
 		element->NodalFunctions(basis,gauss);
 
-		/***/
                 base_input->GetInputValue(&bed,gauss);
                 thickness_input->GetInputValue(&thickness,gauss);
@@ -288,6 +287,4 @@
    IssmDouble  PMPheat,dissipation,dpressure_water[2],dbed[2];	
 	IssmDouble* xyz_list = NULL;
-//        IssmDouble dgapxx; /***/
-//	IssmDouble dgapyy; /***/
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -315,6 +312,4 @@
 	Input* br_input             = element->GetInput(HydrologyBumpHeightEnum);        _assert_(br_input);
    Input* headold_input        = element->GetInput(HydrologyHeadOldEnum);           _assert_(headold_input);
-//	Input* dgapxx_input	    = element->GetInput(HydrologyGapHeightXXEnum); /***/
-//	Input* dgapyy_input	    = element->GetInput(HydrologyGapHeightYYEnum); /***/
 
 	/*Get conductivity from inputs*/
@@ -346,6 +341,4 @@
 		br_input->GetInputValue(&br,gauss);
                 headold_input->GetInputValue(&head_old,gauss);
-//		dgapxx_input->GetInputValue(&dgapxx,gauss); /***/
-//		dgapyy_input->GetInputValue(&dgapyy,gauss); /***/
 
 		/*Get ice A parameter*/
@@ -365,8 +358,4 @@
 		frictionheat=alpha2*(vx*vx+vy*vy);
 
-		/* Take out frictional heat for large gap height */
-		if(gap>br)
-		 frictionheat=0.;
-
 		/*Get water and ice pressures*/
 		IssmDouble pressure_ice   = rho_ice*g*thickness;    _assert_(pressure_ice>0.); 
@@ -379,10 +368,8 @@
 
 		/*Compute change in sensible heat due to changes in pressure melting point*/
-   	dpressure_water[0] = rho_water*g*(dh[0] - dbed[0]);
+   		dpressure_water[0] = rho_water*g*(dh[0] - dbed[0]);
 		dpressure_water[1] = rho_water*g*(dh[1] - dbed[1]);
-		PMPheat=CT*CW*conductivity*rho_water*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
-		PMPheat=0; /*** TEST no PMPheat***/
-
-   	meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
+
+   	meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1]));
 
                   for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*
@@ -396,16 +383,4 @@
                     )*basis[i];
 
-                /* Test with experimental diffusivity term*/
-//                   for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*
- //                   (
-  //                   meltrate*(1/rho_water-1/rho_ice)
-   //                  +A*pow(fabs(pressure_ice - pressure_water),n-1)*(pressure_ice + rho_water*g*bed)*gap
-    //                 +(n-1)*A*pow(fabs(pressure_ice - pressure_water),n-1)*(rho_water*g*head)*gap
-     //                -beta*sqrt(vx*vx+vy*vy)
-      //               +ieb
-       //              +storage*head_old/dt
-        //             +0.e-5*(dgapxx+dgapyy)
-         //            )*basis[i];
-
 	
 	}
@@ -458,14 +433,4 @@
 		values[i]=solution[doflist[i]];
 
-		/*overburden cap: make sure that p_water<p_ice ->  h<rho_i H/rho_w + zb*/
-//		if(values[i]>rho_ice*thickness[i]/rho_water+bed[i]){
-//			values[i] = rho_ice*thickness[i]/rho_water+bed[i];
-//		}
-
-		/*Make sure that negative pressure is not allowed*/
-//      if(values[i]<bed[i]){
-//			values[i] = bed[i];
-//		}
-
 		/*Under-relaxation*/
 	   values[i] = head_old[i] - relaxation*(head_old[i]-values[i]);
@@ -549,9 +514,7 @@
 	IssmDouble  alpha2,frictionheat;
 	IssmDouble* xyz_list = NULL;
-   IssmDouble  dpressure_water[2],dbed[2],PMPheat,dissipation;
+  	IssmDouble  dpressure_water[2],dbed[2],PMPheat,dissipation;
 	IssmDouble q = 0.;
-   IssmDouble channelization = 0.;
-//	IssmDouble dgapxx; /***/
-//	IssmDouble dgapyy; /***/
+   	IssmDouble channelization = 0.;
 
 	/*Retrieve all inputs and parameters*/
@@ -571,6 +534,4 @@
 	Input* lr_input             = element->GetInput(HydrologyBumpSpacingEnum);       _assert_(lr_input);
 	Input* br_input             = element->GetInput(HydrologyBumpHeightEnum);        _assert_(br_input);
- //       Input* dgapxx_input         = element->GetInput(HydrologyGapHeightXXEnum); /***/
-  //      Input* dgapyy_input         = element->GetInput(HydrologyGapHeightYYEnum); /***/
 
 	/*Get conductivity from inputs*/
@@ -598,6 +559,4 @@
 		lr_input->GetInputValue(&lr,gauss);
 		br_input->GetInputValue(&br,gauss);
-//		dgapxx_input->GetInputValue(&dgapxx,gauss); /***/
-//		dgapyy_input->GetInputValue(&dgapyy,gauss); /***/
 
 		/*Get ice A parameter*/
@@ -617,8 +576,4 @@
 		frictionheat=alpha2*(vx*vx+vy*vy);
 
-		/* Take out frictional heat for large gap height */
-		if(gap>br)
-		 frictionheat=0.;
-
 		/*Get water and ice pressures*/
 		IssmDouble pressure_ice   = rho_ice*g*thickness;    _assert_(pressure_ice>0.); 
@@ -629,9 +584,7 @@
 	   dpressure_water[0] = rho_water*g*(dh[0] - dbed[0]);
 		dpressure_water[1] = rho_water*g*(dh[1] - dbed[1]);
-		PMPheat=CT*CW*conductivity*rho_water*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
-PMPheat=0; /*** TEST no PMPheat***/
 		dissipation=rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1]);
 
-		meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
+		meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1]));
 
 		element->AddInput(DummyEnum,&meltrate,P0Enum);
@@ -647,12 +600,4 @@
 					));
 
-		/* TEST with experimental gap height "diffusivity" for melting walls */
-//                newgap += gauss->weight*Jdet*(gap+dt*(
- //                                        meltrate/rho_ice
-  //                                       -A*pow(fabs(pressure_ice-pressure_water),n-1)*(pressure_ice-pressure_water)*lc
-   //                                      +beta*sqrt(vx*vx+vy*vy)
-//					 +0.e-5*(dgapxx+dgapyy))
- //                                        );
-
 
 		totalweights +=gauss->weight*Jdet;
@@ -667,10 +612,8 @@
 	/*Divide by connectivity*/
 	newgap = newgap/totalweights;
-	IssmDouble mingap = 1e-6;
+	IssmDouble mingap = 1e-3;
 	if(newgap<mingap) newgap=mingap;
 
-	/*Limit gap height to grow to surface*/
-//	if(newgap>thickness)
-//	 newgap = thickness;
+	/*Limit gap height*/
 	if(newgap>1)
 	 newgap = 1;
Index: issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 27232)
@@ -320,5 +320,5 @@
 	element->AddInput(AccumulatedDeltaTwsEnum,deltawatercolumn,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(oldwatercolumn);
 	xDelete<IssmDouble>(deltawatercolumn);
Index: issm/trunk/src/c/analyses/LevelsetAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/LevelsetAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/LevelsetAnalysis.cpp	(revision 27232)
@@ -114,6 +114,4 @@
 			break;
 		case CalvingParameterizationEnum:
-			iomodel->FetchDataToInput(inputs,elements,"md.calving.stress_threshold_groundedice",CalvingStressThresholdGroundediceEnum);
-			iomodel->FetchDataToInput(inputs,elements,"md.calving.stress_threshold_floatingice",CalvingStressThresholdFloatingiceEnum);
 			iomodel->FetchDataToInput(inputs,elements,"md.geometry.bed",BedEnum);
 			break;
@@ -221,10 +219,12 @@
 			break;
 		case CalvingParameterizationEnum:
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.use_param",CalvingUseParamEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.calving.min_thickness",CalvingMinthicknessEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.use_param",CalvingUseParamEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.scale_theta",CalvingScaleThetaEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.amp_alpha",CalvingAmpAlphaEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.midp",CalvingMidpointEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.nonlinearlaw",CalvingNonlinearLawEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.theta",CalvingThetaEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.alpha",CalvingAlphaEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.xoffset",CalvingXoffsetEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.yoffset",CalvingYoffsetEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.vel_lowerbound",CalvingVelLowerboundEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.vel_upperbound",CalvingVelUpperboundEnum));
 			break;
 		default:
@@ -891,5 +891,5 @@
 		}
 
-		/*Free ressources:*/
+		/*Free resources:*/
 		delete vec_constraint_nodes;
 
Index: issm/trunk/src/c/analyses/MasstransportAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 27232)
@@ -86,5 +86,5 @@
 	}
 
-	/*free ressources: */
+	/*Free resources: */
 	iomodel->DeleteData(vertex_pairing,"md.masstransport.vertex_pairing");
 	iomodel->DeleteData(nodeonbase,"md.mesh.vertexonbase");
@@ -928,5 +928,5 @@
 	element->AddBasalInput(BaseEnum,newbase,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(newthickness);
 	xDelete<IssmDouble>(newbase);
Index: issm/trunk/src/c/analyses/OceantransportAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/OceantransportAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/OceantransportAnalysis.cpp	(revision 27232)
@@ -147,5 +147,5 @@
 	solution->SetValues(numdof,doflist,values,INS_VAL);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete gauss;
 	xDelete<int>(doflist);
@@ -197,5 +197,5 @@
 	element->AddInput(StrEnum,&strmean,P0Enum); 
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(bp);
 	xDelete<IssmDouble>(str);
Index: issm/trunk/src/c/analyses/SamplingAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/SamplingAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/SamplingAnalysis.cpp	(revision 27232)
@@ -289,5 +289,5 @@
     element->AddInput(SampleEnum,newsample,element->GetElementType());
 
-    /*Free ressources:*/
+    /*Free resources:*/
     xDelete<IssmDouble>(newsample);
 		xDelete<IssmDouble>(tau);
Index: issm/trunk/src/c/analyses/SealevelchangeAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/SealevelchangeAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/SealevelchangeAnalysis.cpp	(revision 27232)
@@ -17,4 +17,13 @@
 void SealevelchangeAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel,bool isamr){/*{{{*/
 	::CreateNodes(nodes,iomodel,SealevelchangeAnalysisEnum,P1Enum);
+}/*}}}*/
+void SealevelchangeAnalysis::DeleteBarystaticContributionsParam(FemModel* femmodel){/*{{{*/
+	BarystaticContributions* barycontrib=NULL;
+	GenericParam<BarystaticContributions*>* barycontribparam=NULL;
+
+	barycontribparam = xDynamicCast<GenericParam<BarystaticContributions*>*>(femmodel->parameters->FindParamObject(BarystaticContributionsEnum));
+	barycontrib=barycontribparam->GetParameterValue();
+
+	delete barycontrib;
 }/*}}}*/
 int  SealevelchangeAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
@@ -115,4 +124,7 @@
 	IssmDouble  planetradius=0;
 	IssmDouble  planetarea=0;
+	IssmDouble  constant=0;
+	IssmDouble  rho_earth;
+	int		isgrd=0;
 	bool		selfattraction=false;
 	bool		elastic=false;
@@ -128,4 +140,6 @@
 	int     numoutputs;
 	char**  requestedoutputs = NULL;
+	int* recvcounts = NULL;
+	int* displs=NULL;
 
 	/*transition vectors: */
@@ -149,4 +163,5 @@
 	if(isexternal) parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.external.nature",SolidearthExternalNatureEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.settings.runfrequency",SolidearthSettingsRunFrequencyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.settings.degacc",SolidearthSettingsDegreeAccuracyEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.settings.reltol",SolidearthSettingsReltolEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.settings.abstol",SolidearthSettingsAbstolEnum));
@@ -172,7 +187,7 @@
 	parameters->AddObject(new DoubleParam(CumBslcHydroEnum,0.0));
 	parameters->AddObject(new DoubleParam(CumGmtslcEnum,0.0));
-
 	/*compute planet area and plug into parameters:*/
 	iomodel->FetchData(&planetradius,"md.solidearth.planetradius");
+	iomodel->FetchData(&rho_earth,"md.materials.earth_density");
 	planetarea=4*M_PI*planetradius*planetradius;
 	parameters->AddObject(new DoubleParam(SolidearthPlanetAreaEnum,planetarea));
@@ -236,5 +251,6 @@
 
 	parameters->FindParam(&grdmodel,GrdModelEnum);
-	if(grdmodel==ElasticEnum){
+	parameters->FindParam(&isgrd,SolidearthSettingsGRDEnum);
+	if(grdmodel==ElasticEnum && isgrd){
 		/*Deal with elasticity {{{*/
 		iomodel->FetchData(&selfattraction,"md.solidearth.settings.selfattraction");
@@ -250,4 +266,7 @@
 		}
 
+		//default values
+		nt=1;
+		ntimesteps=1;
 		/*love numbers: */
 		if(viscous || elastic){
@@ -264,7 +283,7 @@
 
 			parameters->AddObject(new DoubleParam(SolidearthSettingsTimeAccEnum,timeacc));
-			parameters->AddObject(new DoubleMatParam(LoadLoveHEnum,love_h,ndeg,precomputednt));
-			parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,love_k,ndeg,precomputednt));
-			parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,love_l,ndeg,precomputednt));
+			//parameters->AddObject(new DoubleMatParam(LoadLoveHEnum,love_h,ndeg,precomputednt));
+			//parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,love_k,ndeg,precomputednt));
+			//parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,love_l,ndeg,precomputednt));
 
 			if (rotation){
@@ -277,7 +296,7 @@
 				parameters->AddObject(new DoubleMatParam(LovePolarMotionTransferFunctionColinearEnum,love_pmtf_colinear,1,precomputednt));
 				parameters->AddObject(new DoubleMatParam(LovePolarMotionTransferFunctionOrthogonalEnum,love_pmtf_ortho,1,precomputednt));
-				parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,love_th,ndeg,precomputednt));
-				parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,love_tk,ndeg,precomputednt));
-				parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,love_tl,ndeg,precomputednt));
+				//parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,love_th,ndeg,precomputednt));
+				//parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,love_tk,ndeg,precomputednt));
+				//parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,love_tl,ndeg,precomputednt));
 			}
 
@@ -308,15 +327,8 @@
 				}
 			}
-			else {
-				ntimesteps=1;
-				nt=1;
-			}
-
 #ifdef _HAVE_AD_
-			G_viscoelastic=xNew<IssmDouble>(M*ntimesteps,"t");
 			U_viscoelastic=xNew<IssmDouble>(M*ntimesteps,"t");
 			if(horiz)H_viscoelastic=xNew<IssmDouble>(M*ntimesteps,"t");
 #else
-			G_viscoelastic=xNew<IssmDouble>(M*ntimesteps);
 			U_viscoelastic=xNew<IssmDouble>(M*ntimesteps);
 			if(horiz)H_viscoelastic=xNew<IssmDouble>(M*ntimesteps);
@@ -324,99 +336,97 @@
 		}
 		if(selfattraction){
-#ifdef _HAVE_AD_
-			G_gravi=xNew<IssmDouble>(M,"t");
-#else
-			G_gravi=xNew<IssmDouble>(M);
-#endif
-		}
-
-		if(rotation) parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.lovenumbers.tk2secular",TidalLoveK2SecularEnum));
-		if(selfattraction){
-
 			/*compute combined legendre + love number (elastic green function):*/
 			m=DetermineLocalSize(M,IssmComm::GetComm());
 			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,IssmComm::GetComm());
+#ifdef _HAVE_AD_
+			G_gravi=xNew<IssmDouble>(M,"t");
+			G_gravi_local=xNew<IssmDouble>(m,"t");
+			G_viscoelastic=xNew<IssmDouble>(M*ntimesteps,"t");
+			G_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps,"t");
+#else
+			G_gravi=xNew<IssmDouble>(M);
+			G_gravi_local=xNew<IssmDouble>(m);
+			G_viscoelastic=xNew<IssmDouble>(M*ntimesteps);
+			G_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps);
+#endif
 		}
 		if(viscous | elastic){
 #ifdef _HAVE_AD_
-			G_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps,"t");
 			U_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps,"t");
 			if(horiz)H_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps,"t");
 #else
-			G_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps);
 			U_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps);
 			if(horiz)H_viscoelastic_local=xNew<IssmDouble>(m*ntimesteps);
 #endif
 		}
-		if(selfattraction){
-#ifdef _HAVE_AD_
-			G_gravi_local=xNew<IssmDouble>(m,"t");
-#else
-			G_gravi_local=xNew<IssmDouble>(m);
-#endif
-		}
-
+
+		if(rotation) parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.lovenumbers.tk2secular",TidalLoveK2SecularEnum));
+		constant=3/rho_earth/planetarea;
 		if(selfattraction){
 			for(int i=lower_row;i<upper_row;i++){
 				IssmDouble alpha,x;
 				alpha= reCast<IssmDouble>(i)*degacc * M_PI / 180.0;
-				G_gravi_local[i-lower_row]= .5/sin(alpha/2.0);
-			}
-		}
-		if(viscous | elastic){
-			for(int i=lower_row;i<upper_row;i++){
-				IssmDouble alpha,x;
-				alpha= reCast<IssmDouble>(i)*degacc * M_PI / 180.0;
-
-				for(int t=0;t<ntimesteps;t++){
-					G_viscoelastic_local[(i-lower_row)*ntimesteps+t]= (love_k[(ndeg-1)*precomputednt+t]-love_h[(ndeg-1)*precomputednt+t])*G_gravi_local[i-lower_row];
-					U_viscoelastic_local[(i-lower_row)*ntimesteps+t]= (love_h[(ndeg-1)*precomputednt+t])*G_gravi_local[i-lower_row];
-					if(horiz)H_viscoelastic_local[(i-lower_row)*ntimesteps+t]= 0; 
-				}
-
-				IssmDouble Pn = 0.; 
-				IssmDouble Pn1 = 0.; 
-				IssmDouble Pn2 = 0.; 
-				IssmDouble Pn_p = 0.; 
-				IssmDouble Pn_p1 = 0.; 
-				IssmDouble Pn_p2 = 0.; 
-
-				for (int n=0;n<ndeg;n++) {
-
-					/*compute legendre polynomials: P_n(cos\theta) & d P_n(cos\theta)/ d\theta: */
-					if(n==0){
-						Pn=1; 
-						Pn_p=0; 
+				G_gravi_local[i-lower_row]= constant*.5/sin(alpha/2.0);
+			}
+			if(viscous | elastic){
+				for(int i=lower_row;i<upper_row;i++){
+					IssmDouble alpha,x;
+					alpha= reCast<IssmDouble>(i)*degacc * M_PI / 180.0;
+
+					for(int t=0;t<ntimesteps;t++){
+						G_viscoelastic_local[(i-lower_row)*ntimesteps+t]= (1.0+love_k[(ndeg-1)*precomputednt+t]-love_h[(ndeg-1)*precomputednt+t])*G_gravi_local[i-lower_row];
+						U_viscoelastic_local[(i-lower_row)*ntimesteps+t]= (love_h[(ndeg-1)*precomputednt+t])*G_gravi_local[i-lower_row];
+						if(horiz)H_viscoelastic_local[(i-lower_row)*ntimesteps+t]= 0; 
 					}
-					else if(n==1){ 
-						Pn = cos(alpha); 
-						Pn_p = 1; 
+
+					IssmDouble Pn = 0.; 
+					IssmDouble Pn1 = 0.; 
+					IssmDouble Pn2 = 0.; 
+					IssmDouble Pn_p = 0.; 
+					IssmDouble Pn_p1 = 0.; 
+					IssmDouble Pn_p2 = 0.; 
+
+					for (int n=0;n<ndeg;n++) {
+
+						/*compute legendre polynomials: P_n(cos\theta) & d P_n(cos\theta)/ d\theta: */
+						if(n==0){
+							Pn=1; 
+							Pn_p=0; 
+						}
+						else if(n==1){ 
+							Pn = cos(alpha); 
+							Pn_p = 1; 
+						}
+						else{
+							Pn = ( (2*n-1)*cos(alpha)*Pn1 - (n-1)*Pn2 ) /n;
+							Pn_p = ( (2*n-1)*(Pn1+cos(alpha)*Pn_p1) - (n-1)*Pn_p2 ) /n;
+						}
+						Pn2=Pn1; Pn1=Pn;
+						Pn_p2=Pn_p1; Pn_p1=Pn_p;
+
+						for(int t=0;t<ntimesteps;t++){
+							IssmDouble deltalove_G;
+							IssmDouble deltalove_U;
+
+							deltalove_G = (love_k[n*precomputednt+t]-love_k[(ndeg-1)*precomputednt+t]-love_h[n*precomputednt+t]+love_h[(ndeg-1)*precomputednt+t]);
+							deltalove_U = (love_h[n*precomputednt+t]-love_h[(ndeg-1)*precomputednt+t]);
+
+							G_viscoelastic_local[(i-lower_row)*ntimesteps+t] += constant*deltalove_G*Pn;		                // gravitational potential 
+							U_viscoelastic_local[(i-lower_row)*ntimesteps+t] += constant*deltalove_U*Pn;		                // vertical (up) displacement 
+							if(horiz)H_viscoelastic_local[(i-lower_row)*ntimesteps+t] += constant*sin(alpha)*love_l[n*precomputednt+t]*Pn_p;		// horizontal displacements 
+						}
 					}
-					else{
-						Pn = ( (2*n-1)*cos(alpha)*Pn1 - (n-1)*Pn2 ) /n;
-						Pn_p = ( (2*n-1)*(Pn1+cos(alpha)*Pn_p1) - (n-1)*Pn_p2 ) /n;
+				}
+			}
+			else { //just copy G_gravi into G_viscoelastic
+				for(int i=lower_row;i<upper_row;i++){
+					for(int t=0;t<ntimesteps;t++){
+						G_viscoelastic_local[(i-lower_row)*ntimesteps+t]= G_gravi_local[i-lower_row];
 					}
-					Pn2=Pn1; Pn1=Pn;
-					Pn_p2=Pn_p1; Pn_p1=Pn_p;
-
-					for(int t=0;t<ntimesteps;t++){
-						IssmDouble deltalove_G;
-						IssmDouble deltalove_U;
-
-						deltalove_G = (love_k[n*precomputednt+t]-love_k[(ndeg-1)*precomputednt+t]-love_h[n*precomputednt+t]+love_h[(ndeg-1)*precomputednt+t]);
-						deltalove_U = (love_h[n*precomputednt+t]-love_h[(ndeg-1)*precomputednt+t]);
-
-						G_viscoelastic_local[(i-lower_row)*ntimesteps+t] += deltalove_G*Pn;		                // gravitational potential 
-						U_viscoelastic_local[(i-lower_row)*ntimesteps+t] += deltalove_U*Pn;		                // vertical (up) displacement 
-						if(horiz)H_viscoelastic_local[(i-lower_row)*ntimesteps+t] += sin(alpha)*love_l[n*precomputednt+t]*Pn_p;		// horizontal displacements 
-					}
-				}
-			}
-		}
-		if(selfattraction){
-
+				}
+			}
 			/*merge G_viscoelastic_local into G_viscoelastic; U_viscoelastic_local into U_viscoelastic; H_viscoelastic_local to H_viscoelastic:{{{*/
-			int* recvcounts=xNew<int>(IssmComm::GetSize());
-			int* displs=xNew<int>(IssmComm::GetSize());
+			recvcounts=xNew<int>(IssmComm::GetSize());
+			displs=xNew<int>(IssmComm::GetSize());
 			int  rc;
 			int  offset;
@@ -424,18 +434,15 @@
 			//deal with selfattraction first: 
 			ISSM_MPI_Allgather(&m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,IssmComm::GetComm());
-
 			/*displs: */
 			ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,IssmComm::GetComm());
-
 			/*All gather:*/
 			ISSM_MPI_Allgatherv(G_gravi_local, m, ISSM_MPI_DOUBLE, G_gravi, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
 
+			rc=m*ntimesteps;
+			offset=lower_row*ntimesteps;
+			ISSM_MPI_Allgather(&rc,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,IssmComm::GetComm());
+			ISSM_MPI_Allgather(&offset,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,IssmComm::GetComm());
+			ISSM_MPI_Allgatherv(G_viscoelastic_local, m*ntimesteps, ISSM_MPI_DOUBLE, G_viscoelastic, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
 			if(elastic){
-				rc=m*ntimesteps;
-				offset=lower_row*ntimesteps;
-				ISSM_MPI_Allgather(&rc,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,IssmComm::GetComm());
-				ISSM_MPI_Allgather(&offset,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,IssmComm::GetComm());
-
-				ISSM_MPI_Allgatherv(G_viscoelastic_local, m*ntimesteps, ISSM_MPI_DOUBLE, G_viscoelastic, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
 				ISSM_MPI_Allgatherv(U_viscoelastic_local, m*ntimesteps, ISSM_MPI_DOUBLE, U_viscoelastic, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
 				if(horiz)ISSM_MPI_Allgatherv(H_viscoelastic_local, m*ntimesteps, ISSM_MPI_DOUBLE, H_viscoelastic, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
@@ -448,7 +455,9 @@
 			/*Avoid singularity at 0: */
 			G_gravi[0]=G_gravi[1];
+			for(int t=0;t<ntimesteps;t++){
+				G_viscoelastic[t]=G_viscoelastic[ntimesteps+t];
+			}
 			if(elastic){
 				for(int t=0;t<ntimesteps;t++){
-					G_viscoelastic[t]=G_viscoelastic[ntimesteps+t];
 					U_viscoelastic[t]=U_viscoelastic[ntimesteps+t];
 					if(horiz)H_viscoelastic[t]=H_viscoelastic[ntimesteps+t];
@@ -463,5 +472,5 @@
 				G_viscoelastic_interpolated=xNew<IssmDouble>(M*nt,"t");
 				U_viscoelastic_interpolated=xNew<IssmDouble>(M*nt,"t");
-				if(horiz)H_viscoelastic_interpolated=xNew<IssmDouble>(M*nt,"t");
+				if(horiz) H_viscoelastic_interpolated=xNew<IssmDouble>(M*nt,"t");
 				if(rotation){
 					Pmtf_col_interpolated=xNew<IssmDouble>(nt,"t");
@@ -475,5 +484,5 @@
 				G_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
 				U_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
-				if(horiz)H_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
+				if(horiz) H_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
 				if(rotation){
 					Pmtf_col_interpolated=xNew<IssmDouble>(nt);
@@ -485,10 +494,8 @@
 				}
 #endif
-
 				for(int t=0;t<nt;t++){
 					IssmDouble lincoeff;
 					IssmDouble viscoelastic_time=t*timeacc;
 					int        timeindex2=-1;
-
 					/*Find a way to interpolate precomputed Gkernels to our solution time stepping:*/
 					if(t!=0){
@@ -509,5 +516,4 @@
 
 					for(int index=0;index<M;index++){
-
 						int timeindex=index*nt+t;
 						int timepreindex= index*ntimesteps+timeindex2;
@@ -527,48 +533,57 @@
 					}
 				}
-
-			}
-			else if(elastic){
+			}
+			else {
+
 				nt=1; //in elastic, or if we run only selfattraction, we need only one step
 #ifdef _HAVE_AD_
-				G_viscoelastic_interpolated=G_viscoelastic;
-				U_viscoelastic_interpolated=U_viscoelastic;
-				if(horiz)H_viscoelastic_interpolated=H_viscoelastic;
+				G_viscoelastic_interpolated=xNew<IssmDouble>(M,"t");
 #else
-				G_viscoelastic_interpolated=G_viscoelastic;
-				U_viscoelastic_interpolated=U_viscoelastic;
-				if(horiz)H_viscoelastic_interpolated=H_viscoelastic;
+				G_viscoelastic_interpolated=xNew<IssmDouble>(M);
 #endif
-
-				if(rotation){ //if this cpu handles degree 2
+				xMemCpy<IssmDouble>(G_viscoelastic_interpolated,G_viscoelastic,M);
+
+				if(elastic){
 #ifdef _HAVE_AD_
-					Pmtf_col_interpolated=xNew<IssmDouble>(1,"t");
-					Pmtf_ortho_interpolated=xNew<IssmDouble>(1,"t");
-					Pmtf_z_interpolated=xNew<IssmDouble>(1,"t");
-					Love_tk2_interpolated=xNew<IssmDouble>(1,"t");
-					Love_th2_interpolated=xNew<IssmDouble>(1,"t");
-					if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(1,"t");
+					U_viscoelastic_interpolated=xNew<IssmDouble>(M,"t");
+					if (horiz) H_viscoelastic_interpolated=xNew<IssmDouble>(M,"t");
 #else
-					Pmtf_col_interpolated=xNew<IssmDouble>(1);
-					Pmtf_ortho_interpolated=xNew<IssmDouble>(1);
-					Pmtf_z_interpolated=xNew<IssmDouble>(1);
-					Love_tk2_interpolated=xNew<IssmDouble>(1);
-					Love_th2_interpolated=xNew<IssmDouble>(1);
-					if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(1);
+					U_viscoelastic_interpolated=xNew<IssmDouble>(M);
+					if (horiz) H_viscoelastic_interpolated=xNew<IssmDouble>(M);
 #endif
-
-					Pmtf_col_interpolated=love_pmtf_colinear;
-					Pmtf_ortho_interpolated=love_pmtf_ortho;
-					Pmtf_z_interpolated[0]=1.0+love_k[2];
-					Love_tk2_interpolated[0]=love_tk[2];
-					Love_th2_interpolated[0]=love_th[2];
-					if (horiz) Love_tl2_interpolated[0]=love_tl[2];
+					xMemCpy<IssmDouble>(U_viscoelastic_interpolated,U_viscoelastic,M);
+					if (horiz) xMemCpy<IssmDouble>(H_viscoelastic_interpolated,H_viscoelastic,M);
+
+					if(rotation){ //if this cpu handles degree 2
+#ifdef _HAVE_AD_
+						Pmtf_col_interpolated=xNew<IssmDouble>(1,"t");
+						Pmtf_ortho_interpolated=xNew<IssmDouble>(1,"t");
+						Pmtf_z_interpolated=xNew<IssmDouble>(1,"t");
+						Love_tk2_interpolated=xNew<IssmDouble>(1,"t");
+						Love_th2_interpolated=xNew<IssmDouble>(1,"t");
+						if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(1,"t");
+#else
+						Pmtf_col_interpolated=xNew<IssmDouble>(1);
+						Pmtf_ortho_interpolated=xNew<IssmDouble>(1);
+						Pmtf_z_interpolated=xNew<IssmDouble>(1);
+						Love_tk2_interpolated=xNew<IssmDouble>(1);
+						Love_th2_interpolated=xNew<IssmDouble>(1);
+						if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(1);
+#endif
+
+						Pmtf_col_interpolated[0]=love_pmtf_colinear[0];
+						Pmtf_ortho_interpolated[0]=love_pmtf_ortho[0];
+						Pmtf_z_interpolated[0]=1.0+love_k[2];
+						Love_tk2_interpolated[0]=love_tk[2];
+						Love_th2_interpolated[0]=love_th[2];
+						if (horiz) Love_tl2_interpolated[0]=love_tl[2];
+					}
+
 				}
 			}	
-
 			/*Save our precomputed tables into parameters*/
 			parameters->AddObject(new DoubleVecParam(SealevelchangeGSelfAttractionEnum,G_gravi,M));
+			parameters->AddObject(new DoubleVecParam(SealevelchangeGViscoElasticEnum,G_viscoelastic_interpolated,M*nt));
 			if(viscous || elastic){
-				parameters->AddObject(new DoubleVecParam(SealevelchangeGViscoElasticEnum,G_viscoelastic_interpolated,M*nt));
 				parameters->AddObject(new DoubleVecParam(SealevelchangeUViscoElasticEnum,U_viscoelastic_interpolated,M*nt));
 				if(horiz)parameters->AddObject(new DoubleVecParam(SealevelchangeHViscoElasticEnum,H_viscoelastic_interpolated,M*nt));
@@ -582,9 +597,12 @@
 				}
 			}
-
 			/*free resources: */
 			xDelete<IssmDouble>(G_gravi);
 			xDelete<IssmDouble>(G_gravi_local);
+			xDelete<IssmDouble>(G_viscoelastic);
+			xDelete<IssmDouble>(G_viscoelastic_local);
+			xDelete<IssmDouble>(G_viscoelastic_interpolated);
 			if(elastic){
+				xDelete<IssmDouble>(love_timefreq);
 				xDelete<IssmDouble>(love_h);
 				xDelete<IssmDouble>(love_k);
@@ -593,16 +611,25 @@
 				xDelete<IssmDouble>(love_tk);
 				xDelete<IssmDouble>(love_tl);
-				xDelete<IssmDouble>(G_viscoelastic);
-				xDelete<IssmDouble>(G_viscoelastic_local);
+
+				xDelete<IssmDouble>(G_viscoelastic_interpolated);
 				xDelete<IssmDouble>(U_viscoelastic);
+				xDelete<IssmDouble>(U_viscoelastic_interpolated);
 				xDelete<IssmDouble>(U_viscoelastic_local);
+				xDelete<IssmDouble>(U_viscoelastic_interpolated);
 				if(horiz){
 					xDelete<IssmDouble>(H_viscoelastic);
+					xDelete<IssmDouble>(H_viscoelastic_interpolated);
 					xDelete<IssmDouble>(H_viscoelastic_local);
+					xDelete<IssmDouble>(H_viscoelastic_interpolated);
 				}
 				if(rotation){
 					xDelete<IssmDouble>(love_pmtf_colinear);
 					xDelete<IssmDouble>(love_pmtf_ortho);
-
+					xDelete<IssmDouble>(Pmtf_col_interpolated);
+					xDelete<IssmDouble>(Pmtf_ortho_interpolated);
+					xDelete<IssmDouble>(Pmtf_z_interpolated);
+					xDelete<IssmDouble>(Love_tk2_interpolated);
+					xDelete<IssmDouble>(Love_th2_interpolated);
+					if (horiz) xDelete<IssmDouble>(Love_tl2_interpolated);
 				}
 			}
@@ -632,4 +659,5 @@
 	iomodel->DeleteData(&requestedoutputs,numoutputs,"md.solidearth.requested_outputs");
 	/*}}}*/
+
 }/*}}}*/
 
Index: issm/trunk/src/c/analyses/SealevelchangeAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/SealevelchangeAnalysis.h	(revision 27035)
+++ issm/trunk/src/c/analyses/SealevelchangeAnalysis.h	(revision 27232)
@@ -16,4 +16,5 @@
 		void CreateLoads(Loads* loads, IoModel* iomodel);
 		void CreateNodes(Nodes* nodes,IoModel* iomodel,bool isamr=false);
+		static void DeleteBarystaticContributionsParam(FemModel* femmodel);
 		int  DofsPerNode(int** doflist,int domaintype,int approximation);
 		void UpdateElements(Elements* elements,Inputs* inputs,IoModel* iomodel,int analysis_counter,int analysis_type);
Index: issm/trunk/src/c/analyses/SmbAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/SmbAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/SmbAnalysis.cpp	(revision 27232)
@@ -249,4 +249,5 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.aIdx",SmbAIdxEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.eIdx",SmbEIdxEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.smb.tcIdx",SmbTcIdxEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.swIdx",SmbSwIdxEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.denIdx",SmbDenIdxEnum));
Index: issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 27232)
@@ -502,5 +502,5 @@
 	}
 
-	/*free ressources: */
+	/*Free resources: */
 	iomodel->DeleteData(penalties,"md.stressbalance.vertex_pairing");
 
@@ -1308,5 +1308,5 @@
 	solution->SetValues(numdof,doflist,values,INS_VAL);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete gauss;
 	xDelete<IssmDouble>(values);
@@ -2143,5 +2143,5 @@
 	element->AddBasalInput(VelEnum,vel,element->GetElementType());
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(vel);
 	xDelete<IssmDouble>(vz);
@@ -2749,5 +2749,5 @@
 	element->AddBasalInput(VyBaseEnum,vy,element->GetElementType());
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(vel);
 	xDelete<IssmDouble>(vz);
@@ -3275,5 +3275,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(vel);
 	xDelete<IssmDouble>(vx);
@@ -3343,5 +3343,5 @@
 	solution->SetValues(numdof,doflist,values,INS_VAL);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete gauss;
 	xDelete<IssmDouble>(values);
@@ -3992,5 +3992,5 @@
 	element->AddInput(VelEnum,vel,element->GetElementType());
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(vel);
 	xDelete<IssmDouble>(vz);
@@ -6505,5 +6505,5 @@
 	if(pnumdof>0) solution->SetValues(pnumdof,pdoflist,pvalues,INS_VAL);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete gauss;
 	xDelete<int>(pdoflist);
@@ -6668,5 +6668,5 @@
 	if(dim==3) element->AddInput(VzEnum,vz,v_interp);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(pressure);
 	xDelete<IssmDouble>(vel);
@@ -8566,5 +8566,5 @@
 	element->AddInput(PressureEnum,pressure,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(pressure);
 	xDelete<IssmDouble>(vel);
@@ -8669,5 +8669,5 @@
 	element->AddInput(PressureEnum,pressure,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(pressure);
 	xDelete<IssmDouble>(vel);
@@ -8760,5 +8760,5 @@
 	element->AddInput(PressureEnum,pressure,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(surface);
 	xDelete<IssmDouble>(pressure);
Index: issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 27232)
@@ -554,5 +554,5 @@
 	solution->SetValues(numdof,doflist,values,INS_VAL);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete gauss;
 	xDelete<int>(doflist);
@@ -630,5 +630,5 @@
 	element->AddInput(PressureEnum,pressure,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(thickness);
 	xDelete<IssmDouble>(surface);
Index: issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 27232)
@@ -657,5 +657,5 @@
 	element->AddInput(VelEnum,vel,P1Enum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(surface);
 	xDelete<IssmDouble>(pressure);
Index: issm/trunk/src/c/analyses/ThermalAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 27232)
@@ -65,5 +65,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	iomodel->DeleteData(spcvector,"md.thermal.spctemperature");
 	iomodel->DeleteData(spcvectorstatic,"md.thermal.spctemperature");
@@ -839,5 +839,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(surface);
Index: issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 27035)
+++ issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 27232)
@@ -287,5 +287,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(valueslambda);
Index: issm/trunk/src/c/analyses/analyses.h
===================================================================
--- issm/trunk/src/c/analyses/analyses.h	(revision 27035)
+++ issm/trunk/src/c/analyses/analyses.h	(revision 27232)
@@ -11,4 +11,5 @@
 #include "./AdjointBalancethickness2Analysis.h"
 #include "./AdjointHorizAnalysis.h"
+#include "./AgeAnalysis.h"
 #include "./BalancethicknessAnalysis.h"
 #include "./Balancethickness2Analysis.h"
Index: issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp
===================================================================
--- issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp	(revision 27232)
@@ -69,5 +69,13 @@
 /*}}}*/
 void Cfdragcoeffabsgrad::Marshall(MarshallHandle* marshallhandle){/*{{{*/
-	_error_("not implemented yet!"); 
+
+	/*ok, marshall operations: */
+   int object_enum=CfdragcoeffabsgradEnum;
+   marshallhandle->call(object_enum);
+
+	marshallhandle->call(this->definitionenum);
+	marshallhandle->call(this->name);
+	marshallhandle->call(this->weights_enum);
+	marshallhandle->call(this->timepassedflag);
 } 
 /*}}}*/
Index: issm/trunk/src/c/classes/Dakota/IssmDirectApplicInterface.h
===================================================================
--- issm/trunk/src/c/classes/Dakota/IssmDirectApplicInterface.h	(revision 27035)
+++ issm/trunk/src/c/classes/Dakota/IssmDirectApplicInterface.h	(revision 27232)
@@ -118,5 +118,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				xDelete<IssmDouble>(variables);
 				for(i=0;i<numACV;i++){
Index: issm/trunk/src/c/classes/Dakota/IssmParallelDirectApplicInterface.cpp
===================================================================
--- issm/trunk/src/c/classes/Dakota/IssmParallelDirectApplicInterface.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Dakota/IssmParallelDirectApplicInterface.cpp	(revision 27232)
@@ -134,5 +134,5 @@
 		}
 
-		/*Free ressources:*/
+		/*Free resources:*/
 		xDelete<IssmDouble>(variables);
 		for(i=0;i<numACV;i++){
Index: issm/trunk/src/c/classes/Elements/Element.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Element.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Element.cpp	(revision 27232)
@@ -22,4 +22,5 @@
 #include "../Inputs/ControlInput.h"
 #include "../Inputs/ArrayInput.h"
+#include "../Inputs/IntArrayInput.h"
 /*}}}*/
 #define MAXVERTICES 6 /*Maximum number of vertices per element, currently Penta, to avoid dynamic mem allocation*/
@@ -1533,5 +1534,5 @@
 	solution->SetValues(numnodes,doflist,values,INS_VAL);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(doflist);
 	xDelete<IssmDouble>(values);
@@ -4012,4 +4013,5 @@
 	int        aIdx=0;
 	int        eIdx=0;
+	int        tcIdx=0;
 	int        denIdx=0;
 	int        dsnowIdx=0;
@@ -4096,4 +4098,5 @@
 	parameters->FindParam(&aIdx,SmbAIdxEnum);
 	parameters->FindParam(&eIdx,SmbEIdxEnum);
+	parameters->FindParam(&tcIdx,SmbTcIdxEnum);
 	parameters->FindParam(&denIdx,SmbDenIdxEnum);
 	parameters->FindParam(&swIdx,SmbSwIdxEnum);
@@ -4348,5 +4351,5 @@
 	}
 	/*Thermal profile computation:*/
-	if(isthermal)thermo(&EC, &T, &ulw, re, dz, d, swf, dlw, Ta, V, eAir, pAir, eIdx, teValue, dulwrfValue, teThresh, W[0], smb_dt, m, Vz, Tz, thermo_scaling,rho_ice,this->Sid(),isconstrainsurfaceT,isdeltaLWup);
+	if(isthermal)thermo(&shf, &lhf, &EC, &T, &ulw, re, dz, d, swf, dlw, Ta, V, eAir, pAir, tcIdx, eIdx, teValue, dulwrfValue, teThresh, W[0], smb_dt, dzMin, m, Vz, Tz, thermo_scaling,rho_ice,this->Sid(),isconstrainsurfaceT,isdeltaLWup);
 
 	/*Change in thickness of top cell due to evaporation/condensation  assuming same density as top cell.
@@ -4364,14 +4367,7 @@
 	if(isdensification)densification(&d,&dz, T, re, denIdx, aIdx, swIdx, adThresh, C, smb_dt, Tmean,rho_ice,m,this->Sid());
 
-	/*Calculate upward longwave radiation flux [W m-2] not used in energy balance. Calculated for every
-	 * sub-time step in thermo equations*/
-	//ulw = 5.67E-8 * pow(T[0],4.0) * teValue; // + deltatest here
-
 	/*Calculate net longwave [W m-2]*/
 	meanULW = meanULW + ulw*smb_dt/dt;
 	netLW = netLW + (dlw - ulw)*smb_dt/dt;
-
-	/*Calculate turbulent heat fluxes [W m-2]*/
-	if(isturbulentflux)turbulentFlux(&shf, &lhf, &dayEC, Ta, T[0], V, eAir, pAir, d[0], W[0], Vz, Tz,rho_ice,this->Sid());
 
 	/*Verbose some results in debug mode: {{{*/
Index: issm/trunk/src/c/classes/Elements/Element.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Element.h	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Element.h	(revision 27232)
@@ -404,5 +404,5 @@
 		virtual void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom)=0;
 		virtual void       SealevelchangeShift(GrdLoads* loads, IssmDouble offset, SealevelGeometry* slgeom)=0;
-		virtual void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae)=0;
+		virtual void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae, int* lids)=0;
 		virtual void       SealevelchangeGeometryCentroidLoads(SealevelGeometry* slgeom, IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae)=0;
 		virtual void       SealevelchangeGeometrySubElementLoads(SealevelGeometry* slgeom, IssmDouble* areae)=0;
Index: issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 27232)
@@ -120,5 +120,5 @@
 	if(this->hneighbors)this->hneighbors->Marshall(marshallhandle);
 
-	/*Free ressources: */
+	/*Free resources: */
 	if(hnodesi_null) xDelete<bool>(hnodesi_null);
 
Index: issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 27232)
@@ -2604,5 +2604,5 @@
 	this->AddInput(enum_type,values,this->element_type);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
@@ -2645,5 +2645,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(doflist);
 }
@@ -2699,5 +2699,5 @@
 			inputs->SetPentaInput(name,P1Enum,NUMVERTICES,lidlist,values);
 
-			/*Free ressources:*/
+			/*Free resources:*/
 			xDelete<int>(doflist);
 			return;
@@ -2712,5 +2712,5 @@
 			inputs->SetPentaInput(name,P1Enum,NUMVERTICES,lidlist,values);
 
-			/*Free ressources:*/
+			/*Free resources:*/
 			xDelete<int>(doflist);
 			return;
Index: issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Penta.h	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Penta.h	(revision 27232)
@@ -227,5 +227,5 @@
 		void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){_error_("not implemented yet");};
 		void       SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom){_error_("not implemented yet");};
-		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
+		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae, int* lids){_error_("not implemented yet");};
 		void       SealevelchangeGeometryCentroidLoads(SealevelGeometry* slgeom, IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
 		void       SealevelchangeGeometrySubElementLoads(SealevelGeometry* slgeom, IssmDouble* areae){_error_("not implemented yet");};
Index: issm/trunk/src/c/classes/Elements/Seg.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Seg.h	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Seg.h	(revision 27232)
@@ -180,5 +180,5 @@
 		void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){_error_("not implemented yet");};
 		void       SealevelchangeShift(GrdLoads* loads, IssmDouble offset, SealevelGeometry* slgeom){_error_("not implemented yet");};
-		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
+		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae, int* lids){_error_("not implemented yet");};
 		void       SealevelchangeGeometryCentroidLoads(SealevelGeometry* slgeom, IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
 		void       SealevelchangeGeometrySubElementLoads(SealevelGeometry* slgeom, IssmDouble* areae){_error_("not implemented yet");};
Index: issm/trunk/src/c/classes/Elements/Tetra.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 27232)
@@ -446,5 +446,5 @@
 	this->AddInput(enum_type,values,this->element_type);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
Index: issm/trunk/src/c/classes/Elements/Tetra.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Tetra.h	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Tetra.h	(revision 27232)
@@ -187,5 +187,5 @@
 		void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){_error_("not implemented yet");};
 		void       SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom){_error_("not implemented yet");};
-		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
+		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae, int* lids){_error_("not implemented yet");};
 		void       SealevelchangeGeometryCentroidLoads(SealevelGeometry* slgeom, IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
 		void       SealevelchangeGeometrySubElementLoads(SealevelGeometry* slgeom, IssmDouble* areae){_error_("not implemented yet");};
Index: issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 27232)
@@ -376,4 +376,5 @@
 	IssmDouble  time;
 	IssmDouble  coeff, indrate;
+	IssmDouble  bed, bedrate = 1.0;
 
 	/*Retrieve all inputs and parameters we will need*/
@@ -382,4 +383,5 @@
 	parameters->FindParam(&indrate,CalvingTestIndependentRateEnum,time);
 
+	Input *bs_input = this->GetInput(BedEnum);_assert_(bs_input);
 	Input* vx_input = this->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input = this->GetInput(VyEnum); _assert_(vy_input);
@@ -399,9 +401,12 @@
       lsf_slopey_input->GetInputValue(&dphidy,&gauss);
 
+		bs_input->GetInputValue(&bed,&gauss);
+		bedrate = (bed>0)?0.0:1.0;
+
       vel=sqrt(vx*vx + vy*vy) + 1e-14;
       dphi=sqrt(dphidx*dphidx+dphidy*dphidy)+ 1e-14;
 
-		calvingratex[iv]= coeff*vx + indrate*dphidx/dphi;
-		calvingratey[iv]= coeff*vy + indrate*dphidy/dphi;
+		calvingratex[iv]= coeff*vx + bedrate*indrate*dphidx/dphi;
+		calvingratey[iv]= coeff*vy + bedrate*indrate*dphidy/dphi;
 		calvingrate[iv] = sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
 	}
@@ -835,10 +840,10 @@
 	IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
 	IssmDouble  sigma_vm[NUMVERTICES];
-	IssmDouble  B,sigma_max,sigma_max_floating,sigma_max_grounded,n;
+	IssmDouble  B, n;
 	IssmDouble  epse_2,groundedice,bed,sealevel;
-	IssmDouble  arate, rho_ice, rho_water, thickness, paramX, Hab;
-	int			use_parameter=0;
-	int			nonlinear_law=0;
-	IssmDouble  theta, alpha, midp, gamma;
+	IssmDouble  arate, rho_ice, rho_water, thickness;
+	int			use_parameter=-1;
+	IssmDouble  gamma, theta, alpha, xoffset, yoffset;
+	IssmDouble  vel_lower, vel_upper, vrate, truncateVrate;
 
 	/* Get node coordinates and dof list: */
@@ -852,6 +857,4 @@
 	Input *bs_input      = this->GetInput(BedEnum);                               _assert_(bs_input);
 	Input *H_input       = this->GetInput(ThicknessEnum);                         _assert_(H_input);
-	Input *smax_fl_input = this->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
-	Input *smax_gr_input = this->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
 	Input *n_input       = this->GetInput(MaterialsRheologyNEnum);                _assert_(n_input);
 	Input *sl_input      = this->GetInput(SealevelEnum);                          _assert_(sl_input);
@@ -864,8 +867,10 @@
 	/* Use which parameter  */
 	this->FindParam(&use_parameter, CalvingUseParamEnum);
-	this->FindParam(&theta, CalvingScaleThetaEnum);
-	this->FindParam(&alpha, CalvingAmpAlphaEnum);
-	this->FindParam(&midp, CalvingMidpointEnum);
-	this->FindParam(&nonlinear_law, CalvingNonlinearLawEnum);
+	this->FindParam(&theta, CalvingThetaEnum);
+	this->FindParam(&alpha, CalvingAlphaEnum);
+	this->FindParam(&xoffset, CalvingXoffsetEnum);
+	this->FindParam(&yoffset, CalvingYoffsetEnum);
+	this->FindParam(&vel_lower, CalvingVelLowerboundEnum);
+	this->FindParam(&vel_upper, CalvingVelUpperboundEnum);
 
 	/* Start looping on the number of vertices: */
@@ -882,9 +887,9 @@
 		bs_input->GetInputValue(&bed,gauss);
 		H_input->GetInputValue(&thickness,gauss);
-		smax_fl_input->GetInputValue(&sigma_max_floating,gauss);
-		smax_gr_input->GetInputValue(&sigma_max_grounded,gauss);
 		vel=sqrt(vx*vx+vy*vy)+1.e-14;
 		sl_input->GetInputValue(&sealevel,gauss);
 		arate_input->GetInputValue(&arate,gauss);
+		vrate = 1.0;
+		if (vel < vel_upper) vrate = vel / vel_upper;
 
 		/*Compute strain rate and viscosity: */
@@ -904,30 +909,30 @@
 		sigma_vm[iv]  = sqrt(3.) * B * pow(epse_2,1./(2.*n));
 
-		/*Tensile stress threshold*/
-		if(groundedice<0)
-		 sigma_max = sigma_max_floating;
-		else
-		 sigma_max = sigma_max_grounded;
-
 		switch (use_parameter) { 
 			case 0:
-				/* bed elevation */
-				paramX = bed;
+				/* 0 Linear: f(x) = y_{o} + \alpha (x+x_{o}) */
+				gamma = yoffset = alpha * (bed+xoffset);
 				break;
 			case 1:
-				/* Height above floatation */
-				if (bed>sealevel)	paramX = 0.0;
-				else paramX = thickness - (rho_water/rho_ice) * (sealevel-bed);
+				/* 1 tanh: f(x)=y_{o}-\frac{\theta}{2}\tanh(\alpha(x+x_{o})) */
+				gamma = yoffset -  0.5*theta*tanh(alpha*(bed+xoffset));
 				break;
 			case 2:
-				/* Thicknese */
-				paramX = thickness;
+				/* 2 tanh(thicknes): f(x)=y_{o}-\frac{\theta}{2}\tanh(\alpha(x+x_{o})) */
+				gamma = yoffset -  0.5*theta*tanh(alpha*(-thickness+xoffset));
+				break;
+			case 3:
+				/* 3 tanh(normal vel): f(x)=y_{o}-\frac{\theta}{2}\tanh(\alpha(x+x_{o})) */
+				_error_("The normalized velocity is not supported yet!");
+				gamma = yoffset -  0.5*theta*tanh(alpha*(vel+xoffset));
 				break;
 			case 4:
-				/* bed elevation+linear curve fitting */
-				paramX = bed;
+				/* 4 tanh(truncated vel): f(x)=y_{o}-\frac{\theta}{2}\tanh(\alpha(x+x_{o})) */
+				truncateVrate = (min(vel_upper, max(vel_lower, vel))-vel_lower) / vel_upper;
+				gamma = 0.5*theta*(tanh(alpha*xoffset) - tanh(alpha*(truncateVrate+xoffset)));
 				break;
 			case -1:
-				/* use nothing, just the arate*/
+				/* nothing, just the arate*/
+				gamma = 1;
 				break;
 			default:
@@ -935,32 +940,17 @@
 		}
 
-		/* Compute the hyperbolic tangent function */
-		if ((use_parameter>-0.5) & (use_parameter<3)) {
-			gamma = 0.5*theta*(1.0-tanh((paramX+midp)/alpha))+(1.0-theta);
-			if (gamma<0.0) gamma =0.0;
-		}
-		else if (use_parameter>=3) {
-			gamma = alpha*paramX + theta;
-			if (gamma > 1.0) gamma = 1.0;
-			if (gamma < 0.0) gamma = 0.0;
-		}
-		else gamma = 1;
+		/* set upper and lower bounds */
+		if (gamma > 1.0) gamma = 1.0;
+		if (gamma < 0.0) gamma = 0.0;
+		if (bed >= sealevel) gamma = 0.0;
 
 		/*-------------------------------------------*/
-		if (nonlinear_law) {
-			/*This von Mises type has too strong positive feedback with vel included
-			 * calvingrate[iv] = (arate+sigma_vm[iv]*vel/sigma_max)*gamma;
-			 */
-			Hab = thickness - (rho_water/rho_ice) * (sealevel-bed);
-			if (Hab < 0.) Hab = 0.;
-			if (bed > sealevel) Hab = 0.;
-
-			calvingrate[iv] = (arate+Hab/sigma_max)*gamma;
-		}
+		if (use_parameter < 3) {
+			calvingrate[iv] = arate*gamma*vrate;
+		} 
 		else {
 			calvingrate[iv] = arate*gamma;
 		}
 	}
-
 	/*Add input*/
 	this->AddInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum);
@@ -2018,5 +2008,5 @@
 	else for(int i=0;i<NUMVERTICES;i++)weights[i]=0;
 
-	/*free ressources:*/
+	/*Free resources:*/
 	delete gauss;
 
@@ -3905,5 +3895,5 @@
 	this->AddInput(enum_type,values,this->element_type);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
@@ -6044,5 +6034,5 @@
 	pY->SetValues(gsize,indices,Y_values,ADD_VAL);
 
-	/*free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(indices);
 	xDelete<IssmDouble>(U_values); xDelete<IssmDouble>(N_values); xDelete<IssmDouble>(E_values);
@@ -6206,5 +6196,5 @@
 	pEast->SetValues(gsize,indices,E_values,ADD_VAL);
 
-	/*free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(indices);
 	xDelete<IssmDouble>(U_values); xDelete<IssmDouble>(N_values); xDelete<IssmDouble>(E_values);
@@ -6313,5 +6303,5 @@
 	}
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<IssmDouble>(hes);
 	xDelete<IssmDouble>(times);
@@ -6320,5 +6310,5 @@
 }
 /*}}}*/
-void       Tria::SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){ /*{{{*/
+void       Tria::SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae, int* lids){ /*{{{*/
 
 	/*Declarations:{{{*/
@@ -6342,21 +6332,7 @@
 
 	#ifdef _HAVE_RESTRICT_
-	IssmDouble* __restrict__ G=NULL;
-	IssmDouble* __restrict__ GU=NULL;
-	IssmDouble* __restrict__ GN=NULL;
-	IssmDouble* __restrict__ GE=NULL;
-	IssmDouble* __restrict__ G_viscoelastic_precomputed=NULL;
 	IssmDouble* __restrict__ G_gravi_precomputed=NULL;
-	IssmDouble* __restrict__ U_viscoelastic_precomputed=NULL;
-	IssmDouble* __restrict__ H_viscoelastic_precomputed=NULL;
 	#else
-	IssmDouble* G=NULL;
-	IssmDouble* GU=NULL;
-	IssmDouble* GN=NULL;
-	IssmDouble* GE=NULL;
-	IssmDouble* G_viscoelastic_precomputed=NULL;
 	IssmDouble* G_gravi_precomputed=NULL;
-	IssmDouble* U_viscoelastic_precomputed=NULL;
-	IssmDouble* H_viscoelastic_precomputed=NULL;
 	#endif
 
@@ -6364,4 +6340,5 @@
 	int index;
 	int M;
+	IssmDouble degacc;
 	IssmDouble doubleindex,lincoef;
 
@@ -6380,4 +6357,8 @@
 	/*Rotational:*/
 	#ifdef _HAVE_RESTRICT_
+	IssmDouble* __restrict__ Grot=NULL;
+	IssmDouble* __restrict__ GUrot=NULL;
+	IssmDouble* __restrict__ GNrot=NULL;
+	IssmDouble* __restrict__ GErot=NULL;
 	IssmDouble* __restrict__ tide_love_h  = NULL;
 	IssmDouble* __restrict__ tide_love_k  = NULL;
@@ -6386,9 +6367,11 @@
 	IssmDouble* __restrict__ LoveRotU     = NULL;
 	IssmDouble* __restrict__ LoveRothoriz = NULL;
-	IssmDouble* __restrict__  Grot        = NULL;
-	IssmDouble* __restrict__ GUrot        = NULL;
-	IssmDouble* __restrict__ GNrot        = NULL;
-	IssmDouble* __restrict__ GErot        = NULL;
+	int* __restrict__ AplhaIndex   = NULL;
+	int* __restrict__ AzimuthIndex = NULL;
 	#else
+	IssmDouble* Grot=NULL;
+	IssmDouble* GUrot=NULL;
+	IssmDouble* GNrot=NULL;
+	IssmDouble* GErot=NULL;
 	IssmDouble* tide_love_h  = NULL;
 	IssmDouble* tide_love_k  = NULL;
@@ -6397,8 +6380,6 @@
 	IssmDouble* LoveRotU     = NULL;
 	IssmDouble* LoveRothoriz = NULL;
-	IssmDouble*  Grot        = NULL;
-	IssmDouble* GUrot        = NULL;
-	IssmDouble* GNrot        = NULL;
-	IssmDouble* GErot        = NULL;
+	int* AlphaIndex   = NULL;
+	int* AzimuthIndex = NULL;
 	#endif
 
@@ -6439,19 +6420,9 @@
 
 	/*Recover precomputed green function kernels:{{{*/
-	DoubleVecParam* parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeGSelfAttractionEnum)); _assert_(parameter);
-	parameter->GetParameterValueByPointer((IssmDouble**)&G_gravi_precomputed,&M);
-
+	parameters->FindParam(&degacc,SolidearthSettingsDegreeAccuracyEnum);
+	M=reCast<int,IssmDouble>(180.0/degacc+1.);
+
+	DoubleVecParam* parameter;
 	if(computeelastic){
-		parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeGViscoElasticEnum)); _assert_(parameter);
-		parameter->GetParameterValueByPointer((IssmDouble**)&G_viscoelastic_precomputed,NULL);
-
-		parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeUViscoElasticEnum)); _assert_(parameter);
-		parameter->GetParameterValueByPointer((IssmDouble**)&U_viscoelastic_precomputed,NULL);
-
-		if(horiz){
-			parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeHViscoElasticEnum)); _assert_(parameter);
-			parameter->GetParameterValueByPointer((IssmDouble**)&H_viscoelastic_precomputed,NULL);
-		}
-
 		if(computerotation){
 			parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeTidalH2Enum)); _assert_(parameter);
@@ -6489,92 +6460,45 @@
 	}
 
-	constant=3/rho_earth/planetarea;
-
-	G=xNewZeroInit<IssmDouble>(3*nel*nt);
-	if(computeelastic){
-		GU=xNewZeroInit<IssmDouble>(3*nel*nt);
-		if(horiz){
-			GN=xNewZeroInit<IssmDouble>(3*nel*nt);
-			GE=xNewZeroInit<IssmDouble>(3*nel*nt);
-		}
-	}
-
-	for(int e=0;e<nel;e++){
-		ratioe=constant*areae[e];
-		for (int i=0;i<3;i++){
-			IssmDouble alpha;
-			IssmDouble delPhi,delLambda;
-			/*recovers info for this element and vertex:*/
-			IssmDouble late= asin(zze[e]/sqrt( pow(xxe[e],2.0)+ pow(yye[e],2.0)+ pow(zze[e],2.0)));
-			IssmDouble longe= atan2(yye[e],xxe[e]);
-
-			lati=latitude[i];
-			longi=longitude[i];
-
-			/*Computes alpha angle between centroid and current vertex, and indexes alpha in precomputed tables: */
-			delPhi=fabs(lati-late); delLambda=fabs(longi-longe); if (delLambda>M_PI)delLambda=2*M_PI-delLambda;
-			alpha=2.*asin(sqrt(pow(sin(delPhi/2),2)+cos(lati)*cos(late)*pow(sin(delLambda/2),2)));
-			doubleindex=alpha/M_PI*reCast<IssmDouble,int>(M-1); //maps 0<alpha<PI on [0:M-1]
-			index=reCast<int,IssmDouble>(doubleindex); //truncates doubleindex to integer part
-			_assert_(index>=0 && index<M);
-
-			lincoef=doubleindex-index; //where between index and index+1 is alpha
-			if (index==M-1){ //avoids out of bound case
-				index-=1;
-				lincoef=1;
-			}
-
-			if(horiz){
-				/*Compute azimuths, both north and east components: */
-				x = xyz_list[i][0]; y = xyz_list[i][1]; z = xyz_list[i][2];
-				if(lati==M_PI/2){
-					x=1e-12; y=1e-12;
+	AlphaIndex=xNewZeroInit<int>(3*nel);
+	if (horiz) AzimuthIndex=xNewZeroInit<int>(3*nel);
+	int intmax=pow(2,16)-1;
+
+
+	for (int i=0;i<3;i++){
+		if(lids[this->vertices[i]->lid]==this->lid){
+			for(int e=0;e<nel;e++){
+				IssmDouble alpha;
+				IssmDouble delPhi,delLambda;
+				/*recovers info for this element and vertex:*/
+				IssmDouble late= asin(zze[e]/sqrt( pow(xxe[e],2.0)+ pow(yye[e],2.0)+ pow(zze[e],2.0)));
+				IssmDouble longe= atan2(yye[e],xxe[e]);
+
+				lati=latitude[i];
+				longi=longitude[i];
+
+				/*Computes alpha angle between centroid and current vertex, and indexes alpha in precomputed tables: */
+				delPhi=fabs(lati-late); delLambda=fabs(longi-longe); if (delLambda>M_PI)delLambda=2*M_PI-delLambda;
+				alpha=2.*asin(sqrt(pow(sin(delPhi/2),2)+cos(lati)*cos(late)*pow(sin(delLambda/2),2)));
+				doubleindex=alpha/M_PI*reCast<IssmDouble,int>(M-1); //maps 0<alpha<PI on [0:M-1]
+				index=reCast<int,IssmDouble>(doubleindex); //truncates doubleindex to integer part
+				if ((doubleindex-index)>=0.5) index+=1; //nearest neighbour
+				_assert_(index>=0 && index<M);
+
+				if(horiz){
+					/*Compute azimuths*/
+					dx=cos(lati)*sin(late)-sin(lati)*cos(late)*cos(longe-longi);
+					dy=sin(longe-longi)*cos(late);
+					//angle between horiz motion and North, remapped from a double on [0,2*pi] to a int [0,intmax]
+					AzimuthIndex[i*nel+e]=reCast<int,IssmDouble>(intmax*(atan2(dy,dx)/2/M_PI));
 				}
-				if(lati==-M_PI/2){
-					x=1e-12; y=1e-12;
-				}
-				dx = xxe[e]-x; dy = yye[e]-y; dz = zze[e]-z;
-				N_azim = (-z*x*dx-z*y*dy+(pow(x,2)+pow(y,2))*dz) /pow((pow(x,2)+pow(y,2))*(pow(x,2)+pow(y,2)+pow(z,2))*(pow(dx,2)+pow(dy,2)+pow(dz,2)),0.5);
-				E_azim = (-y*dx+x*dy) /pow((pow(x,2)+pow(y,2))*(pow(dx,2)+pow(dy,2)+pow(dz,2)),0.5);
-			}
-
-			for(int t=0;t<nt;t++){
-				int timeindex=i*nel*nt+e*nt+t; 
-
-				/*Rigid earth gravitational perturbation: */
-				G[timeindex]+=G_gravi_precomputed[index+0]*(1.-lincoef) 
-					     +G_gravi_precomputed[index+1]*lincoef; //linear interpolation
-
-				/*Find a way to interpolate precomputed Gkernels to our solution time stepping:*/
-				if(computeelastic){
-					G[timeindex]+=G_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-						     +G_viscoelastic_precomputed[(index+1)*nt+t]*lincoef; //linear interpolation
-				}
-				G[timeindex]=G[timeindex]*ratioe;
-
-				/*Elastic components:*/
-				if(computeelastic){
-					GU[timeindex] =  ratioe *(U_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-								 +U_viscoelastic_precomputed[(index+1)*nt+t]*lincoef);
-					if(horiz){
-						GN[timeindex] = N_azim*ratioe *(H_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-								 	       +H_viscoelastic_precomputed[(index+1)*nt+t]*lincoef);
-						GE[timeindex] = E_azim*ratioe *(H_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-								 	       +H_viscoelastic_precomputed[(index+1)*nt+t]*lincoef);
-					}
-				}
-			} //for(int t=0;t<nt;t++)
+				AlphaIndex[i*nel+e]=index;
+			}			
 		} //for (int i=0;i<3;i++)
 	} //for(int e=0;e<nel;e++)
 
 	/*Add in inputs:*/
-	this->inputs->SetArrayInput(SealevelchangeGEnum,this->lid,G,nel*3*nt);
-	if(computeelastic){
-		this->inputs->SetArrayInput(SealevelchangeGUEnum,this->lid,GU,nel*3*nt);
-		if(horiz){
-			this->inputs->SetArrayInput(SealevelchangeGNEnum,this->lid,GN,nel*3*nt);
-			this->inputs->SetArrayInput(SealevelchangeGEEnum,this->lid,GE,nel*3*nt);
-		}
-	}
+	this->inputs->SetIntArrayInput(SealevelchangeAlphaIndexEnum,this->lid,AlphaIndex,nel*3);
+	if(horiz) this->inputs->SetIntArrayInput(SealevelchangeAzimuthIndexEnum,this->lid,AzimuthIndex,nel*3);
+
 	/*}}}*/
 	/*Compute rotation kernel:{{{*/
@@ -6583,5 +6507,5 @@
 		LoveRotRSL  = xNewZeroInit<IssmDouble>(nt);
 		LoveRotU    = xNewZeroInit<IssmDouble>(nt);
-		LoveRothoriz= xNewZeroInit<IssmDouble>(nt);
+		if(horiz)LoveRothoriz= xNewZeroInit<IssmDouble>(nt);
 		Grot        = xNewZeroInit<IssmDouble>(3*3*nt); //3 polar motion components * 3 vertices * number of time steps
 		GUrot       = xNewZeroInit<IssmDouble>(3*3*nt);
@@ -6669,4 +6593,8 @@
 			}
 		}
+		/*Free resources:*/
+		xDelete<IssmDouble>(LoveRotRSL);
+		xDelete<IssmDouble>(LoveRotU);
+		if(horiz)xDelete<IssmDouble>(LoveRothoriz);
 	}
 	/*}}}*/
@@ -6690,38 +6618,183 @@
 	/*Free allocations:{{{*/
 	#ifdef _HAVE_RESTRICT_
-	delete G;
-	if(computeelastic){
-		delete GU;
-		if(horiz){
-			delete GN;
-			delete GE;
-		}
-		if(computerotation){
-			delete Grot;
-			delete GUrot;
-			if (horiz){
-				delete GNrot;
-				delete GErot;
-			}
-		}
-	}
+	delete AlphaIndex;
+	if(horiz) AzimuthIndex;
+
+	if(computerotation){
+		delete Grot;
+		delete GUrot;
+		if (horiz){
+			delete GNrot;
+			delete GErot;
+		}
+	}
+
 	#else
-	xDelete(G);
-	if(computeelastic){
-		xDelete(GU);
-		if(horiz){
-			xDelete(GN);
-			xDelete(GE);
-		}
-		if(computerotation){
-			xDelete(Grot);
-			xDelete(GUrot);
-			if (horiz){
-				xDelete(GNrot);
-				xDelete(GErot);
-			}
+	xDelete<int>(AlphaIndex);
+	if(horiz){
+		xDelete<int>(AzimuthIndex);
+	}
+	if(computerotation){
+		xDelete<IssmDouble>(Grot);
+		xDelete<IssmDouble>(GUrot);
+		if (horiz){
+			xDelete<IssmDouble>(GNrot);
+			xDelete<IssmDouble>(GErot);
 		}
 	}
 	#endif
+	/*}}}*/
+	return;
+
+}
+/*}}}*/
+
+void       Tria::SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){ /*{{{*/
+
+	/*Declarations:{{{*/
+	int nel;
+	IssmDouble planetarea,planetradius;
+	IssmDouble constant,ratioe;
+	IssmDouble rho_earth;
+	IssmDouble lati,longi;
+	IssmDouble latitude[NUMVERTICES];
+	IssmDouble longitude[NUMVERTICES];
+	IssmDouble x,y,z,dx,dy,dz,N_azim,E_azim;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	#ifdef _HAVE_RESTRICT_
+	int** __restrict__ AlphaIndex=NULL;
+	int** __restrict__ AzimIndex=NULL;
+
+	#else
+	int** AlphaIndex=NULL;
+	int** AzimIndex=NULL;
+	#endif
+
+	/*viscoelastic green function:*/
+	int index;
+	int M;
+	IssmDouble doubleindex,lincoef, degacc;
+
+	/*Computational flags:*/
+	bool computeselfattraction = false;
+	bool computeelastic = false;
+	bool computeviscous = false;
+	int  horiz;
+	int grd, grdmodel;
+
+	bool istime=true;
+	IssmDouble timeacc=0;
+	IssmDouble start_time,final_time;
+	int  nt,precomputednt;
+	int intmax=pow(2,16)-1;
+
+	/*}}}*/
+	/*Recover parameters:{{{ */
+	rho_earth=FindParam(MaterialsEarthDensityEnum);
+	this->parameters->FindParam(&computeselfattraction,SolidearthSettingsSelfAttractionEnum);
+	this->parameters->FindParam(&computeelastic,SolidearthSettingsElasticEnum);
+	this->parameters->FindParam(&computeviscous,SolidearthSettingsViscousEnum);
+	this->parameters->FindParam(&nel,MeshNumberofelementsEnum);
+	this->parameters->FindParam(&planetarea,SolidearthPlanetAreaEnum);
+	this->parameters->FindParam(&planetradius,SolidearthPlanetRadiusEnum);
+	this->parameters->FindParam(&horiz,SolidearthSettingsHorizEnum);
+	this->parameters->FindParam(&grd,SolidearthSettingsGRDEnum); 
+	this->parameters->FindParam(&grdmodel,GrdModelEnum);
+	/*}}}*/
+
+	/*early return:*/
+	if (!grd || grdmodel!=ElasticEnum) return; //Love numbers won't be found in this case, return before loading them
+	if(!computeselfattraction)return;
+
+	/*Recover precomputed green function kernels:{{{*/
+	parameters->FindParam(&degacc,SolidearthSettingsDegreeAccuracyEnum);
+	M=reCast<int,IssmDouble>(180.0/degacc+1.);
+
+	/*}}}*/
+	/*Compute lat long of all vertices in the element:{{{*/
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	for(int i=0;i<NUMVERTICES;i++){
+		latitude[i]= asin(xyz_list[i][2]/planetradius);
+		longitude[i]= atan2(xyz_list[i][1],xyz_list[i][0]);
+	}
+	/*}}}*/
+	/*Compute green functions:{{{ */
+
+	if(computeviscous){
+		this->parameters->FindParam(&istime,LoveIsTimeEnum);
+		if(!istime)_error_("Frequency love numbers not supported yet!");
+		this->parameters->FindParam(&timeacc,SolidearthSettingsTimeAccEnum);
+		this->parameters->FindParam(&start_time,TimesteppingStartTimeEnum);
+		this->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+		nt=reCast<int,IssmDouble>((final_time-start_time)/timeacc)+1;
+	}
+	else{
+		nt=1; //in elastic, or if we run only selfattraction, we need only one step
+	}
+	AlphaIndex=xNew<int*>(SLGEOM_NUMLOADS);
+	if(horiz) AzimIndex=xNew<int*>(SLGEOM_NUMLOADS);
+
+
+	//Allocate: 
+	for(int l=0;l<SLGEOM_NUMLOADS;l++){
+		int nbar=slgeom->nbar[l];
+		AlphaIndex[l]=xNewZeroInit<int>(3*nbar);
+		if(horiz) AzimIndex[l]=xNewZeroInit<int>(3*nbar);
+
+
+		for (int i=0;i<3;i++){
+			if(slgeom->lids[this->vertices[i]->lid]==this->lid){
+				for(int e=0;e<nbar;e++){
+					IssmDouble alpha;
+					IssmDouble delPhi,delLambda;
+					/*recover info for this element and vertex:*/
+					IssmDouble late= slgeom->latbarycentre[l][e]; 
+					IssmDouble longe= slgeom->longbarycentre[l][e]; 
+					late=late/180*M_PI;
+					longe=longe/180*M_PI;
+
+					lati=latitude[i];
+					longi=longitude[i];
+
+					if(horiz){
+						/*Compute azimuths*/
+						dx=cos(lati)*sin(late)-sin(lati)*cos(late)*cos(longe-longi);
+						dy=sin(longe-longi)*cos(late);
+						//angle between horiz motion and North, remapped from a double on [0,2*pi] to a int [0,intmax]
+						AzimIndex[l][i*nbar+e]=reCast<int,IssmDouble>(intmax*(atan2(dy,dx)/2/M_PI));
+					}
+
+					/*Compute alpha angle between centroid and current vertex and index into precomputed tables: */
+					delPhi=fabs(lati-late); delLambda=fabs(longi-longe); if (delLambda>M_PI)delLambda=2*M_PI-delLambda;
+					alpha=2.*asin(sqrt(pow(sin(delPhi/2.0),2.0)+cos(lati)*cos(late)*pow(sin(delLambda/2.0),2.0)));
+					doubleindex=alpha/M_PI*reCast<IssmDouble,int>(M-1); //maps 0<alpha<PI on [0:M-1]
+					index=reCast<int,IssmDouble>(doubleindex); //truncates doubleindex to integer part
+
+					if ((doubleindex-index)>=0.5) index+=1; //nearest neighbour
+					if (index==M-1){ //avoids out of bound case
+						index-=1;
+						lincoef=1;
+					}
+					AlphaIndex[l][i*nbar+e]=index;
+				}
+			}
+		}
+	}
+
+	/*Save all these arrayins for each element:*/
+	for (int l=0;l<SLGEOM_NUMLOADS;l++){
+		this->inputs->SetIntArrayInput(slgeom->AlphaIndexEnum(l),this->lid,AlphaIndex[l],slgeom->nbar[l]*3);
+		if(horiz) this->inputs->SetIntArrayInput(slgeom->AzimuthIndexEnum(l),this->lid,AzimIndex[l],slgeom->nbar[l]*3);
+	}
+	/*}}}*/
+	/*Free memory:{{{*/
+	for (int l=0;l<SLGEOM_NUMLOADS;l++){
+		xDelete<int>(AlphaIndex[l]);
+		if(horiz) xDelete<int>(AzimIndex[l]);
+	}
+	xDelete<int*>(AlphaIndex);
+	if(horiz) xDelete<int*>(AzimIndex); 
+	
 	/*}}}*/
 	return;
@@ -6936,4 +7009,89 @@
 }
 /*}}}*/
+void       Tria::SealevelchangeBarystaticLoads(GrdLoads* loads,  BarystaticContributions* barycontrib, SealevelGeometry* slgeom){ /*{{{*/
+
+	int nel;
+
+	/*Inputs:*/
+	IssmDouble I[NUMVERTICES]; 
+	IssmDouble W[NUMVERTICES];
+	IssmDouble BP[NUMVERTICES];
+	IssmDouble* areae=NULL;
+
+	/*output: */
+	IssmDouble bslcice=0;
+	IssmDouble bslchydro=0;
+	IssmDouble bslcbp=0;
+	IssmDouble BPavg=0;
+	IssmDouble Iavg=0;
+	IssmDouble Wavg=0;
+
+	/*ice properties: */
+	IssmDouble rho_ice,rho_water,rho_freshwater;
+
+	/*recover some parameters:*/
+	this->parameters->FindParam(&rho_ice,MaterialsRhoIceEnum);
+	this->parameters->FindParam(&rho_water,MaterialsRhoSeawaterEnum);
+	this->parameters->FindParam(&rho_freshwater,MaterialsRhoFreshwaterEnum);
+	this->parameters->FindParam(&areae,&nel,AreaeEnum);
+
+	/*Retrieve inputs:*/
+	Element::GetInputListOnVertices(&I[0],DeltaIceThicknessEnum);
+	Element::GetInputListOnVertices(&W[0],DeltaTwsEnum);
+	Element::GetInputListOnVertices(&BP[0],DeltaBottomPressureEnum);
+
+	for(int i=0;i<NUMVERTICES;i++){
+		Iavg+=I[i]*slgeom->LoadWeigths[SLGEOM_ICE][i][this->lid]*slgeom->LoadArea[SLGEOM_ICE][this->lid];
+		Wavg+=W[i]*slgeom->LoadWeigths[SLGEOM_WATER][i][this->lid]*slgeom->LoadArea[SLGEOM_WATER][this->lid];
+		BPavg+=BP[i]*slgeom->LoadWeigths[SLGEOM_OCEAN][i][this->lid]*slgeom->LoadArea[SLGEOM_OCEAN][this->lid];
+	}
+
+	/*convert from m^3 to kg:*/
+	Iavg*=rho_ice;
+	Wavg*=rho_freshwater;
+	BPavg*=rho_water;
+
+	#ifdef _ISSM_DEBUG_ 
+	this->AddInput(SealevelBarystaticIceLoadEnum,&Iavg,P0Enum);
+	this->AddInput(SealevelBarystaticHydroLoadEnum,&Wavg,P0Enum);
+	this->AddInput(SealevelBarystaticBpLoadEnum,&BPavg,P0Enum);
+	#endif
+
+	/*Compute barystatic component in kg:*/
+	// Note: Iavg, etc, already include partial area factor phi for subelement loading
+	bslcice =   -Iavg;
+	bslchydro = -Wavg;
+	bslcbp =    -BPavg;
+
+	_assert_(!xIsNan<IssmDouble>(bslcice));
+	_assert_(!xIsNan<IssmDouble>(bslchydro));
+	_assert_(!xIsNan<IssmDouble>(bslcbp));
+
+	/*Plug values into subelement load vector:*/
+	if(slgeom->issubelement[SLGEOM_ICE][this->lid]){
+		int intj=slgeom->subelementmapping[SLGEOM_ICE][this->lid];
+		loads->vsubloads[SLGEOM_ICE]->SetValue(intj,Iavg,INS_VAL);
+		Iavg=0; //avoid double counting centroid loads and subelement loads!
+	}
+	if(slgeom->issubelement[SLGEOM_WATER][this->lid]){
+		int intj=slgeom->subelementmapping[SLGEOM_WATER][this->lid];
+		loads->vsubloads[SLGEOM_WATER]->SetValue(intj,Wavg,INS_VAL);
+		Wavg=0;
+	}
+	if(slgeom->issubelement[SLGEOM_OCEAN][this->lid]){
+		int intj=slgeom->subelementmapping[SLGEOM_OCEAN][this->lid];
+		loads->vsubloads[SLGEOM_OCEAN]->SetValue(intj,BPavg,INS_VAL); 
+		BPavg=0;
+	}
+	/*Plug remaining values into centroid load vector:*/
+	loads->vloads->SetValue(this->sid,Iavg+Wavg+BPavg,INS_VAL);
+
+	/*Keep track of barystatic contributions:*/
+	barycontrib->Set(this->Sid(),bslcice,bslchydro,bslcbp);
+
+	/*Free ressources*/
+	xDelete<IssmDouble>(areae);
+
+}/*}}}*/
 void       Tria::SealevelchangeGeometrySubElementLoads(SealevelGeometry* slgeom, IssmDouble* areae){ /*{{{*/
 
@@ -7036,242 +7194,4 @@
 }
 /*}}}*/
-void       Tria::SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){ /*{{{*/
-
-	/*Declarations:{{{*/
-	int nel;
-	IssmDouble planetarea,planetradius;
-	IssmDouble constant,ratioe;
-	IssmDouble rho_earth;
-	IssmDouble lati,longi;
-	IssmDouble latitude[NUMVERTICES];
-	IssmDouble longitude[NUMVERTICES];
-	IssmDouble x,y,z,dx,dy,dz,N_azim,E_azim;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	#ifdef _HAVE_RESTRICT_
-	IssmDouble* __restrict__ G_viscoelastic_precomputed=NULL;
-	IssmDouble* __restrict__ G_gravi_precomputed=NULL;
-	IssmDouble* __restrict__ U_viscoelastic_precomputed=NULL;
-	IssmDouble* __restrict__ H_viscoelastic_precomputed=NULL;
-	IssmDouble** __restrict__ Gsubel=NULL;
-	IssmDouble** __restrict__ GUsubel=NULL;
-	IssmDouble** __restrict__ GNsubel=NULL;
-	IssmDouble** __restrict__ GEsubel=NULL;
-
-	#else
-	IssmDouble* G_viscoelastic_precomputed=NULL;
-	IssmDouble* G_gravi_precomputed=NULL;
-	IssmDouble* U_viscoelastic_precomputed=NULL;
-	IssmDouble* H_viscoelastic_precomputed=NULL;
-	IssmDouble** Gsubel=NULL;
-	IssmDouble** GUsubel=NULL;
-	IssmDouble** GNsubel=NULL;
-	IssmDouble** GEsubel=NULL;
-	#endif
-
-	/*viscoelastic green function:*/
-	int index;
-	int M;
-	IssmDouble doubleindex,lincoef;
-
-	/*Computational flags:*/
-	bool computeselfattraction = false;
-	bool computeelastic = false;
-	bool computeviscous = false;
-	int  horiz;
-	int grd, grdmodel;
-
-	bool istime=true;
-	IssmDouble timeacc=0;
-	IssmDouble start_time,final_time;
-	int  nt,precomputednt;
-
-	/*}}}*/
-	/*Recover parameters:{{{ */
-	rho_earth=FindParam(MaterialsEarthDensityEnum);
-	this->parameters->FindParam(&computeselfattraction,SolidearthSettingsSelfAttractionEnum);
-	this->parameters->FindParam(&computeelastic,SolidearthSettingsElasticEnum);
-	this->parameters->FindParam(&computeviscous,SolidearthSettingsViscousEnum);
-	this->parameters->FindParam(&nel,MeshNumberofelementsEnum);
-	this->parameters->FindParam(&planetarea,SolidearthPlanetAreaEnum);
-	this->parameters->FindParam(&planetradius,SolidearthPlanetRadiusEnum);
-	this->parameters->FindParam(&horiz,SolidearthSettingsHorizEnum);
-	this->parameters->FindParam(&grd,SolidearthSettingsGRDEnum); 
-	this->parameters->FindParam(&grdmodel,GrdModelEnum);
-	/*}}}*/
-
-	/*early return:*/
-	if (!grd || grdmodel!=ElasticEnum) return; //Love numbers won't be found in this case, return before loading them
-	if(!computeselfattraction)return;
-
-	/*Recover precomputed green function kernels:{{{*/
-	DoubleVecParam* parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeGSelfAttractionEnum)); _assert_(parameter);
-	parameter->GetParameterValueByPointer((IssmDouble**)&G_gravi_precomputed,&M);
-
-	if(computeelastic){
-		parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeGViscoElasticEnum)); _assert_(parameter);
-		parameter->GetParameterValueByPointer((IssmDouble**)&G_viscoelastic_precomputed,NULL);
-
-		parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeUViscoElasticEnum)); _assert_(parameter);
-		parameter->GetParameterValueByPointer((IssmDouble**)&U_viscoelastic_precomputed,NULL);
-
-		if(horiz){
-			parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeHViscoElasticEnum)); _assert_(parameter);
-			parameter->GetParameterValueByPointer((IssmDouble**)&H_viscoelastic_precomputed,NULL);
-
-		}
-	}
-	/*}}}*/
-	/*Compute lat long of all vertices in the element:{{{*/
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(int i=0;i<NUMVERTICES;i++){
-		latitude[i]= asin(xyz_list[i][2]/planetradius);
-		longitude[i]= atan2(xyz_list[i][1],xyz_list[i][0]);
-	}
-	/*}}}*/
-	/*Compute green functions:{{{ */
-	constant=3/rho_earth/planetarea;
-
-	if(computeviscous){
-		this->parameters->FindParam(&istime,LoveIsTimeEnum);
-		if(!istime)_error_("Frequency love numbers not supported yet!");
-		this->parameters->FindParam(&timeacc,SolidearthSettingsTimeAccEnum);
-		this->parameters->FindParam(&start_time,TimesteppingStartTimeEnum);
-		this->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
-		nt=reCast<int,IssmDouble>((final_time-start_time)/timeacc)+1;
-	}
-	else{
-		nt=1; //in elastic, or if we run only selfattraction, we need only one step
-	}
-	Gsubel=xNew<IssmDouble*>(SLGEOM_NUMLOADS);
-	if(computeelastic){
-		GUsubel=xNew<IssmDouble*>(SLGEOM_NUMLOADS);
-		if(horiz){
-			GNsubel=xNew<IssmDouble*>(SLGEOM_NUMLOADS);
-			GEsubel=xNew<IssmDouble*>(SLGEOM_NUMLOADS);
-		}
-	}
-
-	//Allocate: 
-	for(int l=0;l<SLGEOM_NUMLOADS;l++){
-		int nbar=slgeom->nbar[l];
-		Gsubel[l]=xNewZeroInit<IssmDouble>(3*nbar*nt);
-		if(computeelastic){
-			GUsubel[l]=xNewZeroInit<IssmDouble>(3*nbar*nt);
-			if(horiz){
-				GNsubel[l]=xNewZeroInit<IssmDouble>(3*nbar*nt);
-				GEsubel[l]=xNewZeroInit<IssmDouble>(3*nbar*nt);
-			}
-		}
-
-		for(int e=0;e<nbar;e++){
-			ratioe=constant*slgeom->area_subel[l][e];
-			for (int i=0;i<3;i++){
-				IssmDouble alpha;
-				IssmDouble delPhi,delLambda;
-				/*recover info for this element and vertex:*/
-				IssmDouble late= slgeom->latbarycentre[l][e]; 
-				IssmDouble longe= slgeom->longbarycentre[l][e]; 
-				late=late/180*M_PI;
-				longe=longe/180*M_PI;
-
-				lati=latitude[i];
-				longi=longitude[i];
-
-				if(horiz){
-					/*Compute azimuths, both north and east components: */
-					x = xyz_list[i][0]; y = xyz_list[i][1]; z = xyz_list[i][2];
-					if(lati==90){
-						x=1e-12; y=1e-12;
-					}
-					if(lati==-90){
-						x=1e-12; y=1e-12;
-					}
-					IssmDouble xbar=planetradius*cos(late)*cos(longe);
-					IssmDouble ybar=planetradius*cos(late)*sin(longe);
-					IssmDouble zbar=planetradius*sin(late);
-
-					dx = xbar-x; dy = ybar-y; dz = zbar-z;
-					N_azim = (-z*x*dx-z*y*dy+(pow(x,2)+pow(y,2))*dz) /pow((pow(x,2)+pow(y,2))*(pow(x,2)+pow(y,2)+pow(z,2))*(pow(dx,2)+pow(dy,2)+pow(dz,2)),0.5);
-					E_azim = (-y*dx+x*dy) /pow((pow(x,2)+pow(y,2))*(pow(dx,2)+pow(dy,2)+pow(dz,2)),0.5);
-				}
-
-				/*Compute alpha angle between centroid and current vertex and index into precomputed tables: */
-				delPhi=fabs(lati-late); delLambda=fabs(longi-longe); if (delLambda>M_PI)delLambda=2*M_PI-delLambda;
-				alpha=2.*asin(sqrt(pow(sin(delPhi/2.0),2.0)+cos(lati)*cos(late)*pow(sin(delLambda/2.0),2.0)));
-				doubleindex=alpha/M_PI*reCast<IssmDouble,int>(M-1); //maps 0<alpha<PI on [0:M-1]
-				index=reCast<int,IssmDouble>(doubleindex); //truncates doubleindex to integer part
-
-				lincoef=doubleindex-index; //where between index and index+1 is alpha
-				if (index==M-1){ //avoids out of bound case
-					index-=1;
-					lincoef=1;
-				}
-
-				for(int t=0;t<nt;t++){
-					int timeindex=i*nbar*nt+e*nt+t; 
-
-					/*Rigid earth gravitational perturbation: */
-					Gsubel[l][timeindex]+=G_gravi_precomputed[index+0]*(1.-lincoef) 
-					    		     +G_gravi_precomputed[index+1]*lincoef; //linear interpolation
-
-					if(computeelastic){
-						Gsubel[l][timeindex]+=G_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-								     +G_viscoelastic_precomputed[(index+1)*nt+t]*lincoef; //linear interpolation
-					}
-					Gsubel[l][timeindex]*=ratioe;
-
-					/*Elastic components:*/
-					if(computeelastic){
-						GUsubel[l][timeindex] =  ratioe *(U_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-										 +U_viscoelastic_precomputed[(index+1)*nt+t]*lincoef);
-						if(horiz){
-							GNsubel[l][timeindex] = N_azim*ratioe *(H_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-								 			      +H_viscoelastic_precomputed[(index+1)*nt+t]*lincoef);
-							GEsubel[l][timeindex] = E_azim*ratioe *(H_viscoelastic_precomputed[(index+0)*nt+t]*(1.-lincoef)
-								 			      +H_viscoelastic_precomputed[(index+1)*nt+t]*lincoef);
-						}
-					}
-				}
-			}
-		}
-	}
-
-	/*Save all these arrayins for each element:*/
-	for (int l=0;l<SLGEOM_NUMLOADS;l++){
-		this->inputs->SetArrayInput(slgeom->GEnum(l),this->lid,Gsubel[l],slgeom->nbar[l]*3*nt);
-		if(computeelastic){
-			this->inputs->SetArrayInput(slgeom->GUEnum(l),this->lid,GUsubel[l],slgeom->nbar[l]*3*nt);
-			if(horiz){
-				this->inputs->SetArrayInput(slgeom->GNEnum(l),this->lid,GNsubel[l],slgeom->nbar[l]*3*nt);
-				this->inputs->SetArrayInput(slgeom->GEEnum(l),this->lid,GEsubel[l],slgeom->nbar[l]*3*nt);
-			}
-		}
-	}
-	/*}}}*/
-	/*Free memory:{{{*/
-	for (int l=0;l<SLGEOM_NUMLOADS;l++){
-		xDelete<IssmDouble>(Gsubel[l]);
-		if(computeelastic){
-			xDelete<IssmDouble>(GUsubel[l]);
-			if(horiz){
-				xDelete<IssmDouble>(GNsubel[l]);
-				xDelete<IssmDouble>(GEsubel[l]);
-			}
-		}
-	}
-	xDelete<IssmDouble*>(Gsubel);
-	if(computeelastic){
-		xDelete<IssmDouble*>(GUsubel);
-		if(horiz){
-			xDelete<IssmDouble*>(GNsubel); 
-			xDelete<IssmDouble*>(GEsubel);
-		}
-	}
-	/*}}}*/
-	return;
-
-}
-/*}}}*/
 void       Tria::SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset){ /*{{{*/
 
@@ -7282,5 +7202,5 @@
 	IssmDouble* viscousE=NULL;
 	int         viscousnumsteps;
-	int         dummy;
+	int         size;
 	bool        viscous=false;
 	int	    horiz=0;
@@ -7292,9 +7212,9 @@
 		this->parameters->FindParam(&viscousnumsteps,SealevelchangeViscousNumStepsEnum);
 
-		this->inputs->GetArrayPtr(SealevelchangeViscousRSLEnum,this->lid,&viscousRSL,&dummy);
-		this->inputs->GetArrayPtr(SealevelchangeViscousUEnum,this->lid,&viscousU,&dummy);
+		this->inputs->GetArrayPtr(SealevelchangeViscousRSLEnum,this->lid,&viscousRSL,&size);
+		this->inputs->GetArrayPtr(SealevelchangeViscousUEnum,this->lid,&viscousU,&size);
 		if(horiz){
-			this->inputs->GetArrayPtr(SealevelchangeViscousNEnum,this->lid,&viscousN,&dummy);
-			this->inputs->GetArrayPtr(SealevelchangeViscousEEnum,this->lid,&viscousE,&dummy);
+			this->inputs->GetArrayPtr(SealevelchangeViscousNEnum,this->lid,&viscousN,&size);
+			this->inputs->GetArrayPtr(SealevelchangeViscousEEnum,this->lid,&viscousE,&size);
 		}
 
@@ -7307,90 +7227,40 @@
 			}
 		}
-
-	}
-
-}
-/*}}}*/
-void       Tria::SealevelchangeBarystaticLoads(GrdLoads* loads,  BarystaticContributions* barycontrib, SealevelGeometry* slgeom){ /*{{{*/
-
-	int nel;
-
-	/*Inputs:*/
-	IssmDouble I[NUMVERTICES]; 
-	IssmDouble W[NUMVERTICES];
-	IssmDouble BP[NUMVERTICES];
-	IssmDouble* areae=NULL;
-
-	/*output: */
-	IssmDouble bslcice=0;
-	IssmDouble bslchydro=0;
-	IssmDouble bslcbp=0;
-	IssmDouble BPavg=0;
-	IssmDouble Iavg=0;
-	IssmDouble Wavg=0;
-
-	/*ice properties: */
-	IssmDouble rho_ice,rho_water,rho_freshwater;
-
-	/*recover some parameters:*/
-	this->parameters->FindParam(&rho_ice,MaterialsRhoIceEnum);
+	}
+}
+/*}}}*/
+void       Tria::SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom){ /*{{{*/
+
+	IssmDouble oceanaverage=0;
+	IssmDouble oceanarea=0;
+	IssmDouble rho_water;
+
 	this->parameters->FindParam(&rho_water,MaterialsRhoSeawaterEnum);
-	this->parameters->FindParam(&rho_freshwater,MaterialsRhoFreshwaterEnum);
-	this->parameters->FindParam(&areae,&nel,AreaeEnum);
-
-	/*Retrieve inputs:*/
-	Element::GetInputListOnVertices(&I[0],DeltaIceThicknessEnum);
-	Element::GetInputListOnVertices(&W[0],DeltaTwsEnum);
-	Element::GetInputListOnVertices(&BP[0],DeltaBottomPressureEnum);
-
+
+	/*retrieve ocean average and area:*/
 	for(int i=0;i<NUMVERTICES;i++){
-		Iavg+=I[i]*slgeom->LoadWeigths[SLGEOM_ICE][i][this->lid];
-		Wavg+=W[i]*slgeom->LoadWeigths[SLGEOM_WATER][i][this->lid];
-		BPavg+=BP[i]*slgeom->LoadWeigths[SLGEOM_OCEAN][i][this->lid];
-	}
-
-	/*convert from m to kg/m^2:*/
-	Iavg*=rho_ice;
-	Wavg*=rho_freshwater;
-	BPavg*=rho_water;
-
+		oceanaverage+=sealevelpercpu[this->vertices[i]->lid]*slgeom->LoadWeigths[SLGEOM_OCEAN][i][this->lid];
+	}
 	#ifdef _ISSM_DEBUG_ 
-	this->AddInput(SealevelBarystaticIceLoadEnum,&Iavg,P0Enum);
-	this->AddInput(SealevelBarystaticHydroLoadEnum,&Wavg,P0Enum);
-	this->AddInput(SealevelBarystaticBpLoadEnum,&BPavg,P0Enum);
+	this->AddInput(SealevelBarystaticOceanLoadEnum,&oceanaverage,P0Enum);
 	#endif
-
-	/*Compute barystatic component in kg:*/
-	// Note: Iavg, etc, already include partial area factor phi for subelement loading
-	bslcice =   -slgeom->LoadArea[SLGEOM_ICE][this->lid]*Iavg;
-	bslchydro = -slgeom->LoadArea[SLGEOM_WATER][this->lid]*Wavg;
-	bslcbp =    -slgeom->LoadArea[SLGEOM_OCEAN][this->lid]*BPavg;
-
-	_assert_(!xIsNan<IssmDouble>(bslcice));
-	_assert_(!xIsNan<IssmDouble>(bslchydro));
-	_assert_(!xIsNan<IssmDouble>(bslcbp));
-
-	/*Plug values into subelement load vector:*/
-	if(slgeom->issubelement[SLGEOM_ICE][this->lid]){
-		int intj=slgeom->subelementmapping[SLGEOM_ICE][this->lid];
-		loads->vsubloads[SLGEOM_ICE]->SetValue(intj,Iavg,INS_VAL);
-		Iavg=0; //avoid double counting centroid loads and subelement loads!
-	}
-	if(slgeom->issubelement[SLGEOM_WATER][this->lid]){
-		int intj=slgeom->subelementmapping[SLGEOM_WATER][this->lid];
-		loads->vsubloads[SLGEOM_WATER]->SetValue(intj,Wavg,INS_VAL);
-		Wavg=0;
-	}
+	oceanarea=slgeom->LoadArea[SLGEOM_OCEAN][this->lid];
+
+	/*add ocean average in the global sealevelloads vector:*/
 	if(slgeom->issubelement[SLGEOM_OCEAN][this->lid]){
 		int intj=slgeom->subelementmapping[SLGEOM_OCEAN][this->lid];
-		loads->vsubloads[SLGEOM_OCEAN]->SetValue(intj,BPavg,INS_VAL); 
-		BPavg=0;
-	}
-	/*Plug remaining values into centroid load vector:*/
-	loads->vloads->SetValue(this->sid,Iavg+Wavg+BPavg,INS_VAL);
-
-	/*Keep track of barystatic contributions:*/
-	barycontrib->Set(this->Sid(),bslcice,bslchydro,bslcbp);
-
+		loads->vsubsealevelloads->SetValue(intj,oceanaverage*rho_water*oceanarea,INS_VAL);
+		loads->vsealevelloads->SetValue(this->sid,0.,INS_VAL);
+	}
+	else loads->vsealevelloads->SetValue(this->sid,oceanaverage*rho_water*oceanarea,INS_VAL);
+
+	/*add ocean area into a global oceanareas vector:*/
+	if(!loads->sealevelloads){
+		oceanareas->SetValue(this->sid,oceanarea,INS_VAL);
+		if(slgeom->issubelement[SLGEOM_OCEAN][this->lid]){
+			int intj=slgeom->subelementmapping[SLGEOM_OCEAN][this->lid];
+			subelementoceanareas->SetValue(intj,oceanarea,INS_VAL);
+		}
+	}
 }
 /*}}}*/
@@ -7398,8 +7268,11 @@
 
 	/*sal green function:*/
+	int* AlphaIndex=NULL;
+	int* AlphaIndexsub[SLGEOM_NUMLOADS];
 	IssmDouble* G=NULL;
 	IssmDouble* Grot=NULL;
-	IssmDouble* Gsub[SLGEOM_NUMLOADS];
+	DoubleVecParam* parameter;
 	bool computefuture=false;
+	int spatial_component=0;
 
 	bool sal = false;
@@ -7417,47 +7290,12 @@
 
 	if(sal){
-		this->inputs->GetArrayPtr(SealevelchangeGEnum,this->lid,&G,&size);
-		this->inputs->GetArrayPtr(SealevelchangeGsubelIceEnum,this->lid,&Gsub[SLGEOM_ICE],&size);
-		this->inputs->GetArrayPtr(SealevelchangeGsubelHydroEnum,this->lid,&Gsub[SLGEOM_WATER],&size);
-		this->inputs->GetArrayPtr(SealevelchangeGsubelOceanEnum,this->lid,&Gsub[SLGEOM_OCEAN],&size);
+		parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeGViscoElasticEnum)); _assert_(parameter);
+		parameter->GetParameterValueByPointer((IssmDouble**)&G,NULL);
+
+		this->inputs->GetIntArrayPtr(SealevelchangeAlphaIndexEnum,this->lid,&AlphaIndex,&size);
+		for (int l=0;l<SLGEOM_NUMLOADS;l++) this->inputs->GetIntArrayPtr(slgeom->AlphaIndexEnum(l),this->lid,&AlphaIndexsub[l],&size);
 		if (rotation)	this->inputs->GetArrayPtr(SealevelchangeGrotEnum,this->lid,&Grot,&size);
 
-		this->SealevelchangeGxL(sealevelpercpu, G, Gsub, Grot, loads, polarmotionvector, slgeom, nel,percpu=true,SealevelchangeViscousRSLEnum,computefuture=false);
-	}
-
-	return;
-} /*}}}*/
-void       Tria::SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom){ /*{{{*/
-
-	IssmDouble oceanaverage=0;
-	IssmDouble oceanarea=0;
-	IssmDouble rho_water;
-
-	this->parameters->FindParam(&rho_water,MaterialsRhoSeawaterEnum);
-
-	/*retrieve ocean average and area:*/
-	for(int i=0;i<NUMVERTICES;i++){
-		oceanaverage+=sealevelpercpu[this->vertices[i]->lid]*slgeom->LoadWeigths[SLGEOM_OCEAN][i][this->lid];
-	}
-	#ifdef _ISSM_DEBUG_ 
-	this->AddInput(SealevelBarystaticOceanLoadEnum,&oceanaverage,P0Enum);
-	#endif
-	oceanarea=slgeom->LoadArea[SLGEOM_OCEAN][this->lid];
-
-	/*add ocean average in the global sealevelloads vector:*/
-	if(slgeom->issubelement[SLGEOM_OCEAN][this->lid]){
-		int intj=slgeom->subelementmapping[SLGEOM_OCEAN][this->lid];
-		loads->vsubsealevelloads->SetValue(intj,oceanaverage*rho_water,INS_VAL);
-		loads->vsealevelloads->SetValue(this->sid,0.,INS_VAL);
-	}
-	else loads->vsealevelloads->SetValue(this->sid,oceanaverage*rho_water,INS_VAL);
-
-	/*add ocean area into a global oceanareas vector:*/
-	if(!loads->sealevelloads){
-		oceanareas->SetValue(this->sid,oceanarea,INS_VAL);
-		if(slgeom->issubelement[SLGEOM_OCEAN][this->lid]){
-			int intj=slgeom->subelementmapping[SLGEOM_OCEAN][this->lid];
-			subelementoceanareas->SetValue(intj,oceanarea,INS_VAL);
-		}
+		this->SealevelchangeGxL(sealevelpercpu, spatial_component=0,AlphaIndex, AlphaIndexsub, NULL, NULL, G, Grot, loads, polarmotionvector, slgeom, nel,percpu=true,SealevelchangeViscousRSLEnum,computefuture=false);
 	}
 
@@ -7473,16 +7311,18 @@
 	int nel,nbar;
 	bool sal = false;
+	int* AlphaIndex=NULL;
+	int* AzimIndex=NULL;
+	int* AlphaIndexsub[SLGEOM_NUMLOADS];
+	int* AzimIndexsub[SLGEOM_NUMLOADS];
+	int spatial_component=0;
 	IssmDouble* G=NULL;
 	IssmDouble* GU=NULL;
-	IssmDouble* GE=NULL;
-	IssmDouble* GN=NULL;
+	IssmDouble* GH=NULL;
 	IssmDouble* Grot=NULL;
 	IssmDouble* GUrot=NULL;
 	IssmDouble* GNrot=NULL;
 	IssmDouble* GErot=NULL;
-	IssmDouble* Gsub[SLGEOM_NUMLOADS];
-	IssmDouble* GUsub[SLGEOM_NUMLOADS];
-	IssmDouble* GNsub[SLGEOM_NUMLOADS];
-	IssmDouble* GEsub[SLGEOM_NUMLOADS];
+
+	DoubleVecParam* parameter;
 	bool computefuture=false;
 
@@ -7503,25 +7343,20 @@
 
 	if(sal){
-
-		this->inputs->GetArrayPtr(SealevelchangeGEnum,this->lid,&G,&size);
-		this->inputs->GetArrayPtr(SealevelchangeGsubelIceEnum,this->lid,&Gsub[SLGEOM_ICE],&size);
-		this->inputs->GetArrayPtr(SealevelchangeGsubelHydroEnum,this->lid,&Gsub[SLGEOM_WATER],&size);
-		this->inputs->GetArrayPtr(SealevelchangeGsubelOceanEnum,this->lid,&Gsub[SLGEOM_OCEAN],&size);
+		this->inputs->GetIntArrayPtr(SealevelchangeAlphaIndexEnum,this->lid,&AlphaIndex,&size);
+		for (int l=0;l<SLGEOM_NUMLOADS;l++) this->inputs->GetIntArrayPtr(slgeom->AlphaIndexEnum(l),this->lid,&AlphaIndexsub[l],&size);
+
+		parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeGViscoElasticEnum)); _assert_(parameter);
+		parameter->GetParameterValueByPointer((IssmDouble**)&G,NULL);
 
 		if(elastic){
-			this->inputs->GetArrayPtr(SealevelchangeGUEnum,this->lid,&GU,&size);
-			this->inputs->GetArrayPtr(SealevelchangeGUsubelIceEnum,this->lid,&GUsub[SLGEOM_ICE],&size);
-			this->inputs->GetArrayPtr(SealevelchangeGUsubelHydroEnum,this->lid,&GUsub[SLGEOM_WATER],&size);
-			this->inputs->GetArrayPtr(SealevelchangeGUsubelOceanEnum,this->lid,&GUsub[SLGEOM_OCEAN],&size);
+			parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeUViscoElasticEnum)); _assert_(parameter);
+			parameter->GetParameterValueByPointer((IssmDouble**)&GU,NULL);
+
 			if(horiz){
-				this->inputs->GetArrayPtr(SealevelchangeGNEnum,this->lid,&GN,&size);
-				this->inputs->GetArrayPtr(SealevelchangeGNsubelIceEnum,this->lid,&GNsub[SLGEOM_ICE],&size);
-				this->inputs->GetArrayPtr(SealevelchangeGNsubelHydroEnum,this->lid,&GNsub[SLGEOM_WATER],&size);
-				this->inputs->GetArrayPtr(SealevelchangeGNsubelOceanEnum,this->lid,&GNsub[SLGEOM_OCEAN],&size);
-
-				this->inputs->GetArrayPtr(SealevelchangeGEEnum,this->lid,&GE,&size);
-				this->inputs->GetArrayPtr(SealevelchangeGEsubelIceEnum,this->lid,&GEsub[SLGEOM_ICE],&size);
-				this->inputs->GetArrayPtr(SealevelchangeGEsubelHydroEnum,this->lid,&GEsub[SLGEOM_WATER],&size);
-				this->inputs->GetArrayPtr(SealevelchangeGEsubelOceanEnum,this->lid,&GEsub[SLGEOM_OCEAN],&size);
+				this->inputs->GetIntArrayPtr(SealevelchangeAzimuthIndexEnum,this->lid,&AzimIndex,&size);
+				for (int l=0;l<SLGEOM_NUMLOADS;l++) this->inputs->GetIntArrayPtr(slgeom->AzimuthIndexEnum(l),this->lid,&AzimIndexsub[l],&size);
+
+				parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeHViscoElasticEnum)); _assert_(parameter);
+				parameter->GetParameterValueByPointer((IssmDouble**)&GH,NULL);
 			}
 			if (rotation) {
@@ -7534,11 +7369,12 @@
 			}
 		}
-		this->SealevelchangeGxL(&RSLGrd[0],G, Gsub, Grot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousRSLEnum,computefuture=true);
+
+		this->SealevelchangeGxL(&RSLGrd[0],spatial_component=0, AlphaIndex, AlphaIndexsub,NULL, NULL,G, Grot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousRSLEnum,computefuture=true);
 
 		if(elastic){
-			this->SealevelchangeGxL(&UGrd[0],GU, GUsub, GUrot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousUEnum,computefuture=true);
+			this->SealevelchangeGxL(&UGrd[0],spatial_component=0, AlphaIndex, AlphaIndexsub,NULL, NULL, GU, GUrot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousUEnum,computefuture=true);
 			if(horiz){
-				this->SealevelchangeGxL(&NGrd[0],GN, GNsub, GNrot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousNEnum,computefuture=true);
-				this->SealevelchangeGxL(&EGrd[0],GE, GEsub, GErot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousEEnum,computefuture=true);
+				this->SealevelchangeGxL(&NGrd[0],spatial_component=1,AlphaIndex, AlphaIndexsub,AzimIndex,AzimIndexsub,GH, GNrot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousNEnum,computefuture=true);
+				this->SealevelchangeGxL(&EGrd[0],spatial_component=2,AlphaIndex, AlphaIndexsub,AzimIndex,AzimIndexsub,GH, GErot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousEEnum,computefuture=true);
 			}
 		}
@@ -7565,16 +7401,29 @@
 
 } /*}}}*/
-void       Tria::SealevelchangeGxL(IssmDouble* grdfieldout, IssmDouble* G, IssmDouble** Gsub, IssmDouble* Grot, GrdLoads* loads, IssmDouble* polarmotionvector, SealevelGeometry* slgeom, int nel, bool percpu, int viscousenum, bool computefuture) { /*{{{*/
+void       Tria::SealevelchangeGxL(IssmDouble* grdfieldout, int spatial_component, int* AlphaIndex, int** AlphaIndexsub, int* AzimIndex, int**AzimIndexsub, IssmDouble* G, IssmDouble* Grot, GrdLoads* loads, IssmDouble* polarmotionvector, SealevelGeometry* slgeom, int nel, bool percpu, int viscousenum, bool computefuture) { /*{{{*/
 
 	//This function performs the actual convolution between Green functions and surface Loads for a particular grd field
 
 	IssmDouble* grdfield=NULL;
-	int i,e,l,t,nbar;
+	int i,e,l,t,a, index, nbar;
+	bool rotation=false;
+	IssmDouble* Centroid_loads=NULL;
+	IssmDouble* Centroid_loads_copy=NULL;
+	IssmDouble* Subelement_loads[SLGEOM_NUMLOADS];
+	IssmDouble* Subelement_loads_copy[SLGEOM_NUMLOADS];
+	IssmDouble* horiz_projection=NULL;
+	IssmDouble* horiz_projectionsub[SLGEOM_NUMLOADS];
+	int nt=1; //important, ensures there is a defined value if computeviscous is false
+
+	//viscous
 	bool computeviscous=false;
-	bool rotation=false;
-	IssmDouble* viscousfield=NULL;
-	int nt=1; //important, ensures there is a defined value if computeviscous is false
 	int viscousindex=0; //important
 	int viscousnumsteps=1; //important
+	IssmDouble* viscousfield=NULL;
+	IssmDouble* grdfieldinterp=NULL;
+	IssmDouble* viscoustimes=NULL;
+	IssmDouble  final_time;
+	IssmDouble  lincoeff;
+	IssmDouble  timeacc;
 
 	this->parameters->FindParam(&computeviscous,SolidearthSettingsViscousEnum);
@@ -7583,7 +7432,12 @@
 		this->parameters->FindParam(&viscousnumsteps,SealevelchangeViscousNumStepsEnum);
 		this->parameters->FindParam(&viscousindex,SealevelchangeViscousIndexEnum);
+		this->parameters->FindParam(&viscoustimes,NULL,SealevelchangeViscousTimesEnum);
+		this->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+		this->parameters->FindParam(&timeacc,SolidearthSettingsTimeAccEnum);
+		this->inputs->GetArrayPtr(viscousenum,this->lid,&viscousfield,NULL);
 		if(computefuture) {
 			nt=viscousnumsteps-viscousindex+2; //number of time steps remaining to reach final_time, +1 is sufficient with no adaptative time stepping, +2 necessary otherwise; we assume the safe choice here for the sake of simplicity
 			if (nt>viscousnumsteps) nt=viscousnumsteps;
+			grdfieldinterp=xNewZeroInit<IssmDouble>(3*viscousnumsteps); 
 		}
 		else nt=1;
@@ -7605,53 +7459,101 @@
 	}
 
-
-	if(loads->sealevelloads){ // general case: loads + sealevel loads
-		for(i=0;i<NUMVERTICES;i++) {
-			if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
-			for (e=0;e<nel;e++){
-				for(t=0;t<nt;t++){
-					int index=i*nel*viscousnumsteps+e*viscousnumsteps+t;
-					grdfield[i*nt+t]+=G[index]*(loads->sealevelloads[e]+loads->loads[e]);
+	//Determine loads /*{{{*/
+	Centroid_loads=xNewZeroInit<IssmDouble>(nel);
+	for (e=0;e<nel;e++){
+		Centroid_loads[e]=loads->loads[e];
+	}
+	for(l=0;l<SLGEOM_NUMLOADS;l++){
+		nbar=slgeom->nbar[l];
+		Subelement_loads[l]=xNewZeroInit<IssmDouble>(nbar);
+		for (e=0;e<nbar;e++){
+			Subelement_loads[l][e]=(loads->subloads[l][e]);
+		}
+	}
+	if(loads->sealevelloads){
+		for (e=0;e<nel;e++){
+			Centroid_loads[e]+=(loads->sealevelloads[e]);
+		}
+		nbar=slgeom->nbar[SLGEOM_OCEAN];
+		for (e=0;e<nbar;e++){
+			Subelement_loads[SLGEOM_OCEAN][e]+=(loads->subsealevelloads[e]);
+		}
+	}
+
+	//Copy loads if dealing with a horizontal component: the result will need to be projected against the North or East axis for each vertex
+	if (spatial_component!=0){
+		horiz_projection=xNewZeroInit<IssmDouble>(3*nel);
+		Centroid_loads_copy=xNewZeroInit<IssmDouble>(nel);
+		for (e=0;e<nel;e++){
+			Centroid_loads_copy[e]=Centroid_loads[e];
+		}
+
+		for(l=0;l<SLGEOM_NUMLOADS;l++){
+			nbar=slgeom->nbar[l];
+			Subelement_loads_copy[l]=xNewZeroInit<IssmDouble>(nbar);
+			horiz_projectionsub[l]=xNewZeroInit<IssmDouble>(3*nbar);
+			for (e=0;e<nbar;e++){
+				Subelement_loads_copy[l][e]=Subelement_loads[l][e];
+			}
+		}
+	}
+	/*}}}*/
+
+	//Convolution
+	for(i=0;i<NUMVERTICES;i++) { /*{{{*/
+		if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
+
+		if (spatial_component!=0){ //horizontals /*{{{*/
+			//GxL needs to be projected on the right axis before summation into the grd field
+			//here we apply the projection scalar to the load prior to the actual convolution loop for more efficiency
+			if (spatial_component==1){ //north
+				for (e=0;e<nel;e++){
+					horiz_projection[i*nel+e]=cos(2.0*M_PI*reCast<IssmDouble,int>(AzimIndex[i*nel+e])/65535.0); // 65535=2^16-1 = max value of 16 bits unsigned int
 				}
-			}
+				for(l=0;l<SLGEOM_NUMLOADS;l++){
+					nbar=slgeom->nbar[l];
+					for (e=0;e<nbar;e++){
+						horiz_projectionsub[l][i*nbar+e]=cos(2.0*M_PI*reCast<IssmDouble,int>(AzimIndexsub[l][i*nbar+e])/65535.0);;
+					}
+				}
+			}
+			else if (spatial_component==2){ //east
+				for (e=0;e<nel;e++){
+					horiz_projection[i*nel+e]=sin(2.0*M_PI*reCast<IssmDouble,int>(AzimIndex[i*nel+e])/65535.0);
+				}
+				for(l=0;l<SLGEOM_NUMLOADS;l++){
+					nbar=slgeom->nbar[l];
+					for (e=0;e<nbar;e++){
+						horiz_projectionsub[l][i*nbar+e]=sin(2.0*M_PI*reCast<IssmDouble,int>(AzimIndexsub[l][i*nbar+e])/65535.0);;
+					}
+				}
+			}
+			for (e=0;e<nel;e++) Centroid_loads[e]=Centroid_loads_copy[e]*horiz_projection[i*nel+e];
 			for(l=0;l<SLGEOM_NUMLOADS;l++){
 				nbar=slgeom->nbar[l];
 				for (e=0;e<nbar;e++){
-					for(t=0;t<nt;t++){
-						int index=i*nbar*viscousnumsteps+e*viscousnumsteps+t;
-						grdfield[i*nt+t]+=Gsub[l][index]*(loads->subloads[l][e]);
-					}
+					Subelement_loads[l][e]=Subelement_loads_copy[l][e]*horiz_projectionsub[l][i*nbar+e];
 				}
-				if(l==SLGEOM_OCEAN){
-					for (e=0;e<nbar;e++){
-						for(t=0;t<nt;t++){
-							int index=i*nbar*viscousnumsteps+e*viscousnumsteps+t;
-							grdfield[i*nt+t]+=Gsub[l][index]*(loads->subsealevelloads[e]);
-						}
-					}
+			}
+		} /*}}}*/
+
+		for (e=0;e<nel;e++){
+			for(t=0;t<nt;t++){
+				a=AlphaIndex[i*nel+e];
+				grdfield[i*nt+t]+=G[a*viscousnumsteps+t]*Centroid_loads[e];
+			}
+		}
+		for(l=0;l<SLGEOM_NUMLOADS;l++){
+			nbar=slgeom->nbar[l];
+			for (e=0;e<nbar;e++){
+				for(t=0;t<nt;t++){
+					a=AlphaIndexsub[l][i*nbar+e];
+					grdfield[i*nt+t]+=G[a*viscousnumsteps+t]*Subelement_loads[l][e];
 				}
 			}
 		}
-	}
-	else{  //this is the initial convolution where only loads are provided
-		for(i=0;i<NUMVERTICES;i++) {
-			if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
-			for (e=0;e<nel;e++){
-				for(t=0;t<nt;t++){
-					int index=i*nel*viscousnumsteps+e*viscousnumsteps+t;
-					grdfield[i*nt+t]+=G[index]*(loads->loads[e]);
-				}
-			}
-			for(l=0;l<SLGEOM_NUMLOADS;l++){
-				nbar=slgeom->nbar[l];
-				for (e=0;e<nbar;e++){
-					for(t=0;t<nt;t++){
-						int index=i*nbar*viscousnumsteps+e*viscousnumsteps+t;
-						grdfield[i*nt+t]+=Gsub[l][index]*(loads->subloads[l][e]);
-					}
-				}
-			}
-		}
-	}
+	} /*}}}*/
+
+
 
 	if(computeviscous){ /*{{{*/
@@ -7661,17 +7563,6 @@
 		// 3*: subtract from viscous stack the grdfield that has already been accounted for so we don't add it again at the next time step
 
-		IssmDouble* grdfieldinterp=NULL;
-		IssmDouble* viscoustimes=NULL;
-		IssmDouble  final_time;
-		IssmDouble  lincoeff;
-		IssmDouble  timeacc;
-
-		this->parameters->FindParam(&viscoustimes,NULL,SealevelchangeViscousTimesEnum);
-		this->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
-		this->parameters->FindParam(&timeacc,SolidearthSettingsTimeAccEnum);
-		this->inputs->GetArrayPtr(viscousenum,this->lid,&viscousfield,NULL);
 		/* Map new grdfield generated by present-day loads onto viscous time vector*/
 		if(computefuture){
-			grdfieldinterp=xNewZeroInit<IssmDouble>(3*viscousnumsteps); 
 			//viscousindex time and first time step of grdfield coincide, so just copy that value
 			for(int i=0;i<NUMVERTICES;i++){
@@ -7685,5 +7576,6 @@
 					for(int i=0;i<NUMVERTICES;i++){
 						if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
-						grdfieldinterp[i*viscousnumsteps+t]=  (1-lincoeff)*grdfield[i*nt+(t-viscousindex-1)]+lincoeff*grdfield[i*nt+(t-viscousindex)];
+						grdfieldinterp[i*viscousnumsteps+t] = (1-lincoeff)*grdfield[i*nt+(t-viscousindex-1)]
+											 +lincoeff*grdfield[i*nt+(t-viscousindex)];
 					}
 				}
@@ -7699,17 +7591,19 @@
 		/*update viscous stack with future deformation from present load: */
 		if(computefuture){
-			for(int t=viscousnumsteps-1;t>=viscousindex;t--){
+			for(int t=viscousnumsteps-1;t>=viscousindex;t--){ //we need to go backwards so as not to zero out viscousfield[i*viscousnumsteps+viscousindex] until the end
 				for(int i=0;i<NUMVERTICES;i++){
 					if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
 					//offset viscousfield to remove all deformation that has already been added
-					viscousfield[i*viscousnumsteps+t]+=grdfieldinterp[i*viscousnumsteps+t]-grdfieldinterp[i*viscousnumsteps+viscousindex]-viscousfield[i*viscousnumsteps+viscousindex];
+					viscousfield[i*viscousnumsteps+t]+=grdfieldinterp[i*viscousnumsteps+t]
+									  -grdfieldinterp[i*viscousnumsteps+viscousindex]
+									  -viscousfield[i*viscousnumsteps+viscousindex];
 				}
 			}
 			/*Save viscous stack now that we updated the values:*/
 			this->inputs->SetArrayInput(viscousenum,this->lid,viscousfield,3*viscousnumsteps);
-		}
-
-		/*Free allocatoins:*/
-		xDelete<IssmDouble>(viscoustimes);
+
+			/*Free resources:*/
+			xDelete<IssmDouble>(grdfieldinterp);
+		}
 	} 
 	/*}}}*/
@@ -7726,4 +7620,22 @@
 		for(i=0;i<NUMVERTICES;i++) grdfieldout[i]=grdfield[i*nt+0];
 	}
+	//free resources
+	xDelete<IssmDouble>(grdfield);
+	xDelete<IssmDouble>(Centroid_loads);
+	for(l=0;l<SLGEOM_NUMLOADS;l++) xDelete<IssmDouble>(Subelement_loads[l]);
+	if (spatial_component!=0){
+		xDelete<IssmDouble>(horiz_projection);
+		xDelete<IssmDouble>(Centroid_loads_copy);
+		for(l=0;l<SLGEOM_NUMLOADS;l++) {
+			xDelete<IssmDouble>(Subelement_loads_copy[l]);
+			xDelete<IssmDouble>(horiz_projectionsub[l]);
+		}
+	}
+	if (computeviscous){
+		xDelete<IssmDouble>(viscoustimes);
+		if (computefuture){
+			xDelete<IssmDouble>(grdfieldinterp);
+		}
+	}
 
 } /*}}}*/
@@ -7731,4 +7643,5 @@
 void       Tria::SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom){ /*{{{*/
 
+	offset*=slgeom->LoadArea[SLGEOM_OCEAN][this->lid]; //kg.m^-2 to kg 
 	if(slgeom->isoceanin[this->lid]){
 		if(slgeom->issubelement[SLGEOM_OCEAN][this->lid]){
Index: issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Tria.h	(revision 27035)
+++ issm/trunk/src/c/classes/Elements/Tria.h	(revision 27232)
@@ -171,5 +171,5 @@
 		#ifdef _HAVE_SEALEVELCHANGE_
 		void       GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,Matlitho* litho, IssmDouble* x,IssmDouble* y);
-		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae);
+		void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae, int* lids);
 		void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom);
 		void       SealevelchangeGeometrySubElementLoads(SealevelGeometry* slgeom, IssmDouble* areae);
@@ -244,5 +244,5 @@
 		void           UpdateConstraintsExtrudeFromBase(void);
 		void           UpdateConstraintsExtrudeFromTop(void);
-		void           SealevelchangeGxL(IssmDouble* sealevel, IssmDouble* G, IssmDouble** Gsub, IssmDouble* Grot, GrdLoads* loads, IssmDouble* polarmotionvector,SealevelGeometry* slgeom, int nel, bool percpu,int stackenum,bool computefuture);
+		void           SealevelchangeGxL(IssmDouble* grdfieldout, int spatial_component, int* AlphaIndex, int** AlphaIndexsub, int* AzimIndex, int**AzimIndexsub, IssmDouble* G, IssmDouble* Grot, GrdLoads* loads, IssmDouble* polarmotionvector, SealevelGeometry* slgeom, int nel, bool percpu, int viscousenum, bool computefuture);
 		/*}}}*/
 
Index: issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- issm/trunk/src/c/classes/FemModel.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/FemModel.cpp	(revision 27232)
@@ -283,5 +283,5 @@
 	pfclose(restartfid,restartfilename);
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<char>(femmodel_buffer);
 	xDelete<char>(restartfilename);
@@ -634,5 +634,5 @@
 	pfclose(restartfid,restartfilename);
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<char>(restartfilename);
 	xDelete<char>(femmodel_buffer);
@@ -1803,5 +1803,5 @@
 	mass_flux=all_mass_flux;
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	for(i=0;i<M;i++){
 		IssmDouble* matrix=array[i];
@@ -3165,5 +3165,5 @@
 	InputUpdateFromVectorx(this,vz,VzMeshEnum,VertexPIdEnum);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete vx;
 	delete vy;
@@ -4617,5 +4617,5 @@
 			}
 
-			/*Free ressources:*/
+			/*Free resources:*/
 			xDelete<double>(vertex_response);
 			xDelete<double>(qmu_response);
@@ -4668,5 +4668,5 @@
 	/*}}}*/
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	for(i=0;i<response_partitions_num;i++){
 		IssmDouble* matrix=response_partitions[i];
@@ -4712,5 +4712,5 @@
 	pY->Assemble();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(xx);
 	xDelete<IssmDouble>(yy);
@@ -4746,5 +4746,5 @@
 	pEast->Assemble();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(latitude);
 	xDelete<IssmDouble>(longitude);
Index: issm/trunk/src/c/classes/GrdLoads.cpp
===================================================================
--- issm/trunk/src/c/classes/GrdLoads.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/GrdLoads.cpp	(revision 27232)
@@ -19,4 +19,5 @@
 GrdLoads::GrdLoads(int nel,SealevelGeometry* slgeom){ /*{{{*/
 
+	/*allocate:*/
 	vloads=new Vector<IssmDouble>(nel);
 	for (int i=0;i<SLGEOM_NUMLOADS;i++) vsubloads[i]=new Vector<IssmDouble>(slgeom->nbar[i]);
@@ -26,4 +27,11 @@
 
 	vsubsealevelloads=new Vector<IssmDouble>(slgeom->nbar[SLGEOM_OCEAN]);
+
+	/*make sure all pointers that are not allocated are NULL:*/
+	loads=NULL;
+	for (int i=0;i<SLGEOM_NUMLOADS;i++)subloads[i]=NULL;
+	sealevelloads=NULL;
+	subsealevelloads=NULL;
+
 
 }; /*}}}*/
@@ -50,4 +58,11 @@
 	}
 
+	/*Avoid leaks:*/
+	if(loads)xDelete<IssmDouble>(loads);
+	for (int i=0;i<SLGEOM_NUMLOADS;i++){
+		if(subloads[i])xDelete<IssmDouble>(subloads[i]);
+	}
+
+	/*Serialize:*/
 	loads=vloads->ToMPISerial();
 	for (int i=0;i<SLGEOM_NUMLOADS;i++){
@@ -64,13 +79,19 @@
 void GrdLoads::BroadcastSealevelLoads(void){ /*{{{*/
 
+	/*Avoid leakds:*/
+	if(sealevelloads)xDelete<IssmDouble>(sealevelloads);
+	if(subsealevelloads)xDelete<IssmDouble>(subsealevelloads);
+
+	/*Serialize:*/
 	sealevelloads=vsealevelloads->ToMPISerial();
 	subsealevelloads=vsubsealevelloads->ToMPISerial();
 
 } /*}}}*/
-void GrdLoads::SHDegree2Coefficients(IssmDouble* deg2coeff, FemModel* femmodel, SealevelGeometry* slgeom){
+void GrdLoads::SHDegree2Coefficients(IssmDouble* deg2coeff, FemModel* femmodel, SealevelGeometry* slgeom){ /*{{{*/
 
-	IssmDouble area,re, S;
+	IssmDouble re, S;
 	int ylmindex, intj;
 	IssmDouble deg2coeff_local[5];
+	//IssmDouble area;
 
 	femmodel->parameters->FindParam(&re,SolidearthPlanetRadiusEnum);
@@ -86,9 +107,8 @@
 		if(sealevelloads) S+=sealevelloads[element->Sid()];
 		if(S!=0){
-			element->Element::GetInputValue(&area,AreaEnum);
 
 			for (int c=0;c<5;c++){ //degree l=2 has 2*l+1=5 coefficients: 2,0; 2,1cos; 2,1sin; 2,2cos; 2,2sin
 				ylmindex=(4+c)*slgeom->localnel+element->lid; // starting at index=l^2
-				deg2coeff_local[c] += S*area/re/re*slgeom->Ylm[ylmindex];
+				deg2coeff_local[c] += S/re/re*slgeom->Ylm[ylmindex];
 			}
 		}
@@ -101,8 +121,8 @@
 				if(i==SLGEOM_OCEAN && sealevelloads) S+=subsealevelloads[intj];
 				if(S!=0){
-					area=slgeom->area_subel[i][intj];
+					//area=slgeom->area_subel[i][intj];
 					for (int c=0;c<5;c++){ //degree l=2 has 2*l+1=5 coefficients
 						ylmindex=(4+c)*slgeom->localnel+element->lid; // starting at index=l^2
-						deg2coeff_local[c] += S*area/re/re*slgeom->Ylm_subel[i][ylmindex];
+						deg2coeff_local[c] += S/re/re*slgeom->Ylm_subel[i][ylmindex];
 					}
 				}
@@ -119,3 +139,3 @@
 	ISSM_MPI_Bcast(&deg2coeff[2],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 
-} 
+} /*}}}*/ 
Index: issm/trunk/src/c/classes/Inputs/ArrayInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/ArrayInput.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Inputs/ArrayInput.cpp	(revision 27232)
@@ -81,17 +81,38 @@
 	marshallhandle->call(object_enum);
 	marshallhandle->call(this->numberofelements_local);
+
+	/*Allocate memory if reading restart file*/
+	if(marshallhandle->OperationNumber() == MARSHALLING_LOAD){
+		_assert_(this->numberofelements_local>0);
+		_assert_(this->numberofelements_local<1e11);
+		if(this->numberofelements_local){
+			this->N                      = xNewZeroInit<int>(this->numberofelements_local);
+			this->values                 = xNewZeroInit<IssmDouble*>(this->numberofelements_local);
+		}
+		else{
+			this->N      = NULL;
+			this->values = NULL;
+		}
+	}
+
+	/*Marshall N*/
 	if(this->numberofelements_local){
 		marshallhandle->call(this->N,this->numberofelements_local);
+	}
+
+	/*Marshall individual arrays*/
+	if(this->numberofelements_local){
 		for(int i=0;i<this->numberofelements_local;i++){
-			if(this->values[i]){
+			if(this->N[i]){
+
+				/*Allocate if reading restart*/
+				if(marshallhandle->OperationNumber() == MARSHALLING_LOAD){
+					this->values[i] = xNew<IssmDouble>(this->N[i]);
+				}
+				_assert_(this->values[i]);
 				marshallhandle->call(this->values[i],this->N[i]);
 			}
 		}
 	}
-	else{
-		this->N      = NULL;
-		this->values = NULL;
-	}
-
 }
 /*}}}*/
Index: issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 27232)
@@ -24,4 +24,5 @@
 #include "./DatasetInput.h"
 #include "./ArrayInput.h"
+#include "./IntArrayInput.h"
 using namespace std;
 /*}}}*/
@@ -167,4 +168,9 @@
 				this->inputs[index]=input;
 			}
+			else if(object_enum==ArrayInputEnum){
+				ArrayInput* input=new ArrayInput();
+				input->Marshall(marshallhandle);
+				this->inputs[index]=input;
+			}
 			else{
 				_error_("input "<<EnumToStringx(object_enum)<<" not supported");
@@ -566,4 +572,21 @@
 	input->GetArrayPtr(row,pvalues,pN);
 }/*}}}*/
+void Inputs::GetIntArrayPtr(int enum_in,int row,int** pvalues,int* pN){/*{{{*/
+
+	/*Get input id*/
+	int id = EnumToIndex(enum_in);
+
+	/*Create it if necessary*/
+	if(this->inputs[id]){
+		if(this->inputs[id]->ObjectEnum()!=IntArrayInputEnum) _error_(EnumToStringx(this->inputs[id]->ObjectEnum())<<" cannot return an int array");
+	}
+	else{
+		_error_("Input "<<EnumToStringx(enum_in)<<" not found");
+	}
+
+	/*Set input*/
+	IntArrayInput* input = xDynamicCast<IntArrayInput*>(this->inputs[id]);
+	input->GetArrayPtr(row,pvalues,pN);
+}/*}}}*/
 void Inputs::GetArray(int enum_in,int row,IssmDouble** pvalues,int* pN){/*{{{*/
 
@@ -581,4 +604,21 @@
 	/*Set input*/
 	ArrayInput* input = xDynamicCast<ArrayInput*>(this->inputs[id]);
+	input->GetArray(row,pvalues,pN);
+}/*}}}*/
+void Inputs::GetIntArray(int enum_in,int row,int** pvalues,int* pN){/*{{{*/
+
+	/*Get input id*/
+	int id = EnumToIndex(enum_in);
+
+	/*Create it if necessary*/
+	if(this->inputs[id]){
+		if(this->inputs[id]->ObjectEnum()!=IntArrayInputEnum) _error_(EnumToStringx(this->inputs[id]->ObjectEnum())<<" cannot return an int array");
+	}
+	else{
+		_error_("Input "<<EnumToStringx(enum_in)<<" not found");
+	}
+
+	/*Set input*/
+	IntArrayInput* input = xDynamicCast<IntArrayInput*>(this->inputs[id]);
 	input->GetArray(row,pvalues,pN);
 }/*}}}*/
@@ -730,4 +770,30 @@
 	input->SetInput(row,numlayers,values);
 }/*}}}*/
+void Inputs::SetIntArrayInput(int enum_in,int row,int* values,int numlayers){/*{{{*/
+
+	bool recreate = false;
+
+	/*Get input id*/
+	int id = EnumToIndex(enum_in);
+
+	/*Create it if necessary*/
+	if(this->inputs[id]){
+		if(this->inputs[id]->ObjectEnum()!=IntArrayInputEnum){
+			delete this->inputs[id];
+			recreate = true;
+		}
+	}
+	else{
+		recreate = true;
+	}
+
+	if(recreate){
+		this->inputs[id] = new IntArrayInput(this->numberofelements_local);
+	}
+
+	/*Set input*/
+	IntArrayInput* input = xDynamicCast<IntArrayInput*>(this->inputs[id]);
+	input->SetInput(row,numlayers,values);
+}/*}}}*/
 TransientInput* Inputs::SetDatasetTransientInput(int enum_in,int dataset_id,IssmDouble* times,int numtimes){/*{{{*/
 
Index: issm/trunk/src/c/classes/Inputs/Inputs.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 27035)
+++ issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 27232)
@@ -11,4 +11,5 @@
 class DatasetInput;
 class ArrayInput;
+class IntArrayInput;
 class ControlInput;
 class Parameters;
@@ -56,5 +57,7 @@
 		void     GetInputsInterpolations(int* pnuminputs,int** pinterpolations,int** penum);
 		void             GetArray(int enum_in,int row,IssmDouble** pvalues,int* pN);
+		void             GetIntArray(int enum_in,int row,int** pvalues,int* pN);
 		void             GetArrayPtr(int enum_in,int row,IssmDouble** pvalues,int* pN);
+		void             GetIntArrayPtr(int enum_in,int row,int** pvalues,int* pN);
 		SegInput*       GetSegInput(int enum_type);
 		TriaInput*      GetTriaInput(int enum_type);
@@ -82,4 +85,5 @@
 		TransientInput* SetDatasetTransientInput(int enum_in,int id,IssmDouble* times,int numtimes);
 		void  SetArrayInput(int enum_in,int row,IssmDouble* layers,int numlayers);
+		void  SetIntArrayInput(int enum_in,int row,int* layers,int numlayers);
 		void  SetTriaControlInputGradient(int enum_in,int interpolation,int numindices,int* indices,IssmDouble* values);
 		void  SetTriaControlInputGradient(int enum_in,int interpolation,int numindices,int* indices,IssmDouble* values,int n);
Index: issm/trunk/src/c/classes/Inputs/IntArrayInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/IntArrayInput.cpp	(revision 27232)
+++ issm/trunk/src/c/classes/Inputs/IntArrayInput.cpp	(revision 27232)
@@ -0,0 +1,145 @@
+/*!\file IntArrayInput.c
+ * \brief: implementation of the IntArrayInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+#include "./IntArrayInput.h"
+
+/*IntArrayInput constructors and destructor*/
+IntArrayInput::IntArrayInput(void){/*{{{*/
+
+	this->numberofelements_local = -1;
+	this->N                      = NULL;
+	this->values                 = NULL;
+
+}/*}}}*/
+IntArrayInput::IntArrayInput(int nbe_in){/*{{{*/
+
+	_assert_(nbe_in>0);
+	_assert_(nbe_in<1e11);
+	this->numberofelements_local = nbe_in;
+	this->N                      = xNewZeroInit<int>(this->numberofelements_local);
+	this->values                 = xNewZeroInit<int*>(this->numberofelements_local);
+
+}/*}}}*/
+IntArrayInput::~IntArrayInput(){/*{{{*/
+	if(this->values){
+		for(int i=0;i<this->numberofelements_local;i++) if(this->values[i]) xDelete<int>(this->values[i]);
+		xDelete<int>(this->values);
+	}
+	if(this->N) xDelete<int>(this->N);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+Input* IntArrayInput::copy() {/*{{{*/
+
+	IntArrayInput* output = new IntArrayInput(this->numberofelements_local);
+
+	output->N = xNew<int>(this->numberofelements_local);
+	xMemCpy<int>(output->N,this->N,this->numberofelements_local);
+
+	output->values = xNew<int*>(this->numberofelements_local);
+	for(int i=0;i<this->numberofelements_local;i++){
+		if(this->values[i]){
+			_assert_(this->N[i]>0);
+			output->values[i] = xNew<int>(this->N[i]);
+			xMemCpy<int>(output->values[i],this->values[i],this->N[i]);
+		}
+		else{
+			output->values[i] = NULL;
+		}
+	}
+
+	return output;
+}
+/*}}}*/
+void IntArrayInput::DeepEcho(void){/*{{{*/
+	_printf_("IntArrayInput Echo:\n");
+	///_printf_("   Size:          "<<N<<"\n");
+	//printarray(this->values,this->M,this->N);
+	//_printf_(setw(15)<<"   IntArrayInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<(value?"true":"false") << "\n");
+}
+/*}}}*/
+void IntArrayInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+int  IntArrayInput::Id(void){/*{{{*/
+	return -1;
+}/*}}}*/
+void IntArrayInput::Marshall(MarshallHandle* marshallhandle){ /*{{{*/
+
+	int object_enum = IntArrayInputEnum;
+	marshallhandle->call(object_enum);
+	marshallhandle->call(this->numberofelements_local);
+	if(this->numberofelements_local){
+		marshallhandle->call(this->N,this->numberofelements_local);
+		for(int i=0;i<this->numberofelements_local;i++){
+			if(this->values[i]){
+				marshallhandle->call(this->values[i],this->N[i]);
+			}
+		}
+	}
+	else{
+		this->N      = NULL;
+		this->values = NULL;
+	}
+
+}
+/*}}}*/
+int  IntArrayInput::ObjectEnum(void){/*{{{*/
+	return IntArrayInputEnum;
+}
+/*}}}*/
+
+/*IntArrayInput management*/
+void IntArrayInput::SetInput(int row,int numindices,int* values_in){/*{{{*/
+
+	_assert_(this);
+	_assert_(row>=0 && row<this->numberofelements_local);
+
+	if(this->N[row] != numindices){
+		if(this->values[row]) xDelete<int>(this->values[row]);
+		this->values[row] = xNew<int>(numindices);
+	}
+
+	int *el_values = this->values[row];
+	for(int i=0;i<numindices;i++) el_values[i] = values_in[i];
+
+	this->N[row] = numindices;
+}
+/*}}}*/
+void IntArrayInput::GetArray(int row,int** pvalues,int* pN){/*{{{*/
+
+	_assert_(this);
+	_assert_(row>=0 && row<this->numberofelements_local);
+	if(pvalues){
+		int* outvalues = xNew<int>(this->N[row]);
+		xMemCpy<int>(outvalues,this->values[row],this->N[row]);
+		*pvalues = outvalues;
+	}
+	if(pN){
+		*pN = this->N[row];
+	}
+}
+/*}}}*/
+void IntArrayInput::GetArrayPtr(int row,int** pvalues,int* pN){/*{{{*/
+
+	_assert_(this);
+	_assert_(row>=0 && row<this->numberofelements_local);
+	if(pvalues){
+		*pvalues = this->values[row];
+	}
+	if(pN){
+		*pN = this->N[row];
+	}
+}
+/*}}}*/
Index: issm/trunk/src/c/classes/Inputs/IntArrayInput.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/IntArrayInput.h	(revision 27232)
+++ issm/trunk/src/c/classes/Inputs/IntArrayInput.h	(revision 27232)
@@ -0,0 +1,34 @@
+#ifndef _INTARRAYINPUT_H_
+#define _INTARRAYINPUT_H_
+
+/*Headers:*/
+#include "./Input.h"
+
+class IntArrayInput: public Input{
+
+	private:
+		int         numberofelements_local;
+		int*        N;
+		int** values;
+
+	public:
+		/*IntArrayInput constructors, destructors: {{{*/
+		IntArrayInput();
+		IntArrayInput(int nbe_in);
+		~IntArrayInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		Input *copy();
+		void    DeepEcho();
+		void    Echo();
+		int     Id();
+		void    Marshall(MarshallHandle* marshallhandle);
+		int     ObjectEnum();
+		/*}}}*/
+		/*IntArrayInput management:*/
+		void SetInput(int row,int numinds,int* values_in);
+		void GetArray(int row,int** pvalues,int* pN);
+		void GetArrayPtr(int row,int** pvalues,int* pN);
+
+};
+#endif  /* _INTARRAYINPUT_H */
Index: issm/trunk/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 27232)
@@ -9,4 +9,5 @@
 #endif
 
+#include <numeric>
 #include "./TransientInput.h"
 #include "./TriaInput.h"
@@ -208,5 +209,5 @@
 
 	/*This is a new time step! we need to add it to the list*/
-	if(this->numtimesteps>0 && time<this->timesteps[this->numtimesteps-1]) _error_("timestep values must increase sequentially");
+	if(this->numtimesteps>0 && time<this->timesteps[this->numtimesteps-1]) _error_("timestep values must increase sequentially, here " << this->timesteps[this->numtimesteps-1] <<" is the last step but smaller than the preceding "<< time<<"\n");
 
 	IssmDouble *old_timesteps = NULL;
@@ -433,7 +434,8 @@
 
 	/*First, recover current time from parameters: */
-	bool linear_interp,cycle;
+	bool linear_interp,average,cycle;
 	IssmDouble dt;
 	this->parameters->FindParam(&linear_interp,TimesteppingInterpForcingEnum);
+	this->parameters->FindParam(&average,TimesteppingAverageForcingEnum);
 	this->parameters->FindParam(&cycle,TimesteppingCycleForcingEnum);
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);          /*transient core time step*/
@@ -471,6 +473,9 @@
 
 	/*Figure step out*/
-	int offset;
+	int offset, prevoffset;
 	if(!binary_search(&offset,time,this->timesteps,this->numtimesteps)){
+		_error_("Input not found (is TransientInput sorted ?)");
+	}
+	if(!binary_search(&prevoffset,reCast<IssmDouble>(time-dt),this->timesteps,this->numtimesteps)){
 		_error_("Input not found (is TransientInput sorted ?)");
 	}
@@ -488,4 +493,22 @@
 		this->current_step = 0.;
 		this->current_input = this->inputs[0]->copy();
+
+	}
+	else if(offset-prevoffset>1 && prevoffset >=0 && average){
+		/*get values for the last time: */
+		_assert_(time>=this->timesteps[offset]);
+
+		/*If already processed return*/
+		if(this->current_step==reCast<IssmDouble>(offset)) return;
+
+		/*Prepare input*/
+		if(this->current_input) delete this->current_input;
+		this->current_step  = reCast<IssmDouble>(offset);
+
+		this->current_input = this->inputs[prevoffset]->copy();
+		for(int i=prevoffset+1;i<offset;i++) {
+			this->current_input->AXPY(this->inputs[i],+1.0);
+		}
+		this->current_input->Scale(1./(offset-prevoffset));
 
 	}
@@ -535,4 +558,5 @@
 	IssmDouble  timespan,mid_step;
 	int         found,start_offset,end_offset,input_offset;
+
 
 	/*go through the timesteps, and grab offset for start and end*/
@@ -573,6 +597,5 @@
 			_assert_(dt>0.);
 		}
-		Input* stepinput=this->inputs[offset+1];
-
+		Input* stepinput=this->inputs[offset+1]->copy();
 		switch(averaging_method){
 			case 0: /*Arithmetic mean*/
@@ -608,4 +631,5 @@
 				_error_("averaging method is not recognised");
 		}
+		delete stepinput;
 		dtsum+=dt;
 		offset+=1;
Index: issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- issm/trunk/src/c/classes/IoModel.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/IoModel.cpp	(revision 27232)
@@ -1180,5 +1180,5 @@
 		integer_matrix=NULL;
 	}
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmPDouble>(matrix);
 
@@ -1747,5 +1747,5 @@
 	}
 
-	/*Free ressources*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(doublearray);
 }
@@ -1947,5 +1947,5 @@
 			break;
 	}
-	/*Free ressources*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(doublearray);
 }
@@ -2026,5 +2026,5 @@
 			break;
 	}
-	/*Free ressources*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(doublearray);
 }
@@ -2260,5 +2260,5 @@
 		}
 	}
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(codes);
 	xDelete<fpos_t>(file_positions);
@@ -2313,5 +2313,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<fpos_t>(file_positions);
 	xDelete<int>(codes);
@@ -2366,5 +2366,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<fpos_t>(file_positions);
 	xDelete<int>(codes);
@@ -2455,5 +2455,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<fpos_t>(file_positions);
 	xDelete<int>(codes);
@@ -2558,5 +2558,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<fpos_t>(file_positions);
 	xDelete<int>(codes);
Index: issm/trunk/src/c/classes/Loads/Friction.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 27232)
@@ -321,10 +321,10 @@
 
 	/*This routine calculates the basal friction coefficient
-	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p**/
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p
+	  alpha2= min(drag^2 * Neff ^r * | vel | ^(s-1), drag_coulomb^2 * Neff*/
 
 	/*diverse: */
 	IssmDouble  r,s;
 	IssmDouble  drag_p, drag_q;
-	IssmDouble  thickness,base,floatation_thickness,sealevel;
 	IssmDouble  drag_coefficient,drag_coefficient_coulomb;
 	IssmDouble  alpha2,alpha2_coulomb;
@@ -333,7 +333,4 @@
 	element->GetInputValue(&drag_p,gauss,FrictionPEnum);
 	element->GetInputValue(&drag_q,gauss,FrictionQEnum);
-	element->GetInputValue(&thickness, gauss,ThicknessEnum);
-	element->GetInputValue(&base, gauss,BaseEnum);
-	element->GetInputValue(&sealevel, gauss,SealevelEnum);
 	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
 	element->GetInputValue(&drag_coefficient_coulomb, gauss,FrictionCoefficientcoulombEnum);
@@ -347,5 +344,21 @@
 
 	/*Get effective pressure*/
-	IssmDouble Neff = EffectivePressure(gauss);
+	bool ispwStochastic;
+	IssmDouble Neff;
+	element->parameters->FindParam(&ispwStochastic,StochasticForcingIsWaterPressureEnum);
+	if(ispwStochastic){
+		/*Retrieve stochastic water pressure and compute ice pressure*/
+		IssmDouble p_ice,p_water,Neff_limit;
+		element->GetInputValue(&p_water,gauss,FrictionCoulombWaterPressureEnum);
+		element->parameters->FindParam(&Neff_limit,FrictionEffectivePressureLimitEnum);
+		p_ice = IcePressure(gauss);
+		Neff  = max(Neff_limit*p_ice, p_ice - p_water);
+	}	
+	else{
+		/*Compute effective pressure directly*/
+		Neff = EffectivePressure(gauss);
+	}
+	
+	/*Get velocity magnitude*/
 	IssmDouble vmag = VelMag(gauss);
 
@@ -360,11 +373,10 @@
 	}
 
-	floatation_thickness=0;
-	if(base<0) floatation_thickness=-(rho_water/rho_ice)*base;
 	if(vmag==0.){
 		alpha2_coulomb=0.;
 	}
 	else{
-		alpha2_coulomb=drag_coefficient_coulomb*drag_coefficient_coulomb*rho_ice*gravity*max(0.,thickness-floatation_thickness)/vmag;
+		//alpha2_coulomb=drag_coefficient_coulomb*drag_coefficient_coulomb*rho_ice*gravity*max(0.,thickness-floatation_thickness)/vmag;
+		alpha2_coulomb=drag_coefficient_coulomb*drag_coefficient_coulomb*Neff/vmag;
 	}
 
@@ -749,5 +761,5 @@
 	 *               C |u_b|^(m-1)
 	 * alpha2= __________________________
-	 *          (1+(C/(Cmax N))^1/m |u_b| )^m
+	 *          (1+(C/(Cmax Neff))^1/m |u_b| )^m
 	 *
 	 * */
@@ -764,14 +776,30 @@
 	C = coeff*coeff;
 
-	/*Get effective pressure and velocity magnitude*/
-	IssmDouble N  = EffectivePressure(gauss);
+	/*Get effective pressure*/
+	bool ispwStochastic;
+	IssmDouble Neff;
+	element->parameters->FindParam(&ispwStochastic,StochasticForcingIsWaterPressureEnum);
+	if(ispwStochastic){
+		/*Retrieve stochastic water pressure and compute ice pressure*/
+		IssmDouble p_ice,p_water,Neff_limit;
+		element->GetInputValue(&p_water,gauss,FrictionSchoofWaterPressureEnum);
+		element->parameters->FindParam(&Neff_limit,FrictionEffectivePressureLimitEnum);
+		p_ice = IcePressure(gauss);
+		Neff  = max(Neff_limit*p_ice, p_ice - p_water);
+	}	
+	else{
+		/*Compute effective pressure directly*/
+		Neff = EffectivePressure(gauss);
+	}
+
+	/*Get velocity magnitude*/
 	IssmDouble ub = VelMag(gauss);
 
 	/*Compute alpha^2*/
-	if((ub<1e-10) ||(N==0.0)){
+	if((ub<1e-10) ||(Neff==0.0)){
 		alpha2 = 0.;
 	}
 	else{
-		alpha2= (C*pow(ub,m-1.)) / pow(1.+  pow(C/(Cmax*N),1./m)*ub,m);
+		alpha2= (C*pow(ub,m-1.)) / pow(1.+  pow(C/(Cmax*Neff),1./m)*ub,m);
 	}
 
Index: issm/trunk/src/c/classes/Materials/Matlitho.cpp
===================================================================
--- issm/trunk/src/c/classes/Materials/Matlitho.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Materials/Matlitho.cpp	(revision 27232)
@@ -88,5 +88,5 @@
 	for (int i=0;i<this->numlayers;i++)this->issolid[i]=reCast<bool,IssmDouble>(issolidd[i]);*/
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<IssmDouble>(rheologymodeld);
 	xDelete<IssmDouble>(issolidd);
Index: issm/trunk/src/c/classes/Misfit.cpp
===================================================================
--- issm/trunk/src/c/classes/Misfit.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Misfit.cpp	(revision 27232)
@@ -178,5 +178,5 @@
 			 misfit=sqrt(misfit_t/count);
 
-			 /*Free ressources:*/
+			 /*Free resources:*/
 			 xDelete<IssmDouble>(model);
 			 xDelete<IssmDouble>(observation);
@@ -213,5 +213,5 @@
 			 if(time==finaltime)this->lock=1;
 
-			 /*Free ressources:*/
+			 /*Free resources:*/
 			 xDelete<IssmDouble>(model);
 			 xDelete<IssmDouble>(observation);
Index: issm/trunk/src/c/classes/Node.cpp
===================================================================
--- issm/trunk/src/c/classes/Node.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Node.cpp	(revision 27232)
@@ -838,5 +838,5 @@
 		else doflist=NULL;
 
-		/*Free ressources:*/
+		/*Free resources:*/
 		xDelete<int>(ndof_list);
 	}
Index: issm/trunk/src/c/classes/Params/Parameters.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 27232)
@@ -656,5 +656,5 @@
 	strcpy(outstring,strings[found]);
 
-	/*Free ressources*/
+	/*Free resources:*/
 	for(i=0;i<numanalyses;i++){
 		xDelete<char>(toolkits[i]);
Index: issm/trunk/src/c/classes/SealevelGeometry.cpp
===================================================================
--- issm/trunk/src/c/classes/SealevelGeometry.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/SealevelGeometry.cpp	(revision 27232)
@@ -115,11 +115,11 @@
 
 } /*}}}*/
-int SealevelGeometry::GEnum(int l){ /*{{{*/
+int SealevelGeometry::AlphaIndexEnum(int l){ /*{{{*/
 
 	int output = -1;
 	switch(l){
-		case SLGEOM_OCEAN: output=SealevelchangeGsubelOceanEnum; break;
-		case SLGEOM_ICE:   output=SealevelchangeGsubelIceEnum;   break;
-		case SLGEOM_WATER: output=SealevelchangeGsubelHydroEnum; break;
+		case SLGEOM_OCEAN: output=SealevelchangeAlphaIndexOceanEnum; break;
+		case SLGEOM_ICE:   output=SealevelchangeAlphaIndexIceEnum;   break;
+		case SLGEOM_WATER: output=SealevelchangeAlphaIndexHydroEnum; break;
 		default: _error_("not supported");
 	}
@@ -127,35 +127,11 @@
 
 } /*}}}*/
-int SealevelGeometry::GUEnum(int l){ /*{{{*/
+int SealevelGeometry::AzimuthIndexEnum(int l){ /*{{{*/
 
 	int output = -1;
 	switch(l){
-		case SLGEOM_OCEAN: output=SealevelchangeGUsubelOceanEnum; break;
-		case SLGEOM_ICE:   output=SealevelchangeGUsubelIceEnum;   break;
-		case SLGEOM_WATER: output=SealevelchangeGUsubelHydroEnum; break;
-		default: _error_("not supported");
-	}
-	return output;
-
-} /*}}}*/
-int SealevelGeometry::GNEnum(int l){ /*{{{*/
-
-	int output = -1;
-	switch(l){
-		case SLGEOM_OCEAN: output=SealevelchangeGNsubelOceanEnum; break;
-		case SLGEOM_ICE:   output=SealevelchangeGNsubelIceEnum;   break;
-		case SLGEOM_WATER: output=SealevelchangeGNsubelHydroEnum; break;
-		default: _error_("not supported");
-	}
-
-	return output;
-} /*}}}*/
-int SealevelGeometry::GEEnum(int l){ /*{{{*/
-
-	int output = -1;
-	switch(l){
-		case SLGEOM_OCEAN: output=SealevelchangeGEsubelOceanEnum; break;
-		case SLGEOM_ICE:   output=SealevelchangeGEsubelIceEnum;   break;
-		case SLGEOM_WATER: output=SealevelchangeGEsubelHydroEnum; break;
+		case SLGEOM_OCEAN: output=SealevelchangeAzimuthIndexOceanEnum; break;
+		case SLGEOM_ICE:   output=SealevelchangeAzimuthIndexIceEnum;   break;
+		case SLGEOM_WATER: output=SealevelchangeAzimuthIndexHydroEnum; break;
 		default: _error_("not supported");
 	}
Index: issm/trunk/src/c/classes/SealevelGeometry.h
===================================================================
--- issm/trunk/src/c/classes/SealevelGeometry.h	(revision 27035)
+++ issm/trunk/src/c/classes/SealevelGeometry.h	(revision 27232)
@@ -45,8 +45,6 @@
 		void InitializeMappingsAndBarycentres(void);
 		void Assemble(void);
-		int GEnum(int l);
-		int GUEnum(int l);
-		int GNEnum(int l);
-		int GEEnum(int l);
+		int AlphaIndexEnum(int l);
+		int AzimuthIndexEnum(int l);
 		void BuildSphericalHarmonics(void);
 };
Index: issm/trunk/src/c/classes/Vertices.cpp
===================================================================
--- issm/trunk/src/c/classes/Vertices.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/Vertices.cpp	(revision 27232)
@@ -168,5 +168,5 @@
 	IssmDouble* lon_serial=lon->ToMPISerial();
 
-	/*free ressources: */
+	/*Free resources: */
 	*plat = lat_serial;
 	*plon = lon_serial;
Index: issm/trunk/src/c/classes/gauss/GaussSeg.cpp
===================================================================
--- issm/trunk/src/c/classes/gauss/GaussSeg.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/gauss/GaussSeg.cpp	(revision 27232)
@@ -43,5 +43,5 @@
 	}
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<IssmPDouble>(pcoords1);
 	xDelete<IssmPDouble>(pweights);
Index: issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 27035)
+++ issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 27232)
@@ -162,5 +162,5 @@
 		pf->SetValues(fsize,this->fglobaldoflist,localvalues,ADD_VAL);
 
-		/*Free ressources:*/
+		/*Free resources:*/
 		xDelete<IssmDouble>(localvalues);
 	}
Index: issm/trunk/src/c/cores/ResetBoundaryConditions.cpp
===================================================================
--- issm/trunk/src/c/cores/ResetBoundaryConditions.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/ResetBoundaryConditions.cpp	(revision 27232)
@@ -25,5 +25,5 @@
 	UpdateDynamicConstraintsx(femmodel->constraints,femmodel->nodes,femmodel->parameters,yg);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete yg;
 }
Index: issm/trunk/src/c/cores/adgradient_core.cpp
===================================================================
--- issm/trunk/src/c/cores/adgradient_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/adgradient_core.cpp	(revision 27232)
@@ -168,5 +168,5 @@
 			if(VerboseAutodiff())_printf0_("   end ad core\n");
 
-			/* delete the allocated space for the parameters and free ressources:{{{*/
+			/* delete the allocated space for the parameters and Free resources:{{{*/
 			xDelete(anEDF_for_solverx_p->dp_x);
 			xDelete(anEDF_for_solverx_p->dp_X);
Index: issm/trunk/src/c/cores/control_core.cpp
===================================================================
--- issm/trunk/src/c/cores/control_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/control_core.cpp	(revision 27232)
@@ -107,5 +107,5 @@
 	}
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<int>(control_type);
 	xDelete<int>(maxiter);
@@ -189,5 +189,5 @@
 	_printf0_("\n");
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(XU);
 	xDelete<IssmDouble>(XL);
Index: issm/trunk/src/c/cores/dakota_core.cpp
===================================================================
--- issm/trunk/src/c/cores/dakota_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/dakota_core.cpp	(revision 27232)
@@ -228,5 +228,5 @@
 	OutputResultsx(femmodel);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
 
Index: issm/trunk/src/c/cores/esa_core.cpp
===================================================================
--- issm/trunk/src/c/cores/esa_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/esa_core.cpp	(revision 27232)
@@ -106,5 +106,5 @@
 		if(solution_type==EsaSolutionEnum)femmodel->RequestedDependentsx();
 
-		/*Free ressources:*/	
+		/*Free resources:*/	
 		delete U_radial;
 		delete U_north;
Index: issm/trunk/src/c/cores/groundingline_core.cpp
===================================================================
--- issm/trunk/src/c/cores/groundingline_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/groundingline_core.cpp	(revision 27232)
@@ -40,5 +40,5 @@
 	if(save_results) femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
 
-	/*Free ressources:*/
+	/*Free resources:*/
    if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 
Index: issm/trunk/src/c/cores/hydrology_core.cpp
===================================================================
--- issm/trunk/src/c/cores/hydrology_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/hydrology_core.cpp	(revision 27232)
@@ -57,9 +57,9 @@
 		InputDuplicatex(femmodel,WatercolumnEnum,WaterColumnOldEnum);
 
-		/*grab tws from the hydrology.spcwatercolumn field input and update 
+		/*grab tws from the hydrology.spcwatercolumn field input and update
 		 * the solution with it:*/
 		Vector<IssmDouble>*  ug  = NULL;
 		GetVectorFromInputsx(&ug,femmodel,HydrologyTwsSpcEnum,VertexPIdEnum);
-		InputUpdateFromSolutionx(femmodel,ug); 
+		InputUpdateFromSolutionx(femmodel,ug);
 
 		/*solid earth considerations:*/
@@ -83,13 +83,17 @@
 		if(ThawedNodes>0){
 			/*check if we need sub steps*/
-			int        dtslices;
-			femmodel->parameters->FindParam(&dtslices,HydrologyStepsPerStepEnum);
-
-			if(dtslices>1){
-				int        substep, numaveragedinput, hydro_averaging;
-				IssmDouble global_time, subtime, yts;
+			int  dtslices;
+			bool sliceadapt;
+         bool conv_fail=false;
+         femmodel->parameters->FindParam(&dtslices,HydrologyStepsPerStepEnum);
+         femmodel->parameters->FindParam(&sliceadapt,HydrologyStepAdaptEnum);
+
+			if(dtslices>1 || sliceadapt){
+				int        step, substep, numaveragedinput, hydro_averaging, remainingslices;
+				IssmDouble global_time, subtime, yts, remainingtime, averagetime;
 				IssmDouble dt, subdt;
 
             femmodel->parameters->FindParam(&global_time,TimeEnum);
+				femmodel->parameters->FindParam(&step,StepEnum);
             femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
             femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
@@ -124,7 +128,9 @@
 				}
 				femmodel->InitTransientInputx(&transientinput[0],numaveragedinput);
+				averagetime=0;
 				while(substep<dtslices){ //loop on hydro dts
 					substep+=1;
 					subtime+=subdt;
+					averagetime+=subtime*subdt;
 					/*Setting substep time as global time*/
 					femmodel->parameters->SetParam(subtime,TimeEnum);
@@ -138,7 +144,32 @@
 					}
 					/*Proceed now to heads computations*/
-					solutionsequence_hydro_nonlinear(femmodel);
-               /*If we have a sub-timestep we store the substep inputs in a transient input here*/
-					femmodel->StackTransientInputonBasex(&substepinput[0],&transientinput[0],subtime,numaveragedinput);
+					solutionsequence_hydro_nonlinear(femmodel, &conv_fail);
+					if(conv_fail){
+                  /*convergence failed, we want to go back to the begining of the main step and increase the number of subslices*/
+                  /*First we get teh time and step counter back to the begining of the step that did not converge*/
+                  averagetime-=subtime*subdt;
+                  subtime-=subdt;
+                  substep-=1;
+                  /*compute the number of slice that are remaining and the time left in the timestep*/
+                  remainingslices=dtslices-substep;
+                  remainingtime=global_time-subtime;
+                  /*We double the number of remaining slices and compute their duration*/
+                  dtslices=dtslices-remainingslices+(2*remainingslices);
+                  subdt=remainingtime/(2*remainingslices);
+                  if(VerboseSolution())_printf0_("convergence failed for sub-step "<< substep <<" total number of slice is now "<< dtslices <<" for step "<<step<<"\n");
+                  if(VerboseSolution())_printf0_("next slice duration is "<< subdt/yts <<" years\n");
+                  conv_fail = false;  //re-initialize the control keyword
+                  if (dtslices>500){
+                     _error_("   We reached (" << dtslices << ") which exceeds the hard limit of 500");
+                  }
+
+                  femmodel->parameters->SetParam(subdt,TimesteppingTimeStepEnum);
+                  femmodel->parameters->SetParam(subtime,TimeEnum);
+
+               }
+               else{
+						/*If we have a sub-timestep we store the substep inputs in a transient input here*/
+						femmodel->StackTransientInputonBasex(&substepinput[0],&transientinput[0],subtime,numaveragedinput);
+					}
 				}
 				/*averaging the stack*/
@@ -147,4 +178,8 @@
 				femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
 				femmodel->parameters->SetParam(global_time,TimeEnum);
+				if(save_results){
+               femmodel->results->AddResult(new GenericExternalResult<int>(femmodel->results->Size()+1,HydrologySubstepsEnum,dtslices,step,global_time));
+               femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,HydrologySubTimeEnum,(averagetime/dt)/yts,step,global_time));
+            }
 			}
 			else{
@@ -156,5 +191,5 @@
 				/*Proceed now to heads computations*/
 				if(VerboseSolution()) _printf0_("   computing water heads\n");
-				solutionsequence_hydro_nonlinear(femmodel);
+				solutionsequence_hydro_nonlinear(femmodel, &conv_fail);
 				/*If no substeps are present we want to duplicate the results for coupling purposes*/
 				InputDuplicatex(femmodel,SedimentHeadSubstepEnum,SedimentHeadEnum);
@@ -236,5 +271,5 @@
 		}
 	}
-	/*Free ressources:*/
+	/*Free resources:*/
 	if(numoutputs){
 		for(int i=0;i<numoutputs;i++){
Index: issm/trunk/src/c/cores/masstransport_core.cpp
===================================================================
--- issm/trunk/src/c/cores/masstransport_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/masstransport_core.cpp	(revision 27232)
@@ -97,5 +97,5 @@
 	if(solution_type==MasstransportSolutionEnum)femmodel->RequestedDependentsx();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 
Index: issm/trunk/src/c/cores/oceantransport_core.cpp
===================================================================
--- issm/trunk/src/c/cores/oceantransport_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/oceantransport_core.cpp	(revision 27232)
@@ -52,5 +52,5 @@
 	femmodel->profiler->Stop(OCEANTRANSPORTCORE);
 
-	/*free ressources:*/
+	/*Free resources:*/
 	delete ug;
 
Index: issm/trunk/src/c/cores/sampling_core.cpp
===================================================================
--- issm/trunk/src/c/cores/sampling_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/sampling_core.cpp	(revision 27232)
@@ -69,5 +69,5 @@
 	if(solution_type==SamplingSolutionEnum)femmodel->RequestedDependentsx();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 
Index: issm/trunk/src/c/cores/sealevelchange_core.cpp
===================================================================
--- issm/trunk/src/c/cores/sealevelchange_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/sealevelchange_core.cpp	(revision 27232)
@@ -29,4 +29,5 @@
 void ivins_deformation_core(FemModel* femmodel);
 IssmDouble* CombineLoads(IssmDouble* load,IssmDouble* subload,FemModel* femmodel, SealevelGeometry* slgeom,int loadtype,int nel);
+void slc_geometry_cleanup(SealevelGeometry* slgeom, FemModel* femmodel);
 /*}}}*/
 
@@ -81,4 +82,7 @@
 	/*End profiler*/
 	femmodel->profiler->Stop(SLRCORE);
+
+	/*Free resources:*/
+	slc_geometry_cleanup(slgeom, femmodel);
 }
 /*}}}*/
@@ -143,5 +147,5 @@
 	}
 
-	/*Free ressources:*/	
+	/*Free resources:*/	
 	delete bedrock; delete bedrock_rate;
 	delete geoid; delete geoid_rate;
@@ -358,5 +362,5 @@
 		//Conserve ocean mass: 
 		oceanaverage=SealevelloadsOceanAverage(loads, oceanareas,subelementoceanareas, totaloceanarea);
-		ConserveOceanMass(femmodel,loads,barycontrib->Total()/totaloceanarea - oceanaverage,slgeom);
+		ConserveOceanMass(femmodel,loads,barycontrib->Total()/totaloceanarea -oceanaverage,slgeom);
 
 		//broadcast sea level loads 
@@ -364,9 +368,14 @@
 
 		//convergence?
-		if(slcconvergence(loads->vsealevelloads,oldsealevelloads,eps_rel,eps_abs))break;
+		if(slcconvergence(loads->vsealevelloads,oldsealevelloads,eps_rel,eps_abs)){
+			delete oldsealevelloads; break;
+		}
 
 		//early return?
-		if(iterations>=max_nonlinear_iterations)break;
+		if(iterations>=max_nonlinear_iterations){
+			delete oldsealevelloads; break;
+		}
 		iterations++;
+		delete oldsealevelloads;
 	}
 
@@ -388,5 +397,5 @@
 	if(planethasocean){
 		if (!sealevelloading){ //we haven't done so before, so we need to compute the ocean average and area
-			loads->sealevelloads=NULL; //needed to trigger the calculation of areas
+			if(loads->sealevelloads)xDelete<IssmDouble>(loads->sealevelloads); loads->sealevelloads=NULL; //needed to trigger the calculation of areas
 			/*retrieve sea level average  and ocean area:*/
 			for(Object* & object : femmodel->elements->objects){
@@ -430,4 +439,9 @@
 	}
 
+	/*Free resources:*/
+	delete loads;
+	delete subelementoceanareas;
+	delete oceanareas;
+	xDelete<IssmDouble>(sealevelpercpu); 
 }
 /*}}}*/
@@ -487,5 +501,5 @@
 	InputUpdateFromVectorx(femmodel,sealevel,SealevelEnum,VertexSIdEnum);	
 
-	/*Free ressources:*/	
+	/*Free resources:*/	
 	delete sealevel;
 	delete deltadsl;
@@ -557,5 +571,5 @@
 	femmodel->inputs->AXPY(1,BedGRDEnum,BedEnum);
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<IssmDouble>(xx);
 	xDelete<IssmDouble>(yy);
@@ -574,4 +588,5 @@
 	IssmDouble* areae  = NULL;
 	int  nel;
+	int* lids;
 	int  grdmodel=0;
 
@@ -589,8 +604,21 @@
 	ElementCoordinatesx(&xxe,&yye,&zze,&areae,femmodel->elements);
 
+
+	/*Compute element ids, used to speed up computations in convolution phase:{{{*/
+	lids=xNew<int>(femmodel->vertices->Size());
+
+	for(Object* & object : femmodel->elements->objects){
+		Element*   element=xDynamicCast<Element*>(object);
+		for(int i=0;i<3;i++){
+			lids[element->vertices[i]->lid]=element->lid;
+		}
+	}
+
+	/*}}}*/
+
 	/*Run sealevel geometry routine in elements:*/
 	for(Object* & object : femmodel->elements->objects){
 		Element*   element=xDynamicCast<Element*>(object);
-		element->SealevelchangeGeometryInitial(xxe,yye,zze,areae);
+		element->SealevelchangeGeometryInitial(xxe,yye,zze,areae,lids);
 	}
 
@@ -607,4 +635,10 @@
 	#endif
 
+	xDelete<IssmDouble>(xxe);
+	xDelete<IssmDouble>(yye);
+	xDelete<IssmDouble>(zze);
+	xDelete<IssmDouble>(areae);
+	xDelete(lids);
+
 	return;
 
@@ -623,9 +657,11 @@
 	int nel;
 	int  grdmodel=0;
+	int isgrd=0;
 	SealevelGeometry* slgeom=NULL;
 
 	/*early return?:*/
 	femmodel->parameters->FindParam(&grdmodel,GrdModelEnum);
-	if(grdmodel==IvinsEnum) return NULL;
+	femmodel->parameters->FindParam(&isgrd,SolidearthSettingsGRDEnum);
+	if(grdmodel!=ElasticEnum || !isgrd) return NULL;
 
 	/*retrieve parameters:*/
@@ -673,7 +709,31 @@
 	femmodel->parameters->AddObject(new DoubleVecParam(AreaeEnum,areae,nel));
 
+	/*Free resources:*/
+	xDelete<IssmDouble>(xxe);
+	xDelete<IssmDouble>(yye);
+	xDelete<IssmDouble>(zze);
+	xDelete<IssmDouble>(areae);
+
 	return slgeom;
 
 }/*}}}*/
+void slc_geometry_cleanup(SealevelGeometry* slgeom, FemModel* femmodel){  /*{{{*/
+	int  grdmodel=0;
+	int isgrd=0;
+	int horiz=0;
+
+	/*early return?:*/
+	femmodel->parameters->FindParam(&grdmodel,GrdModelEnum);
+	femmodel->parameters->FindParam(&isgrd,SolidearthSettingsGRDEnum);
+	femmodel->parameters->FindParam(&horiz,SolidearthSettingsHorizEnum);
+	if(grdmodel!=ElasticEnum || !isgrd) return;
+
+	for (int l=0;l<SLGEOM_NUMLOADS;l++){
+		femmodel->inputs->DeleteInput(slgeom->AlphaIndexEnum(l));
+		if (horiz) femmodel->inputs->DeleteInput(slgeom->AzimuthIndexEnum(l));
+	}
+
+	delete slgeom;
+} /*}}}*/
 
 /*subroutines:*/
@@ -731,7 +791,4 @@
 	Vector<IssmDouble>* vsealevelloadsvolume=loads->vsealevelloads->Duplicate();
 	Vector<IssmDouble>* vsubsealevelloadsvolume=loads->vsubsealevelloads->Duplicate();
-
-	vsealevelloadsvolume->PointwiseMult(loads->vsealevelloads,oceanareas);
-	vsubsealevelloadsvolume->PointwiseMult(loads->vsubsealevelloads,suboceanareas); 
 
 	vsealevelloadsvolume->Sum(&sealevelloadsaverage);
@@ -870,5 +927,10 @@
 			xDelete<IssmDouble>(m3interp);
 		}
-	}
+		xDelete<IssmDouble>(viscoustimes);
+		xDelete<IssmDouble>(viscouspolarmotion);
+	}
+	xDelete<IssmDouble>(pmtf_col);
+	xDelete<IssmDouble>(pmtf_ortho);
+	xDelete<IssmDouble>(pmtf_z);
 
 } /*}}}*/
@@ -935,4 +997,5 @@
 		/*free allocations:*/
 		xDelete<IssmDouble>(viscoustimes);
+		if (rotation) 	xDelete<IssmDouble>(viscouspolarmotion);
 	}
 
@@ -1097,5 +1160,5 @@
 	/*}}}*/
 
-	/*Free ressources:{{{*/
+	/*Free resources:{{{*/
 	if(forcings){
 		for(int i=0;i<nummodels-1;i++){
@@ -1209,5 +1272,5 @@
 	/*}}}*/
 
-	/*Free ressources:{{{*/
+	/*Free resources:{{{*/
 	if(forcingglobal)xDelete<IssmDouble>(forcingglobal);
 	if(forcing)xDelete<IssmDouble>(forcing);
Index: issm/trunk/src/c/cores/smb_core.cpp
===================================================================
--- issm/trunk/src/c/cores/smb_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/smb_core.cpp	(revision 27232)
@@ -108,5 +108,5 @@
 	if(solution_type==SmbSolutionEnum)femmodel->RequestedDependentsx();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 
Index: issm/trunk/src/c/cores/steadystate_core.cpp
===================================================================
--- issm/trunk/src/c/cores/steadystate_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/steadystate_core.cpp	(revision 27232)
@@ -81,5 +81,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete tg_old;
 	delete ug_old;
Index: issm/trunk/src/c/cores/stressbalance_core.cpp
===================================================================
--- issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 27232)
@@ -98,5 +98,5 @@
 	if(solution_type==StressbalanceSolutionEnum && !control_analysis)femmodel->RequestedDependentsx();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 
Index: issm/trunk/src/c/cores/thermal_core.cpp
===================================================================
--- issm/trunk/src/c/cores/thermal_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/thermal_core.cpp	(revision 27232)
@@ -53,5 +53,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 
Index: issm/trunk/src/c/cores/transient_core.cpp
===================================================================
--- issm/trunk/src/c/cores/transient_core.cpp	(revision 27035)
+++ issm/trunk/src/c/cores/transient_core.cpp	(revision 27232)
@@ -130,5 +130,5 @@
 
 	/*parameters: */
-	bool isstressbalance,ismasstransport,isoceantransport,issmb,isthermal,isgroundingline,isesa,issampling;;
+	bool isstressbalance,ismasstransport,isage,isoceantransport,issmb,isthermal,isgroundingline,isesa,issampling;
 	bool isslc,ismovingfront,isdamageevolution,ishydrology,isoceancoupling,isstochasticforcing,save_results;
 	int  step,sb_coupling_frequency;
@@ -142,4 +142,5 @@
 	femmodel->parameters->FindParam(&isstressbalance,TransientIsstressbalanceEnum);
 	femmodel->parameters->FindParam(&ismasstransport,TransientIsmasstransportEnum);
+	femmodel->parameters->FindParam(&isage,TransientIsageEnum);
 	femmodel->parameters->FindParam(&isoceantransport,TransientIsoceantransportEnum);
 	femmodel->parameters->FindParam(&issmb,TransientIssmbEnum);
@@ -249,5 +250,5 @@
 		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs,save_results);
 
-		/*Free ressources:*/
+		/*Free resources:*/
 		for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);
 	}
Index: issm/trunk/src/c/datastructures/DataSet.cpp
===================================================================
--- issm/trunk/src/c/datastructures/DataSet.cpp	(revision 27035)
+++ issm/trunk/src/c/datastructures/DataSet.cpp	(revision 27232)
@@ -266,4 +266,9 @@
 				this->AddObject(cfsurf);
 			}
+			else if(obj_enum==CfdragcoeffabsgradEnum){
+				Cfdragcoeffabsgrad* cfdragcoeff=new Cfdragcoeffabsgrad();
+				cfdragcoeff->Marshall(marshallhandle);
+				this->AddObject(cfdragcoeff);
+			}
 			else if(obj_enum==MassfluxatgateEnum){
 				Massfluxatgate<IssmDouble>* massfluxgate=new Massfluxatgate<IssmDouble>();
Index: issm/trunk/src/c/main/issm_ocean.cpp
===================================================================
--- issm/trunk/src/c/main/issm_ocean.cpp	(revision 27035)
+++ issm/trunk/src/c/main/issm_ocean.cpp	(revision 27232)
@@ -62,5 +62,5 @@
 	ExceptionTrapEnd();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 
 	/*Return unix success: */
Index: issm/trunk/src/c/main/issm_slc.cpp
===================================================================
--- issm/trunk/src/c/main/issm_slc.cpp	(revision 27035)
+++ issm/trunk/src/c/main/issm_slc.cpp	(revision 27232)
@@ -122,5 +122,5 @@
 	ExceptionTrapEnd();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(commsizes);
 	for(int i=0;i<nummodels;i++){
Index: issm/trunk/src/c/main/kriging.cpp
===================================================================
--- issm/trunk/src/c/main/kriging.cpp	(revision 27035)
+++ issm/trunk/src/c/main/kriging.cpp	(revision 27232)
@@ -68,5 +68,5 @@
 	WriteLockFile(lockfilename);
 
-	/*Free ressources */
+	/*Free resources: */
 	xDelete<char>(lockfilename);
 	xDelete<char>(binfilename);
Index: issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp
===================================================================
--- issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 27232)
@@ -77,5 +77,5 @@
 	}
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<char>(toolkittype);
 
Index: issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 27232)
@@ -45,5 +45,5 @@
 	average=vec_average->ToMPISerial();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete partition_contributions;
 	delete partition_areas;
Index: issm/trunk/src/c/modules/ElementCoordinatesx/ElementCoordinatesx.cpp
===================================================================
--- issm/trunk/src/c/modules/ElementCoordinatesx/ElementCoordinatesx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/ElementCoordinatesx/ElementCoordinatesx.cpp	(revision 27232)
@@ -37,5 +37,5 @@
 	IssmDouble* areae=vareae->ToMPISerial();
 
-	/*Free ressources: */
+	/*Free resources: */
 	delete vxe;
 	delete vye;
@@ -79,5 +79,5 @@
 	IssmDouble* areae=vareae->ToMPISerial();
 
-	/*Free ressources: */
+	/*Free resources: */
 	delete vlonge;
 	delete vlate;
Index: issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 27232)
@@ -109,5 +109,5 @@
 	vector=vec_vector->ToMPISerial();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete vec_vector;
 
@@ -126,5 +126,5 @@
 	vector=vec_vector->ToMPISerial();
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete vec_vector;
 
Index: issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp
===================================================================
--- issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 27232)
@@ -106,5 +106,5 @@
 	*pdwidt=reCast<IssmDouble>(blocks_.aswokm_dwdt);
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<IssmPDouble>(blockt_time);
 	xDelete<IssmPDouble>(blockt_bi);
Index: issm/trunk/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 27232)
@@ -89,5 +89,5 @@
 	IssmDouble* gradient=vec_gradient->ToMPISerial();
 
-	/*Free ressources and assign output pointer*/
+	/*Free resources: and assign output pointer*/
 	delete vec_gradient;
 	*pgradient=gradient;
Index: issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 27232)
@@ -177,5 +177,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete vec_phi;
 	xDelete<IssmDouble>(elements_neighboring_floatingce);
Index: issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 27232)
@@ -145,5 +145,5 @@
 	femmodel->results->AddResult(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,"uq_variables",variables,numdakotavariables,1,1,0));
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	for(i=0;i<variable_partitions_num;i++){
 		IssmDouble* matrix=variable_partitions[i];
Index: issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 27232)
@@ -12,5 +12,5 @@
 	InputUpdateFromVectorDakotax(femmodel,serial_vector,name, type);
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<double>(serial_vector);
 }
Index: issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 27232)
@@ -589,5 +589,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(times);
 	xDelete<IssmDouble>(values);
@@ -723,5 +723,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(times);
 	xDelete<IssmDouble>(values);
Index: issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 27035)
+++ issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 27232)
@@ -112,5 +112,5 @@
 	*pnpart=npart;
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<int>(index);
 	xDelete<int>(epart2d);
Index: issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 27232)
@@ -109,5 +109,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete segments_dataset;
 
Index: issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 27232)
@@ -69,5 +69,5 @@
 		parameters->AddObject(theAdolcEDF_p);
 
-		/*Free ressources: */
+		/*Free resources: */
 		xDelete<char>(options);
 		/*}}}*/
@@ -96,5 +96,5 @@
 							_error_("solver type not supported yet!");
 		}
-		/*Free ressources: */
+		/*Free resources: */
 		xDelete<char>(options);
 		#endif
@@ -159,5 +159,5 @@
 			}
 
-			/*Free ressources:*/
+			/*Free resources:*/
 			for(i=0;i<num_dependent_objects;i++){
 				char* string=names[i]; xDelete<char>(string);
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 27232)
@@ -223,4 +223,5 @@
 											{
 												Tria* tria= xDynamicCast<Tria*>(element);
+												if(tria->hmaterial)delete tria->hmaterial; 
 												tria->hmaterial=NULL;
 											}
@@ -290,5 +291,5 @@
 				}
 			}
-			//Free ressources:
+			//Free resources:
 			xDelete<int>(nature);
 			break;
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 27232)
@@ -50,5 +50,5 @@
 					output_definitions->AddObject(new Massfluxatgate<IssmDouble>(gatenames[j],StringToEnumx(gatedefinitionstrings[j]),gatesegments_M[j],gatesegments[j]));
 				}
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<numgates;j++){
 					char*       string  = gatenames[j];             xDelete<char>(string);
@@ -126,5 +126,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<nummisfits;j++){
 					char* string=NULL;
@@ -217,5 +217,5 @@
 				}
 
-				  /*Free ressources:*/
+				  /*Free resources:*/
 				for(j=0;j<num_cfsurfacesquares;j++){
 					char* string=NULL;
@@ -288,5 +288,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<num_cfdragcoeffabsgrads;j++){
 					char* string=NULL;
@@ -374,5 +374,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<num_cfsurfacelogvels;j++){
 					char* string=NULL;
@@ -463,5 +463,5 @@
 				}
 
-				  /*Free ressources:*/
+				  /*Free resources:*/
 				for(j=0;j<num_cflevelsetmisfits;j++){
 					char* string=NULL;
@@ -512,5 +512,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<numnodalvalues;j++){
 					char* string=NULL;
@@ -546,5 +546,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<nummasscons;j++){
 					char* string=NULL;
@@ -589,5 +589,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<num;j++){
 					char* string=NULL;
@@ -629,5 +629,5 @@
 				}
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<numout;j++){
 					char* string=NULL;
@@ -707,5 +707,5 @@
 				xDelete<char*>(cost_functions);
 
-				/*Free ressources:*/
+				/*Free resources:*/
 				for(j=0;j<numout;j++){
 					xDelete<char>(ncf_name_s[j]);
@@ -744,5 +744,5 @@
 	parameters->AddObject(new DataSetParam(OutputdefinitionEnum,output_definitions));
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete output_definitions;
 	xDelete<int>(output_definition_enums);
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 27232)
@@ -79,4 +79,5 @@
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.ismasstransport",TransientIsmasstransportEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.isoceantransport",TransientIsoceantransportEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.transient.isage",TransientIsageEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.issmb",TransientIssmbEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.isthermal",TransientIsthermalEnum));
@@ -270,11 +271,11 @@
 			iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.upperwater_melting_rate");
          parameters->AddObject(new DoubleVecParam(BasalforcingsUpperwaterMeltingRateEnum,transparam,N));
-         xDelete<IssmDouble>(transparam);   
+         xDelete<IssmDouble>(transparam);
          iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.upperwater_elevation");
          parameters->AddObject(new DoubleVecParam(BasalforcingsUpperwaterElevationEnum,transparam,N));
-         xDelete<IssmDouble>(transparam); 
+         xDelete<IssmDouble>(transparam);
 			iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.deepwater_elevation");
          parameters->AddObject(new DoubleVecParam(BasalforcingsDeepwaterElevationEnum,transparam,N));
-         xDelete<IssmDouble>(transparam);   
+         xDelete<IssmDouble>(transparam);
 			break;
 		default:
@@ -294,4 +295,5 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.time_step",TimesteppingTimeStepEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.interp_forcing",TimesteppingInterpForcingEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.average_forcing",TimesteppingAverageForcingEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.cycle_forcing",TimesteppingCycleForcingEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.coupling_time",TimesteppingCouplingTimeEnum));
@@ -304,4 +306,5 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.cfl_coefficient",TimesteppingCflCoefficientEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.interp_forcing",TimesteppingInterpForcingEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.average_forcing",TimesteppingAverageForcingEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.cycle_forcing",TimesteppingCycleForcingEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.coupling_time",TimesteppingCouplingTimeEnum));
@@ -480,10 +483,4 @@
 	if(hydrology_model==HydrologydcEnum){
 		IssmDouble sedcomp, sedporo, watcomp, rhofresh, g;
-
-		/*FIXME: this should go to Analysis!!!*/
-		parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.sediment_porosity",HydrologydcSedimentPorosityEnum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.sediment_thickness",HydrologydcSedimentThicknessEnum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.isefficientlayer",HydrologydcIsefficientlayerEnum));
-
 		iomodel->FindConstant(&sedcomp,"md.hydrology.sediment_compressibility");
 		iomodel->FindConstant(&sedporo,"md.hydrology.sediment_porosity");
@@ -499,9 +496,4 @@
 		if(isefficientlayer){
 			IssmDouble eplcomp, eplporo;
-			parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.epl_initial_thickness",HydrologydcEplInitialThicknessEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.epl_colapse_thickness",HydrologydcEplColapseThicknessEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.epl_max_thickness",HydrologydcEplMaxThicknessEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.epl_conductivity",HydrologydcEplConductivityEnum));
-
 			iomodel->FindConstant(&eplcomp,"md.hydrology.epl_compressibility");
 			iomodel->FindConstant(&eplporo,"md.hydrology.epl_porosity");
Index: issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 27232)
@@ -72,5 +72,5 @@
 	 _printf_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<bool>(already);
 
Index: issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 27232)
@@ -53,5 +53,5 @@
 	}
 
-	/*Free ressources and return*/
+	/*Free resources: and return*/
 	delete y_s0;
 	delete Kfsy_s;
Index: issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 27232)
@@ -16,5 +16,7 @@
 	/*If fsize is 0, return NULL vector*/
 	if(fsize==0){
-		*puf=NULL;
+		Vector<IssmDouble>* uf=new Vector<IssmDouble>(0);
+		*puf=uf;
+		//*puf=NULL;
 		return;
 	}
Index: issm/trunk/src/c/modules/StochasticForcingx/StochasticForcingx.cpp
===================================================================
--- issm/trunk/src/c/modules/StochasticForcingx/StochasticForcingx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/StochasticForcingx/StochasticForcingx.cpp	(revision 27232)
@@ -207,8 +207,49 @@
 							gauss->GaussVertex(i);
 							p_water_deterministic[i] = friction->SubglacialWaterPressure(gauss);
-							p_water[i]               = p_water_deterministic[i] + noisefield[dimensionid]; //make sure positive (29Nov2021)
-							p_water[i]               = max(0.0,p_water[i]);
+							p_water[i]               = p_water_deterministic[i] + noisefield[dimensionid]; 
 						}
 						element->AddInput(FrictionWaterPressureEnum,p_water,P1DGEnum);
+						delete gauss;
+						delete friction;
+					}
+					break;
+				case FrictionSchoofWaterPressureEnum:
+					/*Specify that WaterPressure is stochastic*/ 
+					femmodel->parameters->SetParam(true,StochasticForcingIsWaterPressureEnum);
+					for(Object* &object:femmodel->elements->objects){
+                  Element* element = xDynamicCast<Element*>(object);
+                  int numvertices  = element->GetNumberOfVertices();
+                  IssmDouble p_water_deterministic[numvertices];
+                  IssmDouble p_water[numvertices];
+						element->GetInputValue(&dimensionid,StochasticForcingDefaultIdEnum);
+						Gauss* gauss=element->NewGauss();
+						Friction* friction = new Friction(element);
+						for(int i=0;i<numvertices;i++){
+							gauss->GaussVertex(i);
+							p_water_deterministic[i] = friction->SubglacialWaterPressure(gauss);
+							p_water[i]               = p_water_deterministic[i] + noisefield[dimensionid]; 
+						}
+						element->AddInput(FrictionSchoofWaterPressureEnum,p_water,P1DGEnum);
+						delete gauss;
+						delete friction;
+					}
+					break;
+				case FrictionCoulombWaterPressureEnum:
+					/*Specify that WaterPressure is stochastic*/ 
+					femmodel->parameters->SetParam(true,StochasticForcingIsWaterPressureEnum);
+					for(Object* &object:femmodel->elements->objects){
+                  Element* element = xDynamicCast<Element*>(object);
+                  int numvertices  = element->GetNumberOfVertices();
+                  IssmDouble p_water_deterministic[numvertices];
+                  IssmDouble p_water[numvertices];
+						element->GetInputValue(&dimensionid,StochasticForcingDefaultIdEnum);
+						Gauss* gauss=element->NewGauss();
+						Friction* friction = new Friction(element);
+						for(int i=0;i<numvertices;i++){
+							gauss->GaussVertex(i);
+							p_water_deterministic[i] = friction->SubglacialWaterPressure(gauss);
+							p_water[i]               = p_water_deterministic[i] + noisefield[dimensionid]; 
+						}
+						element->AddInput(FrictionCoulombWaterPressureEnum,p_water,P1DGEnum);
 						delete gauss;
 						delete friction;
Index: issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp
===================================================================
--- issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp	(revision 27232)
@@ -23,8 +23,8 @@
 
 const double CI = 2102.0;                       // heat capacity of snow/ice (J kg-1 k-1)
-const double LF = 0.3345E6;             // latent heat of fusion (J kg-1)
-const double LV = 2.495E6;               // latent heat of vaporization (J kg-1)
-const double LS = 2.8295E6;             // latent heat of sublimation (J kg-1)
-const double SB = 5.67E-8;                // Stefan-Boltzmann constant (W m-2 K-4)
+const double LF = 0.3345e6;             // latent heat of fusion (J kg-1)
+const double LV = 2.495e6;               // latent heat of vaporization (J kg-1)
+const double LS = 2.8295e6;             // latent heat of sublimation (J kg-1)
+const double SB = 5.67e-8;                // Stefan-Boltzmann constant (W m-2 K-4)
 const double CA = 1005.0;                    // heat capacity of air (J kg-1 K-1)
 const double R = 8.314;                      // gas constant (J mol-1 K-1)
@@ -159,4 +159,6 @@
 	// convert T from K to degC
 	T = T - CtoK;
+	// convert dT from degC/m to degC/cm
+	dT = dT/100;
 
 	// temperature coefficient F
@@ -279,5 +281,5 @@
 
 	 INPUTS
-	 * T: grid cell temperature [k]
+	 * T: grid cell temperature [K]
 	 * dz: grid cell depth [m]
 	 * d: grid cell density [kg m-3]
@@ -295,4 +297,5 @@
 	/*intermediary: */
 	IssmDouble  dt=0.0;
+	IssmDouble  Ti=0.0;
 	IssmDouble* gsz=NULL;
 	IssmDouble* dT=NULL;
@@ -332,5 +335,5 @@
 
 	/* Calculate temperature gradiant across grid cells 
-	 * Returns the avereage gradient across the upper and lower grid cell */
+	 * Returns the average gradient across the upper and lower grid cell */
 
 	//initialize
@@ -345,5 +348,9 @@
 
 	// Take forward differences on left and right edges
-	if(m>1){
+	if(m>2){
+		dT[0] = (T[2] - T[0])/(zGPC[2]-zGPC[0]);
+		dT[m-1] = (T[m-1] - T[m-3])/(zGPC[m-1]-zGPC[m-3]);
+	}
+	else if(m>1){
 		dT[0] = (T[1] - T[0])/(zGPC[1]-zGPC[0]);
 		dT[m-1] = (T[m-1] - T[m-2])/(zGPC[m-1]-zGPC[m-2]);
@@ -358,4 +365,8 @@
 	/*Snow metamorphism. Depends on value of snow dendricity and wetness of the snowpack: */
 	for(int i=0;i<m;i++){
+
+		// T for this layer
+		Ti = T[i];
+
 		if (gdn[i]>0.0+Gdntol){
 
@@ -363,8 +374,8 @@
 				//_printf_("Dendritic dry snow metamorphism\n");
 				//index for dentricity > 0 and T gradients < 5 degC m-1 and >= 5 degC m-1
-				if(dT[i]<=5.0+Ttol){
+				if(fabs(dT[i])<=5.0+Ttol){
 					//determine coefficients
-					IssmDouble A = - 2e8 * exp(-6e3 / T[i]) * dt;
-					IssmDouble B = 1e9 * exp(-6e3 / T[i]) * dt;
+					IssmDouble A = - 2e8 * exp(-6e3 / Ti) * dt;
+					IssmDouble B = 1e9 * exp(-6e3 / Ti) * dt;
 					//new dentricity and sphericity for dT < 5 degC m-1
 					gdn[i] += A;
@@ -374,6 +385,6 @@
 					// new dendricity and sphericity for dT >= 5 degC m-1
 
-					//determine coeff0icients
-					IssmDouble C = (-2e8 * exp(-6e3 / T[i]) * dt) * pow(dT[i],.4);
+					//determine coefficients
+					IssmDouble C = (-2e8 * exp(-6e3 / Ti) * dt) * pow(fabs(dT[i]),.4);
 					gdn[i] +=C;
 					gsp[i] +=C;
@@ -399,5 +410,5 @@
 
          // determine new grain size (mm)
-         gsz[i] = 0.1 + (1.0-gdn[i])*0.25 + (0.5-gsp[i])*0.1;
+			gsz[i] = 1e-1*(gdn[i]/.99+(1-1*gdn[i]/.99)*(gsp[i]/.99*3+(1-gsp[i]/.99)*4));
 
 		}
@@ -413,6 +424,6 @@
 				IssmDouble F = 0.0;
 
-				if (dT[i]>5.0+Ttol){
-					F = (-2e8 * exp(-6e3 / T[i]) * dt) * pow(dT[i],.4);
+				if (fabs(dT[i])>5.0+Ttol){
+					F = (-2e8 * exp(-6e3 / Ti) * dt) * pow(fabs(dT[i]),.4);
 				}
 				else if (W[i]>0.0+Wtol){
@@ -420,5 +431,5 @@
 				}
 				else{
-					F = 1e9 * exp(-6e3 / T[i]) * dt;
+					F = 1e9 * exp(-6e3 / Ti) * dt;
 				}
 				gsp[i] +=F;
@@ -430,7 +441,7 @@
 			/*Dry snow metamorphism (Marbouty, 1980) grouped model coefficents
 			 *from Marbouty, 1980: Figure 9*/
-			if(W[i]<=0.0+Wtol || (gsp[i]<=0.0+Gdntol && dT[i]>5.0+Ttol)){
+			if(W[i]<=0.0+Wtol || (gsp[i]<=0.0+Gdntol && fabs(dT[i])>5.0+Ttol)){
 				//_printf_("Nondendritic snow metamorphism\n");
-				Q = Marbouty(T[i],d[i],dT[i]);
+				Q = Marbouty(Ti,d[i],dT[i]);
 
 				// calculate grain growth
@@ -568,5 +579,5 @@
 			// spectral range:
 			// 0.3 - 0.8um
-			IssmDouble a0 = min(0.98, 1 - 1.58 *pow(gsz,0.5));
+			IssmDouble a0 = min(0.98, 0.95 - 1.58 *pow(gsz,0.5));
 			// 0.8 - 1.5um
 			IssmDouble a1 = max(0., 0.95 - 15.4 *pow(gsz,0.5));
@@ -694,5 +705,5 @@
 
 }  /*}}}*/
-void thermo(IssmDouble* pEC, IssmDouble** pT, IssmDouble* pulwrf, IssmDouble* re, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlwrf, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble eIdx, IssmDouble teValue, IssmDouble dulwrfValue, IssmDouble teThresh, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid, bool isconstrainsurfaceT, bool isdeltaLWup) { /*{{{*/
+void thermo(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble** pT, IssmDouble* pulwrf, IssmDouble* re, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlwrf, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble tcIdx, IssmDouble eIdx, IssmDouble teValue, IssmDouble dulwrfValue, IssmDouble teThresh, IssmDouble Ws, IssmDouble dt0, IssmDouble dzMin, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid, bool isconstrainsurfaceT, bool isdeltaLWup) { /*{{{*/
 
 	/* ENGLACIAL THERMODYNAMICS*/
@@ -742,13 +753,21 @@
 	IssmDouble* Td = NULL;
 
-	IssmDouble  z0=0.0;	
-	IssmDouble  dt=0.0;
+	IssmDouble z0=0.0;	
+	IssmDouble zT=0.0;
+	IssmDouble zQ=0.0;
+	IssmDouble zratio=1;
+	IssmDouble dt=0.0;
 	IssmDouble max_fdt=0.0;
-	IssmDouble  Ts=0.0;
-	IssmDouble  L=0.0;
-	IssmDouble  eS=0.0;
-	IssmDouble  Ri=0.0;
-	IssmDouble  coefM=0.0;
-	IssmDouble  coefH=0.0;
+	IssmDouble Ts=0.0;
+	IssmDouble L=0.0;
+	IssmDouble eS=0.0;
+	IssmDouble Ri=0.0;
+	IssmDouble coefM=0.0;
+	IssmDouble coefH=0.0;
+	IssmDouble coefHT=0.0;
+	IssmDouble coefHQ=0.0;
+	IssmDouble An_num=0.0;
+	IssmDouble An_den_T=0.0;
+	IssmDouble An_den_Q=0.0;
 	IssmDouble An=0.0;
 	IssmDouble C=0.0;
@@ -759,4 +778,6 @@
 	IssmDouble lhf=0.0;
 	IssmDouble EC_day=0.0;
+	IssmDouble lhf_cum=0.0;
+	IssmDouble shf_cum=0.0;
 	IssmDouble dT_turb=0.0;
 	IssmDouble turb=0.0;
@@ -789,15 +810,21 @@
 	// SURFACE ROUGHNESS (Bougamont, 2006)
 	// wind/temperature surface roughness height [m]
-	if (ds < dIce-Dtol && fabs(Ws) < Wtol) z0 = 0.00012;       // 0.12 mm for dry snow
+	if (ds < dIce-Dtol && Ws < Wtol) z0 = 0.00012;        // 0.12 mm for dry snow
 	else if (ds >= dIce-Dtol) z0 = 0.0032;             // 3.2 mm for ice
 	else z0 = 0.0013;                            // 1.3 mm for wet snow
 
+	//zT and zQ are percentage of z0 (Foken 2008)
+	zratio=10;
+	zT=z0/zratio;
+	zQ=z0/zratio;
+
 	// if V = 0 goes to infinity therfore if V = 0 change
 	if(V<0.01-Dtol)V=0.01;
 
 	// Bulk-transfer coefficient for turbulent fluxes
-	//An =  pow(0.4,2) / pow(log(Tz/z0),2);     // Bulk-transfer coefficient
-	An =  pow(0.4,2) / (log(Tz/z0)*log(Vz/z0));     // Bulk-transfer coefficient
-	C = An * dAir * V;                        // shf & lhf common coefficient
+	An =  pow(0.4,2); // Bulk-transfer coefficient
+	C = An*V;  // shf & lhf common coefficient
+	An_den_T = (log(Tz/zT)*log(Vz/z0)); 
+	An_den_Q = (log(Tz/zQ)*log(Vz/z0)); 
 
 	// THERMAL CONDUCTIVITY (Sturm, 1997: J. Glaciology)
@@ -807,9 +834,14 @@
 	K= xNewZeroInit<IssmDouble>(m);
 
-	// for snow and firn (density < 910 kg m-3) (Sturn et al, 1997)
-	for(int i=0;i<m;i++) if(d[i]<dIce-Dtol) K[i] = 0.138 - 1.01E-3 * d[i] + 3.233E-6 * (pow(d[i],2));
+	// for snow and firn (density < 910 kg m-3) (Sturm et al, 1997) or (Calonne et al., 2011)
+	if (tcIdx == 2){
+		for(int i=0;i<m;i++) if(d[i]<dIce-Dtol) K[i] = 0.024 - 1.23e-4 * d[i] + 2.5e-6 * (pow(d[i],2));
+	}
+	else{ //default (Sturm et al, 1997)
+		for(int i=0;i<m;i++) if(d[i]<dIce-Dtol) K[i] = 0.138 - 1.01e-3 * d[i] + 3.233e-6 * (pow(d[i],2));
+	}
 
 	// for ice (density >= 910 kg m-3)
-	for(int i=0;i<m;i++) if(d[i]>=dIce-Dtol) K[i] = 9.828 * exp(-5.7E-3*T[i]);
+	for(int i=0;i<m;i++) if(d[i]>=dIce-Dtol) K[i] = 9.828 * exp(-5.7e-3*T[i]);
 
 	// THERMAL DIFFUSION COEFFICIENTS
@@ -824,6 +856,6 @@
 	// where neighbor coefficients Au, Ap, & Ad are
 
-	//                   Au = [dz_u/2KP + dz_p/2KE]^-1
-	//                   Ad = [dz_d/2KP + dz_d/2KD]^-1 
+	//                   Au = [dz_u/2KU + dz/2KP]^-1
+	//                   Ad = [dz_d/2KD + dz/2KP]^-1
 	//                   Ap = d*CI*dz/Dt 
 
@@ -836,5 +868,5 @@
 	KP = xNew<IssmDouble>(m);
 
-	KU[0] = Delflag;
+	KU[0] = Delflag; //Thermal conductivity of air = 0.025 W/m/K
 	KD[m-1] = Delflag;
 	for(int i=1;i<m;i++) KU[i]= K[i-1];
@@ -854,5 +886,5 @@
 	// NS: 2.16.18 divided dt by scaling factor, default set to 1/11 for stability
 	dt=1e12; 
-	for(int i=0;i<m;i++)dt = min(dt,CI * pow(dz[i],2) * d[i]  / (3 * K[i]) * thermo_scaling);
+	for(int i=0;i<m;i++) dt = min(dt,CI * pow(dz[i],2) * d[i]  / (3 * K[i]) * thermo_scaling);
 
 	// smallest possible even integer of 60 min where diffusion number > 1/2
@@ -875,13 +907,13 @@
 	Ap = xNew<IssmDouble>(m);
 	for(int i=0;i<m;i++){
-		Au[i] = pow((dzU[i]/2.0/KP[i] + dz[i]/2.0/KU[i]),-1.0);
-		Ad[i] = pow((dzD[i]/2.0/KP[i] + dz[i]/2.0/KD[i]),-1.0);
+		Au[i] = pow((dzU[i]/2.0/KU[i] + dz[i]/2.0/KP[i]),-1.0);
+		Ad[i] = pow((dzD[i]/2.0/KD[i] + dz[i]/2.0/KP[i]),-1.0);
 		Ap[i] = (d[i]*dz[i]*CI)/dt;
 	}
 
 	// create "neighbor" coefficient matrix
-	Nu = xNew<IssmDouble>(m);
-	Nd = xNew<IssmDouble>(m);
-	Np = xNew<IssmDouble>(m);
+	Nu = xNewZeroInit<IssmDouble>(m);
+	Nd = xNewZeroInit<IssmDouble>(m);
+	Np = xNewZeroInit<IssmDouble>(m);
 	for(int i=0;i<m;i++){
 		Nu[i] = Au[i] / Ap[i];
@@ -934,10 +966,5 @@
 
 		// calculate temperature of snow surface (Ts)
-		// when incoming SW radition is allowed to penetrate the surface,
-		// the modeled energy balance becomes very sensitive to how Ts is
-		// calculated.  The estimated enegy balance & melt are significanly
-		// less when Ts is taken as the mean of the x top grid cells.
-		if(m>1) Ts = (T[0] + T[1])/2.0;
-		else Ts = T[0];
+		Ts = T[0];
 		Ts = min(CtoK,Ts);    // don't allow Ts to exceed 273.15 K (0 degC)
 
@@ -950,55 +977,179 @@
 
 		// calculate the Bulk Richardson Number (Ri)
-		Ri = (2.0*9.81* (Vz - z0) * (Ta - Ts)) / ((Ta + Ts)* pow(V,2.0));
-		//Ri = (2.0*9.81*(Ta - Ts)) / ((Tz - z0)*(Ta + Ts)* pow(V/(Vz - z0),2.0));
+		Ri = pow(100000/pAir,0.286)*(2.0*9.81*(Ta - Ts)) / (Tz*(Ta + Ts)* pow(V/(Vz),2.0));
+
+		IssmDouble PhiM;
+		IssmDouble PhiH;
 
 		// calculate Monin-Obukhov stability factors 'coefM' and 'coefH'
-
-		// do not allow Ri to exceed 0.16
-		// Ri = min(Ri, 0.19);
-		Ri = min(Ri, 0.16); //Ohmura, 1982
-
-		// calculate momentum 'coefM' stability factor
-		if (Ri > 0.0+Ttol){
-			// if stable
-			coefM = 1.0/(1.0-5.2*Ri);
-		}
-		else {
-			coefM =pow (1.0-18*Ri,-0.25);
-		}
-
-		// calculate heat/wind 'coef_H' stability factor
-		if (Ri <= -0.03+Ttol) coefH = coefM/1.3;
-		else coefH = coefM;
-
-		//// Sensible Heat
-		// calculate the sensible heat flux [W m-2](Patterson, 1998)
-		shf = C * CA * (Ta - Ts);
-
-		// adjust using Monin-Obukhov stability theory
-		shf = shf / (coefM * coefH);
-
-		//// Latent Heat
-		// determine if snow pack is melting & calcualte surface vapour pressure over ice or liquid water
-		if (Ts >= CtoK-Ttol){
-			L = LV; //for liquid water at 273.15 k to vapor
-
-			//for liquid surface (assume liquid on surface when Ts == 0 deg C)
-			// Wright (1997), US Meteorological Handbook from Murphy and Koop, 2005 Appendix A
-			eS = 611.21 * exp(17.502 * (Ts - CtoK) / (240.97 + Ts - CtoK));
-		}
-		else{
-			L = LS; // latent heat of sublimation 
-
-			// for an ice surface Murphy and Koop, 2005 [Equation 7]
-			eS = exp(9.550426 - 5723.265/Ts + 3.53068 * log(Ts) - 0.00728332 * Ts);
-		}
-
-		// Latent heat flux [W m-2]
-		lhf = C * L * (eAir - eS) * 0.622 / pAir;
-
-		// adjust using Monin-Obukhov stability theory (if lhf '+' then there is energy and mass gained at the surface, 
-		// if '-' then there is mass and energy loss at the surface.
-		lhf = lhf / (coefM * coefH);
+		if (false){
+			// do not allow Ri to exceed 0.16
+			Ri = min(Ri, 0.16); //Ohmura, 1982
+
+			// calculate momentum 'coefM' stability factor
+			if (Ri > 0.0+Ttol){
+				// if stable
+				coefM = 1.0/(1.0-5.2*Ri);
+			}
+			else {
+				coefM =pow (1.0-18*Ri,-0.25);
+			}
+
+			// calculate heat/wind 'coef_H' stability factor
+			if (Ri <= -0.03+Ttol) coefH = coefM/1.3;
+			else coefH = coefM;
+
+         coefHT = coefH*An_den_T;
+         coefHQ = coefH*An_den_Q;
+
+		}
+		else if(false){
+
+			// do not allow Ri to exceed 0.19
+			Ri = min(Ri, 0.19); //Ohmura, 1982
+
+			// calculate momentum 'coefM' stability factor
+			if (Ri > 0.0+Ttol){
+				// if stable
+				//coefM = pow(1.0-5.0*Ri,2.0); //Fitzpatrick et al., 2017, from Brock et al., 2010
+				coefM=1+5.3*min((Ri/(1-5*Ri)),0.5);
+				coefH=1+8*min((Ri/(1-5*Ri)),0.5);
+			}
+			else {
+				//coefM =pow(1.0-16.0*max(Ri,-1.0),0.75); //Fitzpatrick et al., 2017, from Brock et al., 2010
+				coefM=pow(1-19*max(Ri/1.5,-2.0),-0.25);
+				coefH=0.95*pow(1-11.6*max(Ri/1.5,-2.0),-0.5);
+			}
+
+			coefHT = coefH*An_den_T;
+			coefHQ = coefH*An_den_Q;
+
+		}
+      else if (false){
+         // Greuell and Konzelman, 1994
+         // calculate momentum 'coefM' stability factor
+
+         if (Ri > 0.0+Ttol){
+            // if stable
+            coefM=1+15*Ri*pow(1+Ri,1/2);
+            coefH=1;
+         }
+         else {
+            coefM=pow(1-15*Ri/(1+75*pow(0.4/log(Tz/zT),2)*pow(Tz/zT*fabs(Ri),1/2)),-1);
+            coefH=1;
+         }
+
+         coefHT = coefH*An_den_T;
+         coefHQ = coefH*An_den_Q;
+
+      }
+      else {
+         IssmDouble a1=1.0;
+         IssmDouble b1=2/3;
+         IssmDouble c1=5.0;
+         IssmDouble d1=0.35;
+         IssmDouble PhiMz;
+         IssmDouble PhiHz;
+         IssmDouble PhiMz0=0.0;
+         IssmDouble PhiHzT=0.0;
+         IssmDouble PhiHzQ=0.0;
+         IssmDouble zL;
+         IssmDouble zLT;
+         IssmDouble zLM;
+
+         if (Ri > 0.0+Ttol){
+            // if stable
+
+            if(Ri < 0.2-Ttol){
+               zL = Ri/(1-5*Ri);
+            }
+            else{
+               zL=Ri;
+            }
+            //zL = min(zL, 0.5); //Sjoblom, 2014
+            zLM=max(zL/Vz*z0,1e-3);
+            zLT=max(zL/Tz*zT,1e-3);
+
+            //Ding et al. 2020, from Beljaars and Holtslag (1991)
+            PhiMz=-1*(a1*zL + b1*(zL-c1/d1)*exp(-1*d1*zL) + b1*c1/d1);
+            PhiHz=-1*(pow(1+2*a1*zL/3,1.5) + b1*(zL-c1/d1)*exp(-1*d1*zL) + b1*c1/d1 - 1);
+            PhiMz0=-1*(a1*zLM + b1*(zLM-c1/d1)*exp(-1*d1*zLM) + b1*c1/d1);
+            PhiHzT=-1*(pow(1+2*a1*zLT/3,1.5) + b1*(zLT-c1/d1)*exp(-1*d1*zLT) + b1*c1/d1 - 1);
+
+            PhiHzQ=PhiHzT;
+         }
+         else {
+            IssmDouble xm;
+            IssmDouble xh;
+            IssmDouble xmT;
+            IssmDouble xmM;
+
+            zL = Ri/1.5; //max(Ri, -0.5+Ttol)/1.5; //Hogstrom (1996)
+            //zL = max(zL, -2.0); //Sjoblom, 2014
+            zLM=min(zL/Vz*z0,-1e-3);
+            zLT=min(zL/Tz*zT,-1e-3);
+
+            if (true){ //Sjoblom, 2014
+               xm=pow(1.0-19*zL,-0.25);
+               PhiMz=2*log((1+xm)/2.0) + log((1+pow(xm,2))/2.0) - 2*atan(xm) + Pi/2;
+
+               xh=0.95*pow(1.0-11.6*zL,-0.5);
+               PhiHz=2*log((1+pow(xh,2))/2.0);
+            }
+            else{ //Ding et al., 2020
+               xm=pow(1.0-16*zL,0.25);
+               xmM=pow(1.0-16*zLM,0.25);
+               xmT=pow(1.0-16*zLT,0.25);
+               PhiMz=2*log((1+xm)/2.0) + log((1+pow(xm,2))/2.0) - 2*atan(xm) + Pi/2;
+               PhiMz0=2*log((1+xmM)/2.0) + log((1+pow(xmM,2))/2.0) - 2*atan(xmM) + Pi/2;
+
+               PhiHz=2*log((1+pow(xm,2))/2.0);
+               PhiHzT=2*log((1+pow(xmT,2))/2.0);
+
+               PhiHzQ=PhiHzT;
+            }
+         }
+
+         PhiM=PhiMz;
+         PhiH=PhiHz;
+         coefM = log(Vz/z0) - PhiMz + PhiMz0; //Ding et al., 2019
+         coefHT = log(Tz/zT) - PhiHz + PhiHzT; //Sjoblom, 2014, after Foken 2008
+         coefHQ = log(Tz/zQ) - PhiHz + PhiHzQ; //Sjoblom, 2014, after Foken 2008
+
+      }
+
+      //// Sensible Heat
+      // calculate the sensible heat flux [W m-2](Patterson, 1998)
+      shf = dAir * C * CA * (Ta - Ts) * pow(100000/pAir,0.286);
+
+      // adjust using Monin-Obukhov stability theory
+      shf = shf/(coefM*coefHT);
+
+      //// Latent Heat
+      // determine if snow pack is melting & calcualte surface vapour pressure over ice or liquid water
+      if (Ts >= CtoK-Ttol){
+         L = LV; //for liquid water at 273.15 k to vapor
+
+         //for liquid surface (assume liquid on surface when Ts == 0 deg C)
+         // Wright (1997), US Meteorological Handbook from Murphy and Koop, 2005 Appendix A
+         //eS = 611.21 * exp(17.502 * (Ts - CtoK) / (240.97 + Ts - CtoK));
+         // Murray 1967, https://cran.r-project.org/web/packages/humidity/vignettes/humidity-measures.html
+         eS = 610.78 * exp(17.2693882 * (Ts - CtoK - 0.01) / (Ts - 35.86));
+      }
+      else{
+         L = LS; // latent heat of sublimation
+
+         // for an ice surface Murphy and Koop, 2005 [Equation 7]
+         //eS = exp(9.550426 - 5723.265/Ts + 3.53068 * log(Ts) - 0.00728332 * Ts);
+         // for an ice surface Ding et al., 2019 after Bolton, 1980
+         eS = 610.78 * exp(21.8745584 * (Ts - CtoK - 0.01) / (Ts - 7.66));
+      }
+
+      // Latent heat flux [W m-2]
+      lhf = C * L * (eAir - eS) / (461.9*(Ta+Ts)/2);
+
+      // adjust using Monin-Obukhov stability theory (if lhf '+' then there is energy and mass gained at the surface,
+      // if '-' then there is mass and energy loss at the surface.
+      lhf = lhf/(coefM*coefHQ);
 
 		//mass loss (-)/acreation(+) due to evaporation/condensation [kg]
@@ -1025,9 +1176,13 @@
 
 		//SW penetrates surface
-		if(!isconstrainsurfaceT) for(int j=0;j<m;j++) T[j] = T[j] + dT_sw[j];
-		if(!isconstrainsurfaceT) T[0] = T[0] + dT_dlw + dT_ulw + dT_turb;
+		if(!isconstrainsurfaceT){
+			for(int j=0;j<m;j++) T[j] = T[j] + dT_sw[j];
+			T[0] = T[0] + dT_dlw + dT_ulw + dT_turb;
+		}
 
 		// temperature diffusion
 		for(int j=0;j<m;j++) T0[1+j]=T[j];
+		T0[0]=Ta;
+		T0[m+1]=T[m-1];
 		for(int j=0;j<m;j++) Tu[j] = T0[j];
 		for(int j=0;j<m;j++) Td[j] = T0[2+j];
@@ -1036,4 +1191,6 @@
 		// calculate cumulative evaporation (+)/condensation(-)
 		if(!isconstrainsurfaceT) EC = EC + (EC_day/dts)*dt;
+		lhf_cum=lhf_cum+lhf*dt/dt0;
+		shf_cum=shf_cum+shf*dt/dt0;
 
 		/* CHECK FOR ENERGY (E) CONSERVATION [UNITS: J]
@@ -1073,4 +1230,6 @@
 	/*Assign output pointers:*/
 	*pEC=EC;
+	*plhf=lhf_cum;
+	*pshf=shf_cum;
 	*pT=T;
 	*pulwrf=ulwrf;
@@ -1111,5 +1270,5 @@
 
 	// SHORTWAVE FUNCTION
-	if (swIdx == 0) {// all sw radation is absorbed in by the top grid cell
+	if (swIdx == 0 | (dIce - d[0])<Dtol) {// all sw radation is absorbed in by the top grid cell
 
 		// calculate surface shortwave radiation fluxes [W m-2]
@@ -1154,5 +1313,5 @@
 			// spectral albedos:
 			// 0.3 - 0.8um
-			IssmDouble a0 = min(0.98, 1.0 - 1.58 *pow(gsz[0],0.5));
+			IssmDouble a0 = min(0.98, 0.95 - 1.58 *pow(gsz[0],0.5));
 			// 0.8 - 1.5um
 			IssmDouble a1 = max(0.0, 0.95 - 15.4 *pow(gsz[0],0.5));
@@ -1308,7 +1467,7 @@
 	// specify constants
 	IssmDouble dSnow = 150;    // density of snow [kg m-3]
-	const IssmDouble reNew = 0.05;    // new snow grain size [mm]
-	const IssmDouble gdnNew = 1.0;     // new snow dendricity 
-	const IssmDouble gspNew = 0.5;   // new snow sphericity 
+	IssmDouble reNew = 0.05;    // new snow grain size [mm]
+	IssmDouble gdnNew = 1.0;     // new snow dendricity 
+	IssmDouble gspNew = 0.5;   // new snow sphericity 
 
 	/*intermediary: */
@@ -1359,4 +1518,8 @@
 		case 2: // Density of Greenland snow, Fausto et al., 2018
 			dSnow = 315;
+			//From Vionnet et al., 2012 (Crocus)
+			gdnNew = min(max(1.29 - 0.17*V,0.20),1.0);
+			gspNew = min(max(0.08*V + 0.38,0.5),0.9);
+			reNew=max(1e-1*(gdnNew/.99+(1-1*gdnNew/.99)*(gspNew/.99*3+(1-gspNew/.99)*4))/2,Gdntol);
 			break;
 
@@ -1386,9 +1549,4 @@
 			IssmDouble sfall = gspNew;
 			IssmDouble refall = reNew;
-
-			//From Vionnet et al., 2012 (Crocus)
-			dfall = min(max(1.29 - 0.17*V,0.20),1.0);
-			sfall = min(max(0.08*V + 0.38,0.5),0.9);
-			refall = max((0.1 + (1.0-dfall)*0.25 + (0.5-sfall)*0.1)/2.0,Gdntol);
 
 			// if snow depth is greater than specified min dz, new cell created
@@ -1419,7 +1577,7 @@
 				// adjust a, re, gdn & gsp
 				if(aIdx>0)a[0] = (aSnow * P + a[0] * mInit[0])/mass;
-				gdn[0] = (dfall * P + gdn[0] * mInit[0])/mass;
-				gsp[0] = (sfall * P + gsp[0] * mInit[0])/mass;
-				re[0] = max((0.1 + (1.0-gdn[0])*0.25 + (0.5-gsp[0])*0.1)/2.0,Gdntol);
+				gdn[0] = dfall; 
+				gsp[0] = sfall; 
+				re[0] = max(1e-1*(gdn[0]/.99+(1-1*gdn[0]/.99)*(gsp[0]/.99*3+(1-gsp[0]/.99)*4))/2,Gdntol);
 			}
 		}
@@ -1512,27 +1670,4 @@
 	IssmDouble X=0.0;
 	IssmDouble Wi=0.0;
-
-	IssmDouble Ztot=0.0;
-	IssmDouble T_bot=0.0;
-	IssmDouble m_bot=0.0;
-	IssmDouble dz_bot=0.0;
-	IssmDouble d_bot=0.0;
-	IssmDouble W_bot=0.0;
-	IssmDouble a_bot=0.0;
-	IssmDouble adiff_bot=0.0;
-	IssmDouble re_bot=0.0;
-	IssmDouble gdn_bot=0.0;
-	IssmDouble gsp_bot=0.0;
-	IssmDouble EI_bot=0.0;
-	IssmDouble EW_bot=0.0;
-	bool        top=false;
-
-	IssmDouble* Zcum=NULL;
-	IssmDouble* dzMin2=NULL;
-	IssmDouble* dzMax2=NULL;
-	IssmDouble zY2=zY;
-	bool lastCellFlag = false;
-	int X1=0;
-	int X2=0;
 
 	int        D_size = 0;
@@ -1828,4 +1963,109 @@
 	xDelete<IssmDouble>(F);
 
+	//Manage the layering to match the user defined requirements
+	managelayers(&mAdd, &dz_add, &addE, &m, &EI, &EW, &T, &d, &dz, &W, &a, &adiff, &re, &gdn, &gsp, &n, dzMin, zMax, zMin, zTop, zY);
+
+	//// CHECK FOR MASS AND ENERGY CONSERVATION
+
+	// calculate final mass [kg] and energy [J]
+	sumER = Rsum * (LF + CtoK * CI);
+	for(int i=0;i<n;i++)EI[i] = m[i] * T[i] * CI;
+	for(int i=0;i<n;i++)EW[i] = W[i] * (LF + CtoK * CI);
+
+	mSum1 = cellsum(W,n) + cellsum(m,n) + Rsum;
+	sumE1 = cellsum(EI,n) + cellsum(EW,n);
+
+	/*checks: */
+	for(int i=0;i<n;i++) if (W[i]<0.0-Wtol) _error_("negative pore water generated in melt equations\n");
+
+	/*only in forward mode! avoid round in AD mode as it is not differentiable: */
+	#ifndef _HAVE_AD_
+	dm = round((mSum0 - mSum1 + mAdd)*100.0)/100.0;
+	dE = round(sumE0 - sumE1 - sumER +  addE - surplusE);
+	if (dm !=0  || dE !=0) _error_("mass or energy are not conserved in melt equations\n"
+			<< "dm: " << dm << " dE: " << dE << "\n");
+	#endif
+
+	/*Free resources:*/
+	if(m)xDelete<IssmDouble>(m);
+	if(EI)xDelete<IssmDouble>(EI);
+	if(EW)xDelete<IssmDouble>(EW);
+	if(maxF)xDelete<IssmDouble>(maxF);
+	if(dW)xDelete<IssmDouble>(dW);
+	if(exsW)xDelete<IssmDouble>(exsW);
+	if(exsT)xDelete<IssmDouble>(exsT);
+	if(surpT)xDelete<IssmDouble>(surpT);
+	if(surpE)xDelete<IssmDouble>(surpE);
+	if(flxDn)xDelete<IssmDouble>(flxDn);
+	if(D)xDelete<int>(D);
+	if(M)xDelete<IssmDouble>(M);
+
+	/*Assign output pointers:*/
+	*pMs=Msurf;
+	*pM=sumM;
+	*pR=Rsum;
+	*pF=Fsum;
+	*pmAdd=mAdd;
+	*pdz_add=dz_add;
+
+	*pT=T;
+	*pd=d;
+	*pdz=dz;
+	*pW=W;
+	*pa=a;
+	*padiff=adiff;
+	*pre=re;
+	*pgdn=gdn;
+	*pgsp=gsp;
+	*pn=n;
+
+} /*}}}*/ 
+void managelayers(IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble* paddE, IssmDouble** pm, IssmDouble** pEI, IssmDouble** pEW, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** padiff, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, IssmDouble zY){ /*{{{*/
+
+	/*intermediary:*/
+	IssmDouble* Zcum=NULL;
+	IssmDouble* dzMin2=NULL;
+	IssmDouble* dzMax2=NULL;
+	int*        D=NULL;
+
+	IssmDouble zY2=zY;
+	IssmDouble X=0.0;
+	int X1=0;
+	int X2=0;
+	int D_size = 0;
+
+	IssmDouble Ztot=0.0;
+	IssmDouble T_bot=0.0;
+	IssmDouble m_bot=0.0;
+	IssmDouble dz_bot=0.0;
+	IssmDouble d_bot=0.0;
+	IssmDouble W_bot=0.0;
+	IssmDouble a_bot=0.0;
+	IssmDouble adiff_bot=0.0;
+	IssmDouble re_bot=0.0;
+	IssmDouble gdn_bot=0.0;
+	IssmDouble gsp_bot=0.0;
+	IssmDouble EI_bot=0.0;
+	IssmDouble EW_bot=0.0;
+	bool       top=false;
+
+	/*outputs:*/
+	IssmDouble  mAdd = 0.0;
+	IssmDouble  addE = 0.0;
+	IssmDouble  dz_add = 0.0;
+	IssmDouble* T=*pT;
+	IssmDouble* d=*pd;
+	IssmDouble* dz=*pdz;
+	IssmDouble* W=*pW;
+	IssmDouble* a=*pa;
+	IssmDouble* adiff=*padiff;
+	IssmDouble* re=*pre;
+	IssmDouble* gdn=*pgdn;
+	IssmDouble* gsp=*pgsp;
+	IssmDouble* m=*pm;
+	IssmDouble* EI=*pEI;
+	IssmDouble* EW=*pEW;
+	int         n=*pn;
+
 	//Merging of cells as they are burried under snow.
 	Zcum=xNew<IssmDouble>(n);
@@ -1875,7 +2115,8 @@
 			a[X1] = (a[X2]*m[X2] + a[X1]*m[X1]) / m_new;
 			adiff[X1] = (adiff[X2]*m[X2] + adiff[X1]*m[X1]) / m_new;
-			re[X1] = (re[X2]*m[X2] + re[X1]*m[X1]) / m_new;
-			gdn[X1] = (gdn[X2]*m[X2] + gdn[X1]*m[X1]) / m_new;
-			gsp[X1] = (gsp[X2]*m[X2] + gsp[X1]*m[X1]) / m_new;
+         //use grain properties from lower cell
+			re[X1] = re[X2]; 
+			gdn[X1] = gdn[X2]; 
+			gsp[X1] = gsp[X2]; 
 
 			// merge with underlying grid cell and delete old cell
@@ -2019,50 +2260,11 @@
 	}
 
-	//// CHECK FOR MASS AND ENERGY CONSERVATION
-
-	// calculate final mass [kg] and energy [J]
-	sumER = Rsum * (LF + CtoK * CI);
-	for(int i=0;i<n;i++)EI[i] = m[i] * T[i] * CI;
-	for(int i=0;i<n;i++)EW[i] = W[i] * (LF + CtoK * CI);
-
-	mSum1 = cellsum(W,n) + cellsum(m,n) + Rsum;
-	sumE1 = cellsum(EI,n) + cellsum(EW,n);
-
-	/*checks: */
-	for(int i=0;i<n;i++) if (W[i]<0.0-Wtol) _error_("negative pore water generated in melt equations\n");
-
-	/*only in forward mode! avoid round in AD mode as it is not differentiable: */
-	#ifndef _HAVE_AD_
-	dm = round((mSum0 - mSum1 + mAdd)*100.0)/100.0;
-	dE = round(sumE0 - sumE1 - sumER +  addE - surplusE);
-	if (dm !=0  || dE !=0) _error_("mass or energy are not conserved in melt equations\n"
-			<< "dm: " << dm << " dE: " << dE << "\n");
-	#endif
-
 	/*Free resources:*/
-	if(m)xDelete<IssmDouble>(m);
-	if(EI)xDelete<IssmDouble>(EI);
-	if(EW)xDelete<IssmDouble>(EW);
-	if(maxF)xDelete<IssmDouble>(maxF);
-	if(dW)xDelete<IssmDouble>(dW);
-	if(exsW)xDelete<IssmDouble>(exsW);
-	if(exsT)xDelete<IssmDouble>(exsT);
-	if(surpT)xDelete<IssmDouble>(surpT);
-	if(surpE)xDelete<IssmDouble>(surpE);
-	if(flxDn)xDelete<IssmDouble>(flxDn);
-	if(D)xDelete<int>(D);
-	if(M)xDelete<IssmDouble>(M);
  	xDelete<IssmDouble>(Zcum);
 	xDelete<IssmDouble>(dzMin2);
 	xDelete<IssmDouble>(dzMax2);
+	if(D)xDelete<int>(D);
 
 	/*Assign output pointers:*/
-	*pMs=Msurf;
-	*pM=sumM;
-	*pR=Rsum;
-	*pF=Fsum;
-	*pmAdd=mAdd;
-	*pdz_add=dz_add;
-
 	*pT=T;
 	*pd=d;
@@ -2075,4 +2277,11 @@
 	*pgsp=gsp;
 	*pn=n;
+	*pm=m;
+	*pEI=EI;
+	*pEW=EW;
+
+	*pmAdd=mAdd;
+	*paddE=addE;
+	*pdz_add=dz_add;
 
 } /*}}}*/ 
@@ -2128,7 +2337,9 @@
 	IssmDouble c0=0.0;
 	IssmDouble c1=0.0;
+   IssmDouble c2=0.0;
 	IssmDouble H=0.0;
 	IssmDouble M0=0.0;
 	IssmDouble M1=0.0;
+   IssmDouble M2=0.0;
 	IssmDouble c0arth=0.0;
 	IssmDouble c1arth=0.0;
@@ -2206,10 +2417,7 @@
 				if (aIdx==1 && swIdx==0){
 					if (fabs(adThresh - 820) < Dtol){
-						// ERA5 new aIdx=1, swIdx=0, MODIS 820
-						//M0 = max(1.8230 - (0.1645 * log(C)),0.25);
-						//M1 = max(2.5134 - (0.3244 * log(C)),0.25);
-						// ERA5 new aIdx=1, swIdx=0, MODIS 820, p90 new (ERA5, 40 and e97)
-						M0 = max(1.3045 - (0.0988 * log(C)),0.25);
-						M1 = max(1.3694 - (0.1354 * log(C)),0.25);
+                  // ERA5 v4
+                  M0 = max(1.5131 - (0.1317 * log(C)),0.25);
+                  M1 = max(1.8819 - (0.2158 * log(C)),0.25);
 					}
 					else{
@@ -2234,9 +2442,10 @@
 				//M0 = max(1.435 - (0.151 * log(C)),0.25);
 				//M1 = max(2.366 - (0.293 * log(C)),0.25);
-				//RACMO
-				M0 = max(1.6599 - (0.1724 * log(C)),0.25);
-				M1 = max(2.0102 - (0.2458 * log(C)),0.25);
+            //RACMO
+            M0 = max(1.6383 - (0.1691 * log(C)),0.25);
+            M1 = max(1.9991 - (0.2414 * log(C)),0.25);
 				c0 = M0*c0arth;
 				c1 = M1*c1arth;
+				c2 = M2*c1arth;
 				break;
 
@@ -2253,10 +2462,7 @@
 				if (aIdx==1 && swIdx==0){
 					if (fabs(adThresh - 820) < Dtol){
-						// ERA5 new aIdx=1, swIdx=0, MODIS 820
-						//M0 = max(1.4174 - (0.1037 * log(C)),0.25);
-						//M1 = max(2.2010 - (0.2460 * log(C)),0.25);
-						// ERA5 new aIdx=1, swIdx=0, MODIS 820, p90 new (ERA5 lwt, 40 and e97)
-						M0 = max(1.2138 - (0.1057 * log(C)),0.25);
-						M1 = max(1.4946 - (0.1607 * log(C)),0.25);
+						// ERA5 v4
+						M0 = max(1.3566 - (0.1350 * log(C)),0.25);
+						M1 = max(1.8705 - (0.2290 * log(C)),0.25);
 					}
 					else{
@@ -2281,16 +2487,16 @@
 				//M1 = max(1.734 - (0.2039 * log(C)),0.25);
 				// RACMO
-				M0 = max(1.6201 - (0.1450 * log(C)),0.25);
-				M1 = max(2.5577 - (0.2899 * log(C)),0.25);
-				c0 = M0*c0arth;
-				c1 = M1*c1arth;
+            M0 = max(1.2691 - (0.1184 * log(C)),0.25);
+            M1 = max(1.9983 - (0.2511 * log(C)),0.25);
+            c0 = M0*c0arth;
+            c1 = M1*c1arth;
+            c2 = M2*c1arth;
 				break;
 		}
 
-		// new snow density
-		if(d[i] <= 550.0+Dtol) d[i] = d[i] + (c0 * (dIce - d[i]) / 365.0 * dt);
-		else            d[i] = d[i] + (c1 * (dIce - d[i]) / 365.0 * dt);
-
-		//disp((num2str(nanmean(c0 .* (dIce - d(idx)) / 365 * dt))))
+      // new snow density
+      if(d[i] <= 550.0+Dtol) d[i] = d[i] + (c0 * (dIce - d[i]) / 365.0 * dt);
+      else if(d[i] <= 830.0+Dtol | fabs(c2)<Dtol) d[i] = d[i] + (c1 * (dIce - d[i]) / 365.0 * dt);
+      else d[i] = d[i] + (c2 * (dIce - d[i]) / 365.0 * dt);
 
 		// do not allow densities to exceed the density of ice
@@ -2311,129 +2517,2 @@
 
 } /*}}}*/
-void turbulentFlux(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble Ta, IssmDouble Ts, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble ds, IssmDouble Ws, IssmDouble Vz, IssmDouble Tz, IssmDouble dIce, int sid){ /*{{{*/
-
-	//// TURBULENT HEAT FLUX
-
-	// Description: 
-	// computed the surface sensible and latent heat fluxes [W m-2], this
-	// function also calculated the mass loss/acreation due to
-	// condensation/evaporation [kg]
-
-	// Reference: 
-	// Dingman, 2002.
-
-	//// INPUTS:
-	//   Ta: 2m air temperature [K]
-	//   Ts: snow/firn/ice surface temperature [K]
-	//   V: wind speed [m s^-^1]
-	//   eAir: screen level vapor pressure [Pa]
-	//   pAir: surface pressure [Pa]
-	//   ds: surface density [kg/m^3]
-	//   Ws: surface liquid water content [kg/m^2]
-	//   Vz: height above ground at which wind (V) eas sampled [m]
-	//   Tz: height above ground at which temperature (T) was sampled [m]
-
-	/*intermediary:*/
-	IssmDouble d_air=0.0;
-	IssmDouble Ri=0.0;
-	IssmDouble z0=0.0;
-	IssmDouble coef_M=0.0;
-	IssmDouble coef_H=0.0;
-	IssmDouble An=0.0;
-	IssmDouble C=0.0;
-	IssmDouble L=0.0;
-	IssmDouble eS=0.0;
-
-	/*output: */
-	IssmDouble shf=0.0;
-	IssmDouble lhf=0.0;
-	IssmDouble EC=0.0;
-
-	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   turbulentFlux module\n");
-
-	// calculated air density [kg/m3]
-	d_air = 0.029 * pAir /(R * Ta);
-
-	//// Determine Surface Roughness
-	// Bougamont, 2006
-	// wind/temperature surface roughness height [m]
-	if (ds < dIce-Dtol && fabs(Ws) < Wtol) z0 = 0.00012;               // 0.12 mm for dry snow
-	else if (ds >= dIce-Dtol) z0 = 0.0032;                // 3.2 mm for ice 
-	else z0 = 0.0013;                // 1.3 mm for wet snow
-
-	//// Monin-Obukhov Stability Correction
-	// Reference:
-	// Ohmura, A., 1982: Climate and Energy-Balance on the Arctic Tundra.
-	// Journal of Climatology, 2, 65-84.
-
-	// if V = 0 goes to infinity therfore if V = 0 change
-	if(V< 0.01-Dtol)V=0.01;
-
-	// calculate the Bulk Richardson Number (Ri)
-	Ri = (2.0*9.81* (Vz - z0) * (Ta - Ts)) / ((Ta + Ts)* pow(V,2.0));
-	//Ri = (2.0*9.81*(Ta - Ts)) / ((Tz - z0)*(Ta + Ts)* pow(V/(Vz - z0),2.0));
-
-	// calculate Monin-Obukhov stability factors 'coefM' and 'coefH'
-
-	// do not allow Ri to exceed 0.16
-	// Ri = min(Ri, 0.19);
-	Ri = min(Ri, 0.16); //Ohmura, 1982
-
-	// calculate momentum 'coefM' stability factor
-	if (Ri > 0.0+Ttol){
-		// if stable
-		coef_M = 1.0/(1.0-5.2*Ri);
-	}
-	else {
-		coef_M =pow (1.0-18*Ri,-0.25);
-	}
-
-	// calculate heat/wind 'coef_H' stability factor
-	if (Ri <= -0.03+Ttol) coef_H = coef_M/1.3;
-	else coef_H = coef_M;
-
-	//// Bulk-transfer coefficient
-	//An =  pow(0.4,2) / pow(log(Tz/z0),2);     // Bulk-transfer coefficient
-	An =  pow(0.4,2) / (log(Tz/z0)*log(Vz/z0));     // Bulk-transfer coefficient
-	C = An * d_air * V;             // shf & lhf common coefficient
-
-	//// Sensible Heat
-	// calculate the sensible heat flux [W m-2](Patterson, 1998)
-	shf = C * CA * (Ta - Ts);
-
-	// adjust using Monin-Obukhov stability theory
-	shf = shf / (coef_M * coef_H);
-
-	// Latent Heat
-	// determine if snow pack is melting & calcualte surface vapour pressure over ice or liquid water
-	if (Ts >= CtoK-Ttol){
-		L = LV; //for liquid water at 273.15 k to vapor
-
-		//for liquid surface (assume liquid on surface when Ts == 0 deg C)
-		// Wright (1997), US Meteorological Handbook from Murphy and Koop, 2005 Appendix A
-		eS = 611.21 * exp(17.502 * (Ts - CtoK) / (240.97 + Ts - CtoK));
-	}
-	else{
-		L = LS; // latent heat of sublimation
-
-		// for an ice surface Murphy and Koop, 2005 [Equation 7]
-		eS = exp(9.550426 - 5723.265/Ts + 3.53068 * log(Ts) - 0.00728332 * Ts);
-	}
-
-	// Latent heat flux [W m-2]
-	lhf = C * L * (eAir - eS) * 0.622 / pAir;
-
-	// adjust using Monin-Obukhov stability theory (if lhf '+' then there is
-	// energy and mass gained at the surface, if '-' then there is mass and 
-	// energy loss at the surface. 
-	lhf = lhf / (coef_M * coef_H);
-
-	// mass loss (-)/acreation(+) due to evaporation/condensation [kg]
-	EC = lhf * dts / L;
-
-	/*assign output poitners: */
-	*pshf=shf;
-	*plhf=lhf;
-	*pEC=EC;
-
-} /*}}}*/
Index: issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h
===================================================================
--- issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 27035)
+++ issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 27232)
@@ -34,8 +34,8 @@
 void albedo(IssmDouble** a, IssmDouble** adiff, int aIdx, IssmDouble* re, IssmDouble* dz, IssmDouble* d, IssmDouble cldFrac, IssmDouble aIce, IssmDouble aSnow, IssmDouble aValue, IssmDouble adThresh, IssmDouble* T, IssmDouble* W, IssmDouble P, IssmDouble EC, IssmDouble Msurf, IssmDouble clabSnow, IssmDouble clabIce, IssmDouble SZA, IssmDouble COT, IssmDouble t0wet, IssmDouble t0dry, IssmDouble K, IssmDouble dt, IssmDouble dIce, int m, int sid);
 void shortwave(IssmDouble** pswf, int swIdx, int aIdx, IssmDouble dsw, IssmDouble dswdiff, IssmDouble as, IssmDouble asdiff, IssmDouble* d, IssmDouble* dz, IssmDouble* re, IssmDouble dIce, int m, int sid);
-void thermo(IssmDouble* pEC, IssmDouble** T, IssmDouble* pulwrf, IssmDouble* re, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlw, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble eIdx, IssmDouble teValue, IssmDouble dulwrfValue, IssmDouble teThresh, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid, bool isconstrainsurfaceT, bool isdeltaLWup);
+void thermo(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble** T, IssmDouble* pulwrf, IssmDouble* re, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlw, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble tcIdx, IssmDouble eIdx, IssmDouble teValue, IssmDouble dulwrfValue, IssmDouble teThresh, IssmDouble Ws, IssmDouble dt0, IssmDouble dzMin, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid, bool isconstrainsurfaceT, bool isdeltaLWup);
 void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** padiff, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, IssmDouble* pRa, int* pm, int aIdx, int dsnowIdx, IssmDouble Tmean, IssmDouble Ta, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, IssmDouble C, IssmDouble V, IssmDouble Vmean, IssmDouble dIce, int sid);
 void melt(IssmDouble* pM, IssmDouble* pMs, IssmDouble* pR, IssmDouble* pF, IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** padiff, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble Ra, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, IssmDouble zY, IssmDouble dIce, int sid);
+void managelayers(IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble* paddE, IssmDouble** pm, IssmDouble** pEI, IssmDouble** pEW, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** padiff, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, IssmDouble zY);
 void densification(IssmDouble** pd,IssmDouble** pdz, IssmDouble* T, IssmDouble* re, int denIdx, int aIdx, int swIdx, IssmDouble adThresh, IssmDouble C, IssmDouble dt, IssmDouble Tmean, IssmDouble dIce, int m, int sid);
-void turbulentFlux(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble Ta, IssmDouble Ts, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble ds, IssmDouble Ws, IssmDouble Vz, IssmDouble Tz, IssmDouble dIce, int sid);
 #endif  /* _SurfaceMassBalancex_H*/
Index: issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 27232)
@@ -27,5 +27,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<IssmDouble>(yg_serial);
 }
Index: issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp
===================================================================
--- issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp	(revision 27035)
+++ issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp	(revision 27232)
@@ -34,5 +34,5 @@
 	IssmDouble* z=vz->ToMPISerial();
 
-	/*Free ressources: */
+	/*Free resources: */
 	delete vx;
 	delete vy;
Index: issm/trunk/src/c/modules/modules.h
===================================================================
--- issm/trunk/src/c/modules/modules.h	(revision 27035)
+++ issm/trunk/src/c/modules/modules.h	(revision 27232)
@@ -33,5 +33,4 @@
 #include "./GetVectorFromControlInputsx/GetVectorFromControlInputsx.h"
 #include "./GiaDeflectionCorex/GiaDeflectionCorex.h"
-#include "./FourierLoveCorex/FourierLoveCorex.h"
 #include "./SetControlInputsFromVectorx/SetControlInputsFromVectorx.h"
 #include "./SetActiveNodesLSMx/SetActiveNodesLSMx.h"
Index: issm/trunk/src/c/shared/Enum/Enum.vim
===================================================================
--- issm/trunk/src/c/shared/Enum/Enum.vim	(revision 27035)
+++ issm/trunk/src/c/shared/Enum/Enum.vim	(revision 27232)
@@ -17,4 +17,7 @@
 syn keyword cConstant ParametersSTARTEnum
 syn keyword cConstant AdolcParamEnum
+syn keyword cConstant AgeStabilizationEnum
+syn keyword cConstant AgeNumRequestedOutputsEnum
+syn keyword cConstant AgeRequestedOutputsEnum
 syn keyword cConstant AmrDeviatoricErrorGroupThresholdEnum
 syn keyword cConstant AmrDeviatoricErrorMaximumEnum
@@ -115,8 +118,10 @@
 syn keyword cConstant CalvingTestIndependentRateEnum
 syn keyword cConstant CalvingUseParamEnum
-syn keyword cConstant CalvingScaleThetaEnum
-syn keyword cConstant CalvingAmpAlphaEnum
-syn keyword cConstant CalvingMidpointEnum
-syn keyword cConstant CalvingNonlinearLawEnum
+syn keyword cConstant CalvingThetaEnum
+syn keyword cConstant CalvingAlphaEnum
+syn keyword cConstant CalvingXoffsetEnum
+syn keyword cConstant CalvingYoffsetEnum
+syn keyword cConstant CalvingVelLowerboundEnum
+syn keyword cConstant CalvingVelUpperboundEnum
 syn keyword cConstant ConfigurationTypeEnum
 syn keyword cConstant ConstantsGEnum
@@ -240,4 +245,5 @@
 syn keyword cConstant HydrologydcSedimentPorosityEnum
 syn keyword cConstant HydrologydcSedimentThicknessEnum
+syn keyword cConstant HydrologyStepAdaptEnum
 syn keyword cConstant HydrologydcTransferFlagEnum
 syn keyword cConstant HydrologydcUnconfinedFlagEnum
@@ -289,5 +295,8 @@
 syn keyword cConstant LoveInnerCoreBoundaryEnum
 syn keyword cConstant LoveComplexComputationEnum
+syn keyword cConstant LoveQuadPrecisionEnum
 syn keyword cConstant LoveIntStepsPerLayerEnum
+syn keyword cConstant LoveMinIntegrationStepsEnum
+syn keyword cConstant LoveMaxIntegrationdrEnum
 syn keyword cConstant LoveKernelsEnum
 syn keyword cConstant LoveMu0Enum
@@ -301,4 +310,7 @@
 syn keyword cConstant LoveUnderflowTolEnum
 syn keyword cConstant LovePostWidderThresholdEnum
+syn keyword cConstant LoveDebugEnum
+syn keyword cConstant LoveHypergeomNZEnum
+syn keyword cConstant LoveHypergeomNAlphaEnum
 syn keyword cConstant MassFluxSegmentsEnum
 syn keyword cConstant MassFluxSegmentsPresentEnum
@@ -387,4 +399,6 @@
 syn keyword cConstant SolidearthSettingsElasticEnum
 syn keyword cConstant SolidearthSettingsViscousEnum
+syn keyword cConstant SolidearthSettingsSatelliteGraviEnum
+syn keyword cConstant SolidearthSettingsDegreeAccuracyEnum
 syn keyword cConstant SealevelchangeGeometryDoneEnum
 syn keyword cConstant SealevelchangeViscousNumStepsEnum
@@ -409,4 +423,7 @@
 syn keyword cConstant LoveTimeFreqEnum
 syn keyword cConstant LoveIsTimeEnum
+syn keyword cConstant LoveHypergeomZEnum
+syn keyword cConstant LoveHypergeomTable1Enum
+syn keyword cConstant LoveHypergeomTable2Enum
 syn keyword cConstant SealevelchangeGSelfAttractionEnum
 syn keyword cConstant SealevelchangeGViscoElasticEnum
@@ -513,4 +530,5 @@
 syn keyword cConstant SmbT0dryEnum
 syn keyword cConstant SmbT0wetEnum
+syn keyword cConstant SmbTcIdxEnum
 syn keyword cConstant SmbTeThreshEnum
 syn keyword cConstant SmbTdiffEnum
@@ -550,4 +568,5 @@
 syn keyword cConstant ThermalWatercolumnUpperlimitEnum
 syn keyword cConstant TimeEnum
+syn keyword cConstant TimesteppingAverageForcingEnum
 syn keyword cConstant TimesteppingCflCoefficientEnum
 syn keyword cConstant TimesteppingCouplingTimeEnum
@@ -566,4 +585,5 @@
 syn keyword cConstant ToolkitsTypesEnum
 syn keyword cConstant TransientAmrFrequencyEnum
+syn keyword cConstant TransientIsageEnum
 syn keyword cConstant TransientIsdamageevolutionEnum
 syn keyword cConstant TransientIsesaEnum
@@ -602,4 +622,5 @@
 syn keyword cConstant AdjointyShearEnum
 syn keyword cConstant AdjointzEnum
+syn keyword cConstant AgeEnum
 syn keyword cConstant AirEnum
 syn keyword cConstant ApproximationEnum
@@ -731,4 +752,5 @@
 syn keyword cConstant FrictionCoefficientEnum
 syn keyword cConstant FrictionCoefficientcoulombEnum
+syn keyword cConstant FrictionCoulombWaterPressureEnum
 syn keyword cConstant FrictionEffectivePressureEnum
 syn keyword cConstant FrictionMEnum
@@ -738,5 +760,7 @@
 syn keyword cConstant FrictionSedimentCompressibilityCoefficientEnum
 syn keyword cConstant FrictionTillFrictionAngleEnum
+syn keyword cConstant FrictionSchoofWaterPressureEnum
 syn keyword cConstant FrictionWaterLayerEnum
+syn keyword cConstant FrictionWaterPressureEnum
 syn keyword cConstant FrictionfEnum
 syn keyword cConstant FrontalForcingsBasinIdEnum
@@ -851,4 +875,5 @@
 syn keyword cConstant SealevelEnum
 syn keyword cConstant SealevelGRDEnum
+syn keyword cConstant SatGraviGRDEnum
 syn keyword cConstant SealevelBarystaticMaskEnum
 syn keyword cConstant SealevelBarystaticIceMaskEnum
@@ -890,25 +915,19 @@
 syn keyword cConstant SealevelUNorthEsaEnum
 syn keyword cConstant SealevelchangeIndicesEnum
-syn keyword cConstant SealevelchangeGEnum
-syn keyword cConstant SealevelchangeGUEnum
-syn keyword cConstant SealevelchangeGEEnum
-syn keyword cConstant SealevelchangeGNEnum
+syn keyword cConstant SealevelchangeAlphaIndexEnum
+syn keyword cConstant SealevelchangeAzimuthIndexEnum
 syn keyword cConstant SealevelchangeGrotEnum
+syn keyword cConstant SealevelchangeGSatGravirotEnum
 syn keyword cConstant SealevelchangeGUrotEnum
 syn keyword cConstant SealevelchangeGNrotEnum
 syn keyword cConstant SealevelchangeGErotEnum
-syn keyword cConstant SealevelchangeGsubelOceanEnum
-syn keyword cConstant SealevelchangeGUsubelOceanEnum
-syn keyword cConstant SealevelchangeGEsubelOceanEnum
-syn keyword cConstant SealevelchangeGNsubelOceanEnum
-syn keyword cConstant SealevelchangeGsubelIceEnum
-syn keyword cConstant SealevelchangeGUsubelIceEnum
-syn keyword cConstant SealevelchangeGEsubelIceEnum
-syn keyword cConstant SealevelchangeGNsubelIceEnum
-syn keyword cConstant SealevelchangeGsubelHydroEnum
-syn keyword cConstant SealevelchangeGUsubelHydroEnum
-syn keyword cConstant SealevelchangeGEsubelHydroEnum
-syn keyword cConstant SealevelchangeGNsubelHydroEnum
+syn keyword cConstant SealevelchangeAlphaIndexOceanEnum
+syn keyword cConstant SealevelchangeAlphaIndexIceEnum
+syn keyword cConstant SealevelchangeAlphaIndexHydroEnum
+syn keyword cConstant SealevelchangeAzimuthIndexOceanEnum
+syn keyword cConstant SealevelchangeAzimuthIndexIceEnum
+syn keyword cConstant SealevelchangeAzimuthIndexHydroEnum
 syn keyword cConstant SealevelchangeViscousRSLEnum
+syn keyword cConstant SealevelchangeViscousSGEnum
 syn keyword cConstant SealevelchangeViscousUEnum
 syn keyword cConstant SealevelchangeViscousNEnum
@@ -1112,6 +1131,4 @@
 syn keyword cConstant WaterfractionEnum
 syn keyword cConstant WaterheightEnum
-syn keyword cConstant FrictionWaterPressureEnum
-syn keyword cConstant FrictionWaterPressureNoiseEnum
 syn keyword cConstant WeightsLevelsetObservationEnum
 syn keyword cConstant WeightsSurfaceObservationEnum
@@ -1225,4 +1242,5 @@
 syn keyword cConstant AdjointBalancethicknessAnalysisEnum
 syn keyword cConstant AdjointHorizAnalysisEnum
+syn keyword cConstant AgeAnalysisEnum
 syn keyword cConstant AggressiveMigrationEnum
 syn keyword cConstant AmrBamgEnum
@@ -1295,4 +1313,5 @@
 syn keyword cConstant DoubleArrayInputEnum
 syn keyword cConstant ArrayInputEnum
+syn keyword cConstant IntArrayInputEnum
 syn keyword cConstant DoubleExternalResultEnum
 syn keyword cConstant DoubleMatArrayParamEnum
@@ -1359,4 +1378,6 @@
 syn keyword cConstant HydrologyShreveAnalysisEnum
 syn keyword cConstant HydrologySolutionEnum
+syn keyword cConstant HydrologySubstepsEnum
+syn keyword cConstant HydrologySubTimeEnum
 syn keyword cConstant HydrologydcEnum
 syn keyword cConstant HydrologypismEnum
@@ -1410,4 +1431,6 @@
 syn keyword cConstant LovePMTF1tEnum
 syn keyword cConstant LovePMTF2tEnum
+syn keyword cConstant LoveYiEnum
+syn keyword cConstant LoveRhsEnum
 syn keyword cConstant LoveSolutionEnum
 syn keyword cConstant MINIEnum
@@ -1665,4 +1688,5 @@
 syn keyword cType Input
 syn keyword cType Inputs
+syn keyword cType IntArrayInput
 syn keyword cType IntInput
 syn keyword cType IntMatParam
@@ -1741,4 +1765,5 @@
 syn keyword cType AdjointBalancethicknessAnalysis
 syn keyword cType AdjointHorizAnalysis
+syn keyword cType AgeAnalysis
 syn keyword cType Analysis
 syn keyword cType Balancethickness2Analysis
Index: issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 27035)
+++ issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 27232)
@@ -11,4 +11,7 @@
 	/*Parameters{{{*/
 	AdolcParamEnum,
+	AgeStabilizationEnum,
+	AgeNumRequestedOutputsEnum,
+	AgeRequestedOutputsEnum,
 	AmrDeviatoricErrorGroupThresholdEnum,
 	AmrDeviatoricErrorMaximumEnum,
@@ -109,8 +112,10 @@
 	CalvingTestIndependentRateEnum,
 	CalvingUseParamEnum,
-	CalvingScaleThetaEnum,
-	CalvingAmpAlphaEnum,
-	CalvingMidpointEnum,
-	CalvingNonlinearLawEnum,
+	CalvingThetaEnum,
+	CalvingAlphaEnum,
+	CalvingXoffsetEnum,
+	CalvingYoffsetEnum,
+	CalvingVelLowerboundEnum,
+	CalvingVelUpperboundEnum,
 	ConfigurationTypeEnum,
 	ConstantsGEnum,
@@ -234,4 +239,5 @@
 	HydrologydcSedimentPorosityEnum,
 	HydrologydcSedimentThicknessEnum,
+	HydrologyStepAdaptEnum,
 	HydrologydcTransferFlagEnum,
 	HydrologydcUnconfinedFlagEnum,
@@ -283,5 +289,8 @@
 	LoveInnerCoreBoundaryEnum,
 	LoveComplexComputationEnum,
+	LoveQuadPrecisionEnum,
 	LoveIntStepsPerLayerEnum,
+	LoveMinIntegrationStepsEnum,
+	LoveMaxIntegrationdrEnum,
 	LoveKernelsEnum,
 	LoveMu0Enum,
@@ -295,4 +304,7 @@
 	LoveUnderflowTolEnum,
 	LovePostWidderThresholdEnum,
+	LoveDebugEnum,
+	LoveHypergeomNZEnum,
+	LoveHypergeomNAlphaEnum,
 	MassFluxSegmentsEnum,
 	MassFluxSegmentsPresentEnum,
@@ -381,4 +393,6 @@
 	SolidearthSettingsElasticEnum,
 	SolidearthSettingsViscousEnum,
+	SolidearthSettingsSatelliteGraviEnum,
+	SolidearthSettingsDegreeAccuracyEnum,
 	SealevelchangeGeometryDoneEnum,
 	SealevelchangeViscousNumStepsEnum,
@@ -403,4 +417,7 @@
 	LoveTimeFreqEnum,
 	LoveIsTimeEnum,
+	LoveHypergeomZEnum,
+	LoveHypergeomTable1Enum,
+	LoveHypergeomTable2Enum,
 	SealevelchangeGSelfAttractionEnum,
 	SealevelchangeGViscoElasticEnum,
@@ -507,4 +524,5 @@
 	SmbT0dryEnum,
 	SmbT0wetEnum,
+	SmbTcIdxEnum,
 	SmbTeThreshEnum,
 	SmbTdiffEnum,
@@ -544,4 +562,5 @@
 	ThermalWatercolumnUpperlimitEnum,
 	TimeEnum,
+	TimesteppingAverageForcingEnum,
 	TimesteppingCflCoefficientEnum,
 	TimesteppingCouplingTimeEnum,
@@ -560,4 +579,5 @@
 	ToolkitsTypesEnum,
 	TransientAmrFrequencyEnum,
+	TransientIsageEnum,
 	TransientIsdamageevolutionEnum,
 	TransientIsesaEnum,
@@ -598,4 +618,5 @@
 	AdjointyShearEnum,
 	AdjointzEnum,
+	AgeEnum,
 	AirEnum,
 	ApproximationEnum,
@@ -727,4 +748,5 @@
 	FrictionCoefficientEnum,
 	FrictionCoefficientcoulombEnum,
+	FrictionCoulombWaterPressureEnum,
 	FrictionEffectivePressureEnum,
 	FrictionMEnum,
@@ -734,5 +756,7 @@
 	FrictionSedimentCompressibilityCoefficientEnum,
 	FrictionTillFrictionAngleEnum,
+	FrictionSchoofWaterPressureEnum,
 	FrictionWaterLayerEnum,
+	FrictionWaterPressureEnum,
 	FrictionfEnum,
 	FrontalForcingsBasinIdEnum,
@@ -847,4 +871,5 @@
 	SealevelEnum,
 	SealevelGRDEnum,
+	SatGraviGRDEnum,
 	SealevelBarystaticMaskEnum,
 	SealevelBarystaticIceMaskEnum,
@@ -886,25 +911,19 @@
 	SealevelUNorthEsaEnum,
 	SealevelchangeIndicesEnum,
-	SealevelchangeGEnum,
-	SealevelchangeGUEnum,
-	SealevelchangeGEEnum,
-	SealevelchangeGNEnum,
+	SealevelchangeAlphaIndexEnum,
+	SealevelchangeAzimuthIndexEnum,
 	SealevelchangeGrotEnum,
+	SealevelchangeGSatGravirotEnum,
 	SealevelchangeGUrotEnum,
 	SealevelchangeGNrotEnum,
 	SealevelchangeGErotEnum,
-	SealevelchangeGsubelOceanEnum,
-	SealevelchangeGUsubelOceanEnum,
-	SealevelchangeGEsubelOceanEnum,
-	SealevelchangeGNsubelOceanEnum,
-	SealevelchangeGsubelIceEnum,
-	SealevelchangeGUsubelIceEnum,
-	SealevelchangeGEsubelIceEnum,
-	SealevelchangeGNsubelIceEnum,
-	SealevelchangeGsubelHydroEnum,
-	SealevelchangeGUsubelHydroEnum,
-	SealevelchangeGEsubelHydroEnum,
-	SealevelchangeGNsubelHydroEnum,
+	SealevelchangeAlphaIndexOceanEnum,
+	SealevelchangeAlphaIndexIceEnum,
+	SealevelchangeAlphaIndexHydroEnum,
+	SealevelchangeAzimuthIndexOceanEnum,
+	SealevelchangeAzimuthIndexIceEnum,
+	SealevelchangeAzimuthIndexHydroEnum,
 	SealevelchangeViscousRSLEnum,
+	SealevelchangeViscousSGEnum,
 	SealevelchangeViscousUEnum,
 	SealevelchangeViscousNEnum,
@@ -1109,6 +1128,4 @@
 	WaterfractionEnum,
 	WaterheightEnum,
-	FrictionWaterPressureEnum,
-	FrictionWaterPressureNoiseEnum,
 	WeightsLevelsetObservationEnum,
 	WeightsSurfaceObservationEnum,
@@ -1224,4 +1241,5 @@
 	AdjointBalancethicknessAnalysisEnum,
 	AdjointHorizAnalysisEnum,
+	AgeAnalysisEnum,
 	AggressiveMigrationEnum,
 	AmrBamgEnum,
@@ -1294,4 +1312,5 @@
 	DoubleArrayInputEnum,
 	ArrayInputEnum,
+	IntArrayInputEnum,
 	DoubleExternalResultEnum,
 	DoubleMatArrayParamEnum,
@@ -1358,4 +1377,6 @@
 	HydrologyShreveAnalysisEnum,
 	HydrologySolutionEnum,
+	HydrologySubstepsEnum,
+	HydrologySubTimeEnum,
 	HydrologydcEnum,
 	HydrologypismEnum,
@@ -1409,4 +1430,6 @@
 	LovePMTF1tEnum,
 	LovePMTF2tEnum,
+	LoveYiEnum,
+	LoveRhsEnum,
 	LoveSolutionEnum,
 	MINIEnum,
Index: issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 27035)
+++ issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 27232)
@@ -19,4 +19,7 @@
 		case ParametersSTARTEnum : return "ParametersSTART";
 		case AdolcParamEnum : return "AdolcParam";
+		case AgeStabilizationEnum : return "AgeStabilization";
+		case AgeNumRequestedOutputsEnum : return "AgeNumRequestedOutputs";
+		case AgeRequestedOutputsEnum : return "AgeRequestedOutputs";
 		case AmrDeviatoricErrorGroupThresholdEnum : return "AmrDeviatoricErrorGroupThreshold";
 		case AmrDeviatoricErrorMaximumEnum : return "AmrDeviatoricErrorMaximum";
@@ -117,8 +120,10 @@
 		case CalvingTestIndependentRateEnum : return "CalvingTestIndependentRate";
 		case CalvingUseParamEnum : return "CalvingUseParam";
-		case CalvingScaleThetaEnum : return "CalvingScaleTheta";
-		case CalvingAmpAlphaEnum : return "CalvingAmpAlpha";
-		case CalvingMidpointEnum : return "CalvingMidpoint";
-		case CalvingNonlinearLawEnum : return "CalvingNonlinearLaw";
+		case CalvingThetaEnum : return "CalvingTheta";
+		case CalvingAlphaEnum : return "CalvingAlpha";
+		case CalvingXoffsetEnum : return "CalvingXoffset";
+		case CalvingYoffsetEnum : return "CalvingYoffset";
+		case CalvingVelLowerboundEnum : return "CalvingVelLowerbound";
+		case CalvingVelUpperboundEnum : return "CalvingVelUpperbound";
 		case ConfigurationTypeEnum : return "ConfigurationType";
 		case ConstantsGEnum : return "ConstantsG";
@@ -242,4 +247,5 @@
 		case HydrologydcSedimentPorosityEnum : return "HydrologydcSedimentPorosity";
 		case HydrologydcSedimentThicknessEnum : return "HydrologydcSedimentThickness";
+		case HydrologyStepAdaptEnum : return "HydrologyStepAdapt";
 		case HydrologydcTransferFlagEnum : return "HydrologydcTransferFlag";
 		case HydrologydcUnconfinedFlagEnum : return "HydrologydcUnconfinedFlag";
@@ -291,5 +297,8 @@
 		case LoveInnerCoreBoundaryEnum : return "LoveInnerCoreBoundary";
 		case LoveComplexComputationEnum : return "LoveComplexComputation";
+		case LoveQuadPrecisionEnum : return "LoveQuadPrecision";
 		case LoveIntStepsPerLayerEnum : return "LoveIntStepsPerLayer";
+		case LoveMinIntegrationStepsEnum : return "LoveMinIntegrationSteps";
+		case LoveMaxIntegrationdrEnum : return "LoveMaxIntegrationdr";
 		case LoveKernelsEnum : return "LoveKernels";
 		case LoveMu0Enum : return "LoveMu0";
@@ -303,4 +312,7 @@
 		case LoveUnderflowTolEnum : return "LoveUnderflowTol";
 		case LovePostWidderThresholdEnum : return "LovePostWidderThreshold";
+		case LoveDebugEnum : return "LoveDebug";
+		case LoveHypergeomNZEnum : return "LoveHypergeomNZ";
+		case LoveHypergeomNAlphaEnum : return "LoveHypergeomNAlpha";
 		case MassFluxSegmentsEnum : return "MassFluxSegments";
 		case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
@@ -389,4 +401,6 @@
 		case SolidearthSettingsElasticEnum : return "SolidearthSettingsElastic";
 		case SolidearthSettingsViscousEnum : return "SolidearthSettingsViscous";
+		case SolidearthSettingsSatelliteGraviEnum : return "SolidearthSettingsSatelliteGravi";
+		case SolidearthSettingsDegreeAccuracyEnum : return "SolidearthSettingsDegreeAccuracy";
 		case SealevelchangeGeometryDoneEnum : return "SealevelchangeGeometryDone";
 		case SealevelchangeViscousNumStepsEnum : return "SealevelchangeViscousNumSteps";
@@ -411,4 +425,7 @@
 		case LoveTimeFreqEnum : return "LoveTimeFreq";
 		case LoveIsTimeEnum : return "LoveIsTime";
+		case LoveHypergeomZEnum : return "LoveHypergeomZ";
+		case LoveHypergeomTable1Enum : return "LoveHypergeomTable1";
+		case LoveHypergeomTable2Enum : return "LoveHypergeomTable2";
 		case SealevelchangeGSelfAttractionEnum : return "SealevelchangeGSelfAttraction";
 		case SealevelchangeGViscoElasticEnum : return "SealevelchangeGViscoElastic";
@@ -515,4 +532,5 @@
 		case SmbT0dryEnum : return "SmbT0dry";
 		case SmbT0wetEnum : return "SmbT0wet";
+		case SmbTcIdxEnum : return "SmbTcIdx";
 		case SmbTeThreshEnum : return "SmbTeThresh";
 		case SmbTdiffEnum : return "SmbTdiff";
@@ -552,4 +570,5 @@
 		case ThermalWatercolumnUpperlimitEnum : return "ThermalWatercolumnUpperlimit";
 		case TimeEnum : return "Time";
+		case TimesteppingAverageForcingEnum : return "TimesteppingAverageForcing";
 		case TimesteppingCflCoefficientEnum : return "TimesteppingCflCoefficient";
 		case TimesteppingCouplingTimeEnum : return "TimesteppingCouplingTime";
@@ -568,4 +587,5 @@
 		case ToolkitsTypesEnum : return "ToolkitsTypes";
 		case TransientAmrFrequencyEnum : return "TransientAmrFrequency";
+		case TransientIsageEnum : return "TransientIsage";
 		case TransientIsdamageevolutionEnum : return "TransientIsdamageevolution";
 		case TransientIsesaEnum : return "TransientIsesa";
@@ -604,4 +624,5 @@
 		case AdjointyShearEnum : return "AdjointyShear";
 		case AdjointzEnum : return "Adjointz";
+		case AgeEnum : return "Age";
 		case AirEnum : return "Air";
 		case ApproximationEnum : return "Approximation";
@@ -733,4 +754,5 @@
 		case FrictionCoefficientEnum : return "FrictionCoefficient";
 		case FrictionCoefficientcoulombEnum : return "FrictionCoefficientcoulomb";
+		case FrictionCoulombWaterPressureEnum : return "FrictionCoulombWaterPressure";
 		case FrictionEffectivePressureEnum : return "FrictionEffectivePressure";
 		case FrictionMEnum : return "FrictionM";
@@ -740,5 +762,7 @@
 		case FrictionSedimentCompressibilityCoefficientEnum : return "FrictionSedimentCompressibilityCoefficient";
 		case FrictionTillFrictionAngleEnum : return "FrictionTillFrictionAngle";
+		case FrictionSchoofWaterPressureEnum : return "FrictionSchoofWaterPressure";
 		case FrictionWaterLayerEnum : return "FrictionWaterLayer";
+		case FrictionWaterPressureEnum : return "FrictionWaterPressure";
 		case FrictionfEnum : return "Frictionf";
 		case FrontalForcingsBasinIdEnum : return "FrontalForcingsBasinId";
@@ -853,4 +877,5 @@
 		case SealevelEnum : return "Sealevel";
 		case SealevelGRDEnum : return "SealevelGRD";
+		case SatGraviGRDEnum : return "SatGraviGRD";
 		case SealevelBarystaticMaskEnum : return "SealevelBarystaticMask";
 		case SealevelBarystaticIceMaskEnum : return "SealevelBarystaticIceMask";
@@ -892,25 +917,19 @@
 		case SealevelUNorthEsaEnum : return "SealevelUNorthEsa";
 		case SealevelchangeIndicesEnum : return "SealevelchangeIndices";
-		case SealevelchangeGEnum : return "SealevelchangeG";
-		case SealevelchangeGUEnum : return "SealevelchangeGU";
-		case SealevelchangeGEEnum : return "SealevelchangeGE";
-		case SealevelchangeGNEnum : return "SealevelchangeGN";
+		case SealevelchangeAlphaIndexEnum : return "SealevelchangeAlphaIndex";
+		case SealevelchangeAzimuthIndexEnum : return "SealevelchangeAzimuthIndex";
 		case SealevelchangeGrotEnum : return "SealevelchangeGrot";
+		case SealevelchangeGSatGravirotEnum : return "SealevelchangeGSatGravirot";
 		case SealevelchangeGUrotEnum : return "SealevelchangeGUrot";
 		case SealevelchangeGNrotEnum : return "SealevelchangeGNrot";
 		case SealevelchangeGErotEnum : return "SealevelchangeGErot";
-		case SealevelchangeGsubelOceanEnum : return "SealevelchangeGsubelOcean";
-		case SealevelchangeGUsubelOceanEnum : return "SealevelchangeGUsubelOcean";
-		case SealevelchangeGEsubelOceanEnum : return "SealevelchangeGEsubelOcean";
-		case SealevelchangeGNsubelOceanEnum : return "SealevelchangeGNsubelOcean";
-		case SealevelchangeGsubelIceEnum : return "SealevelchangeGsubelIce";
-		case SealevelchangeGUsubelIceEnum : return "SealevelchangeGUsubelIce";
-		case SealevelchangeGEsubelIceEnum : return "SealevelchangeGEsubelIce";
-		case SealevelchangeGNsubelIceEnum : return "SealevelchangeGNsubelIce";
-		case SealevelchangeGsubelHydroEnum : return "SealevelchangeGsubelHydro";
-		case SealevelchangeGUsubelHydroEnum : return "SealevelchangeGUsubelHydro";
-		case SealevelchangeGEsubelHydroEnum : return "SealevelchangeGEsubelHydro";
-		case SealevelchangeGNsubelHydroEnum : return "SealevelchangeGNsubelHydro";
+		case SealevelchangeAlphaIndexOceanEnum : return "SealevelchangeAlphaIndexOcean";
+		case SealevelchangeAlphaIndexIceEnum : return "SealevelchangeAlphaIndexIce";
+		case SealevelchangeAlphaIndexHydroEnum : return "SealevelchangeAlphaIndexHydro";
+		case SealevelchangeAzimuthIndexOceanEnum : return "SealevelchangeAzimuthIndexOcean";
+		case SealevelchangeAzimuthIndexIceEnum : return "SealevelchangeAzimuthIndexIce";
+		case SealevelchangeAzimuthIndexHydroEnum : return "SealevelchangeAzimuthIndexHydro";
 		case SealevelchangeViscousRSLEnum : return "SealevelchangeViscousRSL";
+		case SealevelchangeViscousSGEnum : return "SealevelchangeViscousSG";
 		case SealevelchangeViscousUEnum : return "SealevelchangeViscousU";
 		case SealevelchangeViscousNEnum : return "SealevelchangeViscousN";
@@ -1114,6 +1133,4 @@
 		case WaterfractionEnum : return "Waterfraction";
 		case WaterheightEnum : return "Waterheight";
-		case FrictionWaterPressureEnum : return "FrictionWaterPressure";
-		case FrictionWaterPressureNoiseEnum : return "FrictionWaterPressureNoise";
 		case WeightsLevelsetObservationEnum : return "WeightsLevelsetObservation";
 		case WeightsSurfaceObservationEnum : return "WeightsSurfaceObservation";
@@ -1227,4 +1244,5 @@
 		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
 		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
+		case AgeAnalysisEnum : return "AgeAnalysis";
 		case AggressiveMigrationEnum : return "AggressiveMigration";
 		case AmrBamgEnum : return "AmrBamg";
@@ -1297,4 +1315,5 @@
 		case DoubleArrayInputEnum : return "DoubleArrayInput";
 		case ArrayInputEnum : return "ArrayInput";
+		case IntArrayInputEnum : return "IntArrayInput";
 		case DoubleExternalResultEnum : return "DoubleExternalResult";
 		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
@@ -1361,4 +1380,6 @@
 		case HydrologyShreveAnalysisEnum : return "HydrologyShreveAnalysis";
 		case HydrologySolutionEnum : return "HydrologySolution";
+		case HydrologySubstepsEnum : return "HydrologySubsteps";
+		case HydrologySubTimeEnum : return "HydrologySubTime";
 		case HydrologydcEnum : return "Hydrologydc";
 		case HydrologypismEnum : return "Hydrologypism";
@@ -1412,4 +1433,6 @@
 		case LovePMTF1tEnum : return "LovePMTF1t";
 		case LovePMTF2tEnum : return "LovePMTF2t";
+		case LoveYiEnum : return "LoveYi";
+		case LoveRhsEnum : return "LoveRhs";
 		case LoveSolutionEnum : return "LoveSolution";
 		case MINIEnum : return "MINI";
Index: issm/trunk/src/c/shared/Enum/Enumjl.vim
===================================================================
--- issm/trunk/src/c/shared/Enum/Enumjl.vim	(revision 27035)
+++ issm/trunk/src/c/shared/Enum/Enumjl.vim	(revision 27232)
@@ -10,4 +10,7 @@
 syn keyword juliaConstC ParametersSTARTEnum
 syn keyword juliaConstC AdolcParamEnum
+syn keyword juliaConstC AgeStabilizationEnum
+syn keyword juliaConstC AgeNumRequestedOutputsEnum
+syn keyword juliaConstC AgeRequestedOutputsEnum
 syn keyword juliaConstC AmrDeviatoricErrorGroupThresholdEnum
 syn keyword juliaConstC AmrDeviatoricErrorMaximumEnum
@@ -108,8 +111,10 @@
 syn keyword juliaConstC CalvingTestIndependentRateEnum
 syn keyword juliaConstC CalvingUseParamEnum
-syn keyword juliaConstC CalvingScaleThetaEnum
-syn keyword juliaConstC CalvingAmpAlphaEnum
-syn keyword juliaConstC CalvingMidpointEnum
-syn keyword juliaConstC CalvingNonlinearLawEnum
+syn keyword juliaConstC CalvingThetaEnum
+syn keyword juliaConstC CalvingAlphaEnum
+syn keyword juliaConstC CalvingXoffsetEnum
+syn keyword juliaConstC CalvingYoffsetEnum
+syn keyword juliaConstC CalvingVelLowerboundEnum
+syn keyword juliaConstC CalvingVelUpperboundEnum
 syn keyword juliaConstC ConfigurationTypeEnum
 syn keyword juliaConstC ConstantsGEnum
@@ -233,4 +238,5 @@
 syn keyword juliaConstC HydrologydcSedimentPorosityEnum
 syn keyword juliaConstC HydrologydcSedimentThicknessEnum
+syn keyword juliaConstC HydrologyStepAdaptEnum
 syn keyword juliaConstC HydrologydcTransferFlagEnum
 syn keyword juliaConstC HydrologydcUnconfinedFlagEnum
@@ -282,5 +288,8 @@
 syn keyword juliaConstC LoveInnerCoreBoundaryEnum
 syn keyword juliaConstC LoveComplexComputationEnum
+syn keyword juliaConstC LoveQuadPrecisionEnum
 syn keyword juliaConstC LoveIntStepsPerLayerEnum
+syn keyword juliaConstC LoveMinIntegrationStepsEnum
+syn keyword juliaConstC LoveMaxIntegrationdrEnum
 syn keyword juliaConstC LoveKernelsEnum
 syn keyword juliaConstC LoveMu0Enum
@@ -294,4 +303,7 @@
 syn keyword juliaConstC LoveUnderflowTolEnum
 syn keyword juliaConstC LovePostWidderThresholdEnum
+syn keyword juliaConstC LoveDebugEnum
+syn keyword juliaConstC LoveHypergeomNZEnum
+syn keyword juliaConstC LoveHypergeomNAlphaEnum
 syn keyword juliaConstC MassFluxSegmentsEnum
 syn keyword juliaConstC MassFluxSegmentsPresentEnum
@@ -380,4 +392,6 @@
 syn keyword juliaConstC SolidearthSettingsElasticEnum
 syn keyword juliaConstC SolidearthSettingsViscousEnum
+syn keyword juliaConstC SolidearthSettingsSatelliteGraviEnum
+syn keyword juliaConstC SolidearthSettingsDegreeAccuracyEnum
 syn keyword juliaConstC SealevelchangeGeometryDoneEnum
 syn keyword juliaConstC SealevelchangeViscousNumStepsEnum
@@ -402,4 +416,7 @@
 syn keyword juliaConstC LoveTimeFreqEnum
 syn keyword juliaConstC LoveIsTimeEnum
+syn keyword juliaConstC LoveHypergeomZEnum
+syn keyword juliaConstC LoveHypergeomTable1Enum
+syn keyword juliaConstC LoveHypergeomTable2Enum
 syn keyword juliaConstC SealevelchangeGSelfAttractionEnum
 syn keyword juliaConstC SealevelchangeGViscoElasticEnum
@@ -506,4 +523,5 @@
 syn keyword juliaConstC SmbT0dryEnum
 syn keyword juliaConstC SmbT0wetEnum
+syn keyword juliaConstC SmbTcIdxEnum
 syn keyword juliaConstC SmbTeThreshEnum
 syn keyword juliaConstC SmbTdiffEnum
@@ -543,4 +561,5 @@
 syn keyword juliaConstC ThermalWatercolumnUpperlimitEnum
 syn keyword juliaConstC TimeEnum
+syn keyword juliaConstC TimesteppingAverageForcingEnum
 syn keyword juliaConstC TimesteppingCflCoefficientEnum
 syn keyword juliaConstC TimesteppingCouplingTimeEnum
@@ -559,4 +578,5 @@
 syn keyword juliaConstC ToolkitsTypesEnum
 syn keyword juliaConstC TransientAmrFrequencyEnum
+syn keyword juliaConstC TransientIsageEnum
 syn keyword juliaConstC TransientIsdamageevolutionEnum
 syn keyword juliaConstC TransientIsesaEnum
@@ -595,4 +615,5 @@
 syn keyword juliaConstC AdjointyShearEnum
 syn keyword juliaConstC AdjointzEnum
+syn keyword juliaConstC AgeEnum
 syn keyword juliaConstC AirEnum
 syn keyword juliaConstC ApproximationEnum
@@ -724,4 +745,5 @@
 syn keyword juliaConstC FrictionCoefficientEnum
 syn keyword juliaConstC FrictionCoefficientcoulombEnum
+syn keyword juliaConstC FrictionCoulombWaterPressureEnum
 syn keyword juliaConstC FrictionEffectivePressureEnum
 syn keyword juliaConstC FrictionMEnum
@@ -731,5 +753,7 @@
 syn keyword juliaConstC FrictionSedimentCompressibilityCoefficientEnum
 syn keyword juliaConstC FrictionTillFrictionAngleEnum
+syn keyword juliaConstC FrictionSchoofWaterPressureEnum
 syn keyword juliaConstC FrictionWaterLayerEnum
+syn keyword juliaConstC FrictionWaterPressureEnum
 syn keyword juliaConstC FrictionfEnum
 syn keyword juliaConstC FrontalForcingsBasinIdEnum
@@ -844,4 +868,5 @@
 syn keyword juliaConstC SealevelEnum
 syn keyword juliaConstC SealevelGRDEnum
+syn keyword juliaConstC SatGraviGRDEnum
 syn keyword juliaConstC SealevelBarystaticMaskEnum
 syn keyword juliaConstC SealevelBarystaticIceMaskEnum
@@ -883,25 +908,19 @@
 syn keyword juliaConstC SealevelUNorthEsaEnum
 syn keyword juliaConstC SealevelchangeIndicesEnum
-syn keyword juliaConstC SealevelchangeGEnum
-syn keyword juliaConstC SealevelchangeGUEnum
-syn keyword juliaConstC SealevelchangeGEEnum
-syn keyword juliaConstC SealevelchangeGNEnum
+syn keyword juliaConstC SealevelchangeAlphaIndexEnum
+syn keyword juliaConstC SealevelchangeAzimuthIndexEnum
 syn keyword juliaConstC SealevelchangeGrotEnum
+syn keyword juliaConstC SealevelchangeGSatGravirotEnum
 syn keyword juliaConstC SealevelchangeGUrotEnum
 syn keyword juliaConstC SealevelchangeGNrotEnum
 syn keyword juliaConstC SealevelchangeGErotEnum
-syn keyword juliaConstC SealevelchangeGsubelOceanEnum
-syn keyword juliaConstC SealevelchangeGUsubelOceanEnum
-syn keyword juliaConstC SealevelchangeGEsubelOceanEnum
-syn keyword juliaConstC SealevelchangeGNsubelOceanEnum
-syn keyword juliaConstC SealevelchangeGsubelIceEnum
-syn keyword juliaConstC SealevelchangeGUsubelIceEnum
-syn keyword juliaConstC SealevelchangeGEsubelIceEnum
-syn keyword juliaConstC SealevelchangeGNsubelIceEnum
-syn keyword juliaConstC SealevelchangeGsubelHydroEnum
-syn keyword juliaConstC SealevelchangeGUsubelHydroEnum
-syn keyword juliaConstC SealevelchangeGEsubelHydroEnum
-syn keyword juliaConstC SealevelchangeGNsubelHydroEnum
+syn keyword juliaConstC SealevelchangeAlphaIndexOceanEnum
+syn keyword juliaConstC SealevelchangeAlphaIndexIceEnum
+syn keyword juliaConstC SealevelchangeAlphaIndexHydroEnum
+syn keyword juliaConstC SealevelchangeAzimuthIndexOceanEnum
+syn keyword juliaConstC SealevelchangeAzimuthIndexIceEnum
+syn keyword juliaConstC SealevelchangeAzimuthIndexHydroEnum
 syn keyword juliaConstC SealevelchangeViscousRSLEnum
+syn keyword juliaConstC SealevelchangeViscousSGEnum
 syn keyword juliaConstC SealevelchangeViscousUEnum
 syn keyword juliaConstC SealevelchangeViscousNEnum
@@ -1105,6 +1124,4 @@
 syn keyword juliaConstC WaterfractionEnum
 syn keyword juliaConstC WaterheightEnum
-syn keyword juliaConstC FrictionWaterPressureEnum
-syn keyword juliaConstC FrictionWaterPressureNoiseEnum
 syn keyword juliaConstC WeightsLevelsetObservationEnum
 syn keyword juliaConstC WeightsSurfaceObservationEnum
@@ -1218,4 +1235,5 @@
 syn keyword juliaConstC AdjointBalancethicknessAnalysisEnum
 syn keyword juliaConstC AdjointHorizAnalysisEnum
+syn keyword juliaConstC AgeAnalysisEnum
 syn keyword juliaConstC AggressiveMigrationEnum
 syn keyword juliaConstC AmrBamgEnum
@@ -1288,4 +1306,5 @@
 syn keyword juliaConstC DoubleArrayInputEnum
 syn keyword juliaConstC ArrayInputEnum
+syn keyword juliaConstC IntArrayInputEnum
 syn keyword juliaConstC DoubleExternalResultEnum
 syn keyword juliaConstC DoubleMatArrayParamEnum
@@ -1352,4 +1371,6 @@
 syn keyword juliaConstC HydrologyShreveAnalysisEnum
 syn keyword juliaConstC HydrologySolutionEnum
+syn keyword juliaConstC HydrologySubstepsEnum
+syn keyword juliaConstC HydrologySubTimeEnum
 syn keyword juliaConstC HydrologydcEnum
 syn keyword juliaConstC HydrologypismEnum
@@ -1403,4 +1424,6 @@
 syn keyword juliaConstC LovePMTF1tEnum
 syn keyword juliaConstC LovePMTF2tEnum
+syn keyword juliaConstC LoveYiEnum
+syn keyword juliaConstC LoveRhsEnum
 syn keyword juliaConstC LoveSolutionEnum
 syn keyword juliaConstC MINIEnum
Index: issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 27035)
+++ issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 27232)
@@ -19,4 +19,7 @@
 	      if (strcmp(name,"ParametersSTART")==0) return ParametersSTARTEnum;
 	      else if (strcmp(name,"AdolcParam")==0) return AdolcParamEnum;
+	      else if (strcmp(name,"AgeStabilization")==0) return AgeStabilizationEnum;
+	      else if (strcmp(name,"AgeNumRequestedOutputs")==0) return AgeNumRequestedOutputsEnum;
+	      else if (strcmp(name,"AgeRequestedOutputs")==0) return AgeRequestedOutputsEnum;
 	      else if (strcmp(name,"AmrDeviatoricErrorGroupThreshold")==0) return AmrDeviatoricErrorGroupThresholdEnum;
 	      else if (strcmp(name,"AmrDeviatoricErrorMaximum")==0) return AmrDeviatoricErrorMaximumEnum;
@@ -117,8 +120,10 @@
 	      else if (strcmp(name,"CalvingTestIndependentRate")==0) return CalvingTestIndependentRateEnum;
 	      else if (strcmp(name,"CalvingUseParam")==0) return CalvingUseParamEnum;
-	      else if (strcmp(name,"CalvingScaleTheta")==0) return CalvingScaleThetaEnum;
-	      else if (strcmp(name,"CalvingAmpAlpha")==0) return CalvingAmpAlphaEnum;
-	      else if (strcmp(name,"CalvingMidpoint")==0) return CalvingMidpointEnum;
-	      else if (strcmp(name,"CalvingNonlinearLaw")==0) return CalvingNonlinearLawEnum;
+	      else if (strcmp(name,"CalvingTheta")==0) return CalvingThetaEnum;
+	      else if (strcmp(name,"CalvingAlpha")==0) return CalvingAlphaEnum;
+	      else if (strcmp(name,"CalvingXoffset")==0) return CalvingXoffsetEnum;
+	      else if (strcmp(name,"CalvingYoffset")==0) return CalvingYoffsetEnum;
+	      else if (strcmp(name,"CalvingVelLowerbound")==0) return CalvingVelLowerboundEnum;
+	      else if (strcmp(name,"CalvingVelUpperbound")==0) return CalvingVelUpperboundEnum;
 	      else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
 	      else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
@@ -132,13 +137,13 @@
 	      else if (strcmp(name,"CumBslcIce")==0) return CumBslcIceEnum;
 	      else if (strcmp(name,"CumBslcHydro")==0) return CumBslcHydroEnum;
-	      else if (strcmp(name,"CumBslcOcean")==0) return CumBslcOceanEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"CumBslcOcean")==0) return CumBslcOceanEnum;
 	      else if (strcmp(name,"CumBslcIcePartition")==0) return CumBslcIcePartitionEnum;
 	      else if (strcmp(name,"CumBslcHydroPartition")==0) return CumBslcHydroPartitionEnum;
 	      else if (strcmp(name,"CumBslcOceanPartition")==0) return CumBslcOceanPartitionEnum;
 	      else if (strcmp(name,"CumGmtslc")==0) return CumGmtslcEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"CumGmslc")==0) return CumGmslcEnum;
+	      else if (strcmp(name,"CumGmslc")==0) return CumGmslcEnum;
 	      else if (strcmp(name,"DamageC1")==0) return DamageC1Enum;
 	      else if (strcmp(name,"DamageC2")==0) return DamageC2Enum;
@@ -245,4 +250,5 @@
 	      else if (strcmp(name,"HydrologydcSedimentPorosity")==0) return HydrologydcSedimentPorosityEnum;
 	      else if (strcmp(name,"HydrologydcSedimentThickness")==0) return HydrologydcSedimentThicknessEnum;
+	      else if (strcmp(name,"HydrologyStepAdapt")==0) return HydrologyStepAdaptEnum;
 	      else if (strcmp(name,"HydrologydcTransferFlag")==0) return HydrologydcTransferFlagEnum;
 	      else if (strcmp(name,"HydrologydcUnconfinedFlag")==0) return HydrologydcUnconfinedFlagEnum;
@@ -254,5 +260,8 @@
 	      else if (strcmp(name,"Indices")==0) return IndicesEnum;
 	      else if (strcmp(name,"InputToDepthaverageIn")==0) return InputToDepthaverageInEnum;
-	      else if (strcmp(name,"InputToDepthaverageOut")==0) return InputToDepthaverageOutEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"InputToDepthaverageOut")==0) return InputToDepthaverageOutEnum;
 	      else if (strcmp(name,"InputToExtrude")==0) return InputToExtrudeEnum;
 	      else if (strcmp(name,"InputToL2Project")==0) return InputToL2ProjectEnum;
@@ -260,8 +269,5 @@
 	      else if (strcmp(name,"InversionAlgorithm")==0) return InversionAlgorithmEnum;
 	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
+	      else if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
 	      else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
 	      else if (strcmp(name,"InversionDxmin")==0) return InversionDxminEnum;
@@ -297,5 +303,8 @@
 	      else if (strcmp(name,"LoveInnerCoreBoundary")==0) return LoveInnerCoreBoundaryEnum;
 	      else if (strcmp(name,"LoveComplexComputation")==0) return LoveComplexComputationEnum;
+	      else if (strcmp(name,"LoveQuadPrecision")==0) return LoveQuadPrecisionEnum;
 	      else if (strcmp(name,"LoveIntStepsPerLayer")==0) return LoveIntStepsPerLayerEnum;
+	      else if (strcmp(name,"LoveMinIntegrationSteps")==0) return LoveMinIntegrationStepsEnum;
+	      else if (strcmp(name,"LoveMaxIntegrationdr")==0) return LoveMaxIntegrationdrEnum;
 	      else if (strcmp(name,"LoveKernels")==0) return LoveKernelsEnum;
 	      else if (strcmp(name,"LoveMu0")==0) return LoveMu0Enum;
@@ -309,4 +318,7 @@
 	      else if (strcmp(name,"LoveUnderflowTol")==0) return LoveUnderflowTolEnum;
 	      else if (strcmp(name,"LovePostWidderThreshold")==0) return LovePostWidderThresholdEnum;
+	      else if (strcmp(name,"LoveDebug")==0) return LoveDebugEnum;
+	      else if (strcmp(name,"LoveHypergeomNZ")==0) return LoveHypergeomNZEnum;
+	      else if (strcmp(name,"LoveHypergeomNAlpha")==0) return LoveHypergeomNAlphaEnum;
 	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
 	      else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
@@ -371,5 +383,8 @@
 	      else if (strcmp(name,"QmuNdirectories")==0) return QmuNdirectoriesEnum;
 	      else if (strcmp(name,"QmuNfilesPerDirectory")==0) return QmuNfilesPerDirectoryEnum;
-	      else if (strcmp(name,"QmuStatisticsMethod")==0) return QmuStatisticsMethodEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"QmuStatisticsMethod")==0) return QmuStatisticsMethodEnum;
 	      else if (strcmp(name,"QmuMethods")==0) return QmuMethodsEnum;
 	      else if (strcmp(name,"RestartFileName")==0) return RestartFileNameEnum;
@@ -383,8 +398,5 @@
 	      else if (strcmp(name,"SamplingSeed")==0) return SamplingSeedEnum;
 	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"SolidearthPartitionIce")==0) return SolidearthPartitionIceEnum;
+	      else if (strcmp(name,"SolidearthPartitionIce")==0) return SolidearthPartitionIceEnum;
 	      else if (strcmp(name,"SolidearthPartitionHydro")==0) return SolidearthPartitionHydroEnum;
 	      else if (strcmp(name,"SolidearthPartitionOcean")==0) return SolidearthPartitionOceanEnum;
@@ -398,4 +410,6 @@
 	      else if (strcmp(name,"SolidearthSettingsElastic")==0) return SolidearthSettingsElasticEnum;
 	      else if (strcmp(name,"SolidearthSettingsViscous")==0) return SolidearthSettingsViscousEnum;
+	      else if (strcmp(name,"SolidearthSettingsSatelliteGravi")==0) return SolidearthSettingsSatelliteGraviEnum;
+	      else if (strcmp(name,"SolidearthSettingsDegreeAccuracy")==0) return SolidearthSettingsDegreeAccuracyEnum;
 	      else if (strcmp(name,"SealevelchangeGeometryDone")==0) return SealevelchangeGeometryDoneEnum;
 	      else if (strcmp(name,"SealevelchangeViscousNumSteps")==0) return SealevelchangeViscousNumStepsEnum;
@@ -420,4 +434,7 @@
 	      else if (strcmp(name,"LoveTimeFreq")==0) return LoveTimeFreqEnum;
 	      else if (strcmp(name,"LoveIsTime")==0) return LoveIsTimeEnum;
+	      else if (strcmp(name,"LoveHypergeomZ")==0) return LoveHypergeomZEnum;
+	      else if (strcmp(name,"LoveHypergeomTable1")==0) return LoveHypergeomTable1Enum;
+	      else if (strcmp(name,"LoveHypergeomTable2")==0) return LoveHypergeomTable2Enum;
 	      else if (strcmp(name,"SealevelchangeGSelfAttraction")==0) return SealevelchangeGSelfAttractionEnum;
 	      else if (strcmp(name,"SealevelchangeGViscoElastic")==0) return SealevelchangeGViscoElasticEnum;
@@ -489,5 +506,8 @@
 	      else if (strcmp(name,"SmbIsaccumulation")==0) return SmbIsaccumulationEnum;
 	      else if (strcmp(name,"SmbIsalbedo")==0) return SmbIsalbedoEnum;
-	      else if (strcmp(name,"SmbIsconstrainsurfaceT")==0) return SmbIsconstrainsurfaceTEnum;
+         else stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"SmbIsconstrainsurfaceT")==0) return SmbIsconstrainsurfaceTEnum;
 	      else if (strcmp(name,"SmbIsd18opd")==0) return SmbIsd18opdEnum;
 	      else if (strcmp(name,"SmbIsdelta18o")==0) return SmbIsdelta18oEnum;
@@ -506,8 +526,5 @@
 	      else if (strcmp(name,"SmbK")==0) return SmbKEnum;
 	      else if (strcmp(name,"SmbLapseRates")==0) return SmbLapseRatesEnum;
-         else stage=5;
-   }
-   if(stage==5){
-	      if (strcmp(name,"SmbNumBasins")==0) return SmbNumBasinsEnum;
+	      else if (strcmp(name,"SmbNumBasins")==0) return SmbNumBasinsEnum;
 	      else if (strcmp(name,"SmbNumElevationBins")==0) return SmbNumElevationBinsEnum;
 	      else if (strcmp(name,"SmbNumRequestedOutputs")==0) return SmbNumRequestedOutputsEnum;
@@ -527,4 +544,5 @@
 	      else if (strcmp(name,"SmbT0dry")==0) return SmbT0dryEnum;
 	      else if (strcmp(name,"SmbT0wet")==0) return SmbT0wetEnum;
+	      else if (strcmp(name,"SmbTcIdx")==0) return SmbTcIdxEnum;
 	      else if (strcmp(name,"SmbTeThresh")==0) return SmbTeThreshEnum;
 	      else if (strcmp(name,"SmbTdiff")==0) return SmbTdiffEnum;
@@ -564,4 +582,5 @@
 	      else if (strcmp(name,"ThermalWatercolumnUpperlimit")==0) return ThermalWatercolumnUpperlimitEnum;
 	      else if (strcmp(name,"Time")==0) return TimeEnum;
+	      else if (strcmp(name,"TimesteppingAverageForcing")==0) return TimesteppingAverageForcingEnum;
 	      else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
 	      else if (strcmp(name,"TimesteppingCouplingTime")==0) return TimesteppingCouplingTimeEnum;
@@ -580,4 +599,5 @@
 	      else if (strcmp(name,"ToolkitsTypes")==0) return ToolkitsTypesEnum;
 	      else if (strcmp(name,"TransientAmrFrequency")==0) return TransientAmrFrequencyEnum;
+	      else if (strcmp(name,"TransientIsage")==0) return TransientIsageEnum;
 	      else if (strcmp(name,"TransientIsdamageevolution")==0) return TransientIsdamageevolutionEnum;
 	      else if (strcmp(name,"TransientIsesa")==0) return TransientIsesaEnum;
@@ -609,5 +629,8 @@
 	      else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
 	      else if (strcmp(name,"Adjointp")==0) return AdjointpEnum;
-	      else if (strcmp(name,"Adjointx")==0) return AdjointxEnum;
+         else stage=6;
+   }
+   if(stage==6){
+	      if (strcmp(name,"Adjointx")==0) return AdjointxEnum;
 	      else if (strcmp(name,"AdjointxBase")==0) return AdjointxBaseEnum;
 	      else if (strcmp(name,"AdjointxShear")==0) return AdjointxShearEnum;
@@ -616,4 +639,5 @@
 	      else if (strcmp(name,"AdjointyShear")==0) return AdjointyShearEnum;
 	      else if (strcmp(name,"Adjointz")==0) return AdjointzEnum;
+	      else if (strcmp(name,"Age")==0) return AgeEnum;
 	      else if (strcmp(name,"Air")==0) return AirEnum;
 	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
@@ -629,8 +653,5 @@
 	      else if (strcmp(name,"BasalforcingsFloatingiceMeltingRate")==0) return BasalforcingsFloatingiceMeltingRateEnum;
 	      else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
-         else stage=6;
-   }
-   if(stage==6){
-	      if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
 	      else if (strcmp(name,"BasalforcingsLinearBasinId")==0) return BasalforcingsLinearBasinIdEnum;
 	      else if (strcmp(name,"BasalforcingsPerturbationMeltingRate")==0) return BasalforcingsPerturbationMeltingRateEnum;
@@ -731,5 +752,8 @@
 	      else if (strcmp(name,"EplHeadSlopeY")==0) return EplHeadSlopeYEnum;
 	      else if (strcmp(name,"EplHeadSubstep")==0) return EplHeadSubstepEnum;
-	      else if (strcmp(name,"EplHeadTransient")==0) return EplHeadTransientEnum;
+         else stage=7;
+   }
+   if(stage==7){
+	      if (strcmp(name,"EplHeadTransient")==0) return EplHeadTransientEnum;
 	      else if (strcmp(name,"EsaEmotion")==0) return EsaEmotionEnum;
 	      else if (strcmp(name,"EsaNmotion")==0) return EsaNmotionEnum;
@@ -748,15 +772,15 @@
 	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
 	      else if (strcmp(name,"FrictionCoefficientcoulomb")==0) return FrictionCoefficientcoulombEnum;
+	      else if (strcmp(name,"FrictionCoulombWaterPressure")==0) return FrictionCoulombWaterPressureEnum;
 	      else if (strcmp(name,"FrictionEffectivePressure")==0) return FrictionEffectivePressureEnum;
 	      else if (strcmp(name,"FrictionM")==0) return FrictionMEnum;
 	      else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
 	      else if (strcmp(name,"FrictionPressureAdjustedTemperature")==0) return FrictionPressureAdjustedTemperatureEnum;
-         else stage=7;
-   }
-   if(stage==7){
-	      if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
+	      else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
 	      else if (strcmp(name,"FrictionSedimentCompressibilityCoefficient")==0) return FrictionSedimentCompressibilityCoefficientEnum;
 	      else if (strcmp(name,"FrictionTillFrictionAngle")==0) return FrictionTillFrictionAngleEnum;
+	      else if (strcmp(name,"FrictionSchoofWaterPressure")==0) return FrictionSchoofWaterPressureEnum;
 	      else if (strcmp(name,"FrictionWaterLayer")==0) return FrictionWaterLayerEnum;
+	      else if (strcmp(name,"FrictionWaterPressure")==0) return FrictionWaterPressureEnum;
 	      else if (strcmp(name,"Frictionf")==0) return FrictionfEnum;
 	      else if (strcmp(name,"FrontalForcingsBasinId")==0) return FrontalForcingsBasinIdEnum;
@@ -851,5 +875,8 @@
 	      else if (strcmp(name,"P1")==0) return P1Enum;
 	      else if (strcmp(name,"Partitioning")==0) return PartitioningEnum;
-	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
+         else stage=8;
+   }
+   if(stage==8){
+	      if (strcmp(name,"Pressure")==0) return PressureEnum;
 	      else if (strcmp(name,"Radar")==0) return RadarEnum;
 	      else if (strcmp(name,"RadarAttenuationMacGregor")==0) return RadarAttenuationMacGregorEnum;
@@ -871,12 +898,10 @@
 	      else if (strcmp(name,"Sealevel")==0) return SealevelEnum;
 	      else if (strcmp(name,"SealevelGRD")==0) return SealevelGRDEnum;
+	      else if (strcmp(name,"SatGraviGRD")==0) return SatGraviGRDEnum;
 	      else if (strcmp(name,"SealevelBarystaticMask")==0) return SealevelBarystaticMaskEnum;
 	      else if (strcmp(name,"SealevelBarystaticIceMask")==0) return SealevelBarystaticIceMaskEnum;
 	      else if (strcmp(name,"SealevelBarystaticIceWeights")==0) return SealevelBarystaticIceWeightsEnum;
 	      else if (strcmp(name,"SealevelBarystaticIceArea")==0) return SealevelBarystaticIceAreaEnum;
-         else stage=8;
-   }
-   if(stage==8){
-	      if (strcmp(name,"SealevelBarystaticIceLatbar")==0) return SealevelBarystaticIceLatbarEnum;
+	      else if (strcmp(name,"SealevelBarystaticIceLatbar")==0) return SealevelBarystaticIceLatbarEnum;
 	      else if (strcmp(name,"SealevelBarystaticIceLongbar")==0) return SealevelBarystaticIceLongbarEnum;
 	      else if (strcmp(name,"SealevelBarystaticIceLoad")==0) return SealevelBarystaticIceLoadEnum;
@@ -913,25 +938,19 @@
 	      else if (strcmp(name,"SealevelUNorthEsa")==0) return SealevelUNorthEsaEnum;
 	      else if (strcmp(name,"SealevelchangeIndices")==0) return SealevelchangeIndicesEnum;
-	      else if (strcmp(name,"SealevelchangeG")==0) return SealevelchangeGEnum;
-	      else if (strcmp(name,"SealevelchangeGU")==0) return SealevelchangeGUEnum;
-	      else if (strcmp(name,"SealevelchangeGE")==0) return SealevelchangeGEEnum;
-	      else if (strcmp(name,"SealevelchangeGN")==0) return SealevelchangeGNEnum;
+	      else if (strcmp(name,"SealevelchangeAlphaIndex")==0) return SealevelchangeAlphaIndexEnum;
+	      else if (strcmp(name,"SealevelchangeAzimuthIndex")==0) return SealevelchangeAzimuthIndexEnum;
 	      else if (strcmp(name,"SealevelchangeGrot")==0) return SealevelchangeGrotEnum;
+	      else if (strcmp(name,"SealevelchangeGSatGravirot")==0) return SealevelchangeGSatGravirotEnum;
 	      else if (strcmp(name,"SealevelchangeGUrot")==0) return SealevelchangeGUrotEnum;
 	      else if (strcmp(name,"SealevelchangeGNrot")==0) return SealevelchangeGNrotEnum;
 	      else if (strcmp(name,"SealevelchangeGErot")==0) return SealevelchangeGErotEnum;
-	      else if (strcmp(name,"SealevelchangeGsubelOcean")==0) return SealevelchangeGsubelOceanEnum;
-	      else if (strcmp(name,"SealevelchangeGUsubelOcean")==0) return SealevelchangeGUsubelOceanEnum;
-	      else if (strcmp(name,"SealevelchangeGEsubelOcean")==0) return SealevelchangeGEsubelOceanEnum;
-	      else if (strcmp(name,"SealevelchangeGNsubelOcean")==0) return SealevelchangeGNsubelOceanEnum;
-	      else if (strcmp(name,"SealevelchangeGsubelIce")==0) return SealevelchangeGsubelIceEnum;
-	      else if (strcmp(name,"SealevelchangeGUsubelIce")==0) return SealevelchangeGUsubelIceEnum;
-	      else if (strcmp(name,"SealevelchangeGEsubelIce")==0) return SealevelchangeGEsubelIceEnum;
-	      else if (strcmp(name,"SealevelchangeGNsubelIce")==0) return SealevelchangeGNsubelIceEnum;
-	      else if (strcmp(name,"SealevelchangeGsubelHydro")==0) return SealevelchangeGsubelHydroEnum;
-	      else if (strcmp(name,"SealevelchangeGUsubelHydro")==0) return SealevelchangeGUsubelHydroEnum;
-	      else if (strcmp(name,"SealevelchangeGEsubelHydro")==0) return SealevelchangeGEsubelHydroEnum;
-	      else if (strcmp(name,"SealevelchangeGNsubelHydro")==0) return SealevelchangeGNsubelHydroEnum;
+	      else if (strcmp(name,"SealevelchangeAlphaIndexOcean")==0) return SealevelchangeAlphaIndexOceanEnum;
+	      else if (strcmp(name,"SealevelchangeAlphaIndexIce")==0) return SealevelchangeAlphaIndexIceEnum;
+	      else if (strcmp(name,"SealevelchangeAlphaIndexHydro")==0) return SealevelchangeAlphaIndexHydroEnum;
+	      else if (strcmp(name,"SealevelchangeAzimuthIndexOcean")==0) return SealevelchangeAzimuthIndexOceanEnum;
+	      else if (strcmp(name,"SealevelchangeAzimuthIndexIce")==0) return SealevelchangeAzimuthIndexIceEnum;
+	      else if (strcmp(name,"SealevelchangeAzimuthIndexHydro")==0) return SealevelchangeAzimuthIndexHydroEnum;
 	      else if (strcmp(name,"SealevelchangeViscousRSL")==0) return SealevelchangeViscousRSLEnum;
+	      else if (strcmp(name,"SealevelchangeViscousSG")==0) return SealevelchangeViscousSGEnum;
 	      else if (strcmp(name,"SealevelchangeViscousU")==0) return SealevelchangeViscousUEnum;
 	      else if (strcmp(name,"SealevelchangeViscousN")==0) return SealevelchangeViscousNEnum;
@@ -979,5 +998,8 @@
 	      else if (strcmp(name,"SmbDailywindspeed")==0) return SmbDailywindspeedEnum;
 	      else if (strcmp(name,"SmbDini")==0) return SmbDiniEnum;
-	      else if (strcmp(name,"SmbDlwrf")==0) return SmbDlwrfEnum;
+         else stage=9;
+   }
+   if(stage==9){
+	      if (strcmp(name,"SmbDlwrf")==0) return SmbDlwrfEnum;
 	      else if (strcmp(name,"SmbDulwrfValue")==0) return SmbDulwrfValueEnum;
 	      else if (strcmp(name,"SmbDswrf")==0) return SmbDswrfEnum;
@@ -998,8 +1020,5 @@
 	      else if (strcmp(name,"SmbGdnini")==0) return SmbGdniniEnum;
 	      else if (strcmp(name,"SmbGsp")==0) return SmbGspEnum;
-         else stage=9;
-   }
-   if(stage==9){
-	      if (strcmp(name,"SmbGspini")==0) return SmbGspiniEnum;
+	      else if (strcmp(name,"SmbGspini")==0) return SmbGspiniEnum;
 	      else if (strcmp(name,"SmbHref")==0) return SmbHrefEnum;
 	      else if (strcmp(name,"SmbIsInitialized")==0) return SmbIsInitializedEnum;
@@ -1102,5 +1121,8 @@
 	      else if (strcmp(name,"ThermalforcingAutoregressionNoise")==0) return ThermalforcingAutoregressionNoiseEnum;
 	      else if (strcmp(name,"ThermalforcingValuesAutoregression")==0) return ThermalforcingValuesAutoregressionEnum;
-	      else if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
+         else stage=10;
+   }
+   if(stage==10){
+	      if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
 	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
 	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
@@ -1121,8 +1143,5 @@
 	      else if (strcmp(name,"VxSurface")==0) return VxSurfaceEnum;
 	      else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
-         else stage=10;
-   }
-   if(stage==10){
-	      if (strcmp(name,"VyBase")==0) return VyBaseEnum;
+	      else if (strcmp(name,"VyBase")==0) return VyBaseEnum;
 	      else if (strcmp(name,"Vy")==0) return VyEnum;
 	      else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
@@ -1141,6 +1160,4 @@
 	      else if (strcmp(name,"Waterfraction")==0) return WaterfractionEnum;
 	      else if (strcmp(name,"Waterheight")==0) return WaterheightEnum;
-	      else if (strcmp(name,"FrictionWaterPressure")==0) return FrictionWaterPressureEnum;
-	      else if (strcmp(name,"FrictionWaterPressureNoise")==0) return FrictionWaterPressureNoiseEnum;
 	      else if (strcmp(name,"WeightsLevelsetObservation")==0) return WeightsLevelsetObservationEnum;
 	      else if (strcmp(name,"WeightsSurfaceObservation")==0) return WeightsSurfaceObservationEnum;
@@ -1227,5 +1244,8 @@
 	      else if (strcmp(name,"Outputdefinition80")==0) return Outputdefinition80Enum;
 	      else if (strcmp(name,"Outputdefinition81")==0) return Outputdefinition81Enum;
-	      else if (strcmp(name,"Outputdefinition82")==0) return Outputdefinition82Enum;
+         else stage=11;
+   }
+   if(stage==11){
+	      if (strcmp(name,"Outputdefinition82")==0) return Outputdefinition82Enum;
 	      else if (strcmp(name,"Outputdefinition83")==0) return Outputdefinition83Enum;
 	      else if (strcmp(name,"Outputdefinition84")==0) return Outputdefinition84Enum;
@@ -1244,8 +1264,5 @@
 	      else if (strcmp(name,"Outputdefinition96")==0) return Outputdefinition96Enum;
 	      else if (strcmp(name,"Outputdefinition97")==0) return Outputdefinition97Enum;
-         else stage=11;
-   }
-   if(stage==11){
-	      if (strcmp(name,"Outputdefinition98")==0) return Outputdefinition98Enum;
+	      else if (strcmp(name,"Outputdefinition98")==0) return Outputdefinition98Enum;
 	      else if (strcmp(name,"Outputdefinition99")==0) return Outputdefinition99Enum;
 	      else if (strcmp(name,"Outputdefinition9")==0) return Outputdefinition9Enum;
@@ -1257,4 +1274,5 @@
 	      else if (strcmp(name,"AdjointBalancethicknessAnalysis")==0) return AdjointBalancethicknessAnalysisEnum;
 	      else if (strcmp(name,"AdjointHorizAnalysis")==0) return AdjointHorizAnalysisEnum;
+	      else if (strcmp(name,"AgeAnalysis")==0) return AgeAnalysisEnum;
 	      else if (strcmp(name,"AggressiveMigration")==0) return AggressiveMigrationEnum;
 	      else if (strcmp(name,"AmrBamg")==0) return AmrBamgEnum;
@@ -1327,4 +1345,5 @@
 	      else if (strcmp(name,"DoubleArrayInput")==0) return DoubleArrayInputEnum;
 	      else if (strcmp(name,"ArrayInput")==0) return ArrayInputEnum;
+	      else if (strcmp(name,"IntArrayInput")==0) return IntArrayInputEnum;
 	      else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
 	      else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
@@ -1348,5 +1367,8 @@
 	      else if (strcmp(name,"FSpressure")==0) return FSpressureEnum;
 	      else if (strcmp(name,"FSvelocity")==0) return FSvelocityEnum;
-	      else if (strcmp(name,"FemModel")==0) return FemModelEnum;
+         else stage=12;
+   }
+   if(stage==12){
+	      if (strcmp(name,"FemModel")==0) return FemModelEnum;
 	      else if (strcmp(name,"FileParam")==0) return FileParamEnum;
 	      else if (strcmp(name,"FixedTimestepping")==0) return FixedTimesteppingEnum;
@@ -1367,8 +1389,5 @@
 	      else if (strcmp(name,"GaussTetra")==0) return GaussTetraEnum;
 	      else if (strcmp(name,"GaussTria")==0) return GaussTriaEnum;
-         else stage=12;
-   }
-   if(stage==12){
-	      if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
+	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
 	      else if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
 	      else if (strcmp(name,"GenericExternalResult")==0) return GenericExternalResultEnum;
@@ -1394,4 +1413,6 @@
 	      else if (strcmp(name,"HydrologyShreveAnalysis")==0) return HydrologyShreveAnalysisEnum;
 	      else if (strcmp(name,"HydrologySolution")==0) return HydrologySolutionEnum;
+	      else if (strcmp(name,"HydrologySubsteps")==0) return HydrologySubstepsEnum;
+	      else if (strcmp(name,"HydrologySubTime")==0) return HydrologySubTimeEnum;
 	      else if (strcmp(name,"Hydrologydc")==0) return HydrologydcEnum;
 	      else if (strcmp(name,"Hydrologypism")==0) return HydrologypismEnum;
@@ -1445,4 +1466,6 @@
 	      else if (strcmp(name,"LovePMTF1t")==0) return LovePMTF1tEnum;
 	      else if (strcmp(name,"LovePMTF2t")==0) return LovePMTF2tEnum;
+	      else if (strcmp(name,"LoveYi")==0) return LoveYiEnum;
+	      else if (strcmp(name,"LoveRhs")==0) return LoveRhsEnum;
 	      else if (strcmp(name,"LoveSolution")==0) return LoveSolutionEnum;
 	      else if (strcmp(name,"MINI")==0) return MINIEnum;
@@ -1467,5 +1490,8 @@
 	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
 	      else if (strcmp(name,"MaxDivergence")==0) return MaxDivergenceEnum;
-	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
+         else stage=13;
+   }
+   if(stage==13){
+	      if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
 	      else if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
 	      else if (strcmp(name,"MaxVy")==0) return MaxVyEnum;
@@ -1490,8 +1516,5 @@
 	      else if (strcmp(name,"Nodal")==0) return NodalEnum;
 	      else if (strcmp(name,"Nodalvalue")==0) return NodalvalueEnum;
-         else stage=13;
-   }
-   if(stage==13){
-	      if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
+	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
 	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
 	      else if (strcmp(name,"None")==0) return NoneEnum;
@@ -1590,5 +1613,8 @@
 	      else if (strcmp(name,"StressbalanceVerticalAnalysis")==0) return StressbalanceVerticalAnalysisEnum;
 	      else if (strcmp(name,"StringArrayParam")==0) return StringArrayParamEnum;
-	      else if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
+         else stage=14;
+   }
+   if(stage==14){
+	      if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
 	      else if (strcmp(name,"StringParam")==0) return StringParamEnum;
 	      else if (strcmp(name,"SubelementFriction1")==0) return SubelementFriction1Enum;
@@ -1613,8 +1639,5 @@
 	      else if (strcmp(name,"TotalSmbScaled")==0) return TotalSmbScaledEnum;
 	      else if (strcmp(name,"TransientArrayParam")==0) return TransientArrayParamEnum;
-         else stage=14;
-   }
-   if(stage==14){
-	      if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
+	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
 	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
 	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
Index: issm/trunk/src/c/shared/Enum/Synchronize.sh
===================================================================
--- issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 27035)
+++ issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 27232)
@@ -17,5 +17,5 @@
 
 #Deal with Analyses
-if false ; then
+if false; then
 #Build EnumToAnalysis.cpp {{{
 #Header
Index: issm/trunk/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 27035)
+++ issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 27232)
@@ -56,5 +56,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<pthread_t>(threads);
 	xDelete<pthread_handle>(handles);
Index: issm/trunk/src/c/shared/Triangle/TriangleUtils.cpp
===================================================================
--- issm/trunk/src/c/shared/Triangle/TriangleUtils.cpp	(revision 27035)
+++ issm/trunk/src/c/shared/Triangle/TriangleUtils.cpp	(revision 27232)
@@ -232,5 +232,5 @@
 	}// for (;;)
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<int>(GridElements);
 	/*Assign output pointers: */
@@ -422,5 +422,5 @@
 	}
 
-	/*Free ressources: */
+	/*Free resources: */
 	xDelete<int>(segments);
 
Index: issm/trunk/src/c/solutionsequences/convergence.cpp
===================================================================
--- issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 27035)
+++ issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 27232)
@@ -1,5 +1,5 @@
 /*!\file: convergence.cpp
  * \brief: figure out if convergence has been reached
- */ 
+ */
 
 #include "../classes/classes.h"
@@ -21,13 +21,20 @@
 	IssmDouble res;
 	int analysis_type;
+	int ufsize;
 
 	if(VerboseModule()) _printf0_("   checking convergence\n");
 
-	/*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from 
+	/*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from
 	 * the get go: */
-	if(uf->IsEmpty()){
+	uf->GetSize(&ufsize);
+	if(ufsize==0){
 		*pconverged=true;
 		return;
 	}
+
+	/* if(uf->IsEmpty()){ */
+	/* 	*pconverged=true; */
+	/* 	return; */
+	/* } */
 
 	/*Force equilibrium (Mandatory)*/
@@ -38,5 +45,5 @@
 	KUoldF=KUold->Duplicate();KUold->Copy(KUoldF); KUoldF->AYPX(pf,-1.0);
 	nKUoldF=KUoldF->Norm(NORM_TWO);
-	nF=pf->Norm(NORM_TWO);
+	nF=pf->Norm(NORM_TWO)+1.e-14;
 	res=nKUoldF/nF;
 	if (xIsNan<IssmDouble>(res)){
@@ -54,5 +61,5 @@
 		converged=true;
 	}
-	else{ 
+	else{
 		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<<" > "<<eps_res*100<<" %\n");
 		converged=false;
@@ -64,5 +71,5 @@
 		//compute norm(du)/norm(u)
 		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
-		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
+		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO)+1.e-14;
 
 		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
@@ -76,5 +83,5 @@
 				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
 			}
-			else{ 
+			else{
 				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
 				converged=false;
Index: issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp
===================================================================
--- issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 27035)
+++ issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 27232)
@@ -10,5 +10,5 @@
 #include "../solutionsequences/solutionsequences.h"
 
-void solutionsequence_hydro_nonlinear(FemModel* femmodel){
+void solutionsequence_hydro_nonlinear(FemModel* femmodel, bool* pconv_fail){
 	/*solution : */
 	Vector<IssmDouble>* ug_sed=NULL;
@@ -16,14 +16,14 @@
 	Vector<IssmDouble>* uf_sed_sub_iter=NULL;
 	Vector<IssmDouble>* ug_sed_main_iter=NULL;
+	Vector<IssmDouble>* ug_sed_init=NULL;
 
 	Vector<IssmDouble>* ug_epl=NULL;
 	Vector<IssmDouble>* uf_epl=NULL;
 	Vector<IssmDouble>* uf_epl_sub_iter=NULL;
-	Vector<IssmDouble>* ug_epl_sub_iter=NULL;
 	Vector<IssmDouble>* ug_epl_main_iter=NULL;
+	Vector<IssmDouble>* ug_epl_init=NULL;
 
 	Vector<IssmDouble>* ys=NULL;
 	Vector<IssmDouble>* dug=NULL;
-	Vector<IssmDouble>* duf=NULL;
 
 	Matrix<IssmDouble>* Kff=NULL;
@@ -38,10 +38,12 @@
 	bool       sedconverged,eplconverged,hydroconverged;
 	bool       isefficientlayer;
+	bool       sliceadapt;
 	int        constraints_converged;
 	int        num_unstable_constraints;
 	int        sedcount,eplcount,hydrocount;
 	int        hydro_maxiter;
+	int        epl_fsize,epl_sub_fsize,epl_main_fsize;
 	IssmDouble sediment_kmax;
-	IssmDouble eps_hyd;
+	IssmDouble eps_res,eps_rel,eps_abs;
 	IssmDouble ndu_sed,nu_sed;
 	IssmDouble ndu_epl,nu_epl;
@@ -50,6 +52,9 @@
 	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
 	femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	femmodel->parameters->FindParam(&sliceadapt,HydrologyStepAdaptEnum);
 	femmodel->parameters->FindParam(&hydro_maxiter,HydrologydcMaxIterEnum);
-	femmodel->parameters->FindParam(&eps_hyd,HydrologydcRelTolEnum);
+	femmodel->parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	femmodel->parameters->FindParam(&eps_rel,HydrologydcRelTolEnum);
+	femmodel->parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
 	hydrocount=1;
 	hydroconverged=false;
@@ -59,5 +64,11 @@
 	/*{{{*//*Retrieve inputs as the initial state for the non linear iteration*/
 	GetBasalSolutionFromInputsx(&ug_sed,femmodel);
+	/*Initialize the IDS element mask to exclude frozen nodes*/
+	inefanalysis->ElementizeIdsMask(femmodel);
+
 	Reducevectorgtofx(&uf_sed, ug_sed, femmodel->nodes,femmodel->parameters);
+	ug_sed_init=ug_sed->Duplicate();
+	ug_sed->Copy(ug_sed_init);
+
 	if(isefficientlayer) {
 		inefanalysis = new HydrologyDCInefficientAnalysis();
@@ -65,15 +76,12 @@
 		femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
 		GetBasalSolutionFromInputsx(&ug_epl,femmodel);
-		/*Initialize the EPL element mask*/
 		inefanalysis->ElementizeEplMask(femmodel);
 		effanalysis->InitZigZagCounter(femmodel);
-		/*Initialize the IDS element mask*/
-		femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
-		inefanalysis->ElementizeIdsMask(femmodel);
+		ug_epl_init=ug_epl->Duplicate();
+		ug_epl->Copy(ug_epl_init);
 	}
 	/*}}}*/
 	/*The real computation starts here, outermost loop is on the two layer system*/
 	for(;;){
-
 		sedcount=1;
 		eplcount=1;
@@ -105,4 +113,5 @@
 				/*{{{*//*Core of the computation*/
 				if(VerboseSolution()) _printf0_("Building Sediment Matrix...\n");
+
 				femmodel->profiler->Start(SEDMatrix);
 				SystemMatricesx(&Kff,&Kfs,&pf,&df,&sediment_kmax,femmodel);
@@ -114,7 +123,6 @@
 				femmodel->profiler->Start(SOLVER);
 				Solverx(&uf_sed,Kff,pf,uf_sed_sub_iter,df,femmodel->parameters);
+				delete df;
 				femmodel->profiler->Stop(SOLVER);
-
-				delete Kff; delete pf; delete df;
 				delete ug_sed;
 				femmodel->profiler->Start(SEDUpdate);
@@ -125,8 +133,18 @@
 				/*}}}*/
 				if (!sedconverged){
+					/*First check that all the penalizations are applied*/
 					if(VerboseConvergence()) _printf0_("   # Sediment unstable constraints = " << num_unstable_constraints << "\n");
-					if(num_unstable_constraints==0) sedconverged = true;
+					if(num_unstable_constraints==0) {
+						sedconverged = true;
+					}
+					else{//clean up
+						delete Kff;
+						delete pf;
+					}
 					if (sedcount>=hydro_maxiter){
+						delete ug_sed;delete uf_sed;delete inefanalysis; delete ug_sed_main_iter;
+						if(isefficientlayer)delete ug_epl;delete effanalysis; delete ug_epl_main_iter;
 						_error_("   maximum number of Sediment iterations (" << hydro_maxiter << ") exceeded");
+
 					}
 				}
@@ -135,23 +153,9 @@
 				if(sedconverged)break;
 			}
-
 			/*}}}*//*End of the sediment penalization loop*/
 			sedconverged=false;
-
 			/*Checking convergence on the value of the sediment head*/
-			duf=uf_sed_sub_iter->Duplicate();_assert_(duf);
-			uf_sed_sub_iter->Copy(duf);
-			duf->AYPX(uf_sed,-1.0);
-			ndu_sed=duf->Norm(NORM_TWO);
-			delete duf;
-			nu_sed=uf_sed_sub_iter->Norm(NORM_TWO);
-			if (xIsNan<IssmDouble>(ndu_sed) || xIsNan<IssmDouble>(nu_sed)) _error_("convergence criterion is NaN!");
-			if (ndu_sed==0.0 && nu_sed==0.0) nu_sed=1.0e-6; /*Hacking the case where the layer is empty*/
-			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Inner Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << "%, aiming lower than " << eps_hyd*10*100 << " %\n");
-			if((ndu_sed/nu_sed)<eps_hyd*10.){
-				if(VerboseConvergence()) _printf0_("   # Inner sediment convergence achieve \n");
-				sedconverged=true;
-			}
-			delete uf_sed_sub_iter;
+			convergence(&sedconverged,Kff,pf,uf_sed,uf_sed_sub_iter,eps_res,eps_rel,eps_abs);
+			delete Kff; delete pf;delete uf_sed_sub_iter;
 			if(sedconverged){
 				femmodel->parameters->SetParam(sediment_kmax,HydrologySedimentKmaxEnum);
@@ -176,6 +180,4 @@
 			for(;;){
 				eplconverged=false;
-				ug_epl_sub_iter=ug_epl->Duplicate();_assert_(ug_epl_sub_iter);
-				ug_epl->Copy(ug_epl_sub_iter);
 				/*{{{*//*Retrieve the EPL head slopes and compute EPL Thickness*/
 				if(VerboseSolution()) _printf0_("computing EPL Head slope...\n");
@@ -194,20 +196,19 @@
 				/*}}}*/
 				femmodel->profiler->Stop(EPLMasking);
+				Reducevectorgtofx(&uf_epl, ug_epl, femmodel->nodes,femmodel->parameters);
 				if(VerboseSolution()) _printf0_("Building EPL Matrix...\n");
+				uf_epl_sub_iter=uf_epl->Duplicate();_assert_(uf_epl_sub_iter);
+				uf_epl->Copy(uf_epl_sub_iter);
+				uf_epl->GetSize(&epl_sub_fsize);
 				femmodel->profiler->Start(EPLMatrices);
 				SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
 				CreateNodalConstraintsx(&ys,femmodel->nodes);
-				Reduceloadx(pf,Kfs,ys); delete Kfs;
-				delete uf_epl;
+				Reduceloadx(pf,Kfs,ys);
+				delete Kfs;delete uf_epl;
 				femmodel->profiler->Stop(EPLMatrices);
 				femmodel->profiler->Start(SOLVER);
 				Solverx(&uf_epl,Kff,pf,uf_epl_sub_iter,df,femmodel->parameters);
 				femmodel->profiler->Stop(SOLVER);
-
-				delete Kff; delete pf; delete df;
-				delete uf_epl_sub_iter;
-				uf_epl_sub_iter=uf_epl->Duplicate();_assert_(uf_epl_sub_iter);
-				uf_epl->Copy(uf_epl_sub_iter);
-				delete ug_epl;
+				delete df;delete ug_epl;
 				femmodel->profiler->Start(EPLUpdate);
 				Mergesolutionfromftogx(&ug_epl,uf_epl,ys,femmodel->nodes,femmodel->parameters); delete ys;
@@ -215,25 +216,33 @@
 				ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
 				femmodel->profiler->Stop(EPLUpdate);
-
-				dug=ug_epl_sub_iter->Duplicate();_assert_(dug);
-				ug_epl_sub_iter->Copy(dug);
-				dug->AYPX(ug_epl,-1.0);
-				ndu_epl=dug->Norm(NORM_TWO);
-				delete dug;
-				nu_epl=ug_epl_sub_iter->Norm(NORM_TWO);
-				if (xIsNan<IssmDouble>(ndu_epl) || xIsNan<IssmDouble>(nu_epl)) _error_("convergence criterion is NaN!");
-				if (ndu_epl==0.0 && nu_epl==0.0) nu_epl=1.0e-6; /*Hacking the case where the EPL is used but empty*/
-				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Inner EPL Convergence criterion:" << ndu_epl/nu_epl*100 << "%, aiming lower than " << eps_hyd*10*100 << " %\n");
-				if((ndu_epl/nu_epl)<eps_hyd*10.) eplconverged=true;
-				if (eplcount>=hydro_maxiter){
+				uf_epl->GetSize(&epl_fsize);
+				if(epl_fsize-epl_sub_fsize==0){
+					convergence(&eplconverged,Kff,pf,uf_epl,uf_epl_sub_iter,eps_res,eps_rel,eps_abs);
+					delete Kff; delete pf;
+				}
+				else{
+					delete Kff; delete pf;
+				}
+
+				if (eplcount>=hydro_maxiter*9/10 && sliceadapt && !eplconverged) {
+					if(VerboseSolution()) _printf0_("epl did not converged after "<<eplconverged<<" iteration, we refine the steping\n");
+					*pconv_fail = true;
+					InputUpdateFromSolutionx(femmodel,ug_epl_init);
+					delete ug_epl_init;
+					femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
+					InputUpdateFromSolutionx(femmodel,ug_sed_init);
+					delete ug_sed_init;
+					break;
+				}
+				else if (eplcount>=hydro_maxiter){
+					delete ug_sed;delete uf_sed;delete inefanalysis;delete ug_sed_main_iter;
+					delete ug_epl;delete uf_epl;delete effanalysis;delete ug_epl_main_iter;
 					_error_("   maximum number of EPL iterations (" << hydro_maxiter << ") exceeded");
+
 				}
 				eplcount++;
-
-				delete ug_epl_sub_iter;
+				delete uf_epl_sub_iter; delete uf_epl;
 				if(eplconverged){
 					if(VerboseSolution()) _printf0_("eplconverged...\n");
-					InputUpdateFromConstantx(femmodel,eplconverged,ConvergedEnum);
-					InputUpdateFromSolutionx(femmodel,ug_epl);
 					effanalysis->ResetCounter(femmodel);
 					break;
@@ -242,4 +251,7 @@
 		}
 		femmodel->profiler->Stop(EPLLOOP);
+		if(*pconv_fail){
+			break;
+		}
 		/*}}}*//*End of the global EPL loop*/
 		/*{{{*//*Now dealing with the convergence of the whole system*/
@@ -264,18 +276,32 @@
 			if (xIsNan<IssmDouble>(ndu_epl) || xIsNan<IssmDouble>(nu_epl)) _error_("EPL convergence criterion is NaN!");
 			if (ndu_epl==0.0 && nu_epl==0.0) nu_epl=1.0e-6; /*Hacking the case where the EPL is used but empty*/
-			if (!xIsNan<IssmDouble>(eps_hyd)){
-				if ((ndu_epl/nu_epl)<eps_hyd && (ndu_sed/nu_sed)<(eps_hyd)){
+			if (!xIsNan<IssmDouble>(eps_rel)){
+				if ((ndu_epl/nu_epl)<eps_rel && (ndu_sed/nu_sed)<(eps_rel)){
 					if (VerboseConvergence()) _printf0_(setw(50) << left << "   Converged after, " << hydrocount << " iterations \n");
 					hydroconverged=true;
 				}
 				else{
-					if(VerboseConvergence()) _printf0_(setw(50) << left << "   Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << "%, aiming lower than " << eps_hyd*100 << " %\n");
-					if(VerboseConvergence()) _printf0_(setw(50) << left << "   EPL Convergence criterion:" << ndu_epl/nu_epl*100 << "%, aiming lower than " << eps_hyd*100 << " %\n");
+					if(VerboseConvergence()) _printf0_(setw(50) << left << "   for iteration:" << hydrocount << " \n");
+					if(VerboseConvergence()) _printf0_(setw(50) << left << "   Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << "%, aiming lower than " << eps_rel*100 << " %\n");
+					if(VerboseConvergence()) _printf0_(setw(50) << left << "   EPL Convergence criterion:" << ndu_epl/nu_epl*100 << "%, aiming lower than " << eps_rel*100 << " %\n");
 					hydroconverged=false;
 				}
 			}
 			else _printf0_(setw(50) << left << "   Convergence criterion:" << ndu_sed/nu_sed*100 << " %\n");
+
+			if (hydrocount>=hydro_maxiter*9/10  && sliceadapt && !hydroconverged) {
+				if(VerboseSolution()) _printf0_("hydrology main loop  did not converged after "<<hydrocount<<" iteration, we refine the steping\n");
+				*pconv_fail = true;
+				InputUpdateFromSolutionx(femmodel,ug_epl_init);
+				delete ug_epl_init;
+				femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
+				InputUpdateFromSolutionx(femmodel,ug_sed_init);
+				delete ug_sed_init;
+				break;
+			}
 			if (hydrocount>=hydro_maxiter){
 				_error_("   maximum number for hydrological global iterations (" << hydro_maxiter << ") exceeded");
+				delete ug_sed;delete uf_sed;delete effanalysis;
+				delete ug_epl;	delete uf_epl;	delete inefanalysis;
 			}
 		}
@@ -284,14 +310,14 @@
 	}
 	/*}}}*/
-	if(isefficientlayer)InputUpdateFromSolutionx(femmodel,ug_epl);
-	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
-	InputUpdateFromSolutionx(femmodel,ug_sed);
-	/*Free ressources: */
-	delete ug_epl;
-	delete ug_sed;
+	/*To deal with adaptative stepping we only save results if we are actually converged*/
+	if(hydroconverged){
+		if(isefficientlayer){
+			delete ug_epl_init;
+		}
+		delete ug_sed_init;
+	}
+	/*Free resources: */
+	delete ug_epl;delete ug_sed;
 	delete uf_sed;
-	delete uf_epl;
-	delete uf_epl_sub_iter;
-	delete inefanalysis;
-	delete effanalysis;
+	delete inefanalysis;	delete effanalysis;
 }
Index: issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp
===================================================================
--- issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 27035)
+++ issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 27232)
@@ -131,5 +131,5 @@
 	}
 
-	/*Free ressources: */
+	/*Free resources: */
 	delete tg;
 	delete tf;
Index: issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 27035)
+++ issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 27232)
@@ -13,5 +13,5 @@
 
 void solutionsequence_thermal_nonlinear(FemModel* femmodel);
-void solutionsequence_hydro_nonlinear(FemModel* femmodel);
+void solutionsequence_hydro_nonlinear(FemModel* femmodel, bool* conv_fail);
 void solutionsequence_shakti_nonlinear(FemModel* femmodel);
 void solutionsequence_glads_nonlinear(FemModel* femmodel);
Index: issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 27232)
@@ -266,5 +266,5 @@
 			/*}}}*/
 
-			/*Free ressources:{{{*/
+			/*Free resources:{{{*/
 			xDelete<int>(RowRank);
 			xDelete<int>(row_indices_forcpu);
@@ -376,5 +376,5 @@
 			}
 
-			/*Free ressources: */
+			/*Free resources: */
 			xDelete<doubletype>(X_serial);
 		}
Index: issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 27232)
@@ -292,5 +292,5 @@
 			for(int i=0;i<this->m;i++) this->matrix[i]->SetValues(numvalues_perrow[i],cols_perrow[i],values_perrow[i],mods_perrow[i]);
 
-			/*Free ressources*/
+			/*Free resources:*/
 			xDelete<int>(numvalues_perrow);
 			xDelete<int>(RowRank);
@@ -394,5 +394,5 @@
 			}
 
-			/*Free ressources: */
+			/*Free resources: */
 			xDelete<doubletype>(X_serial);
 		}
Index: issm/trunk/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 27232)
@@ -279,5 +279,5 @@
 			this->isassembled=true;
 
-			/*Free ressources:{{{*/
+			/*Free resources:{{{*/
 			xDelete<int>(RowRank);
 			xDelete<int>(row_indices_forcpu);
@@ -468,5 +468,5 @@
 			/*All gather:*/
 			ISSM_MPI_Allgatherv(this->vector, this->m, TypeToMPIType<doubletype>(), buffer, recvcounts, displs, TypeToMPIType<doubletype>(),comm);
-			/*free ressources: */
+			/*Free resources: */
 			xDelete<int>(recvcounts);
 			xDelete<int>(displs);
Index: issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 27232)
@@ -48,5 +48,5 @@
 	else _error_("matrix type not supported yet!");
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<char>(mat_type);
 
@@ -78,5 +78,5 @@
 	else _error_("vector type not supported yet!");
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<char>(vec_type);
 
@@ -107,5 +107,5 @@
 	else _error_("solver type not supported yet!");
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<char>(solver_type);
 
Index: issm/trunk/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp
===================================================================
--- issm/trunk/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp	(revision 27232)
@@ -50,5 +50,5 @@
 	local_size=num_local_rows[my_rank];
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<int>(num_local_rows);
 
Index: issm/trunk/src/c/toolkits/objects/Matrix.h
===================================================================
--- issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 27232)
@@ -151,5 +151,5 @@
 			}
 
-			/*Free ressources: */
+			/*Free resources: */
 			xDelete<char>(toolkittype);
 		}
Index: issm/trunk/src/c/toolkits/objects/Vector.h
===================================================================
--- issm/trunk/src/c/toolkits/objects/Vector.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/objects/Vector.h	(revision 27232)
@@ -123,5 +123,5 @@
 			}
 
-			/*Free ressources: */
+			/*Free resources: */
 			xDelete<char>(toolkittype);
 		}
Index: issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 27232)
@@ -8,6 +8,4 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
-
-#include <petscversion.h>
 
 #include "./PetscSolver.h"
@@ -228,5 +226,5 @@
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(pressure_indices);
 	xDelete<int>(velocity_indices);
Index: issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 27232)
@@ -10,6 +10,4 @@
 
 /*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 27232)
@@ -10,6 +10,4 @@
 
 /*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 27232)
@@ -10,6 +10,4 @@
 
 /*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 27232)
@@ -10,7 +10,4 @@
 
 /*Petsc includes: */
-#include <petscversion.h>
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 27232)
@@ -10,7 +10,4 @@
 
 /*Petsc includes: */
-#include <petscversion.h>
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 27232)
@@ -10,7 +10,4 @@
 
 /*Petsc includes: */
-#include <petscversion.h>
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
@@ -107,5 +104,5 @@
 	VecAssemblyEnd(outvector);; 
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	xDelete<int>(index);
 	xDelete<double>(values);	
Index: issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 27232)
@@ -10,7 +10,4 @@
 
 /*Petsc includes: */
-#include <petscversion.h>
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 27232)
@@ -10,7 +10,5 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscksp.h>
 
 #include "./petscpatches.h"
Index: issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 27232)
@@ -10,7 +10,4 @@
 
 /*Petsc includes: */
-#include <petscversion.h>
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 27232)
@@ -10,7 +10,4 @@
 
 /*Petsc includes: */
-#include <petscversion.h>
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
 
Index: issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 27232)
@@ -93,5 +93,5 @@
 	*pgathered_vector=gathered_vector;
 
-	/*free ressources: */
+	/*Free resources: */
 	xDelete<int>(idxn);
 	xDelete<double>(local_vector);
Index: issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 27232)
@@ -6,8 +6,5 @@
 #define _PETSC_PATCHES_H_
 
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
-#include <petscsys.h>
 
 #include "./SolverEnum.h"
Index: issm/trunk/src/c/toolkits/petsc/petscincludes.h
===================================================================
--- issm/trunk/src/c/toolkits/petsc/petscincludes.h	(revision 27035)
+++ issm/trunk/src/c/toolkits/petsc/petscincludes.h	(revision 27232)
@@ -9,8 +9,5 @@
 
 /*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
 #include <petscksp.h>
-#include <petscsys.h>
 
 /*our own patches: */
Index: issm/trunk/src/m/classes/SMBgemb.m
===================================================================
--- issm/trunk/src/m/classes/SMBgemb.m	(revision 27035)
+++ issm/trunk/src/m/classes/SMBgemb.m	(revision 27232)
@@ -73,5 +73,5 @@
 		% 2: default value of 1, in areas with grain radius below teThresh and areas of dry snow (not bare ice or wet) at the surface
 
-		swIdx  = NaN; % apply all SW to top grid cell (0) or allow SW to penetrate surface (1) (default 1, if aIdx=2 function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002))
+		swIdx  = NaN; %apply all SW to top grid cell (0) or allow SW to penetrate surface (1) (default 0, if swIdx=1 and aIdx=2, function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002))
 
 		denIdx = NaN; %densification model to use (default is 2):
@@ -236,5 +236,5 @@
 			end
 
-			fielddisplay(self,'swIdx','apply all SW to top grid cell (0) or allow SW to penetrate surface (1) [default 1, if aIdx=2 function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002)]');
+			fielddisplay(self,'swIdx','apply all SW to top grid cell (0) or allow SW to penetrate surface (1) [default 0, if swIdx=1 and aIdx=2 function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002)]');
 			fielddisplay(self,'denIdx',{'densification model to use (default is 2):',...
 				'1 = emperical model of Herron and Langway (1980)',...
@@ -343,5 +343,5 @@
 			self.aIdx = 1;
 			self.eIdx = 1;
-			self.swIdx = 1;
+			self.swIdx = 0;
 			self.denIdx = 2;
 			self.dsnowIdx = 1;
Index: issm/trunk/src/m/classes/SMBgemb.py
===================================================================
--- issm/trunk/src/m/classes/SMBgemb.py	(revision 27035)
+++ issm/trunk/src/m/classes/SMBgemb.py	(revision 27232)
@@ -80,5 +80,5 @@
         # 2: default value of 1, in areas with grain radius below teThresh and areas of dry snow (not bare ice or wet) at the surface
 
-        self.swIdx                  = np.nan    # apply all SW to top grid cell (0) or allow SW to penetrate surface (1) (default 1, if aIdx=2 function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002))
+        self.swIdx                  = np.nan    # apply all SW to top grid cell (0) or allow SW to penetrate surface (1) (default 0, if swIdx=1 and aIdx=2, function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002)) 
 
         self.denIdx                 = np.nan    # densification model to use (default is 2):
@@ -238,5 +238,5 @@
             s += '{}\n'.format(fielddisplay(self, 'K', 'time scale temperature coef. (7) [d]'))
 
-        s += '{}\n'.format(fielddisplay(self, 'swIdx', 'apply all SW to top grid cell (0) or allow SW to penetrate surface (1) [default 1, if aIdx=2 function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002)]'))
+        s += '{}\n'.format(fielddisplay(self, 'swIdx', 'apply all SW to top grid cell (0) or allow SW to penetrate surface (1) [default 0, if swIdx=1 and aIdx=2 function of effective radius (Brun et al., 1992) or else dependent on snow density (taken from Bassford, 2002)]'))
         s += '{}\n'.format(fielddisplay(self, 'denIdx', ['densification model to use (default is 2):',
             '1 = emperical model of Herron and Langway (1980)',
@@ -330,5 +330,5 @@
         self.aIdx = 1
         self.eIdx = 1
-        self.swIdx = 1
+        self.swIdx = 0 
         self.denIdx = 2
         self.dsnowIdx = 1
Index: issm/trunk/src/m/classes/age.m
===================================================================
--- issm/trunk/src/m/classes/age.m	(revision 27232)
+++ issm/trunk/src/m/classes/age.m	(revision 27232)
@@ -0,0 +1,115 @@
+%AGE class definition
+%
+%   Usage:
+%      age=age();
+
+classdef age
+	properties (SetAccess=public)
+		 spcage                 = NaN;
+		 stabilization          = 0;
+		 requested_outputs      = {};
+	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of this class and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(self)
+				disp('Recovering age from older version');
+				self = structtoobj(age(),self);
+			end
+		end% }}}
+	end
+	methods
+		function self = age(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('age');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							self.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.spcage=project3d(md,'vector',self.spcage,'type','node');
+		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+
+			list = {'Age'};
+
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
+			self.stabilization=2;
+
+			%default output
+			self.requested_outputs={'default'};
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember('AgeAnalysis',analyses) |  (strcmp(solution,'TransientSolution') & md.transient.isage==0), return; end
+			if dimension(md.mesh)~=3
+				md = checkmessage(md,['age model only supported in 3D']);
+			end
+
+			md = checkfield(md,'fieldname','age.spcage','Inf',1,'timeseries',1);
+			md = checkfield(md,'fieldname','age.stabilization','values',[0 1 2 4 5]);
+			md = checkfield(md,'fieldname','age.requested_outputs','stringrow',1);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Masstransport solution parameters:'));
+			fielddisplay(self,'spcage','Age constraint (NaN means no constraint) [yr]');
+			fielddisplay(self,'stabilization','0: no stabilization, 1: artificial diffusion, 2: streamline upwinding, 4: flux corrected transport, 5: streamline upwind Petrov-Galerkin (SUPG)');
+			fielddisplay(self,'requested_outputs','additional outputs requested');
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+
+			yts=md.constants.yts;
+
+			WriteData(fid,prefix,'object',self,'fieldname','spcage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+			WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer');
+
+			%process requested outputs
+			outputs = self.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
+			end
+			WriteData(fid,prefix,'data',outputs,'name','md.age.requested_outputs','format','StringArray');
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+
+			writejs1Darray(fid,[modelname '.age.spcage'],self.spcage);
+			writejsdouble(fid,[modelname '.age.stabilization'],self.stabilization);
+			writejscellstring(fid,[modelname '.age.requested_outputs'],self.requested_outputs);
+
+		end % }}}
+	end
+end
Index: issm/trunk/src/m/classes/calvingparameterization.m
===================================================================
--- issm/trunk/src/m/classes/calvingparameterization.m	(revision 27035)
+++ issm/trunk/src/m/classes/calvingparameterization.m	(revision 27232)
@@ -6,12 +6,12 @@
 classdef calvingparameterization
 	properties (SetAccess=public) 
-		stress_threshold_groundedice = 0.;
-		stress_threshold_floatingice = 0.;
 		min_thickness = 0.;
 		use_param = 0;
-		scale_theta = 0.;
-		amp_alpha = 0;
-		midp = 0;
-		nonlinearlaw = 0;
+		theta = 0.;
+		alpha = 0;
+		xoffset = 0;
+		yoffset = 0;
+		vel_upperbound = 6000;
+		vel_lowerbound = 0;
 	end
 	methods
@@ -37,24 +37,23 @@
 		end % }}}
 		function self = setdefaultparameters(self) % {{{
-
-			%Default sigma max
-			self.stress_threshold_groundedice = 1e6;
-			self.stress_threshold_floatingice = 150e3;
-
 			%For now we turn this off by setting the threshold to 0
 			self.min_thickness = 0.;
 
 			%parameters for the spatial temporal seperation 
-			%The coefficient follows: \gamma = \frac{\theta}{2}(1-\tanh(\frac{b+p}{\alpha}))+(1-\theta)
-			% 0 - Use bed elevation, 1 - use heigh above floatation
+			%The coefficient follows: gamma= f(x)
+			% 0 - f(x) = y_{o} + \alpha (x+x_{o})
+			% 1 - f(x)=y_{o}-\frac{\theta}{2}\tanh(\alpha(x+x_{o}))
 			self.use_param = 0;
-			% between 0 and 1, larger theta means more reduction for shallower ice
-			self.scale_theta = 0;
-			% alpha in the denominator
-			self.amp_alpha = 0;
-			% mid-point of this step function
-			self.midp = 0;
-			% if use a nonlinear calving law
-			self.nonlinearlaw = 0;
+			% the amplifier
+			self.theta = 0;
+			% the slope alpha 
+			self.alpha = 0;
+			% offset in x-axis 
+			self.xoffset = 0;
+			% offset in y-axis 
+			self.yoffset = 0;
+			% velocity thresholds to reduce calving rate
+			vel_upperbound = 6000; % m/a
+			vel_lowerbound = 0; % m/a
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
@@ -62,36 +61,35 @@
 			if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
 
-			md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'nan',1,'Inf',1);
-			md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'nan',1,'Inf',1);
 			md = checkfield(md,'fieldname','calving.min_thickness','>=',0,'NaN',1,'Inf',1,'numel',1);
 			md = checkfield(md,'fieldname','calving.use_param','values',[-1, 0, 1, 2, 3, 4]);
-			md = checkfield(md,'fieldname','calving.scale_theta','NaN',1,'Inf',1,'numel',1);
-			md = checkfield(md,'fieldname','calving.amp_alpha','<>',0,'NaN',1,'Inf',1,'numel',1);
-			md = checkfield(md,'fieldname','calving.midp','NaN',1,'Inf',1,'numel',1);
-			md = checkfield(md,'fieldname','calving.nonlinearlaw','values',[0, 1]);
+			md = checkfield(md,'fieldname','calving.theta','NaN',1,'Inf',1,'numel',1);
+			md = checkfield(md,'fieldname','calving.alpha','NaN',1,'Inf',1,'numel',1);
+			md = checkfield(md,'fieldname','calving.xoffset','NaN',1,'Inf',1,'numel',1);
+			md = checkfield(md,'fieldname','calving.yoffset','NaN',1,'Inf',1,'numel',1);
+			md = checkfield(md,'fieldname','calving.vel_lowerbound','NaN',1,'Inf',1,'numel',1);
+			md = checkfield(md,'fieldname','calving.vel_upperbound','NaN',1,'Inf',1,'numel',1);
 		end % }}}
 		function disp(self) % {{{
 			disp(sprintf('   Calving test parameters:'));
-			fielddisplay(self,'stress_threshold_groundedice','sigma_max applied to grounded ice only [Pa]');
-			fielddisplay(self,'stress_threshold_floatingice','sigma_max applied to floating ice only [Pa]');
 			fielddisplay(self,'min_thickness','minimum thickness below which no ice is allowed [m]');
-			fielddisplay(self,'use_param','0 - Use bed elevation, 1 - use heigh above floatation, 2 - use ice thickness');
-			fielddisplay(self,'scale_theta','larger than 0, larger theta means more reduction for shallower ice');
-			fielddisplay(self,'amp_alpha','alpha');
-			fielddisplay(self,'midp','mid-point');
-			fielddisplay(self,'nonlinearlaw','use a nonlinear law');
-
+			fielddisplay(self,'use_param','-1 - just use frontal ablation rate, 0 - f(x) = y_{o} + \alpha (x+x_{o}), 1 - f(x)=y_{o}-\frac{\theta}{2}\tanh(\alpha(x+x_{o})), 2 - tanh(thickness), 3 - tanh(normalized vel), 4 - tanh(truncated vel)');
+			fielddisplay(self,'theta','the amplifier');
+			fielddisplay(self,'alpha','the slope');
+			fielddisplay(self,'xoffset','offset in x-axis');
+			fielddisplay(self,'yoffset','offset in y-axis');
+			fielddisplay(self,'vel_lowerbound','lowerbound of ice velocity to reduce the calving rate [m/a]');
+			fielddisplay(self,'vel_upperbound','upperbound of ice velocity to reduce the calving rate [m/a]');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
 			yts=md.constants.yts;
 			WriteData(fid,prefix,'name','md.calving.law','data',9,'format','Integer');
-			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1);
-			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',self,'fieldname','min_thickness','format','Double');
 			WriteData(fid,prefix,'object',self,'fieldname','use_param','format','Integer');
-			WriteData(fid,prefix,'object',self,'fieldname','scale_theta','format','Double');
-			WriteData(fid,prefix,'object',self,'fieldname','amp_alpha','format','Double');
-			WriteData(fid,prefix,'object',self,'fieldname','midp','format','Double');
-			WriteData(fid,prefix,'object',self,'fieldname','nonlinearlaw','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','theta','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','alpha','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','xoffset','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','yoffset','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','vel_lowerbound','format','Double','scale', 1./yts);
+			WriteData(fid,prefix,'object',self,'fieldname','vel_upperbound','format','Double','scale', 1./yts);
 		end % }}}
 	end
Index: issm/trunk/src/m/classes/clusters/generic_static.m
===================================================================
--- issm/trunk/src/m/classes/clusters/generic_static.m	(revision 27035)
+++ issm/trunk/src/m/classes/clusters/generic_static.m	(revision 27232)
@@ -39,4 +39,8 @@
 			disp(sprintf('    interactive: %s',cluster.interactive));
 			disp(sprintf('    shell: %s',cluster.shell));
+		end
+		%}}}
+		function numprocs=nprocs(cluster) % {{{
+			numprocs=cluster.np;
 		end
 		%}}}
Index: issm/trunk/src/m/classes/clusters/generic_static.py
===================================================================
--- issm/trunk/src/m/classes/clusters/generic_static.py	(revision 27035)
+++ issm/trunk/src/m/classes/clusters/generic_static.py	(revision 27232)
@@ -52,4 +52,8 @@
         s += "    shell: %s\n" % self.shell
         return s
+    # }}}
+
+    def nprocs(self):  # {{{
+        return self.np
     # }}}
 
Index: issm/trunk/src/m/classes/frictioncoulomb.m
===================================================================
--- issm/trunk/src/m/classes/frictioncoulomb.m	(revision 27035)
+++ issm/trunk/src/m/classes/frictioncoulomb.m	(revision 27232)
@@ -64,5 +64,5 @@
 		end % }}}
 		function disp(self) % {{{
-			disp(sprintf('Basal shear stress parameters: Sigma_b = min( coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b\n, coefficientcoulomb^2 * rho_i * g * (h-h_f)) (effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p, floatation thickness h_f=max(0,-rho_sw / rho_i * bed))'));
+			disp(sprintf('Basal shear stress parameters: Sigma_b = min( coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b\n, coefficientcoulomb^2 * Neff) (effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p, floatation thickness h_f=max(0,-rho_sw / rho_i * bed))'));
 			fielddisplay(self,'coefficient','power law (Weertman) friction coefficient [SI]');
 			fielddisplay(self,'coefficientcoulomb','Coulomb friction coefficient [SI]');
Index: issm/trunk/src/m/classes/frictioncoulomb.py
===================================================================
--- issm/trunk/src/m/classes/frictioncoulomb.py	(revision 27035)
+++ issm/trunk/src/m/classes/frictioncoulomb.py	(revision 27232)
@@ -28,5 +28,5 @@
     def __repr__(self):  # {{{
         s = 'Basal shear stress parameters: Sigma_b = min(coefficient^2 * Neff ^r * |u_b|^(s - 1) * u_b,\n'
-        s += 'coefficientcoulomb^2 * rho_i * g * (h - h_f)), (effective stress Neff = rho_ice * g * thickness + rho_water * g * bed, r = q / p and s = 1 / p).\n'
+        s += 'coefficientcoulomb^2 * Neff), (effective stress Neff = rho_ice * g * thickness + rho_water * g * bed, r = q / p and s = 1 / p).\n'
         s += '{}\n'.format(fielddisplay(self, "coefficient", "power law (Weertman) friction coefficient [SI]"))
         s += '{}\n'.format(fielddisplay(self, "coefficientcoulomb", "Coulomb friction coefficient [SI]"))
Index: issm/trunk/src/m/classes/frictionschoof.py
===================================================================
--- issm/trunk/src/m/classes/frictionschoof.py	(revision 27035)
+++ issm/trunk/src/m/classes/frictionschoof.py	(revision 27232)
@@ -1,4 +1,3 @@
 import numpy as np
-
 from checkfield import checkfield
 from fielddisplay import fielddisplay
@@ -22,5 +21,5 @@
         self.effective_pressure       = np.nan
         self.effective_pressure_limit = 0
-        
+
         nargs = len(args)
         if nargs == 0:
@@ -55,5 +54,5 @@
         self.Cmax = project3d(md, 'vector', self.Cmax, 'type', 'node')
         self.m = project3d(md, 'vector', self.m, 'type', 'element')
-        if self.coupling in[3, 4]:
+        if self.coupling in [3, 4]:
             self.effective_pressure = project3d(md, 'vector', self.effective_pressure, 'type', 'node', 'layer', 1)
         return self
Index: issm/trunk/src/m/classes/hydrologydc.m
===================================================================
--- issm/trunk/src/m/classes/hydrologydc.m	(revision 27035)
+++ issm/trunk/src/m/classes/hydrologydc.m	(revision 27232)
@@ -14,4 +14,5 @@
 		max_iter                 = 0;
 		steps_per_step           = 0;
+		step_adapt               = 0;
 		averaging                = 0;
 		sedimentlimit_flag       = 0;
@@ -66,5 +67,5 @@
 				list=[list,{'EplHead','HydrologydcMaskEplactiveNode','HydrologydcMaskEplactiveElt','EplHeadSlopeX','EplHeadSlopeY','HydrologydcEplThickness'}];
 			end
-			if self.steps_per_step>1,
+			if self.steps_per_step>1 | self.step_adapt,
 				list = [list,'EffectivePressureSubstep','SedimentHeadSubstep'];
 				if self.isefficientlayer,
@@ -90,4 +91,5 @@
 			self.max_iter                 = 100;
 			self.steps_per_step           = 1;
+			self.step_adapt               = 0;
 			self.averaging                = 0;
 			self.sedimentlimit_flag       = 0;
@@ -126,4 +128,5 @@
 			md = checkfield(md,'fieldname','hydrology.max_iter','>',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.steps_per_step','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.step_adapt','numel',1,'values',[0 1]);
 			md = checkfield(md,'fieldname','hydrology.averaging','numel',[1],'values',[0 1 2]);
 			md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3]);
@@ -172,4 +175,5 @@
 			fielddisplay(self,'max_iter','maximum number of nonlinear iteration');
 			fielddisplay(self,'steps_per_step','number of hydrology steps per timestep');
+			fielddisplay(self,'step_adapt', 'adaptative sub stepping  [1: true 0: false] default is 0');
 			fielddisplay(self, 'averaging', 'averaging methods from short to long steps');
 			disp(sprintf('%55s  0: Arithmetic (default)'));
@@ -226,4 +230,5 @@
 			WriteData(fid,prefix,'object',self,'fieldname','max_iter','format','Integer');
 			WriteData(fid,prefix,'object',self,'fieldname','steps_per_step','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','step_adapt','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','averaging','format','Integer');
 			WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit_flag','format','Integer');
Index: issm/trunk/src/m/classes/hydrologydc.py
===================================================================
--- issm/trunk/src/m/classes/hydrologydc.py	(revision 27035)
+++ issm/trunk/src/m/classes/hydrologydc.py	(revision 27232)
@@ -21,4 +21,5 @@
         self.max_iter = 0
         self.steps_per_step = 0
+        self.step_adapt = 0
         self.averaging = 0
         self.sedimentlimit_flag = 0
@@ -53,5 +54,5 @@
     def __repr__(self):  # {{{
         # TODO:
-        # - Convert all formatting to calls to <string>.format (see any 
+        # - Convert all formatting to calls to <string>.format (see any
         #   already converted <class>.__repr__ method for examples)
         #
@@ -65,4 +66,5 @@
         string = "%s\n%s" % (string, fielddisplay(self, 'max_iter', 'maximum number of nonlinear iteration'))
         string = "%s\n%s" % (string, fielddisplay(self, 'steps_per_step', 'number of hydrology steps per time step'))
+        string = "%s\n%s" % (string, fielddisplay(self, 'step_adapt', 'adaptative sub stepping  [1: true 0: false] default is 0'))
         string = "%s\n%s" % (string, fielddisplay(self, 'averaging', 'averaging methods from short to long steps'))
         string = "%s\n\t\t%s" % (string, '0: Arithmetic (default)')
@@ -134,4 +136,5 @@
         self.max_iter = 100
         self.steps_per_step = 1
+        self.step_adapt = 0
         self.averaging = 0
         self.sedimentlimit_flag = 0
@@ -162,5 +165,5 @@
         if self.isefficientlayer == 1:
             list.extend(['EplHead', 'HydrologydcMaskEplactiveNode', 'HydrologydcMaskEplactiveElt', 'EplHeadSlopeX', 'EplHeadSlopeY', 'HydrologydcEplThickness'])
-        if self.steps_per_step > 1:
+        if self.steps_per_step > 1 or self.step_adapt:
             list.extend(['EffectivePressureSubstep', 'SedimentHeadSubstep'])
             if self.isefficientlayer == 1:
@@ -190,4 +193,5 @@
         md = checkfield(md, 'fieldname', 'hydrology.max_iter', '>', 0., 'numel', [1])
         md = checkfield(md, 'fieldname', 'hydrology.steps_per_step', '>=', 1, 'numel', [1])
+        md = checkfield(md, 'fieldname', 'hydrology.step_adapt', 'numel', [1], 'values', [0, 1])
         md = checkfield(md, 'fieldname', 'hydrology.averaging', 'numel', [1], 'values', [0, 1, 2])
         md = checkfield(md, 'fieldname', 'hydrology.sedimentlimit_flag', 'numel', [1], 'values', [0, 1, 2, 3])
@@ -233,4 +237,5 @@
         WriteData(fid, prefix, 'object', self, 'fieldname', 'max_iter', 'format', 'Integer')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'steps_per_step', 'format', 'Integer')
+        WriteData(fid, prefix, 'object', self, 'fieldname', 'step_adapt', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'averaging', 'format', 'Integer')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'sedimentlimit_flag', 'format', 'Integer')
Index: issm/trunk/src/m/classes/initialization.m
===================================================================
--- issm/trunk/src/m/classes/initialization.m	(revision 27035)
+++ issm/trunk/src/m/classes/initialization.m	(revision 27232)
@@ -150,6 +150,6 @@
 			yts=md.constants.yts;
 
-			WriteData(fid,prefix,'object',self,'fieldname','vx','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,prefix,'object',self,'fieldname','vy','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,prefix,'object',self,'fieldname','vx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+			WriteData(fid,prefix,'object',self,'fieldname','vy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
 			WriteData(fid,prefix,'object',self,'fieldname','vz','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,prefix,'object',self,'fieldname','pressure','format','DoubleMat','mattype',1);
Index: issm/trunk/src/m/classes/initialization.py
===================================================================
--- issm/trunk/src/m/classes/initialization.py	(revision 27035)
+++ issm/trunk/src/m/classes/initialization.py	(revision 27232)
@@ -14,5 +14,5 @@
     """
 
-    def __init__(self): #{{{
+    def __init__(self):  #{{{
         self.vx = np.nan
         self.vy = np.nan
@@ -37,5 +37,6 @@
         self.setdefaultparameters()
     #}}}
-    def __repr__(self): #{{{
+
+    def __repr__(self):  #{{{
         s = '   initial field values:\n'
         s += '{}\n'.format(fielddisplay(self, 'vx', 'x component of velocity [m/yr]'))
@@ -53,11 +54,13 @@
         s += '{}\n'.format(fielddisplay(self, 'hydraulic_potential', 'Hydraulic potential (for GlaDS) [Pa]'))
         s += '{}\n'.format(fielddisplay(self, 'channelarea', 'subglaciale water channel area (for GlaDS) [m2]'))
-        s += '{}\n'.format(fielddisplay(self,'sample', 'Realization of a Gaussian random field'))
+        s += '{}\n'.format(fielddisplay(self, 'sample', 'Realization of a Gaussian random field'))
         return s
     #}}}
-    def setdefaultparameters(self): #{{{
+
+    def setdefaultparameters(self):  #{{{
         return
     #}}}
-    def checkconsistency(self, md, solution, analyses): #{{{
+
+    def checkconsistency(self, md, solution, analyses):  #{{{
         if 'StressbalanceAnalysis' in analyses and not solution == 'TransientSolution' and not md.transient.isstressbalance:
             if not np.any(np.logical_or(np.isnan(md.initialization.vx), np.isnan(md.initialization.vy))):
@@ -93,9 +96,13 @@
                 md = checkfield(md, 'fieldname', 'delta Tpmp', 'field', np.absolute(md.initialization.temperature[pos] - (md.materials.meltingpoint - md.materials.beta * md.initialization.pressure[pos])), '<', 1e-11, 'message', 'set temperature to pressure melting point at locations with waterfraction > 0')
         if 'HydrologyShreveAnalysis' in analyses:
-            if hasattr(md.hydrology, 'hydrologyshreve'):
+            if type(md.hydrology).__name__ == 'hydrologyshreve':
                 if (solution == 'TransientSolution' and md.transient.ishydrology) or solution == 'HydrologySolution':
                     md = checkfield(md, 'fieldname', 'initialization.watercolumn', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices])
+        if 'HydrologyDCAnalysis' in analyses:
+            if type(md.hydrology).__name__ == 'hydrologydc':
+                if (solution == 'TransientSolution' and md.transient.ishydrology) or solution == 'HydrologySolution':
+                    md = checkfield(md, 'fieldname', 'initialization.sediment_head', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices])
         if 'HydrologyTwsAnalysis' in analyses:
-            if hasattr(md.hydrology, 'hydrologytws'):
+            if type(md.hydrology).__name__ == 'hydrologytws':
                 md = checkfield(md, 'fieldname', 'initialization.watercolumn', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices])
         if 'SealevelchangeAnalysis' in analyses:
@@ -103,5 +110,5 @@
                 md = checkfield(md, 'fieldname', 'initialization.sealevel', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices])
         if 'HydrologyGlaDSAnalysis' in analyses:
-            if hasattr(md.hydrology, 'hydrologyglads'):
+            if type(md.hydrology).__name__ == 'hydrologyglads':
                 md = checkfield(md, 'fieldname', 'initialization.watercolumn', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices])
                 md = checkfield(md, 'fieldname', 'initialization.hydraulic_potential', 'NaN', 1, 'Inf', 1, 'size', [md.mesh.numberofvertices])
@@ -112,4 +119,5 @@
         return md
     #}}}
+
     def marshall(self, prefix, md, fid): #{{{
         yts = md.constants.yts
@@ -119,5 +127,5 @@
         WriteData(fid, prefix, 'object', self, 'fieldname', 'vz', 'format', 'DoubleMat', 'mattype', 1, 'scale', 1 / yts)
         WriteData(fid, prefix, 'object', self, 'fieldname', 'pressure', 'format', 'DoubleMat', 'mattype', 1)
-        WriteData(fid, prefix, 'object', self, 'fieldname', 'sealevel', 'format', 'DoubleMat', 'mattype', 1,'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
+        WriteData(fid, prefix, 'object', self, 'fieldname', 'sealevel', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
         WriteData(fid, prefix, 'object', self, 'fieldname', 'bottompressure', 'format', 'DoubleMat', 'mattype', 1)
         WriteData(fid, prefix, 'object', self, 'fieldname', 'str', 'format', 'DoubleMat', 'mattype', 1)
@@ -143,4 +151,5 @@
             WriteData(fid, prefix, 'data', self.enthalpy, 'format', 'DoubleMat', 'mattype', 1, 'name', 'md.initialization.enthalpy')
     #}}}
+
     def extrude(self, md): #{{{
         self.vx = project3d(md, 'vector', self.vx, 'type', 'node')
Index: issm/trunk/src/m/classes/solidearthsettings.m
===================================================================
--- issm/trunk/src/m/classes/solidearthsettings.m	(revision 27035)
+++ issm/trunk/src/m/classes/solidearthsettings.m	(revision 27232)
@@ -20,7 +20,7 @@
 		compute_bp_grd         = 0; %will GRD patterns for bottom pressures be computed? 
 		degacc                 = 0; %degree increment for resolution of Green tables.
-		timeacc                = 0; %time step accuracy required to compute Green tables
+		timeacc                = 1; %time step accuracy required to compute Green tables
 		horiz                  = 0; %compute horizontal deformation
-		grdmodel               = 0; %grd model (0 by default, 1 for (visco-)elastic, 2 for Ivins)
+		grdmodel               = 1; %grd model (0 by default, 1 for (visco-)elastic, 2 for Ivins)
 		cross_section_shape    = 0; %cross section only used when grd model is Ivins
 	end
@@ -89,27 +89,31 @@
 
 			%no grd model by default:
-			self.grdmodel=0;
+			self.grdmodel=1;
 
 		end % }}}
 		function disp(self) % {{{
 			disp(sprintf('   solidearth settings:'));
-
-			fielddisplay(self,'reltol','sea level change relative convergence criterion (default, NaN: not applied)');
-			fielddisplay(self,'abstol','sea level change absolute convergence criterion(default, NaN: not applied)');
-			fielddisplay(self,'maxiter','maximum number of nonlinear iterations');
-			fielddisplay(self,'grdocean','does this planet have an ocean, if set to 1: global water mass is conserved in GRD module (default: 1)'); 
-			fielddisplay(self,'ocean_area_scaling','correction for model representation of ocean area (default: No correction)'); 
-			fielddisplay(self,'sealevelloading','enables surface loading from sea-level change (default: 1)');
+			disp(sprintf('      core:'));
 			fielddisplay(self,'isgrd','compute GRD patterns (default: 1)');
-			fielddisplay(self,'compute_bp_grd','compute GRD patterns for bottom pressure loads (default: 1)');
-			fielddisplay(self,'runfrequency','how many time steps we skip before we run solidearthsettings solver during transient (default: 1)');
+			fielddisplay(self,'grdmodel','type of deformation model, 0 for no GRD, 1 for spherical GRD model (SESAW model), 2 for half-space planar GRD (visco-elastic model from Ivins)');
+			fielddisplay(self,'runfrequency','How many time steps we let masstransport core accumulate changes before each run of the sealevelchange core (default: 1, i.e run slc every time step)');
+			disp(sprintf('      computational flags:'));
 			fielddisplay(self,'selfattraction','enables surface mass load to perturb the gravity field');
 			fielddisplay(self,'elastic','enables elastic deformation from surface loading');
 			fielddisplay(self,'viscous','enables viscous deformation from surface loading');
 			fielddisplay(self,'rotation','enables polar motion to feedback on the GRD fields');
-			fielddisplay(self,'degacc','accuracy (default: .01 deg) for numerical discretization of the Green''s functions');
+			fielddisplay(self,'compute_bp_grd','compute GRD patterns for bottom pressure loads (default: 1)');
+			fielddisplay(self,'cross_section_shape','1: square-edged (default). 2: elliptical. See iedge in GiaDeflectionCore. Used only for grdmodel=2 only');
+			disp(sprintf('      resolution:'));
+			fielddisplay(self,'degacc','spatial accuracy (default: .01 deg) for numerical discretization of the Green''s functions');
 			fielddisplay(self,'timeacc','time accuracy (default: 1 yr) for numerical discretization of the Green''s functions');
-			fielddisplay(self,'grdmodel','type of deformation model, 0 for no GRD, 1 for spherical GRD model (SESAW model), 2 for half-space planar GRD (visco-elastic model from Ivins)');
-			fielddisplay(self,'cross_section_shape','1: square-edged (default). 2: elliptical. See iedge in GiaDeflectionCore');
+			disp(sprintf('      sea-level equation:'));
+			fielddisplay(self,'grdocean','does this planet have an ocean, if set to 1: global water mass is conserved in GRD module (default: 1)'); 
+			fielddisplay(self,'sealevelloading','enables surface loading from sea-level change (default: 1)');
+			fielddisplay(self,'maxiter','maximum number of nonlinear iterations');
+			fielddisplay(self,'reltol','sea level change relative convergence criterion (default, NaN: not applied)');
+			fielddisplay(self,'abstol','sea level change absolute convergence criterion(default, NaN: not applied)');
+			fielddisplay(self,'ocean_area_scaling','correction for model representation of ocean area (default: No correction)'); 
+
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
@@ -133,4 +137,7 @@
 			if self.viscous==1 & self.elastic==0,
 				error('solidearthsettings checkconsistency error message: need elastic on if viscous flag is set');
+			end
+			if self.rotation==1 & self.elastic==0,
+				error('solidearthsettings checkconsistency error message: need elastic on if rotation flag is set');
 			end
 
@@ -164,4 +171,5 @@
 			WriteData(fid,prefix,'object',self,'fieldname','viscous','name','md.solidearth.settings.viscous','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','rotation','name','md.solidearth.settings.rotation','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','rotation','name','md.solidearth.settings.satellitegravity','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','grdocean','name','md.solidearth.settings.grdocean','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','ocean_area_scaling','name','md.solidearth.settings.ocean_area_scaling','format','Boolean');
@@ -187,5 +195,5 @@
 			writejsdouble(fid,[modelname '.solidearth.settings.viscous'],self.viscous);
 			writejsdouble(fid,[modelname '.solidearth.settings.rotation'],self.rotation);
-			writejsdouble(fid,[modelname '.solidearth.settings.grdocean'],self.rotation);
+			writejsdouble(fid,[modelname '.solidearth.settings.grdocean'],self.grdocean);
 			writejsdouble(fid,[modelname '.solidearth.settings.ocean_area_scaling'],self.ocean_area_scaling);
 			writejsdouble(fid,[modelname '.solidearth.settings.run_frequency'],self.run_frequency);
Index: issm/trunk/src/m/classes/stochasticforcing.m
===================================================================
--- issm/trunk/src/m/classes/stochasticforcing.m	(revision 27035)
+++ issm/trunk/src/m/classes/stochasticforcing.m	(revision 27232)
@@ -95,14 +95,18 @@
 				end
 				if(contains(field,'WaterPressure'))
-               mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
-               if~(isequal(class(md.friction),char(mdname)))
-                  error('stochasticforcing field %s is only implemented for default friction', char(field));
+					mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
+					if~(isequal(class(md.friction),char(mdname)))
+                  error('md.friction does not agree with stochasticforcing field %s', char(field));
                end
-               if(md.friction.coupling~=0 && md.friction.coupling~=1 && md.friction.coupling~=2)
-                  error('stochasticforcing field %s is only implemented for cases md.friction.coupling 0 or 1 or 2', char(field));
-               end
-               if(any(md.friction.q==0))
-                  error('stochasticforcing field %s requires non-zero q exponent',char(field));
-               end
+					if(strcmp(class(md.friction),'friction') || strcmp(class(md.friction),'frictionschoof') || strcmp(class(md.friction),'frictioncoulomb'))
+                  if(md.friction.coupling~=0 && md.friction.coupling~=1 && md.friction.coupling~=2)
+                     error('stochasticforcing field %s is only implemented for cases md.friction.coupling 0 or 1 or 2', char(field));
+                  end
+					end
+					if(strcmp(class(md.friction),'friction'))
+                  if(any(md.friction.q==0))
+                     error('stochasticforcing field %s requires non-zero q exponent',char(field));
+                  end
+					end
             end
 				%Checking for specific dimensions
@@ -267,4 +271,6 @@
 		'FloatingMeltRate',...
 		'FrictionWaterPressure',...
+		'FrictionCoulombWaterPressure',...
+		'FrictionSchoofWaterPressure',...
 		'FrontalForcingsRignotAutoregression',...
 		'SMBautoregression',...
@@ -277,4 +283,6 @@
 		'basalforcings',...
 		'friction',...
+		'frictioncoulomb',...
+		'frictionschoof',...
 		'frontalforcingsrignotautoregression',...
 		'SMBautoregression',...
Index: issm/trunk/src/m/classes/stochasticforcing.py
===================================================================
--- issm/trunk/src/m/classes/stochasticforcing.py	(revision 27035)
+++ issm/trunk/src/m/classes/stochasticforcing.py	(revision 27232)
@@ -106,9 +106,11 @@
                 mdname = structstoch[field]
                 if (type(md.friction).__name__ != mdname):
-                    raise TypeError('stochasticforcing field {} is only implemented for default friction'.format(field))
-                if md.friction.coupling not in[0, 1, 2]:
-                    raise TypeError('stochasticforcing field {} is only implemented for cases md.friction.coupling 0 or 1 or 2'.format(field))
-                if (np.any(md.friction.q == 0)):
-                    raise TypeError('stochasticforcing field {} requires non-zero q exponent'.format(field))
+                    raise TypeError('md.friction does not agree with stochasticforcing field {}'.format(field))
+                if (type(md.friction).__name__=='friction' or type(md.friction).__name__=='frictionschoof' or type(md.friction).__name__=='frictioncoulomb'):
+                    if md.friction.coupling not in[0, 1, 2]:
+                        raise TypeError('stochasticforcing field {} is only implemented for cases md.friction.coupling 0 or 1 or 2'.format(field))
+                if (type(md.friction).__name__=='friction'):
+                    if (np.any(md.friction.q == 0)):
+                        raise TypeError('stochasticforcing field {} requires non-zero q exponent'.format(field))
 
             # Checking for specific dimensions
@@ -232,4 +234,6 @@
                      'FloatingMeltRate': 'basalforcings',
                      'FrictionWaterPressure': 'friction',
+                     'FrictionCoulombWaterPressure': 'frictioncoulomb',
+                     'FrictionSchoofWaterPressure': 'frictionschoof',
                      'FrontalForcingsRignotAutoregression': 'frontalforcingsrignotautoregression',
                      'SMBautoregression': 'SMBautoregression',
Index: issm/trunk/src/m/classes/timestepping.m
===================================================================
--- issm/trunk/src/m/classes/timestepping.m	(revision 27035)
+++ issm/trunk/src/m/classes/timestepping.m	(revision 27232)
@@ -5,9 +5,10 @@
 
 classdef timestepping
-	properties (SetAccess=public) 
+	properties (SetAccess=public)
 		start_time      = 0.;
 		final_time      = 0.;
 		time_step       = 0.;
 		interp_forcing  = 1;
+		average_forcing  = 0;
 		cycle_forcing   = 0;
 		coupling_time   = 0.;
@@ -32,4 +33,5 @@
 			fielddisplay(self,'time_step',['length of time steps [' unit ']']);
 			fielddisplay(self,'interp_forcing','interpolate in time between requested forcing values? (0 or 1)');
+			fielddisplay(self,'average_forcing','average in time if there are several forcing values between steps? (0 or 1, default is 0)');
 			fielddisplay(self,'cycle_forcing','cycle through forcing? (0 or 1)');
 			fielddisplay(self,'coupling_time',['length of coupling time step with ocean model [' unit ']']);
@@ -46,4 +48,5 @@
 			%should we interpolate forcing between timesteps?
 			self.interp_forcing=1;
+			self.average_forcing=0;
 			self.cycle_forcing=0;
 		end % }}}
@@ -54,8 +57,9 @@
 			md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','timestepping.interp_forcing','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','timestepping.average_forcing','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','timestepping.cycle_forcing','numel',[1],'values',[0 1]);
 			if self.final_time-self.start_time<0,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
-			end 
+			end
 			if strcmp(solution,'TransientSolution'),
 				md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>',0,'NaN',1,'Inf',1);
@@ -70,13 +74,15 @@
 			WriteData(fid,prefix,'object',self,'fieldname','time_step','format','Double','scale',scale);
 			WriteData(fid,prefix,'object',self,'fieldname','interp_forcing','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','average_forcing','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','cycle_forcing','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','coupling_time','format','Double','scale',scale);
 		end % }}}
 		function savemodeljs(self,fid,modelname) % {{{
-		
+
 			writejsdouble(fid,[modelname '.timestepping.start_time'],self.start_time);
 			writejsdouble(fid,[modelname '.timestepping.final_time'],self.final_time);
 			writejsdouble(fid,[modelname '.timestepping.time_step'],self.time_step);
 			writejsdouble(fid,[modelname '.timestepping.interp_forcing'],self.interp_forcing);
+			writejsdouble(fid,[modelname '.timestepping.average_forcing'],self.interp_forcing);
 			writejsdouble(fid,[modelname '.timestepping.cycle_forcing'],self.cycle_forcing);
 
Index: issm/trunk/src/m/classes/timestepping.py
===================================================================
--- issm/trunk/src/m/classes/timestepping.py	(revision 27035)
+++ issm/trunk/src/m/classes/timestepping.py	(revision 27232)
@@ -11,9 +11,10 @@
     """
 
-    def __init__(self, *args): #{{{
+    def __init__(self, *args):  #{{{
         self.start_time = 0
         self.final_time = 0
         self.time_step = 0
         self.interp_forcing = 1
+        self.average_forcing = 0
         self.cycle_forcing = 0
         self.coupling_time = 0
@@ -24,5 +25,6 @@
             raise RuntimeError('constructor not supported')
     #}}}
-    def __repr__(self): #{{{
+
+    def __repr__(self):  #{{{
         s = '   timestepping parameters:\n'
         unit = 'yr'
@@ -31,9 +33,11 @@
         s += '{}\n'.format(fielddisplay(self, 'time_step', 'length of time steps [' + unit + ']'))
         s += '{}\n'.format(fielddisplay(self, 'interp_forcing', 'interpolate in time between requested forcing values? (0 or 1)'))
+        s += '{}\n'.format(fielddisplay(self, 'average_forcing', 'average in time if there are several forcing values between steps? (0 or 1, default is 0)'))
         s += '{}\n'.format(fielddisplay(self, 'cycle_forcing', 'cycle through forcing? (0 or 1)'))
         s += '{}\n'.format(fielddisplay(self, 'coupling_time', 'length of coupling time steps with ocean model [' + unit + ']'))
         return s
     #}}}
-    def setdefaultparameters(self): #{{{
+
+    def setdefaultparameters(self):  #{{{
         # Time between 2 time steps
         self.time_step = 1 / 2
@@ -44,12 +48,16 @@
         # Should we interpolate forcing between timesteps?
         self.interp_forcing = 1
+        self.average_forcing = 0
         self.cycle_forcing = 0
 
         return self
     #}}}
-    def checkconsistency(self, md, solution, analyses): #{{{
+
+    def checkconsistency(self, md, solution, analyses):  #{{{
         md = checkfield(md, 'fieldname', 'timestepping.start_time', 'numel', [1], 'NaN', 1, 'Inf', 1)
         md = checkfield(md, 'fieldname', 'timestepping.final_time', 'numel', [1], 'NaN', 1, 'Inf', 1)
         md = checkfield(md, 'fieldname', 'timestepping.time_step', 'numel', [1], '>=', 0, 'NaN', 1, 'Inf', 1)
+        md = checkfield(md, 'fieldname', 'timestepping.interp_forcing', 'numel', [1], 'values', [0, 1])
+        md = checkfield(md, 'fieldname', 'timestepping.average_forcing', 'numel', [1], 'values', [0, 1])
         md = checkfield(md, 'fieldname', 'timestepping.cycle_forcing', 'numel', [1], 'values', [0, 1])
         if (self.final_time - self.start_time) < 0:
@@ -60,5 +68,6 @@
         return md
     #}}}
-    def marshall(self, prefix, md, fid): #{{{
+
+    def marshall(self, prefix, md, fid):  #{{{
         scale = md.constants.yts
         WriteData(fid, prefix, 'name', 'md.timestepping.type', 'data', 1, 'format', 'Integer')
@@ -67,4 +76,5 @@
         WriteData(fid, prefix, 'object', self, 'fieldname', 'time_step', 'format', 'Double', 'scale', scale)
         WriteData(fid, prefix, 'object', self, 'fieldname', 'interp_forcing', 'format', 'Boolean')
+        WriteData(fid, prefix, 'object', self, 'fieldname', 'average_forcing', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'cycle_forcing', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'coupling_time', 'format', 'Double', 'scale', scale)
Index: issm/trunk/src/m/classes/timesteppingadaptive.m
===================================================================
--- issm/trunk/src/m/classes/timesteppingadaptive.m	(revision 27035)
+++ issm/trunk/src/m/classes/timesteppingadaptive.m	(revision 27232)
@@ -5,5 +5,5 @@
 
 classdef timesteppingadaptive
-	properties (SetAccess=public) 
+	properties (SetAccess=public)
 		start_time      = 0.;
 		final_time      = 0.;
@@ -11,6 +11,7 @@
 		time_step_max   = 0.;
 		cfl_coefficient = 0.;
-		interp_forcing = 1;
-		cycle_forcing = 1;
+		interp_forcing  = 1;
+		average_forcing = 0;
+		cycle_forcing   = 1;
 		coupling_time   = 0.;
 	end
@@ -40,4 +41,5 @@
 			%should we interpolate forcing between timesteps?
 			self.interp_forcing=1;
+			self.average_forcing=0;
 			self.cycle_forcing=0;
 		end % }}}
@@ -50,9 +52,10 @@
 			md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
 			md = checkfield(md,'fieldname','timestepping.interp_forcing','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','timestepping.average_forcing','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','timestepping.cycle_forcing','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',md.timestepping.coupling_time,'NaN',1,'Inf',1);
 			if self.final_time-self.start_time<0,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
-			end 
+			end
 		end % }}}
 		function disp(self) % {{{
@@ -66,4 +69,5 @@
 			fielddisplay(self,'cfl_coefficient','coefficient applied to cfl condition');
 			fielddisplay(self,'interp_forcing','interpolate in time between requested forcing values ? (0 or 1)');
+			fielddisplay(self,'average_forcing','average in time if there are several forcing values between steps? (0 or 1, default is 0)');
 			fielddisplay(self,'cycle_forcing','cycle through forcing ? (0 or 1)');
 			fielddisplay(self,'coupling_time',['coupling time step with ocean model [' unit ']']);
@@ -80,9 +84,10 @@
 			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','cfl_coefficient','format','Double');
 			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','interp_forcing','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','average_forcing','format','Boolean');
 			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','cycle_forcing','format','Boolean');
 			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','coupling_time','format','Double','scale',scale);
 		end % }}}
 		function savemodeljs(self,fid,modelname) % {{{
-		
+
 			writejsdouble(fid,[modelname '.timesteppingadaptive.start_time'],self.start_time);
 			writejsdouble(fid,[modelname '.timesteppingadaptive.final_time'],self.final_time);
@@ -91,4 +96,5 @@
 			writejsdouble(fid,[modelname '.timesteppingadaptive.cfl_coefficient'],self.cfl_coefficient);
 			writejsdouble(fid,[modelname '.timesteppingadaptive.interp_forcing'],self.interp_forcing);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.average_forcing'],self.interp_forcing);
 			writejsdouble(fid,[modelname '.timesteppingadaptive.cycle_forcing'],self.cycle_forcing);
 			writejsdouble(fid,[modelname '.timesteppingadaptive.coupling_time'],self.time_step_max);
Index: issm/trunk/src/m/classes/timesteppingadaptive.py
===================================================================
--- issm/trunk/src/m/classes/timesteppingadaptive.py	(revision 27035)
+++ issm/trunk/src/m/classes/timesteppingadaptive.py	(revision 27232)
@@ -20,4 +20,5 @@
             self.cfl_coefficient = 0.
             self.interp_forcing = 1
+            self.average_forcing = 0
             self.cycle_forcing = 0
             self.coupling_time = 0.
@@ -33,4 +34,5 @@
             self.final_time = old.final_time
             self.interp_forcing = old.interp_forcing
+            self.average_forcing = old.average_forcing
             self.cycle_forcing = old.cycle_forcing
             self.coupling_time = old.coupling_time
@@ -42,12 +44,13 @@
     def __repr__(self):  # {{{
         string = "   timesteppingadaptive parameters:"
-        string = "%s\n%s" % (string, fielddisplay(self, "start_time", "simulation starting time [yr]"))
-        string = "%s\n%s" % (string, fielddisplay(self, "final_time", "final time to stop the simulation [yr]"))
-        string = "%s\n%s" % (string, fielddisplay(self, "time_step_min", "minimum length of time steps [yr]"))
-        string = "%s\n%s" % (string, fielddisplay(self, "time_step_max", "maximum length of time steps [yr]"))
-        string = "%s\n%s" % (string, fielddisplay(self, "cfl_coefficient", "coefficient applied to cfl condition"))
-        string = "%s\n%s" % (string, fielddisplay(self, "interp_forcing", "interpolate in time between requested forcing values ? (0 or 1)"))
-        string = "%s\n%s" % (string, fielddisplay(self, "cycle_forcing", "cycle through forcing ? (0 or 1)"))
-        string = "%s\n%s" % (string, fielddisplay(self, "coupling_time", "coupling time steps with ocean model [yr]"))
+        string = '{}\n{}'.format (string, fielddisplay(self, "start_time", "simulation starting time [yr]"))
+        string = '{}\n{}'.format(string, fielddisplay(self, "final_time", "final time to stop the simulation [yr]"))
+        string = '{}\n{}'.format (string, fielddisplay(self, "time_step_min", "minimum length of time steps [yr]"))
+        string = '{}\n{}'.format (string, fielddisplay(self, "time_step_max", "maximum length of time steps [yr]"))
+        string = '{}\n{}'.format (string, fielddisplay(self, "cfl_coefficient", "coefficient applied to cfl condition"))
+        string = '{}\n{}'.format (string, fielddisplay(self, "interp_forcing", "interpolate in time between requested forcing values ? (0 or 1)"))
+        string = '{}\n{}'.format(string, fielddisplay(self, 'average_forcing', 'average in time if there are several forcing values between steps? (0 or 1, default is 0)'))
+        string = '{}\n{}'.format(string, fielddisplay(self, "cycle_forcing", "cycle through forcing ? (0 or 1)"))
+        string = '{}\n{}'.format(string, fielddisplay(self, "coupling_time", "coupling time steps with ocean model [yr]"))
         return string
     # }}}
@@ -63,4 +66,5 @@
         #should we interpolate forcing between timesteps?
         self.interp_forcing = 1
+        self.average_forcing = 0
         self.cycle_forcing   = 0
         return self
@@ -76,4 +80,5 @@
             md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
         md = checkfield(md, 'fieldname', 'timestepping.interp_forcing', 'numel', [1], 'values', [0, 1])
+        md = checkfield(md, 'fieldname', 'timestepping.average_forcing', 'numel', [1], 'values', [0, 1])
         md = checkfield(md, 'fieldname', 'timestepping.cycle_forcing', 'numel', [1], 'values', [0, 1])
         md = checkfield(md, 'fieldname', 'timestepping.coupling_time', 'numel', [1], '>=', 0, 'NaN', 1, 'Inf', 1)
@@ -91,4 +96,5 @@
         WriteData(fid, prefix, 'object', self, 'class', 'timestepping', 'fieldname', 'cfl_coefficient', 'format', 'Double')
         WriteData(fid, prefix, 'object', self, 'class', 'timestepping', 'fieldname', 'interp_forcing', 'format', 'Boolean')
+        WriteData(fid, prefix, 'object', self, 'class', 'timestepping', 'fieldname', 'average_forcing', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'class', 'timestepping', 'fieldname', 'cycle_forcing', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'class', 'timestepping', 'fieldname', 'coupling_time', 'format', 'Double', 'scale', yts)
Index: issm/trunk/src/m/classes/transient.js
===================================================================
--- issm/trunk/src/m/classes/transient.js	(revision 27035)
+++ issm/trunk/src/m/classes/transient.js	(revision 27232)
@@ -9,4 +9,5 @@
 
 		//full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+		this.isage             = 0;
 		this.issmb             = 1;
 		this.ismasstransport   = 1;
@@ -32,4 +33,5 @@
 		console.log(sprintf('   transient solution parameters:'));
 
+		fielddisplay(this,'isage','indicates whether age model is requested in the transient');
 		fielddisplay(this,'issmb','indicates whether a surface mass balance solution is used in the transient');
 		fielddisplay(this,'ismasstransport','indicates whether a masstransport solution is used in the transient');
@@ -58,4 +60,5 @@
 			if (solution!='TransientSolution') return;
 
+			checkfield(md,'fieldname','transient.isage','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','transient.issmb','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','transient.ismasstransport','numel',[1],'values',[0, 1]);
@@ -77,4 +80,5 @@
 
 			prefix='md.transient';
+			WriteData(fid,prefix,'object',this,'fieldname','isage','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','issmb','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','ismasstransport','format','Boolean');
@@ -112,4 +116,5 @@
 	// {{{
 
+	this.isage             = 0;
 	this.issmb             = 0;
 	this.ismasstransport   = 0;
Index: issm/trunk/src/m/classes/transient.m
===================================================================
--- issm/trunk/src/m/classes/transient.m	(revision 27035)
+++ issm/trunk/src/m/classes/transient.m	(revision 27232)
@@ -6,4 +6,5 @@
 classdef transient
 	properties (SetAccess=public) 
+		isage             = 0;
 		issmb             = 0;
 		ismasstransport   = 0;
@@ -34,4 +35,5 @@
 
 			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+			self.isage             = 0;
 			self.issmb             = 0;
 			self.ismasstransport   = 0;
@@ -55,4 +57,5 @@
 
 			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+			self.isage             = 0;
 			self.issmb             = 1;
 			self.ismasstransport   = 1;
@@ -85,4 +88,5 @@
 			if ~strcmp(solution,'TransientSolution'), return; end
 
+			md = checkfield(md,'fieldname','transient.isage','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','transient.issmb','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','transient.ismasstransport','numel',[1],'values',[0 1]);
@@ -111,4 +115,5 @@
 			disp(sprintf('   transient solution parameters:'));
 
+			fielddisplay(self,'isage','indicates whether an age model is used in the transient');
 			fielddisplay(self,'issmb','indicates whether a surface mass balance solution is used in the transient');
 			fielddisplay(self,'ismasstransport','indicates whether a masstransport solution is used in the transient');
@@ -129,4 +134,5 @@
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
+			WriteData(fid,prefix,'object',self,'fieldname','isage','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','issmb','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','ismasstransport','format','Boolean');
@@ -155,4 +161,5 @@
 		function savemodeljs(self,fid,modelname) % {{{
 		
+			writejsdouble(fid,[modelname '.trans.isage'],self.isage);
 			writejsdouble(fid,[modelname '.trans.issmb'],self.issmb);
 			writejsdouble(fid,[modelname '.trans.ismasstransport'],self.ismasstransport);
Index: issm/trunk/src/m/classes/transient.py
===================================================================
--- issm/trunk/src/m/classes/transient.py	(revision 27035)
+++ issm/trunk/src/m/classes/transient.py	(revision 27232)
@@ -12,4 +12,5 @@
 
     def __init__(self):  # {{{
+        self.isage = 0
         self.issmb = 0
         self.ismasstransport = 0
@@ -33,4 +34,5 @@
     def __repr__(self):  # {{{
         s = '   transient solution parameters:\n'
+        s += '{}\n'.format(fielddisplay(self, 'isage', 'indicates if age model is requested in the transient'))
         s += '{}\n'.format(fielddisplay(self, 'issmb', 'indicates if a surface mass balance solution is used in the transient'))
         s += '{}\n'.format(fielddisplay(self, 'ismasstransport', 'indicates if a masstransport solution is used in the transient'))
@@ -59,4 +61,5 @@
 
     def deactivateall(self):  #{{{
+        self.isage = 0
         self.issmb = 0
         self.ismasstransport = 0
@@ -82,4 +85,5 @@
         # Full analysis: Stressbalance, Masstransport and Thermal but no 
         # groundingline migration for now
+        self.isage = 0
         self.issmb = 1
         self.ismasstransport = 1
@@ -107,4 +111,5 @@
             return md
 
+        md = checkfield(md, 'fieldname', 'transient.isage', 'numel', [1], 'values', [0, 1])
         md = checkfield(md, 'fieldname', 'transient.issmb', 'numel', [1], 'values', [0, 1])
         md = checkfield(md, 'fieldname', 'transient.ismasstransport', 'numel', [1], 'values', [0, 1])
@@ -130,4 +135,5 @@
 
     def marshall(self, prefix, md, fid):  # {{{
+        WriteData(fid, prefix, 'object', self, 'fieldname', 'isage', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'issmb', 'format', 'Boolean')
         WriteData(fid, prefix, 'object', self, 'fieldname', 'ismasstransport', 'format', 'Boolean')
Index: issm/trunk/src/m/contrib/defleurian/paraview/enveloppeVTK.m
===================================================================
--- issm/trunk/src/m/contrib/defleurian/paraview/enveloppeVTK.m	(revision 27035)
+++ 	(revision )
@@ -1,186 +1,0 @@
-function enveloppeVTK(filename,model,varargin)
-% vtk export
-% function enveloppeVTK(filename,model)
-% creates a directory with the vtk files for displays in paraview
-% only export the enveloppe result (surface and base) on trias
-%
-% input: filename   destination 
-%                   (string)
-%------------------------------------------------------------------
-%        model      this is md 
-%------------------------------------------------------------------
-% By default only the results are exported, you can add whichever
-% field you need as a string:
-% add 'geometry' to export md.geometry
-%
-% Basile de Fleurian:
-
-[path,name,ext]=fileparts(filename);
-separator=filesep;
-mkdir(filename);
-IsEnveloppe=find(model.mesh.vertexonbase | model.mesh.vertexonsurface);
-
-%get the element related variables
-if dimension(model.mesh)==2,
-	points=[model.mesh.x model.mesh.y zeros(model.mesh.numberofvertices,1)];
-	[num_of_elt]=size(model.mesh.elements,1);
-else
-	points=[model.mesh.x(IsEnveloppe) model.mesh.y(IsEnveloppe) model.mesh.z(IsEnveloppe)];
-	[num_of_elt]=size(find(isnan(model.mesh.lowerelements)),1)+size(find(isnan(model.mesh.upperelements)),1);
-	[low_elt_num]=size(find(isnan(model.mesh.lowerelements)),1);
-	[top_elt_num]=size(find(isnan(model.mesh.upperelements)),1);
-end
-
-celltype=5; %triangles
-[num_of_points,dim]=size(points);
-[point_per_elt]=size(model.mesh.elements,2);
-tot_points=model.mesh.numberofvertices;
-
-%this is the result structure
-res_struct=model.results;
-%checking for results
-if (length(fields(res_struct))>0);
-	%Getting all the solutions of the model
-	solnames=fields(res_struct);
-	num_of_sols=length(solnames);
-	num_of_timesteps=1;
-	%building solution structure 
-	for i=1:num_of_sols
-		sol_struct{i}=res_struct.(solnames{i});
-		%looking for multiple time steps
-		if(size(sol_struct{i},2)>num_of_timesteps);
-			num_of_timesteps=size(sol_struct{i},2);
-			outstep=model.timestepping.time_step*model.settings.output_frequency
-    end
-  end
-else
-	num_of_timesteps=1;
-end
-for step=1:num_of_timesteps;
-	
-	timestep=step;
-	fid = fopen(strcat(path,filesep,name,filesep,'timestep.vtk',int2str(timestep),'.vtk'),'w+');
-	fprintf(fid,'# vtk DataFile Version 2.0 \n');
-	fprintf(fid,'Data for run %s \n',model.miscellaneous.name);
-	fprintf(fid,'ASCII \n');
-	fprintf(fid,'DATASET UNSTRUCTURED_GRID \n');
-	
-	fprintf(fid,'POINTS %d float\n',num_of_points);
-	if(dim==3);
-		s='%f %f %f \n';
-	elseif(dim==2);
-		s='%f %f \n';
-  end
-	P=[points zeros(num_of_points,3-dim)];
-	fprintf(fid,s,P');
-	
-	fprintf(fid,'CELLS %d %d\n',num_of_elt,num_of_elt*(3+1));
-	s='%d';
-	for j=1:3
-		s=horzcat(s,{' %d'});
-  end
-	s=cell2mat(horzcat(s,{'\n'}));
-
-	%build the connection matrix for the top and bottom elements
-	if exist('low_elt_num')
-		triaconnect=zeros(num_of_elt,3);
-		triaconnect(1:low_elt_num,:)=model.mesh.elements(find(isnan(model.mesh.lowerelements)),1:3);
-		upshift=-min(min(model.mesh.elements(find(isnan(model.mesh.upperelements)),4:6)))+1+max(max(model.mesh.elements(find(isnan(model.mesh.lowerelements)),1:3)));
-		triaconnect(1+low_elt_num:num_of_elt,:)=model.mesh.elements(find(isnan(model.mesh.upperelements)),4:6)+upshift;
-		fprintf(fid,s,[(3)*ones(num_of_elt,1) triaconnect-1]');
-	else
-		fprintf(fid,s,[(point_per_elt)*ones(num_of_elt,1)	model.mesh.elements-1]');
-  end
-
-	fprintf(fid,'CELL_TYPES %d\n',num_of_elt);
-	s='%d\n';
-	fprintf(fid,s,celltype*ones(num_of_elt,1));
-	fprintf(fid,'POINT_DATA %s \n',num2str(num_of_points));
-
-	%loop over the different solution structures
-	if (exist('num_of_sols'));
-		for j=1:num_of_sols
-			%dealing with results on different timesteps
-			if(size(sol_struct{j},2)>timestep);
-				timestep = step;
-			else
-				timestep = size(sol_struct{j},2);
-	    end
-			%getting the number of fields in the solution
-			resfields=fields(sol_struct{j}(timestep));
-			num_of_fields=length(resfields);
-			%check which field is a real result and print
-			for k=1:num_of_fields
-				if ((numel(sol_struct{j}(timestep).(resfields{k})))==tot_points);
-					%paraview does not like NaN, replacing
-					nanval=find(isnan(sol_struct{j}(timestep).(resfields{k})));
-					sol_struct{j}(timestep).(resfields{k})(nanval)=-9999;
-					%also checking for verry small value that mess up
-					smallval=(abs(sol_struct{j}(timestep).(resfields{k}))<1.0e-20);
-					sol_struct{j}(timestep).(resfields{k})(smallval)=0.0;
-					fprintf(fid,'SCALARS %s float 1 \n',resfields{k});
-					fprintf(fid,'LOOKUP_TABLE default\n');
-					s='%e\n';
-					fprintf(fid,s,sol_struct{j}(timestep).(resfields{k})(IsEnveloppe));
-		    end		
-	    end 
-	  end
-  end
-	%loop on arguments, if something other than result is asked, do
-	%it now
-	for j= 1:nargin-2
-		res_struct=model.(varargin{j});
-		fieldnames=fields(res_struct);
-		num_of_fields=length(fieldnames);
-		for k=1:num_of_fields
-			if ((numel(res_struct.(fieldnames{k})))==tot_points);
-				%paraview does not like NaN, replacing
-				nanval=find(isnan(res_struct.(fieldnames{k})));
-				res_struct.(fieldnames{k})(nanval)=-9999;
-				%also checking for verry small value that mess up
-				smallval=(abs(res_struct.(fieldnames{k}))<1.0e-20);
-				res_struct.(fieldnames{k})(smallval)=0.0;
-				fprintf(fid,'SCALARS %s float 1 \n',fieldnames{k});
-				fprintf(fid,'LOOKUP_TABLE default\n');
-				s='%e\n';
-				fprintf(fid,s,res_struct.(fieldnames{k})(IsEnveloppe));
-				%check for forcings	
-			elseif (size(res_struct.(fieldnames{k}),1)==tot_points+1);
-				%paraview does not like NaN, replacing
-				nanval=find(isnan(res_struct.(fieldnames{k})));
-				res_struct.(fieldnames{k})(nanval)=-9999;
-				%also checking for verry small value that mess up
-				smallval=(abs(res_struct.(fieldnames{k}))<1.0e-20);
-				res_struct.(fieldnames{k})(smallval)=0.0;
-				if (size(res_struct.(fieldnames{k}),2)==num_of_timesteps),
-					fprintf(fid,'SCALARS %s float 1 \n',fieldnames{k});
-					fprintf(fid,'LOOKUP_TABLE default\n');
-					s='%e\n';
-					fprintf(fid,s,res_struct.(fieldnames{k})(IsEnveloppe,timestep));
-				else,
-					%forcing and results not on the same timestep,need some treatment
-					fprintf(fid,'SCALARS %s float 1 \n',fieldnames{k});
-					fprintf(fid,'LOOKUP_TABLE default\n');
-					index=1
-					currenttime=((timestep-1)*outstep)+model.timestepping.start_time+model.timestepping.time_step
-					while (res_struct.(fieldnames{k})(end,index)<=currenttime);
-						index=index+1
-		      end
-					uptime=res_struct.(fieldnames{k})(end,index);
-					uplim=res_struct.(fieldnames{k})(IsEnveloppe,index);
-					uptime
-					while (res_struct.(fieldnames{k})(end,index)>=currenttime);
-						index=index-1
-		      end
-					lowtime=res_struct.(fieldnames{k})(end,index);
-					lowlim=res_struct.(fieldnames{k})(IsEnveloppe,index);
-					lowtime
-					interp=lowlim+(uplim-lowlim)*((currenttime-lowtime)/(uptime-lowtime))
-					s='%e\n';
-					fprintf(fid,s,interp);
-				end	
-		  end		
-		end 
-	end
-	fclose(fid);
-end
Index: issm/trunk/src/m/contrib/defleurian/paraview/enveloppeVTK.py
===================================================================
--- issm/trunk/src/m/contrib/defleurian/paraview/enveloppeVTK.py	(revision 27035)
+++ 	(revision )
@@ -1,171 +1,0 @@
-import numpy as np
-import os
-import glob
-
-
-def enveloppeVTK(filename, model, *args):
-    '''
-    vtk export
-    function exportVTK(filename, model)
-    creates a directory with the vtk files for displays in paraview
-    (only work for triangle and wedges based on their number of nodes)
-
-    Give only the results for nw but could be extended to geometry, mask...
-
-    input: filename   destination
-    (string)
-     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-    model      this is md
-     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-    By default only the results are exported, you can add whichever
-    field you need as a string:
-    add 'geometry' to export md.geometry
-
-    Basile de Fleurian:
-    '''
-    Dir = os.path.basename(filename)
-    Path = filename[: - len(Dir)]
-
-    if os.path.exists(filename):
-        print(('File {} allready exist'.format(filename)))
-        newname = input('Give a new name or "delete" to replace: ')
-        if newname == 'delete':
-            filelist = glob.glob(filename + '/* ')
-            for oldfile in filelist:
-                os.remove(oldfile)
-        else:
-            print(('New file name is {}'.format(newname)))
-            filename = newname
-            os.mkdir(filename)
-    else:
-        os.mkdir(filename)
-
-    # {{{get the element related variables
-    if 'z' in dict.keys(model.mesh.__dict__):
-        is_enveloppe = np.logical_or(model.mesh.vertexonbase, model.mesh.vertexonsurface)
-        enveloppe_index = np.where(is_enveloppe)[0]
-        convert_index = np.nan * np.ones(np.shape(model.mesh.x))
-        convert_index = np.asarray([[i, np.where(enveloppe_index == i)[0][0]] for i, val in enumerate(convert_index) if any(enveloppe_index == i)])
-        points = np.column_stack((model.mesh.x[enveloppe_index],
-                                  model.mesh.y[enveloppe_index],
-                                  model.mesh.z[enveloppe_index]))
-        low_elt_num = np.size(np.where(np.isnan(model.mesh.lowerelements)))
-        top_elt_num = np.size(np.where(np.isnan(model.mesh.upperelements)))
-        num_of_elt = low_elt_num + top_elt_num
-        connect = model.mesh.elements[np.where(is_enveloppe[model.mesh.elements - 1])].reshape(int(num_of_elt), 3) - 1
-        for elt in range(0, num_of_elt):
-            connect[elt, 0] = convert_index[np.where(convert_index == connect[elt, 0])[0], 1][0]
-            connect[elt, 1] = convert_index[np.where(convert_index == connect[elt, 1])[0], 1][0]
-            connect[elt, 2] = convert_index[np.where(convert_index == connect[elt, 2])[0], 1][0]
-
-    else:
-        points = np.column_stack((model.mesh.x,
-                                  model.mesh.y,
-                                  np.zeros(np.shape(model.mesh.x))))
-        num_of_elt = np.shape(model.mesh.elements)[0]
-        connect = model.mesh.elements - 1
-        enveloppe_index = np.arange(0, np.size(model.mesh.x))
-
-    every_nodes = np.size(model.mesh.x)
-    num_of_points = np.size(enveloppe_index)
-    dim = 3
-    point_per_elt = 3
-    celltype = 5  #triangles
-
-    # }}}
-    # {{{this is the result structure
-    res_struct = model.results
-    if (len(res_struct.__dict__) > 0):
-        #Getting all the solutions of the model
-        solnames = (dict.keys(res_struct.__dict__))
-        num_of_sols = len(solnames)
-        num_of_timesteps = 1
-        #%building solutionstructure
-        for solution in solnames:
-            #looking for multiple time steps
-            if (np.size(res_struct.__dict__[solution]) > num_of_timesteps):
-                num_of_timesteps = np.size(res_struct.__dict__[solution])
-                num_of_timesteps = int(num_of_timesteps)
-    else:
-        num_of_timesteps = 1
-    # }}}
-    # {{{write header and mesh
-    for step in range(0, num_of_timesteps):
-        timestep = step
-        fid = open((filename + '/Timestep.vtk' + str(timestep) + '.vtk'), 'w + ')
-        fid.write('  # vtk DataFile Version 2.0 \n')
-        fid.write('Data for run %s \n' % model.miscellaneous.name)
-        fid.write('ASCII \n')
-        fid.write('DATASET UNSTRUCTURED_GRID \n')
-        fid.write('POINTS %d float\n' % num_of_points)
-        for point in points:
-            fid.write('%f %f %f \n' % (point[0], point[1], point[2]))
-
-        fid.write('CELLS %d %d\n' % (num_of_elt, num_of_elt * (point_per_elt + 1)))
-
-        for elt in range(0, num_of_elt):
-            fid.write('3 %d %d %d\n' % (connect[elt, 0],
-                                        connect[elt, 1],
-                                        connect[elt, 2]))
-
-        fid.write('CELL_TYPES %d\n' % num_of_elt)
-        for elt in range(0, num_of_elt):
-            fid.write('%d\n' % celltype)
-
-        fid.write('POINT_DATA %s \n' % str(num_of_points))
-    # }}}
-    # {{{loop over the different solution structures
-        if 'solnames' in locals():
-            for sol in solnames:
-                #dealing with results on different timesteps
-                if(np.size(res_struct.__dict__[sol]) > timestep):
-                    timestep = step
-                else:
-                    timestep = np.size(res_struct.__dict__[sol])
-
-    #getting the  fields in the solution
-                if(type(res_struct.__dict__[sol]) == list):
-                    fieldnames = dict.keys(res_struct.__dict__[sol].__getitem__(timestep).__dict__)
-                else:
-                    fieldnames = dict.keys(res_struct.__dict__[sol].__dict__)
-    #check which field is a real result and print
-                for field in fieldnames:
-                    if(type(res_struct.__dict__[sol]) == list):
-                        fieldstruct = res_struct.__dict__[sol].__getitem__(timestep).__dict__[field]
-                    else:
-                        fieldstruct = res_struct.__dict__[sol].__dict__[field]
-
-                    if ((np.size(fieldstruct)) == every_nodes):
-                        fid.write('SCALARS %s float 1 \n' % field)
-                        fid.write('LOOKUP_TABLE default\n')
-                        for node in range(0, num_of_points):
-                            #paraview does not like NaN, replacing
-                            if np.isnan(fieldstruct[enveloppe_index[node]]):
-                                fid.write('%e\n' % - 9999.9999)
-                                #also checking for verry small value that mess up
-                            elif (abs(fieldstruct[enveloppe_index[node]]) < 1.0e-20):
-                                fid.write('%e\n' % 0.0)
-                            else:
-                                fid.write('%e\n' % fieldstruct[enveloppe_index[node]])
-    # }}}
-    # {{{loop on arguments, if something other than result is asked, do it now
-
-        for other in args:
-            other_struct = model.__dict__[other]
-            othernames = (dict.keys(other_struct.__dict__))
-            for field in othernames:
-                if ((np.size(other_struct.__dict__[field])) == every_nodes):
-                    fid.write('SCALARS %s float 1 \n' % field)
-                    fid.write('LOOKUP_TABLE default\n')
-                    for node in range(0, num_of_points):
-                        #paraview does not like NaN, replacing
-                        if np.isnan(other_struct.__dict__[field][enveloppe_index[node]]):
-                            fid.write('%e\n' % - 9999.9999)
-                            #also checking for verry small value that mess up
-                        elif (abs(other_struct.__dict__[field][enveloppe_index[node]]) < 1.0e-20):
-                            fid.write('%e\n' % 0.0)
-                        else:
-                            fid.write('%e\n' % other_struct.__dict__[field][enveloppe_index[node]])
-
-    # }}}
-    fid.close()
Index: issm/trunk/src/m/contrib/defleurian/paraview/exportVTK.py
===================================================================
--- issm/trunk/src/m/contrib/defleurian/paraview/exportVTK.py	(revision 27035)
+++ issm/trunk/src/m/contrib/defleurian/paraview/exportVTK.py	(revision 27232)
@@ -29,8 +29,22 @@
     Basile de Fleurian:
     '''
+    #verbosity of the code, 0 is no messages, 5 is chatty
+    verbose = 0
+
+    print("""
+    =========================================
+    #     A                                 #
+    #    / \      exportVTK is now obsolete #
+    #   / | \     You should use export VTU #
+    #  /  |  \    faster, smaller files     #
+    # /   o   \   and more capacities       #
+    # ---------                             #
+    #========================================
+    """)
+
 
     for key in kwargs.keys():
         if key not in ['clipping', 'coarsetime', 'singletime']:
-            raise BadOption('Provided option "{}" is not supported possibilities are : {}'.format(key, ['cliping', 'coarsetime']))
+            raise BadOption('Provided option "{}" is not supported possibilities are : {}'.format(key, ['cliping', 'coarsetime', 'singletime']))
 
     if 'coarsetime' in kwargs.keys() and 'singletime' in kwargs.keys():
@@ -56,5 +70,6 @@
 
     # this is the result structure {{{
-    print('Getting accessorie variables')
+    if verbose > 3:
+        print('Getting accessorie variables')
     res_struct = md.results
     moving_mesh = False
@@ -80,9 +95,15 @@
 
     # get the element related variables {{{
-    print('Now treating  the mesh')
+    if verbose > 3:
+        print('Now treating  the mesh')
     #first get the general things
     dim = int(md.mesh.domaintype()[0])
     every_nodes = md.mesh.numberofvertices
     every_cells = md.mesh.numberofelements
+    try:
+        every_edges = md.mesh.numberofedges
+    except AttributeError:
+        #3D meshes do not have edges
+        every_edges = 0
 
     if np.shape(md.mesh.elements)[1] == 3 or enveloppe:
@@ -103,4 +124,6 @@
             convert_index = np.nan * np.ones(np.shape(md.mesh.x))
             convert_index = np.asarray([[i, np.where(enveloppe_index == i)[0][0]] for i, val in enumerate(convert_index) if any(enveloppe_index == i)])
+
+            num_of_points = np.size(enveloppe_index)
             points = np.column_stack((md.mesh.x[enveloppe_index],
                                       md.mesh.y[enveloppe_index],
@@ -114,5 +137,8 @@
                 connect[elt, 2] = convert_index[np.where(convert_index == connect[elt, 2])[0], 1][0]
 
-            num_of_points = np.size(enveloppe_index)
+            num_of_edges = every_edges  #looks like edges is only defined on the 2d mesh
+            if num_of_edges > 0:
+                edges = md.mesh.edges[:, 0:2].reshape(int(num_of_edges), 2) - 1
+
         else:
             raise BadDimension("exportVTK can't get an enveloppe for  dimension {}".format(dim))
@@ -122,4 +148,7 @@
         num_of_elt = every_cells
         connect = md.mesh.elements - 1
+        num_of_edges = every_edges
+        if num_of_edges > 0:
+            edges = md.mesh.edges[:, 0:2].reshape(int(num_of_edges), 2) - 1
         enveloppe_index = np.arange(0, np.size(md.mesh.x))
         num_of_points = every_nodes
@@ -129,5 +158,6 @@
                                         2 : md.geometry.base
                                         3 : md.geometry.bed
-                                        4 : 0\n''')
+                                        4 : 0
+                                        5 : Custom\n''')
             if mesh_alti == '1':
                 points = np.column_stack((md.mesh.x, md.mesh.y, md.geometry.surface))
@@ -138,4 +168,11 @@
             elif mesh_alti == '4':
                 points = np.column_stack((md.mesh.x, md.mesh.y, 0. * md.mesh.x))
+            elif mesh_alti == '5':
+                alti_field = input("Which field should be used as 3rd dimension: ")
+                alti_var = eval(alti_field)
+                if np.shape(np.squeeze(alti_var)) == np.shape(md.mesh.x):
+                    points = np.column_stack((md.mesh.x, md.mesh.y, np.squeeze(alti_var)))
+                else:
+                    raise BadDimension('field given for 3rd dimension should be defined on vertices {} is not.'.format(alti_field))
             else:
                 points = np.column_stack((md.mesh.x, md.mesh.y, md.geometry.surface))
@@ -166,4 +203,5 @@
             clip_convert_index = np.nan * np.ones(np.shape(points)[0])
 
+            #define the vertices that are within clipping window
             Inclipping = np.intersect1d(InX, InY)
             Isinside[Inclipping] = True
@@ -171,4 +209,5 @@
             num_of_points = np.shape(points)[0]
 
+            #go thorough the elements and keep those for which one node is in the clipped arrea
             clipconnect = np.asarray([], dtype=int)
             for elt in connect:
@@ -176,4 +215,5 @@
                     clipconnect = np.append(clipconnect, elt, axis=0)
 
+            #reshape
             num_of_elt = int(np.size(clipconnect) / 3)
             connect = clipconnect.reshape(num_of_elt, 3)
@@ -181,4 +221,6 @@
             clip_convert_index = np.asarray([[i, np.where(Inclipping == i)[0][0]] for i, val in enumerate(clip_convert_index) if any(Inclipping == i)])
             enveloppe_index = enveloppe_index[clip_convert_index[:, 0]]
+
+            #convert indexing and exclude elements that are partly outside of the region
             for elt in range(0, num_of_elt):
                 try:
@@ -198,7 +240,30 @@
             num_of_elt = np.shape(connect)[0]
 
+            if num_of_edges > 0:
+                clipedges = np.asarray([], dtype=int)
+                for edge in edges:
+                    if set(edge).issubset(Inclipping):
+                        clipedges = np.append(clipedges, edge, axis=0)
+
+                num_of_edges = int(np.size(clipedges) / 2)
+                edges = clipedges.reshape(num_of_edges, 2)
+
+                for edge in range(0, num_of_edges):
+                    try:
+                        edges[edge, 0] = clip_convert_index[np.where(clip_convert_index == edges[edge, 0])[0], 1][0]
+                    except IndexError:
+                        edges[edge, 0] = -1
+                    try:
+                        edges[edge, 1] = clip_convert_index[np.where(clip_convert_index == edges[edge, 1])[0], 1][0]
+                    except IndexError:
+                        edges[edge, 1] = -1
+                edges = edges[np.where(edges != -1)[0], :]
+                num_of_edges = np.shape(edges)[0]
+
     # }}}
+
     # write header and mesh {{{
-    print('Now starting to write stuff')
+    if verbose > 3:
+        print('Now starting to write stuff')
 
     if 'coarsetime' in kwargs.keys():
@@ -210,214 +275,241 @@
 
     for step in steplist:
-        print('Writing for step {}'.format(step))
+        if verbose > 2:
+            print('Writing for step {}'.format(step))
         saved_cells = {}
+        saved_edges = {}
         timestep = step
-        fid = open((filename + '/Timestep.vtk' + str(timestep) + '.vtk'), 'w+')
-        fid.write('# vtk DataFile Version 3.0 \n')
-        fid.write('Data for run {} \n'.format(md.miscellaneous.name))
-        fid.write('ASCII \n')
-        fid.write('DATASET UNSTRUCTURED_GRID \n')
-        fid.write('POINTS {:d} float\n'.format(num_of_points))
-    #updating z for mesh evolution
-        if moving_mesh and mesh_alti in ['1', '2']:
-            base = np.squeeze(res_struct.__dict__['TransientSolution'][step].__dict__['Base'][enveloppe_index])
-            thick_change_ratio = (np.squeeze(res_struct.__dict__['TransientSolution'][step].__dict__['Thickness'][enveloppe_index]) / md.geometry.thickness[enveloppe_index])
-            above_bed = points[:, 2] - md.geometry.base[enveloppe_index]
-            altitude = base + thick_change_ratio * above_bed
-        else:
-            altitude = points[:, 2]
-        for index, point in enumerate(points):
-            fid.write('{:f} {:f} {:f} \n'.format(point[0], point[1], altitude[index]))
-
-        fid.write('CELLS {:d} {:d}\n'.format(num_of_elt, num_of_elt * (point_per_elt + 1)))
-
-        for elt in range(0, num_of_elt):
-            if celltype == 5:
-                fid.write('3 {:d} {:d} {:d}\n'.format(connect[elt, 0],
-                                                      connect[elt, 1],
-                                                      connect[elt, 2]))
-            elif celltype == 13:
-                fid.write('6 {:d} {:d} {:d} {:d} {:d} {:d}\n'.format(connect[elt, 0],
-                                                                     connect[elt, 1],
-                                                                     connect[elt, 2],
-                                                                     connect[elt, 3],
-                                                                     connect[elt, 4],
-                                                                     connect[elt, 5]))
-
-        fid.write('CELL_TYPES {:d}\n'.format(num_of_elt))
-        for elt in range(0, num_of_elt):
-            fid.write('{:d}\n'.format(celltype))
-
-        fid.write('POINT_DATA {:s} \n'.format(str(num_of_points)))
+        with open((filename + '/Timestep.vtk' + str(timestep) + '.vtk'), 'w+') as fid:
+            fid.write('# vtk DataFile Version 3.0 \n')
+            fid.write('Data for run {} \n'.format(md.miscellaneous.name))
+            fid.write('ASCII \n')
+            fid.write('DATASET UNSTRUCTURED_GRID \n')
+            fid.write('POINTS {:d} float\n'.format(num_of_points))
+            #updating z for mesh evolution
+            if moving_mesh and mesh_alti in ['1', '2']:
+                base = np.squeeze(res_struct.__dict__['TransientSolution'][step].__dict__['Base'][enveloppe_index])
+                thick_change_ratio = (np.squeeze(res_struct.__dict__['TransientSolution'][step].__dict__['Thickness'][enveloppe_index]) / md.geometry.thickness[enveloppe_index])
+                above_bed = points[:, 2] - md.geometry.base[enveloppe_index]
+                altitude = base + thick_change_ratio * above_bed
+            else:
+                altitude = points[:, 2]
+            for index, point in enumerate(points):
+                fid.write('{:f} {:f} {:f} \n'.format(point[0], point[1], altitude[index]))
+
+            fid.write('CELLS {:d} {:d}\n'.format((num_of_elt + num_of_edges), num_of_elt  * (point_per_elt + 1) + num_of_edges * 3))
+
+            for elt in range(0, num_of_elt):
+                if celltype == 5:
+                    fid.write('3 {:d} {:d} {:d}\n'.format(connect[elt, 0],
+                                                          connect[elt, 1],
+                                                          connect[elt, 2]))
+                elif celltype == 13:
+                    fid.write('6 {:d} {:d} {:d} {:d} {:d} {:d}\n'.format(connect[elt, 0],
+                                                                         connect[elt, 1],
+                                                                         connect[elt, 2],
+                                                                         connect[elt, 3],
+                                                                         connect[elt, 4],
+                                                                         connect[elt, 5]))
+            for edge in range(0, num_of_edges):
+                fid.write('2 {:d} {:d}\n'.format(edges[edge, 0],
+                                                 edges[edge, 1]))
+
+            fid.write('CELL_TYPES {:d}\n'.format(num_of_elt + num_of_edges))
+            for elt in range(0, num_of_elt):
+                fid.write('{:d}\n'.format(celltype))
+                for edge in range(0, num_of_edges):
+                    fid.write('3\n')  #3 is for lines
+
+            fid.write('POINT_DATA {:s} \n'.format(str(num_of_points)))
+            # }}}
+            # {{{loop over the different solution structures
+            # first check if there are solutions to grab
+            if 'solnames' in locals():
+                for sol in solnames:
+                    treated_res = []
+                    #dealing with results on different timesteps
+                    try:
+                        if(len(res_struct.__dict__[sol]) > timestep):
+                            timestep = step
+                        else:
+                            timestep = np.size(res_struct.__dict__[sol])
+                    except TypeError:
+                        #result as no len() so no timesteps
+                        timestep = 1
+
+                    #getting the  fields in the solution
+                    if(type(res_struct.__dict__[sol]).__name__ == 'solution'):
+                        spe_res_struct = res_struct.__dict__[sol].__getitem__(timestep)
+                        fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                    elif(type(res_struct.__dict__[sol]).__name__ == 'solutionstep'):
+                        spe_res_struct = res_struct.__dict__[sol]
+                        fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                    elif(type(res_struct.__dict__[sol]).__name__ == 'results'):  #this is a result without steps
+                        spe_res_struct = res_struct.__dict__[sol]
+                        fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                    else:
+                        print("WARNING, solution type '{}' is not recognise, exported results might be wrong".format(type(res_struct.__dict__[sol])))
+                        spe_res_struct = res_struct.__dict__[sol]
+                        fieldnames = list(dict.keys(spe_res_struct.__dict__))
+
+                    #Sorting scalars, vectors and tensors
+                    tensors = [field for field in fieldnames if field[-2:] in ['xx', 'yy', 'xy', 'zz', 'xz', 'yz']]
+                    non_tensor = [field for field in fieldnames if field not in tensors]
+                    vectors = [field for field in non_tensor if field[-1] in ['x', 'y', 'z'] and field[-4:] not in ['Flux']]
+                    #check which field is a real result and print
+                    for field in fieldnames:
+                        if verbose > 2:
+                            print("Treating {}".format(field))
+                        if field in treated_res:
+                            if verbose > 2:
+                                print("{} is already done".format(field))
+                            continue
+                        elif field in vectors:
+                            if verbose > 2:
+                                print("{} is a vector".format(field))
+                            try:
+                                Vxstruct = np.squeeze(spe_res_struct.__dict__[field[:-1] + 'x'])
+                                Vystruct = np.squeeze(spe_res_struct.__dict__[field[:-1] + 'y'])
+                                treated_res += [field[:-1] + 'x', field[:-1] + 'y']
+                                if dim == 3 and field[:-1] + 'z' in fieldnames:
+                                    #some fields like adjoint or always 2D
+                                    Vzstruct = np.squeeze(spe_res_struct.__dict__[field[:-1] + 'z'])
+                                    treated_res += [field[:-1] + 'z']
+
+                            except KeyError:
+                                fieldnames += field
+                                vectors.remove(field)
+
+                            fid.write('VECTORS {} float \n'.format(field[:-1]))
+                            for node in range(0, num_of_points):
+                                Vx = cleanOutliers(Vxstruct[enveloppe_index[node]])
+                                Vy = cleanOutliers(Vystruct[enveloppe_index[node]])
+                                if dim == 3 and field[:-1] + 'z' in fieldnames:
+                                    Vz = cleanOutliers(Vzstruct[enveloppe_index[node]])
+                                    fid.write('{:f} {:f} {:f}\n'.format(Vx, Vy, Vz))
+                                else:
+                                    fid.write('{:f} {:f} {:f}\n'.format(Vx, Vy, 0))
+
+                        elif field in tensors:
+                            if verbose > 2:
+                                print("{} is a tensor".format(field))
+                            try:
+                                Txxstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'xx'])
+                                Txystruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'xy'])
+                                Tyystruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'yy'])
+                                treated_res += [field[:-2] + 'xx', field[:-2] + 'xy', field[:-2] + 'yy']
+                                if dim == 3:
+                                    Tzzstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'zz'])
+                                    Txzstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'xz'])
+                                    Tyzstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'yz'])
+                                    treated_res += [field[:-2] + 'zz', field[:-2] + 'xz', field[:-2] + 'yz']
+
+                            except KeyError:
+                                fieldnames += field
+                                tensors.remove(field)
+
+                            fid.write('TENSORS {} float \n'.format(field[:-2]))
+                            for node in range(0, num_of_points):
+                                Txx = cleanOutliers(Txxstruct[enveloppe_index[node]])
+                                Tyy = cleanOutliers(Tyystruct[enveloppe_index[node]])
+                                Txy = cleanOutliers(Txystruct[enveloppe_index[node]])
+                                if dim == 3:
+                                    Tzz = cleanOutliers(Tzzstruct[enveloppe_index[node]])
+                                    Txz = cleanOutliers(Txzstruct[enveloppe_index[node]])
+                                    Tyz = cleanOutliers(Tyzstruct[enveloppe_index[node]])
+                                    fid.write('{:f} {:f} {:f}\n'.format(Txx, Txy, Txz))
+                                    fid.write('{:f} {:f} {:f}\n'.format(Txy, Tyy, Tyz))
+                                    fid.write('{:f} {:f} {:f}\n'.format(Txz, Tyz, Tzz))
+                                elif dim == 2:
+                                    fid.write('{:f} {:f} {:f}\n'.format(Txx, Txy, 0))
+                                    fid.write('{:f} {:f} {:f}\n'.format(Txy, Tyy, 0))
+                                    fid.write('{:f} {:f} {:f}\n'.format(0, 0, 0))
+                        else:
+                            if np.size(spe_res_struct.__dict__[field]) == 1:
+                                if field == 'time':
+                                    current_time = spe_res_struct.__dict__[field]
+                                    #skipping integers
+                                continue
+                            elif np.size(spe_res_struct.__dict__[field]) == every_nodes:
+                                fid.write('SCALARS {} float 1 \n'.format(field))
+                                fid.write('LOOKUP_TABLE default\n')
+                                for node in range(0, num_of_points):
+                                    outval = cleanOutliers(np.squeeze(spe_res_struct.__dict__[field][enveloppe_index[node]]))
+                                    fid.write('{:f}\n'.format(outval))
+                            elif np.shape(spe_res_struct.__dict__[field])[0] == np.size(spe_res_struct.__dict__[field]) == every_cells:
+                                saved_cells[field] = np.squeeze(spe_res_struct.__dict__[field])
+                            elif np.shape(spe_res_struct.__dict__[field])[0] == np.size(spe_res_struct.__dict__[field]) == every_edges:
+                                saved_edges[field] = np.squeeze(spe_res_struct.__dict__[field])
+                            else:
+                                print("format for field {}.{} is not suported, field is skipped".format(sol, field))
+            # }}}
+            # loop on arguments, if something other than result is asked, do it now {{{
+            for other in args:
+                other_struct = md.__dict__[other]
+                othernames = (dict.keys(other_struct.__dict__))
+                for field in othernames:
+                    if np.size(other_struct.__dict__[field]) == 1:
+                        #skipping integers
+                        continue
+                    elif np.size(other_struct.__dict__[field]) == every_nodes:
+                        fid.write('SCALARS {} float 1 \n'.format(field))
+                        fid.write('LOOKUP_TABLE default\n')
+                        for node in range(0, num_of_points):
+                            outval = cleanOutliers(other_struct.__dict__[field][enveloppe_index[node]])
+                            fid.write('{:f}\n'.format(outval))
+                    elif np.shape(other_struct.__dict__[field])[0] == every_nodes + 1:
+                        #we are dealing with a forcing of some kind.
+                        forcing_time = other_struct.__dict__[field][-1, :]
+                        if any(forcing_time == current_time):
+                            forcing_index = np.where(forcing_time == current_time)
+                            forcing_val = other_struct.__dict__[field][:, forcing_index]
+                        elif forcing_time[0] > current_time:
+                            forcing_val = other_struct.__dict__[field][:, 0]
+                        elif forcing_time[-1] < current_time:
+                            forcing_val = other_struct.__dict__[field][:, -1]
+                        else:
+                            forcing_index = np.where(forcing_time < current_time)[-1][-1]
+                            delta_time = forcing_time[forcing_index + 1] - forcing_time[forcing_index]  #compute forcing Dt
+                            delta_current = current_time - forcing_time[forcing_index]  # time since last forcing
+                            ratio = delta_current / delta_time  #compute weighting factor for preceding forcing vallue
+                            forcing_evol = (other_struct.__dict__[field][:, forcing_index + 1] - other_struct.__dict__[field][:, forcing_index]) * ratio
+                            forcing_val = other_struct.__dict__[field][:, forcing_index] + forcing_evol
+                        # and now write it down
+                        fid.write('SCALARS {}_{} float 1 \n'.format(other, field))
+                        fid.write('LOOKUP_TABLE default\n')
+                        for node in range(0, num_of_points):
+                            outval = cleanOutliers(forcing_val[enveloppe_index[node]])
+                            fid.write('{:f}\n'.format(outval))
+                    elif np.shape(other_struct.__dict__[field])[0] == np.size(other_struct.__dict__[field]) == every_cells:
+                        saved_cells[field] = other_struct.__dict__[field]
+                    elif np.shape(other_struct.__dict__[field])[0] == np.size(other_struct.__dict__[field]) == every_edges:
+                        saved_edges[field] = other_struct.__dict__[field]
+                    else:
+                        print("format for field {}.{} is not suported, field is skipped".format(other, field))
+                        continue
+            # }}}
+            # Now writting cell variables {{{
+            if np.size(list(saved_cells.keys())) > 0:
+                fid.write('CELL_DATA {:d} \n'.format(num_of_elt + num_of_edges))
+                for key in list(saved_cells.keys()):
+                    fid.write('SCALARS {} float 1 \n'.format(key))
+                    fid.write('LOOKUP_TABLE default\n')
+                    for cell in range(0, num_of_elt):
+                        outval = cleanOutliers(saved_cells[key][cell])
+                        fid.write('{:f}\n'.format(outval))
+                    for edge in range(0, num_of_edges):
+                        fid.write('{:f}\n'.format(-9999.999))
+            # }}}
+            # Now writting edge variables {{{
+            if np.size(list(saved_edges.keys())) > 0:
+                for key in list(saved_edges.keys()):
+                    fid.write('SCALARS {} float 1 \n'.format(key))
+                    fid.write('LOOKUP_TABLE default\n')
+                    for cell in range(0, num_of_elt):
+                        fid.write('{:f}\n'.format(-9999.999))
+                    for edge in range(0, num_of_edges):
+                        outval = cleanOutliers(saved_edges[key][edge])
+                        fid.write('{:f}\n'.format(outval))
     # }}}
-    # {{{loop over the different solution structures
-    # first check if there are solutions to grab
-        if 'solnames' in locals():
-            for sol in solnames:
-                treated_res = []
-                #dealing with results on different timesteps
-                try:
-                    if(len(res_struct.__dict__[sol]) > timestep):
-                        timestep = step
-                    else:
-                        timestep = np.size(res_struct.__dict__[sol])
-                except TypeError:
-                    #result as no len() so no timesteps
-                    timestep = 1
-
-                #getting the  fields in the solution
-                if(type(res_struct.__dict__[sol]).__name__ == 'solution'):
-                    spe_res_struct = res_struct.__dict__[sol].__getitem__(timestep)
-                    fieldnames = dict.keys(spe_res_struct.__dict__)
-                elif(type(res_struct.__dict__[sol]).__name__ == 'solutionstep'):
-                    spe_res_struct = res_struct.__dict__[sol]
-                    fieldnames = dict.keys(spe_res_struct.__dict__)
-                elif(type(res_struct.__dict__[sol]).__name__ == 'results'):  #this is a result without steps
-                    spe_res_struct = res_struct.__dict__[sol]
-                    fieldnames = dict.keys(spe_res_struct.__dict__)
-                else:
-                    print("WARNING, solution type '{}' is not recognise, exported results might be wrong".format(type(res_struct.__dict__[sol])))
-                    spe_res_struct = res_struct.__dict__[sol]
-                    fieldnames = dict.keys(spe_res_struct.__dict__)
-
-                #Sorting scalars, vectors and tensors
-                tensors = [field for field in fieldnames if field[-2:] in ['xx', 'yy', 'xy', 'zz', 'xz', 'yz']]
-                non_tensor = [field for field in fieldnames if field not in tensors]
-                vectors = [field for field in non_tensor if field[-1] in ['x', 'y', 'z'] and field[-4:] not in ['Flux']]
-
-                #check which field is a real result and print
-                for field in fieldnames:
-                    print("Treating {}".format(field))
-                    if field in treated_res:
-                        print("{} is already done".format(field))
-                        continue
-                    elif field in vectors:
-                        print("{} is a vector".format(field))
-                        try:
-                            Vxstruct = np.squeeze(spe_res_struct.__dict__[field[:-1] + 'x'])
-                            Vystruct = np.squeeze(spe_res_struct.__dict__[field[:-1] + 'y'])
-                            treated_res += [field[:-1] + 'x', field[:-1] + 'y']
-                            if dim == 3:
-                                Vzstruct = np.squeeze(spe_res_struct.__dict__[field[:-1] + 'z'])
-                                treated_res += field[:-1] + 'z'
-
-                        except KeyError:
-                            fieldnames += field
-                            vectors.remove(field)
-
-                        fid.write('VECTORS {} float \n'.format(field[:-1]))
-                        for node in range(0, num_of_points):
-                            Vx = cleanOutliers(Vxstruct[enveloppe_index[node]])
-                            Vy = cleanOutliers(Vystruct[enveloppe_index[node]])
-                            if dim == 3:
-                                Vz = cleanOutliers(Vzstruct[enveloppe_index[node]])
-                                fid.write('{:f} {:f} {:f}\n'.format(Vx, Vy, Vz))
-                            elif dim == 2:
-                                fid.write('{:f} {:f} {:f}\n'.format(Vx, Vy, 0))
-
-                    elif field in tensors:
-                        print("{} is a tensor".format(field))
-                        try:
-                            Txxstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'xx'])
-                            Txystruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'xy'])
-                            Tyystruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'yy'])
-                            treated_res += [field[:-2] + 'xx', field[:-2] + 'xy', field[:-2] + 'yy']
-                            if dim == 3:
-                                Tzzstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'zz'])
-                                Txzstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'xz'])
-                                Tyzstruct = np.squeeze(spe_res_struct.__dict__[field[:-2] + 'yz'])
-                                treated_res += [field[:-2] + 'zz', field[:-2] + 'xz', field[:-2] + 'yz']
-
-                        except KeyError:
-                            fieldnames += field
-                            tensors.remove(field)
-
-                        fid.write('TENSORS {} float \n'.format(field[:-2]))
-                        for node in range(0, num_of_points):
-                            Txx = cleanOutliers(Txxstruct[enveloppe_index[node]])
-                            Tyy = cleanOutliers(Tyystruct[enveloppe_index[node]])
-                            Txy = cleanOutliers(Txystruct[enveloppe_index[node]])
-                            if dim == 3:
-                                Tzz = cleanOutliers(Tzzstruct[enveloppe_index[node]])
-                                Txz = cleanOutliers(Txzstruct[enveloppe_index[node]])
-                                Tyz = cleanOutliers(Tyzstruct[enveloppe_index[node]])
-                                fid.write('{:f} {:f} {:f}\n'.format(Txx, Txy, Txz))
-                                fid.write('{:f} {:f} {:f}\n'.format(Txy, Tyy, Tyz))
-                                fid.write('{:f} {:f} {:f}\n'.format(Txz, Tyz, Tzz))
-                            elif dim == 2:
-                                fid.write('{:f} {:f} {:f}\n'.format(Txx, Txy, 0))
-                                fid.write('{:f} {:f} {:f}\n'.format(Txy, Tyy, 0))
-                                fid.write('{:f} {:f} {:f}\n'.format(0, 0, 0))
-                    else:
-                        if np.size(spe_res_struct.__dict__[field]) == 1:
-                            if field == 'time':
-                                current_time = spe_res_struct.__dict__[field]
-                            #skipping integers
-                            continue
-                        elif np.size(spe_res_struct.__dict__[field]) == every_nodes:
-                            fid.write('SCALARS {} float 1 \n'.format(field))
-                            fid.write('LOOKUP_TABLE default\n')
-                            for node in range(0, num_of_points):
-                                outval = cleanOutliers(np.squeeze(spe_res_struct.__dict__[field][enveloppe_index[node]]))
-                                fid.write('{:f}\n'.format(outval))
-                        elif np.shape(spe_res_struct.__dict__[field])[0] == np.size(spe_res_struct.__dict__[field]) == every_cells:
-                            saved_cells[field] = np.squeeze(spe_res_struct.__dict__[field])
-                        else:
-                            print("format for field {}.{} is not suported, field is skipped".format(sol, field))
-    # }}}
-    # loop on arguments, if something other than result is asked, do it now {{{
-        for other in args:
-            other_struct = md.__dict__[other]
-            othernames = (dict.keys(other_struct.__dict__))
-            for field in othernames:
-                if np.size(other_struct.__dict__[field]) == 1:
-                    #skipping integers
-                    continue
-                elif np.size(other_struct.__dict__[field]) == every_nodes:
-                    fid.write('SCALARS {} float 1 \n'.format(field))
-                    fid.write('LOOKUP_TABLE default\n')
-                    for node in range(0, num_of_points):
-                        outval = cleanOutliers(other_struct.__dict__[field][enveloppe_index[node]])
-                        fid.write('{:f}\n'.format(outval))
-                elif np.shape(other_struct.__dict__[field])[0] == every_nodes + 1:
-                    #we are dealing with a forcing of some kind.
-                    forcing_time = other_struct.__dict__[field][-1, :]
-                    if any(forcing_time == current_time):
-                        forcing_index = np.where(forcing_time == current_time)
-                        forcing_val = other_struct.__dict__[field][:, forcing_index]
-                    elif forcing_time[0] > current_time:
-                        forcing_val = other_struct.__dict__[field][:, 0]
-                    elif forcing_time[-1] < current_time:
-                        forcing_val = other_struct.__dict__[field][:, -1]
-                    else:
-                        forcing_index = np.where(forcing_time < current_time)[-1][-1]
-                        delta_time = forcing_time[forcing_index + 1] - forcing_time[forcing_index]  #compute forcing Dt
-                        delta_current = current_time - forcing_time[forcing_index]  # time since last forcing
-                        ratio = delta_current / delta_time  #compute weighting factor for preceding forcing vallue
-                        forcing_evol = (other_struct.__dict__[field][:, forcing_index + 1] - other_struct.__dict__[field][:, forcing_index]) * ratio
-                        forcing_val = other_struct.__dict__[field][:, forcing_index] + forcing_evol
-                    # and now write it down
-                    fid.write('SCALARS {}_{} float 1 \n'.format(other, field))
-                    fid.write('LOOKUP_TABLE default\n')
-                    for node in range(0, num_of_points):
-                        outval = cleanOutliers(forcing_val[enveloppe_index[node]])
-                        fid.write('{:f}\n'.format(outval))
-                elif np.shape(other_struct.__dict__[field])[0] == np.size(other_struct.__dict__[field]) == every_cells:
-                    saved_cells[field] = other_struct.__dict__[field]
-                else:
-                    print("format for field {}.{} is not suported, field is skipped".format(other, field))
-                    continue
-    # }}}
-    # Now writting cell variables {{{
-        if np.size(list(saved_cells.keys())) > 0:
-            fid.write('CELL_DATA {:d} \n'.format(num_of_elt))
-            for key in list(saved_cells.keys()):
-                fid.write('SCALARS {} float 1 \n'.format(key))
-                fid.write('LOOKUP_TABLE default\n')
-                for cell in range(0, num_of_elt):
-                    outval = cleanOutliers(saved_cells[key][cell])
-                    fid.write('{:f}\n'.format(outval))
-    # }}}
-    fid.close()
 
 
Index: issm/trunk/src/m/contrib/defleurian/paraview/exportVTU.py
===================================================================
--- issm/trunk/src/m/contrib/defleurian/paraview/exportVTU.py	(revision 27232)
+++ issm/trunk/src/m/contrib/defleurian/paraview/exportVTU.py	(revision 27232)
@@ -0,0 +1,723 @@
+import numpy as np
+from base64 import b64encode
+from os import path, remove, mkdir
+from glob import glob
+
+
+def exportVTU(filename, md, *args, enveloppe=False, fmtout="binary", **kwargs):
+    '''
+    vtu export
+    function exportVTU(filename, md)
+    Exports resluts in XML based vtu format for visualisation in Paraview.
+    Hopefully it is based on the treatment for export VTK and only the output part is modified.
+    (only work for triangle and wedges based on their number of nodes)
+
+    Usage:
+    exportVTU('FileName', md)
+    exportVTU('FileName', md, 'geometry', 'mesh')
+    exportVTU('FileName', md, 'geometry', 'mesh', enveloppe = True)
+
+    DirName is the name of the output directory, each timestep then has it
+    own file ('Timestep.vtkX.vtk') with X the number of the output step
+    enveloppe is an option keeping only the enveloppe of the md (it is False by default)
+
+    Options:
+        - clipping : allows to reduce your domain (cliping=[Xmin, Xmax, Ymin, Ymax])
+        - coarsetime : output one timestep every X (coarsetime=X, with X an integer)
+        - singletime : output only timestep X (singletime=X, with X an integer or -1 for last)
+
+    TODO: - make time easily accessible
+
+    Basile de Fleurian:
+    '''
+    #verbosity of the code, 0 is no messages, 5 is chatty
+    verbose = 0
+
+    #first check if the user asked for some options to be applied
+    for key in kwargs.keys():
+        if key not in ['clipping', 'coarsetime', 'singletime']:
+            raise BadOption('Provided option "{}" is not supported possibilities are : {}'.format(key, ['cliping', 'coarsetime', 'singletime']))
+
+    if 'coarsetime' in kwargs.keys() and 'singletime' in kwargs.keys():
+        raise BadOption("You can't specify both 'coarsetime' and 'singletime'")
+
+    # File checking and creation {{{
+    Dir = path.basename(filename)
+    if path.exists(filename):
+        print(('File {} allready exist'.format(filename)))
+        newname = input('Give a new name or "delete" to replace: ')
+        if newname == 'delete':
+            filelist = glob(filename + '/* ')
+            for oldfile in filelist:
+                remove(oldfile)
+        else:
+            print(('New file name is {}'.format(newname)))
+            filename = newname
+            mkdir(filename)
+    else:
+        mkdir(filename)
+
+    # }}}
+
+    # make an alias for results {{{
+    if verbose > 3:
+        print('Getting accessory variables')
+    res_struct = md.results
+    moving_mesh = False
+    if(type(res_struct) != list):
+        #Getting all the solutions of the md
+        solnames = dict.keys(res_struct.__dict__)
+        num_of_timesteps = 1
+        #%building solutionstructure
+        for solution in solnames:
+            #looking for multiple time steps
+            try:
+                if len(res_struct.__dict__[solution]) > num_of_timesteps:
+                    num_of_timesteps = len(res_struct.__dict__[solution])
+                    num_of_timesteps = int(num_of_timesteps)
+                    #If Suface is in the resluts we considet that we have a moving mesh
+                    if 'Surface' in dict.keys(res_struct.__dict__[solution][0].__dict__):
+                        moving_mesh = True
+            except TypeError:
+                continue
+    else:
+        num_of_timesteps = 1
+    # }}}
+
+    # get the mesh related variables {{{
+    if verbose > 3:
+        print('Now treating  the mesh')
+    #first get the general things
+    dim = int(md.mesh.domaintype()[0])
+    every_nodes = md.mesh.numberofvertices
+    every_cells = md.mesh.numberofelements
+    try:
+        every_edges = md.mesh.numberofedges
+    except AttributeError:
+        #3D meshes do not have edges
+        every_edges = 0
+
+    if np.shape(md.mesh.elements)[1] == 3 or enveloppe:
+        point_per_elt = 3
+        celltype = 5  #triangles
+    elif np.shape(md.mesh.elements)[1] == 6:
+        point_per_elt = 6
+        celltype = 13  #wedges
+    else:
+        raise BadDimension('exportVTU does not support your element type')
+
+    #only keep the envelope and not the bulk of the results.
+    if enveloppe:  #Treating enveloppe{{{
+        if dim == 3:
+            mesh_alti = '0'
+            is_enveloppe = np.logical_or(md.mesh.vertexonbase, md.mesh.vertexonsurface)
+            enveloppe_index = np.where(is_enveloppe)[0]
+            convert_index = np.nan * np.ones(np.shape(md.mesh.x))
+            convert_index = np.asarray([[i, np.where(enveloppe_index == i)[0][0]] for i, val in enumerate(convert_index) if any(enveloppe_index == i)])
+
+            num_of_points = np.size(enveloppe_index)
+            points = np.column_stack((md.mesh.x[enveloppe_index],
+                                      md.mesh.y[enveloppe_index],
+                                      md.mesh.z[enveloppe_index]))
+
+            num_of_elt = np.size(np.where(np.isnan(md.mesh.lowerelements))) + np.size(np.where(np.isnan(md.mesh.upperelements)))
+            connect = md.mesh.elements[np.where(is_enveloppe[md.mesh.elements - 1])].reshape(int(num_of_elt), 3) - 1
+            for elt in range(0, num_of_elt):
+                connect[elt, 0] = convert_index[np.where(convert_index == connect[elt, 0])[0], 1][0]
+                connect[elt, 1] = convert_index[np.where(convert_index == connect[elt, 1])[0], 1][0]
+                connect[elt, 2] = convert_index[np.where(convert_index == connect[elt, 2])[0], 1][0]
+
+            num_of_edges = every_edges  #looks like edges is only defined on the 2d mesh
+            if num_of_edges > 0:
+                edges = md.mesh.edges[:, 0:2].reshape(int(num_of_edges), 2) - 1
+
+        else:
+            raise BadDimension("exportVTU can't get an enveloppe for  dimension {}".format(dim))
+    # }}}
+
+    else:  #treating mesh{{{
+        #we get all the mesh, mainly defining dummies
+        num_of_elt = every_cells
+        connect = md.mesh.elements - 1
+        num_of_edges = every_edges
+        if num_of_edges > 0:
+            edges = md.mesh.edges[:, 0:2].reshape(int(num_of_edges), 2) - 1
+        enveloppe_index = np.arange(0, np.size(md.mesh.x))
+        num_of_points = every_nodes
+        if dim == 2:
+            mesh_alti = input('''This is a 2D model, what should be the 3rd dimension of the mesh :
+                                        1 : md.geometry.surface
+                                        2 : md.geometry.base
+                                        3 : md.geometry.bed
+                                        4 : 0
+                                        5 : Custom\n''')
+            if mesh_alti == '1':
+                points = np.column_stack((md.mesh.x, md.mesh.y, md.geometry.surface))
+            elif mesh_alti == '2':
+                points = np.column_stack((md.mesh.x, md.mesh.y, md.geometry.base))
+            elif mesh_alti == '3':
+                points = np.column_stack((md.mesh.x, md.mesh.y, md.geometry.bed))
+            elif mesh_alti == '4':
+                points = np.column_stack((md.mesh.x, md.mesh.y, 0. * md.mesh.x))
+            elif mesh_alti == '5':
+                alti_field = input("Which field should be used as 3rd dimension: ")
+                alti_var = eval(alti_field)
+                if np.shape(np.squeeze(alti_var)) == np.shape(md.mesh.x):
+                    points = np.column_stack((md.mesh.x, md.mesh.y, np.squeeze(alti_var)))
+                else:
+                    raise BadDimension('field given for 3rd dimension should be defined on vertices {} is not.'.format(alti_field))
+            else:
+                points = np.column_stack((md.mesh.x, md.mesh.y, md.geometry.surface))
+        elif dim == 3:
+            mesh_alti = '0'
+            points = np.column_stack((md.mesh.x, md.mesh.y, md.mesh.z))
+        else:
+            raise BadDimension('exportVTU does not support dimension {}'.format(dim))
+    # }}}
+
+    if 'clipping' in kwargs.keys():
+        if kwargs['clipping'] is not None:
+            # first get the boundaries and check them
+            [Xmin, Xmax, Ymin, Ymax] = kwargs['clipping']
+            if Xmin > Xmax:
+                raise ClipError('Xmax ({}) should be larger than Xmin ({})'.format(Xmax, Xmin))
+            if Ymin > Ymax:
+                raise ClipError('Ymax ({}) should be larger than Ymin ({})'.format(Ymax, Ymin))
+            if Xmin > np.nanmax(points[:, 0]) or Xmax < np.nanmin(points[:, 0]):
+                raise ClipError('Your X boundaries [{}, {}] are outside of the model domain [{},{}]'.format(Xmin, Xmax, np.nanmin(points[:, 0]), np.nanmax(points[:, 0])))
+            if Ymin > np.nanmax(points[:, 1]) or Ymax < np.nanmin(points[:, 1]):
+                raise ClipError('Your Y boundaries [{}, {}] are outside of the model domain [{},{}]'.format(Ymin, Ymax, np.nanmin(points[:, 1]), np.nanmax(points[:, 1])))
+
+            #boundaries should be fine lets do stuff
+            InX = np.where(np.logical_and(points[:, 0] >= Xmin, points[:, 0] <= Xmax))
+            InY = np.where(np.logical_and(points[:, 1] >= Ymin, points[:, 1] <= Ymax))
+
+            Isinside = np.zeros(np.shape(points)[0], dtype=bool)
+            clip_convert_index = np.nan * np.ones(np.shape(points)[0])
+
+            #define the vertices that are within clipping window
+            Inclipping = np.intersect1d(InX, InY)
+            Isinside[Inclipping] = True
+            points = points[Inclipping, :]
+            num_of_points = np.shape(points)[0]
+
+            #go thorough the elements and keep those for which one node is in the clipped arrea
+            clipconnect = np.asarray([], dtype=int)
+            for elt in connect:
+                if set(elt).issubset(Inclipping):
+                    clipconnect = np.append(clipconnect, elt, axis=0)
+
+            #reshape
+            num_of_elt = int(np.size(clipconnect) / 3)
+            connect = clipconnect.reshape(num_of_elt, 3)
+
+            clip_convert_index = np.asarray([[i, np.where(Inclipping == i)[0][0]] for i, val in enumerate(clip_convert_index) if any(Inclipping == i)])
+            enveloppe_index = enveloppe_index[clip_convert_index[:, 0]]
+
+            #convert indexing and exclude elements that are partly outside of the region
+            for elt in range(0, num_of_elt):
+                try:
+                    connect[elt, 0] = clip_convert_index[np.where(clip_convert_index == connect[elt, 0])[0], 1][0]
+                except IndexError:
+                    connect[elt, 0] = -1
+                try:
+                    connect[elt, 1] = clip_convert_index[np.where(clip_convert_index == connect[elt, 1])[0], 1][0]
+                except IndexError:
+                    connect[elt, 1] = -1
+                try:
+                    connect[elt, 2] = clip_convert_index[np.where(clip_convert_index == connect[elt, 2])[0], 1][0]
+                except IndexError:
+                    connect[elt, 2] = -1
+
+            connect = connect[np.where(connect != -1)[0], :]
+            num_of_elt = np.shape(connect)[0]
+
+            if num_of_edges > 0:
+                clipedges = np.asarray([], dtype=int)
+                for edge in edges:
+                    if set(edge).issubset(Inclipping):
+                        clipedges = np.append(clipedges, edge, axis=0)
+
+                num_of_edges = int(np.size(clipedges) / 2)
+                edges = clipedges.reshape(num_of_edges, 2)
+
+                for edge in range(0, num_of_edges):
+                    try:
+                        edges[edge, 0] = clip_convert_index[np.where(clip_convert_index == edges[edge, 0])[0], 1][0]
+                    except IndexError:
+                        edges[edge, 0] = -1
+                    try:
+                        edges[edge, 1] = clip_convert_index[np.where(clip_convert_index == edges[edge, 1])[0], 1][0]
+                    except IndexError:
+                        edges[edge, 1] = -1
+                edges = edges[np.where(edges != -1)[0], :]
+                num_of_edges = np.shape(edges)[0]
+
+    # }}}
+
+    # write header and mesh {{{
+    if verbose > 3:
+        print('Now starting to write stuff')
+
+    if 'coarsetime' in kwargs.keys():
+        steplist = range(0, num_of_timesteps, kwargs['coarsetime'])
+    elif 'singletime' in kwargs.keys():
+        steplist = [kwargs['singletime']]
+    else:
+        steplist = range(0, num_of_timesteps)
+
+    for step in steplist:
+        if verbose > 2:
+            print('Writing for step {}'.format(step))
+
+        with open(('{}/{}_{}.vtu').format(filename, Dir, step), 'w+') as fid:
+            fid.write('<?xml version="1.0"?>\n')
+            fid.write('<VTKFile type="UnstructuredGrid" version="1.0" byte_order="LittleEndian">\n')
+            fid.write('  <UnstructuredGrid>\n')
+            fid.write('    <Piece NumberOfPoints="{}"  NumberOfCells="{}">\n'.format(num_of_points, num_of_elt + num_of_edges))
+            tensors = []
+            vectors = []
+            scalars = []
+            for sol in solnames:
+                #getting the  fields in the solution
+                if type(res_struct.__dict__[sol]).__name__ == 'solution':
+                    spe_res_struct = res_struct.__dict__[sol].__getitem__(0)
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                elif type(res_struct.__dict__[sol]).__name__ in ['solutionstep', 'results']:
+                    spe_res_struct = res_struct.__dict__[sol]
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                else:
+                    print("WARNING, solution type '{}' is not recognise, exported results might be wrong".format(type(res_struct.__dict__[sol])))
+                    spe_res_struct = res_struct.__dict__[sol]
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+
+                loctensors, locvectors, locscalars = SortFields(fieldnames)
+                tensors.extend(loctensors)
+                vectors.extend(locvectors)
+                scalars.extend(locscalars)
+            for other in args:
+                other_struct = md.__dict__[other]
+                othernames = list(dict.keys(other_struct.__dict__))
+
+                loctensors, locvectors, locscalars = SortFields(othernames)
+                tensors.extend(loctensors)
+                vectors.extend(locvectors)
+                scalars.extend(locscalars)
+
+            fid.write('      <PointData Scalars="{}"'.format(scalars))
+            if len(vectors) > 0:
+                fid.write(' Vectors="{}"'.format(vectors[:-1]))
+            if len(tensors) > 0:
+                fid.write(' Tensors="{}"'.format(tensors[:-2]))
+            fid.write('>\n')
+
+            saved_cells = {}
+            saved_edges = {}
+            saved_const = {}
+            timestep = step
+
+            # }}}
+            # {{{loop over the different solution structures
+            # first check if there are solutions to grab
+            for sol in solnames:
+                treated_res = []
+                #dealing with results on different timesteps
+                try:
+                    if(len(res_struct.__dict__[sol]) > timestep):
+                        timestep = step
+                    else:
+                        timestep = np.size(res_struct.__dict__[sol])
+                except TypeError:
+                    #result as no len() so no timesteps
+                    timestep = 1
+
+                #getting the  fields in the solution
+                if(type(res_struct.__dict__[sol]).__name__ == 'solution'):
+                    spe_res_struct = res_struct.__dict__[sol].__getitem__(timestep)
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                elif(type(res_struct.__dict__[sol]).__name__ == 'solutionstep'):
+                    spe_res_struct = res_struct.__dict__[sol]
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                elif(type(res_struct.__dict__[sol]).__name__ == 'results'):  #this is a result without steps
+                    spe_res_struct = res_struct.__dict__[sol]
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+                else:
+                    print("WARNING, solution type '{}' is not recognise, exported results might be wrong".format(type(res_struct.__dict__[sol])))
+                    spe_res_struct = res_struct.__dict__[sol]
+                    fieldnames = list(dict.keys(spe_res_struct.__dict__))
+
+                tensors, vectors, ScalarNames = SortFields(fieldnames)
+
+                #check which field is a real result and print
+                for field in fieldnames:
+                    if field in treated_res:
+                        if verbose > 2:
+                            print("{}.{} is already done".format(sol, field))
+                        continue
+
+                    elif field in vectors:
+                        if verbose > 2:
+                            print("Treating {}.{} as a vector ".format(sol, field))
+                        TreatVector(fid, fmtout, spe_res_struct, sol, field, treated_res, enveloppe_index)
+
+                    elif field in tensors:
+                        if verbose > 2:
+                            print("Treating {}.{} as a tensor ".format(sol, field))
+                        TreatTensor(fid, fmtout, spe_res_struct, sol, field, treated_res, enveloppe_index)
+
+                    else:
+                        if np.size(spe_res_struct.__dict__[field]) == 1:
+                            if verbose > 2:
+                                print("Treating {}.{} as a constant ".format(sol, field))
+                            if field == 'time':
+                                current_time = spe_res_struct.__dict__[field]
+                            saved_const[".".join((sol, field))] = np.squeeze(spe_res_struct.__dict__[field])
+
+                        elif np.size(spe_res_struct.__dict__[field]) == every_nodes:
+                            if verbose > 2:
+                                print("Treating {}.{} as a node variable ".format(sol, field))
+                            TreatScalar(fid, fmtout, spe_res_struct, sol, field, enveloppe_index)
+
+                        elif np.shape(spe_res_struct.__dict__[field])[0] == np.size(spe_res_struct.__dict__[field]) == every_cells:
+                            saved_cells[".".join((sol, field))] = np.squeeze(spe_res_struct.__dict__[field])
+
+                        elif np.shape(spe_res_struct.__dict__[field])[0] == np.size(spe_res_struct.__dict__[field]) == every_edges and num_of_edges > 0:
+                            saved_edges[".".join((sol, field))] = np.squeeze(spe_res_struct.__dict__[field])
+
+                        else:
+                            print("format for field {}.{} is not suported, field is skipped".format(sol, field))
+            # }}}
+            # loop on arguments, if something other than result is asked, do it now {{{
+            for other in args:
+                treated_res = []
+                if verbose > 3:
+                    print("Now treating {}".format(other))
+                other_struct = md.__dict__[other]
+                othernames = list(dict.keys(other_struct.__dict__))
+                tensors, vectors, ScalarNames = SortFields(othernames)
+                for field in othernames:
+                    if field in treated_res:
+                        if verbose > 2:
+                            print("{}.{} is already done".format(other, field))
+                        continue
+                    elif field in vectors:
+                        TreatVector(fid, fmtout, other_struct, other, field, treated_res, enveloppe_index)
+
+                    elif field in tensors:
+                        if verbose > 2:
+                            print("Treating {}.{} as a tensor ".format(sol, field))
+                        TreatTensor(fid, fmtout, other_struct, other, field, treated_res, enveloppe_index)
+                        #now treating fields that are not vectors or tensors
+
+                    else:
+                        if np.size(other_struct.__dict__[field]) == 1:
+                            if verbose > 2:
+                                print("Treating {}.{} as an constant ".format(other, field))
+                            if field == 'time':
+                                current_time = other_struct.__dict__[field]
+                            saved_const[".".join((other, field))] = np.squeeze(other_struct.__dict__[field])
+
+                        elif np.size(other_struct.__dict__[field]) == every_nodes:
+                            if verbose > 2:
+                                print("Treating {}.{} as a node variable ".format(other, field))
+                            TreatScalar(fid, fmtout, other_struct, other, field, enveloppe_index)
+
+                        elif np.shape(other_struct.__dict__[field])[0] == every_nodes + 1:
+                            if verbose > 3:
+                                print("Treating {}.{} as a node forcing variable".format(other, field))
+                            TreatForcing(fid, fmtout, other_struct, other, field, treated_res, enveloppe_index, current_time)
+
+                        elif np.shape(other_struct.__dict__[field])[0] == np.size(other_struct.__dict__[field]) == every_cells:
+                            if verbose > 3:
+                                print("Treating {}.{} as a cell variable".format(other, field))
+                            saved_cells[".".join((other, field))] = np.squeeze(other_struct.__dict__[field])
+
+                        elif np.shape(other_struct.__dict__[field])[0] == np.size(other_struct.__dict__[field]) == every_edges and num_of_edges > 0:
+                            if verbose > 3:
+                                print("Treating {}.{} as an edge variable".format(other, field))
+                            saved_edges[".".join((other, field))] = np.squeeze(other_struct.__dict__[field])
+
+                        else:
+                            print("format for field {}.{} is not suported, field is skipped".format(other, field))
+            fid.write('      </PointData>\n')
+            # }}}
+            # Now writting cell variables {{{
+            if np.size(list(saved_cells.keys())) > 0 or np.size(list(saved_edges.keys())) > 0:
+                cellkeys = list(saved_cells.keys())
+                edgekeys = list(saved_edges.keys())
+                if len(cellkeys) > 0 and len(edgekeys) > 0:
+                    savekeys = list(saved_cells.keys())
+                    savekeys.extend(edgekeys)
+                elif len(cellkeys) > 0:
+                    savekeys = cellkeys
+                elif len(edgekeys) > 0:
+                    savekeys = edgekeys
+                if verbose > 3:
+                    print("Saving cell for {}".format(savekeys))
+                fid.write('      <CellData Scalars="{}">\n'.format(savekeys))
+
+            if np.size(list(saved_cells.keys())) > 0:
+                for key in cellkeys:
+                    outval = saved_cells[key]
+                    if num_of_edges > 0:
+                        if fmtout == "binary":
+                            outval = np.append(outval, np.nan * np.ones((num_of_edges)))
+                        else:
+                            outval = np.append(outval, -9999.999 * np.ones((num_of_edges)))
+                    if verbose > 3:
+                        print("writing {} values of type {} for {}".format(len(outval), outval.dtype, key))
+
+                    fid.write('        <DataArray type="Float32" Name="{}" format="{}">\n'.format(key, fmtout))
+                    WriteIt(outval, fid, fmtout)
+                    fid.write('        </DataArray>\n')
+
+            # }}}
+            # Now writting edge variables {{{
+            if np.size(list(saved_edges.keys())) > 0:
+                for key in list(saved_edges.keys()):
+                    if fmtout == "binary":
+                        outval = np.nan * np.ones((num_of_elt))
+                    else:
+                        outval = -9999.999 * np.ones((num_of_elt))
+                    outval = np.append(outval, saved_edges[key])
+                    fid.write('        <DataArray type="Float32" Name="{}" format="{}">\n'.format(key, fmtout))
+                    WriteIt(outval, fid, fmtout)
+                    fid.write('        </DataArray>\n')
+            if np.size(list(saved_cells.keys())) > 0 or np.size(list(saved_edges.keys())) > 0:
+                fid.write('      </CellData>\n')
+            # }}}
+
+            # Now writting constants # {{{
+            if np.size(list(saved_const.keys())) > 0:
+                fid.write('      <FieldData>\n')
+                for key in list(saved_const.keys()):
+                    fid.write('        <DataArray type="Float32" Name="{}" format="{}">\n'.format(key, fmtout))
+                    WriteIt(saved_const[key], fid, fmtout)
+                    fid.write('        </DataArray>\n')
+                fid.write('      </FieldData>\n')
+            # }}}
+
+            #Mesh Treatment and write, it needs to loop to allow variable geometry {{{
+            #updating z for mesh evolution
+            if moving_mesh and mesh_alti == '1':
+                points[:, 2] = np.squeeze(res_struct.__dict__['TransientSolution'][step].__dict__['Surface'][enveloppe_index])
+            elif moving_mesh and mesh_alti == '2':
+                points[:, 2] = np.squeeze(res_struct.__dict__['TransientSolution'][step].__dict__['Base'][enveloppe_index])
+
+            #Now write points locations
+            fid.write('      <Points>\n')
+            fid.write('        <DataArray type="Float32" Name="Points" NumberOfComponents="3" format="{}">\n'.format(fmtout))
+            WriteIt(points, fid, fmtout)
+            fid.write('        </DataArray>\n')
+            fid.write('      </Points>\n')
+
+            #cells are a combination of element and edges
+            # we need node conectivity offsets and types
+            #offsets is the cummulative index of the last elemant of each cell (1 indexed)
+            flat_elt = connect.flatten()
+            elt_offset = np.arange(0, num_of_elt * point_per_elt, point_per_elt, dtype=np.int64) + point_per_elt
+            elt_type = celltype * np.ones((num_of_elt), dtype=np.uint8)
+            if num_of_edges > 0:
+                flat_edges = edges.flatten()
+                flat_cells = np.hstack((flat_elt, flat_edges))
+                edge_offset = np.arange(0, num_of_edges * 2, 2) + 2 + elt_offset[-1]
+                cell_offset = np.hstack((elt_offset, edge_offset))
+                edge_type = 3 * np.ones((num_of_edges), dtype=np.uint8)
+                cell_type = np.hstack((elt_type, edge_type))
+            else:
+                flat_cells = flat_elt
+                cell_offset = elt_offset
+                cell_type = elt_type
+
+            if verbose > 3:
+                print("""writing mesh structure:
+                                  connectivity of shape {}
+                                  cell offset of shape {}
+                                  cell types of shape{}""".format(np.shape(flat_cells), np.shape(cell_offset), np.shape(cell_type)))
+            #write cells Informations
+            fid.write('      <Cells>\n')
+            fid.write('        <DataArray type="Int64" Name="connectivity" format="{}">\n'.format(fmtout))
+            WriteIt(flat_cells, fid, fmtout)
+            fid.write('        </DataArray>\n')
+            fid.write('        <DataArray type="Int64" Name="offsets" format="{}">\n'.format(fmtout))
+            WriteIt(cell_offset, fid, fmtout)
+            fid.write('        </DataArray>\n')
+            fid.write('        <DataArray type="UInt8" Name="types" format="{}">\n'.format(fmtout))
+            WriteIt(cell_type, fid, fmtout)
+            fid.write('        </DataArray>\n')
+            fid.write('      </Cells>\n')
+            fid.write('    </Piece>\n')
+            fid.write('  </UnstructuredGrid>\n')
+            fid.write('</VTKFile>\n')
+            # }}}
+
+
+def SortFields(fieldnames):
+    #we check on sizes so there is a slight chance that logs can be picked as results, we remove them to avoid that
+    for trashfield in ['errlog', 'outlog']:
+        if trashfield in fieldnames:
+            fieldnames.remove(trashfield)
+
+    #Sorting scalars, vectors and tensors
+    tensors = [field for field in fieldnames if field[-2:] in ['xx', 'yy', 'xy', 'zz', 'xz', 'yz']]
+    non_tensor = [field for field in fieldnames if field not in tensors]
+    vectors = [field for field in non_tensor if field[-1] in ['x', 'y', 'z']]
+    #get the name of scalar fields remove, vectors, tensors and things that are not proper results
+    scalars = [field for field in fieldnames if field not in tensors + vectors]
+    dump = ["ConvergenceNumSteps", "step", "time"]
+    for trash in dump:
+        try:
+            scalars.remove(trash)
+        except ValueError:
+            [scalars.remove(name) for name in scalars if trash in name]
+            continue
+    #clean up vector and tensors that might be here and should not
+    # we check that at least two of the vector component are here
+    for namelist in [vectors, tensors]:
+        for name in list(namelist):
+            coord = name[-1]
+            if coord == 'x' and name[:-1] + 'y' in namelist:
+                continue
+            elif coord == 'y' and name[:-1] + 'x' in namelist:
+                continue
+            elif coord == 'z' and name[:-1] + 'x' in namelist:
+                continue
+            else:
+                scalars.extend([name])
+                namelist.remove(name)
+    return tensors, vectors, scalars
+
+
+def TreatScalar(fid, fmtout, structure, structname, fieldname, enveloppe_index):
+    array = np.squeeze(structure.__dict__[fieldname][enveloppe_index])
+    fid.write('        <DataArray type="Float32" Name="{}" NumberOfComponents="1" format="{}">\n'.format(".".join((structname, fieldname)), fmtout))
+    WriteIt(array, fid, fmtout)
+    fid.write('        </DataArray>\n')
+
+
+def TreatVector(fid, fmtout, structure, structname, fieldname, treated_res, enveloppe_index):
+    Vxstruct = np.squeeze(structure.__dict__[fieldname[:-1] + 'x'])
+    Vystruct = np.squeeze(structure.__dict__[fieldname[:-1] + 'y'])
+    Vx = Vxstruct[enveloppe_index]
+    Vy = Vystruct[enveloppe_index]
+    treated_res += [fieldname[:-1] + 'x', fieldname[:-1] + 'y']
+    try:
+        Vzstruct = np.squeeze(structure.__dict__[fieldname[:-1] + 'z'])
+        treated_res += [fieldname[:-1] + 'z']
+        Vz = Vzstruct[enveloppe_index]
+    except KeyError:
+        Vz = np.zeros(np.shape(Vx))
+    Vector = (np.vstack((Vx, Vy, Vz)).T).flatten()
+    fid.write('        <DataArray type="Float32" Name="{}" NumberOfComponents="3" format="{}">\n'.format(".".join((structname, fieldname[:-1])), fmtout))
+    WriteIt(Vector, fid, fmtout)
+    fid.write('        </DataArray>\n')
+
+
+def TreatTensor(fid, fmtout, structure, structname, fieldname, treated_res, enveloppe_index):
+    Txxstruct = np.squeeze(structure.__dict__[fieldname[:-2] + 'xx'])
+    Txystruct = np.squeeze(structure.__dict__[fieldname[:-2] + 'xy'])
+    Tyystruct = np.squeeze(structure.__dict__[fieldname[:-2] + 'yy'])
+    treated_res += [fieldname[:-2] + 'xx', fieldname[:-2] + 'xy', fieldname[:-2] + 'yy']
+    Txx = Txxstruct[enveloppe_index]
+    Tyy = Tyystruct[enveloppe_index]
+    Txy = Txystruct[enveloppe_index]
+    try:
+        Tzzstruct = np.squeeze(structure.__dict__[fieldname[:-2] + 'zz'])
+        Txzstruct = np.squeeze(structure.__dict__[fieldname[:-2] + 'xz'])
+        Tyzstruct = np.squeeze(structure.__dict__[fieldname[:-2] + 'yz'])
+        treated_res += [fieldname[:-2] + 'zz', fieldname[:-2] + 'xz', fieldname[:-2] + 'yz']
+        Tzz = Tzzstruct[enveloppe_index]
+        Txz = Txzstruct[enveloppe_index]
+        Tyz = Tyzstruct[enveloppe_index]
+    except KeyError:
+        Tzz = np.zeros(np.shape(Txx))
+        Txz = np.zeros(np.shape(Txx))
+        Tyz = np.zeros(np.shape(Txx))
+
+    Tensor = (np.vstack((Txx, Tyy, Tzz, Txy, Tyz, Txz)).T).flatten()
+    fid.write('        <DataArray type="Float32" Name="{}" NumberOfComponents="6" format="{}">\n'.format(".".join((structname, fieldname[:-1])), fmtout))
+    WriteIt(Tensor, fid, fmtout)
+    fid.write('        </DataArray>\n')
+
+
+def TreatForcing(fid, fmtout, structure, structname, fieldname, treated_res, enveloppe_index, current_time):
+    #we are dealing with a forcing of some kind.
+    forcing_time = structure.__dict__[fieldname][-1, :]
+    if any(forcing_time == current_time):
+        forcing_index = np.where(forcing_time == current_time)
+        forcing_val = structure.__dict__[fieldname][:, forcing_index]
+    elif forcing_time[0] > current_time:
+        forcing_val = structure.__dict__[fieldname][:, 0]
+    elif forcing_time[-1] < current_time:
+        forcing_val = structure.__dict__[fieldname][:, -1]
+    else:
+        forcing_index = np.where(forcing_time < current_time)[-1][-1]
+        delta_time = forcing_time[forcing_index + 1] - forcing_time[forcing_index]  #compute forcing Dt
+        delta_current = current_time - forcing_time[forcing_index]  # time since last forcing
+        ratio = delta_current / delta_time  #compute weighting factor for preceding forcing vallue
+        forcing_evol = (structure.__dict__[fieldname][:, forcing_index + 1] - structure.__dict__[fieldname][:, forcing_index]) * ratio
+        forcing_val = structure.__dict__[fieldname][:, forcing_index] + forcing_evol
+    array = forcing_val[enveloppe_index]
+    # and now write it down
+    fid.write('        <DataArray type="Float32" Name="{}" NumberOfComponents="1" format="{}">\n'.format(".".join((structname, fieldname)), fmtout))
+    WriteIt(array, fid, fmtout)
+    fid.write('        </DataArray>\n')
+
+
+def WriteIt(Data, fid, fmtout):
+    vtu_to_numpy_type = {
+        "Float32": np.dtype(np.float32),
+        "Float64": np.dtype(np.float64),
+        "Int8": np.dtype(np.int8),
+        "Int16": np.dtype(np.int16),
+        "Int32": np.dtype(np.int32),
+        "Int64": np.dtype(np.int64),
+        "UInt8": np.dtype(np.uint8),
+        "UInt16": np.dtype(np.uint16),
+        "UInt32": np.dtype(np.uint32),
+        "UInt64": np.dtype(np.uint64),
+    }
+    if fmtout == 'binary':
+        try:
+            datatype = Data.dtype
+        except AttributeError:
+            datatype = type(Data)
+        if datatype == np.float64:
+            Data = np.float32(Data)
+        try:
+            data_bytes = Data.tobytes()
+        except AttributeError:
+            data_bytes = np.asarray(Data).tobytes()
+        # collect header
+        header = np.array(len(data_bytes), dtype=vtu_to_numpy_type['UInt32'])
+        fid.write(b64encode(header.tobytes() + data_bytes).decode())
+        fid.write('\n')
+        #cell_type.tofile(fid)
+    elif fmtout == 'ascii':
+        np.savetxt(fid, Data, fmt='%g')
+
+
+def cleanOutliers(Val, fmtout):
+    #paraview does not like NaN in ascii files, replacing
+    if np.isnan(Val):
+        if fmtout == 'ascii':
+            CleanVal = -9999.999
+
+    #also checking for very small value that mess up
+    elif (abs(Val) < 1.0e-20):
+        CleanVal = 0.0
+    else:
+        CleanVal = Val
+    return CleanVal
+
+
+class BadDimension(Exception):
+    """The required dimension is not supported yet."""
+
+
+class BadOption(Exception):
+    """The given option does not exist."""
+
+
+class ClipError(Exception):
+    """Error while trying to clip the domain."""
Index: issm/trunk/src/m/contrib/morlighem/modeldata/interpIBCSO2.m
===================================================================
--- issm/trunk/src/m/contrib/morlighem/modeldata/interpIBCSO2.m	(revision 27232)
+++ issm/trunk/src/m/contrib/morlighem/modeldata/interpIBCSO2.m	(revision 27232)
@@ -0,0 +1,24 @@
+function [bedout sid] = interpIBCSO2(X,Y),
+
+%read data
+switch (oshostname()),
+	case {'totten'}
+		ncpath='/totten_1/ModelData/Antarctica/IBCSO2/IBCSO_v2_bed.nc';
+		sidpath='/totten_1/ModelData/Antarctica/IBCSO2/IBCSO_v2_TID.nc';
+	otherwise
+		error('hostname not supported yet');
+end
+
+disp('   -- IBCSOv2: loading bathymetry');
+xdata = double(ncread(ncpath,'x'));
+ydata = double(ncread(ncpath,'y'));
+data  = double(ncread(ncpath,'z'))';
+disp('   -- IBCSOv2: interpolating bed');
+bedout = InterpFromGrid(xdata,ydata,data,double(X),double(Y));
+
+if nargout==2,
+	disp('   -- IBCSOv2: bathymetry sid');
+	data  = ncread(sidpath,'tid')';
+	disp('   -- IBCSOv2: interpolating sids');
+	sid = InterpFromGrid(xdata,ydata,data,double(X),double(Y),'nearest');
+end
Index: issm/trunk/src/m/coordsystems/epsg2proj.py
===================================================================
--- issm/trunk/src/m/coordsystems/epsg2proj.py	(revision 27035)
+++ issm/trunk/src/m/coordsystems/epsg2proj.py	(revision 27232)
@@ -2,6 +2,6 @@
 
 
-def epsg2proj(epsg): #{{{
-    """EPSG2PROJ - uses gdalsrsinfo to provide PROJ.4 compatible string 
+def epsg2proj(epsg):  #{{{
+    """EPSG2PROJ - uses gdalsrsinfo to provide PROJ.4 compatible string
     from EPSG code
 
@@ -21,5 +21,5 @@
     #First, get GDAL version
     subproc_args = "gdalsrsinfo --version | awk '{print $2}' | cut -d '.' -f1"
-    subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
     outs, errs = subproc.communicate()
     if errs != '':
@@ -29,5 +29,5 @@
 
     subproc_args = "gdalsrsinfo epsg:{} | command grep PROJ.4 | tr -d '\n' | sed 's/PROJ.4 : //'".format(epsg)
-    subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
     outs, errs = subproc.communicate()
     if errs != '':
@@ -35,5 +35,5 @@
 
     if version_major == 1:
-        r = r[1:-1]
+        outs = outs[1:-1]
 
     return outs
Index: issm/trunk/src/m/coordsystems/gdaltransform.py
===================================================================
--- issm/trunk/src/m/coordsystems/gdaltransform.py	(revision 27035)
+++ issm/trunk/src/m/coordsystems/gdaltransform.py	(revision 27232)
@@ -46,5 +46,5 @@
 
     subproc_args = shlex.split("gdaltransform -s_srs '{}' -t_srs '{}'".format(proj_in, proj_out))
-    subproc = subprocess.Popen(subproc_args, bufsize=-1, stdin=file_in, stdout=file_out, stderr=subprocess.PIPE, close_fds=True)
+    subproc = subprocess.Popen(subproc_args, bufsize=-1, stdin=file_in, stdout=file_out, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True)
     outs, errs = subproc.communicate()
     if errs != '':
Index: issm/trunk/src/m/coordsystems/gmtmask.m
===================================================================
--- issm/trunk/src/m/coordsystems/gmtmask.m	(revision 27035)
+++ issm/trunk/src/m/coordsystems/gmtmask.m	(revision 27232)
@@ -36,5 +36,5 @@
 
 	%figure out which vertices are on the ocean, which one on the continent:
-	[status,result] = system(['gmtselect ./' filename_all ' -h0 -Df -R0/360/-90/90  -A0 -JQ180/200 -Nk/s/s/k/s > ./' filename_oce]);
+	[status,result] = system(['gmt select ./' filename_all ' -h0 -Df -R0/360/-90/90  -A0 -JQ180/200 -Nk/s/s/k/s > ./' filename_oce]);
 	if status~=0,
 		error(result);
Index: issm/trunk/src/m/coordsystems/gmtmask.py
===================================================================
--- issm/trunk/src/m/coordsystems/gmtmask.py	(revision 27035)
+++ issm/trunk/src/m/coordsystems/gmtmask.py	(revision 27232)
@@ -45,5 +45,5 @@
 
     #figure out which vertices are on the ocean, which one on the continent:
-    subprocess.call('gmtselect ./ all_vertices.txt -h0 -Df -R0/360/-90/90 -A0 -JQ180/200 -Nk/s/s/k/s > ./oce_vertices.txt', shell=True)
+    subprocess.call('gmt select ./ all_vertices.txt -h0 -Df -R0/360/-90/90 -A0 -JQ180/200 -Nk/s/s/k/s > ./oce_vertices.txt', shell=True)
 
     #read the con_vertices.txt file and flag our mesh vertices on the continent
Index: issm/trunk/src/m/coordsystems/gmtmaskparallel.m
===================================================================
--- issm/trunk/src/m/coordsystems/gmtmaskparallel.m	(revision 27035)
+++ issm/trunk/src/m/coordsystems/gmtmaskparallel.m	(revision 27232)
@@ -4,4 +4,7 @@
 %   Usage:
 %      mask.ocean = gmtmaskparallel(md.mesh.lat,md.mesh.long,8);
+%
+%   TODO:
+%   - Remove hardcoded paths and instead find paths dynamically
 %
 
@@ -39,5 +42,5 @@
 	fid=fopen('xjobs.script','w');
 	for i=1:length(nnv)-1,
-		fprintf(fid,'%s gmtselect ./all_vertices%i.txt -h0 -Df -R0/360/-90/90  -A0 -JQ180/200 -Nk/s/s/k/s > ./oce_vertices%i.txt\n',gmtpath,i,i);
+		fprintf(fid,'%s gmt select ./all_vertices%i.txt -h0 -Df -R0/360/-90/90  -A0 -JQ180/200 -Nk/s/s/k/s > ./oce_vertices%i.txt\n',gmtpath,i,i);
 	end
 	fclose(fid);
Index: issm/trunk/src/m/coordsystems/ll2xy.m
===================================================================
--- issm/trunk/src/m/coordsystems/ll2xy.m	(revision 27035)
+++ issm/trunk/src/m/coordsystems/ll2xy.m	(revision 27232)
@@ -44,7 +44,14 @@
 	disp('Calling CoordTransform instead, make sure to change your MATLAB script');
 	if sgn==+1
-		assert(delta==45); assert(slat ==70);
-		[x y]=CoordTransform(lat,lon,'EPSG:4326','EPSG:3413');
-		return;
+		if delta==45 && slat==70      %BedMachine
+			[x y]=CoordTransform(lat,lon,'EPSG:4326','EPSG:3413'); return;
+		elseif delta==0 && slat==75   %IBCAO
+			[x y]=CoordTransform(lat,lon,'EPSG:4326','EPSG:3996'); return;
+		elseif delta==39 && slat==71  %Bamber
+			Bamber_proj = '+proj=stere +lat_0=90 +lat_ts=71 +lon_0=-39 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs';
+			[x y]=CoordTransform(lat,lon,'EPSG:4326',Bamber_proj); return;
+		else
+			error('not supported yet');
+		end
 	else
 		assert(delta==0); assert(slat ==71);
Index: issm/trunk/src/m/coordsystems/xy2ll.m
===================================================================
--- issm/trunk/src/m/coordsystems/xy2ll.m	(revision 27035)
+++ issm/trunk/src/m/coordsystems/xy2ll.m	(revision 27232)
@@ -40,7 +40,14 @@
 	disp('Calling CoordTransform instead, make sure to change your MATLAB script');
 	if sgn==+1
-		assert(delta==45); assert(slat ==70);
-		[lat lon]=CoordTransform(x, y,'EPSG:3413','EPSG:4326');
-		return;
+		if delta==45 && slat==70      %BedMachine
+			[lat lon]=CoordTransform(x, y,'EPSG:3413','EPSG:4326'); return;
+		elseif delta==0 && slat==75   %IBCAO
+			[lat lon]=CoordTransform(x, y,'EPSG:3996','EPSG:4326'); return;
+		elseif delta==39 && slat==71  %Bamber
+			Bamber_proj = '+proj=stere +lat_0=90 +lat_ts=71 +lon_0=-39 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs';
+			[lat lon]=CoordTransform(x, y, Bamber_proj, 'EPSG:4326'); return;
+		else
+			error('not supported yet');
+		end
 	else
 		assert(delta==0); assert(slat ==71);
Index: issm/trunk/src/m/dev/devpath.py
===================================================================
--- issm/trunk/src/m/dev/devpath.py	(revision 27035)
+++ issm/trunk/src/m/dev/devpath.py	(revision 27232)
@@ -37,5 +37,8 @@
         print('Warning: devpath.py: cluster settings should be in {}'.format(jpl_path))
 
-from runme import runme  #first because plotmodel may fail
+try: # Avoid circular import
+    from runme import runme  # First, because plotmodel may fail
+except:
+    pass
 from plotmodel import plotmodel
 
Index: issm/trunk/src/m/mesh/ComputeHessian.py
===================================================================
--- issm/trunk/src/m/mesh/ComputeHessian.py	(revision 27035)
+++ issm/trunk/src/m/mesh/ComputeHessian.py	(revision 27232)
@@ -39,9 +39,9 @@
 
     #compute weights that hold the volume of all the element holding the node i
-    weights = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile(areas, (3, 1)), numberofnodes, 1)
+    weights = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile(areas, (1, 3)), numberofnodes, 1)
 
     #compute field on nodes if on elements
     if np.size(field, axis=0) == numberofelements:
-        field = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile(areas * field, (3, 1)), numberofnodes, 1) / weights
+        field = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile(areas * field, (1, 3)), numberofnodes, 1) / weights
 
     #Compute gradient for each element
@@ -50,6 +50,6 @@
 
     #Compute gradient for each node (average of the elements around)
-    gradx = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * grad_elx), (3, 1)), numberofnodes, 1)
-    grady = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * grad_ely), (3, 1)), numberofnodes, 1)
+    gradx = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * grad_elx), (1, 3)), numberofnodes, 1)
+    grady = m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * grad_ely), (1, 3)), numberofnodes, 1)
     gradx = gradx / weights
     grady = grady / weights
@@ -60,7 +60,7 @@
     if m.strcmpi(type, 'node'):
         #Compute Hessian on the nodes (average of the elements around)
-        hessian = np.hstack((m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * hessian[:, 0]), (3, 1)), numberofnodes, 1) / weights,
-                             m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * hessian[:, 1]), (3, 1)), numberofnodes, 1) / weights,
-                             m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * hessian[:, 2]), (3, 1)), numberofnodes, 1) / weights))
+        hessian = np.hstack((m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * hessian[:, 0]), (1, 3)), numberofnodes, 1) / weights,
+                             m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * hessian[:, 1]), (1, 3)), numberofnodes, 1) / weights,
+                             m.sparse(line, np.ones((linesize, 1), dtype=int), np.tile((areas * hessian[:, 2]), (1, 3)), numberofnodes, 1) / weights))
 
     return hessian
Index: issm/trunk/src/m/mesh/bamg.py
===================================================================
--- issm/trunk/src/m/mesh/bamg.py	(revision 27035)
+++ issm/trunk/src/m/mesh/bamg.py	(revision 27232)
@@ -23,92 +23,92 @@
     Available options (for more details see ISSM website http://issm.jpl.nasa.gov/):
 
-    - domain :                              followed by an ARGUS file that 
+    - domain :                              followed by an ARGUS file that
                                             prescribes the domain outline
-    - holes :                               followed by an ARGUS file that 
+    - holes :                               followed by an ARGUS file that
                                             prescribes the holes
-    - subdomains :                          followed by an ARGUS file that 
-                                            prescribes the list of subdomains 
+    - subdomains :                          followed by an ARGUS file that
+                                            prescribes the list of subdomains
                                             (that need to be inside domain)
 
-    - hmin :                                minimum edge length (default is 
+    - hmin :                                minimum edge length (default is
                                             1.0e-100)
-    - hmax :                                maximum edge length (default is 
+    - hmax :                                maximum edge length (default is
                                             1.0e100)
-    - hVertices :                           imposed edge length for each vertex 
+    - hVertices :                           imposed edge length for each vertex
                                             (geometry or mesh)
-    - hminVertices :                        minimum edge length for each vertex 
+    - hminVertices :                        minimum edge length for each vertex
                                             (mesh)
-    - hmaxVertices :                        maximum edge length for each vertex 
+    - hmaxVertices :                        maximum edge length for each vertex
                                             (mesh)
 
-    - anisomax :                            maximum ratio between the smallest 
-                                            and largest edges (default is 
+    - anisomax :                            maximum ratio between the smallest
+                                            and largest edges (default is
                                             1.0e30)
-    - coeff :                               coefficient applied to the metric 
-                                            (2 -> twice as many elements, 
+    - coeff :                               coefficient applied to the metric
+                                            (2 -> twice as many elements,
                                             default is 1)
-    - cutoff :                              scalar used to compute the metric 
+    - cutoff :                              scalar used to compute the metric
                                             when metric type 2 or 3 are applied
-    - err :                                 error used to generate the metric 
+    - err :                                 error used to generate the metric
                                             from a field
     - errg :                                geometric error (default is 0.1)
-    - field :                               field of the model that will be 
-                                            used to compute the metric to apply 
-                                            several fields, use one column per 
+    - field :                               field of the model that will be
+                                            used to compute the metric to apply
+                                            several fields, use one column per
                                             field
-    - gradation :                           maximum ratio between two adjacent 
+    - gradation :                           maximum ratio between two adjacent
                                             edges
-    - Hessiantype :                         0 -> use double P2 projection 
+    - Hessiantype :                         0 -> use double P2 projection
                                             (default)
                                             1 -> use Green formula
-    - KeepVertices :                        try to keep initial vertices when 
-                                            adaptation is done on an existing 
+    - KeepVertices :                        try to keep initial vertices when
+                                            adaptation is done on an existing
                                             mesh (default 1)
-    - NoBoundaryRefinement :                do not refine boundary, only follow 
-                                            contour provided (default 0). Allow 
-                                            subdomain boundary refinement 
+    - NoBoundaryRefinement :                do not refine boundary, only follow
+                                            contour provided (default 0). Allow
+                                            subdomain boundary refinement
                                             though
-    - NoBoundaryRefinementAllBoundaries :   do not refine boundary, only follow 
+    - NoBoundaryRefinementAllBoundaries :   do not refine boundary, only follow
                                             contour provided (default 0)
-    - maxnbv :                              maximum number of vertices used to 
+    - maxnbv :                              maximum number of vertices used to
                                             allocate memory (default is 1.0e6)
-    - maxsubdiv :                           maximum subdivision of exisiting 
+    - maxsubdiv :                           maximum subdivision of exisiting
                                             elements (default is 10)
-    - metric :                              matrix (numberofnodes x 3) used as 
+    - metric :                              matrix (numberofnodes x 3) used as
                                             a metric
-    - Metrictype :                          1 -> absolute error 
+    - Metrictype :                          1 -> absolute error
                                             c/(err coeff^2) * Abs(H) (default)
-                                            2 -> relative error 
-                                            c / (err coeff^2) * Abs(H) / 
+                                            2 -> relative error
+                                            c / (err coeff^2) * Abs(H) /
                                             max(s, cutoff * max(s))
-                                            3 -> rescaled absolute error 
-                                            c / (err coeff^2) * Abs(H) / 
+                                            3 -> rescaled absolute error
+                                            c / (err coeff^2) * Abs(H) /
                                             (smax - smin)
-    - nbjacoby :                            correction used by Hessiantype = 1 
+    - nbjacoby :                            correction used by Hessiantype = 1
                                             (default is 1)
-    - nbsmooth :                            number of metric smoothing 
+    - nbsmooth :                            number of metric smoothing
                                             procedure (default is 3)
-    - omega :                               relaxation parameter of the 
-                                            smoothing procedure (default is 
+    - omega :                               relaxation parameter of the
+                                            smoothing procedure (default is
                                             1.8)
-    - power :                               power applied to the metric 
+    - power :                               power applied to the metric
                                             (default is 1)
-    - splitcorners :                        split triangles which have 3 
-                                            vertices on the outline (default is 
+    - splitcorners :                        split triangles which have 3
+                                            vertices on the outline (default is
                                             1)
     - verbose :                             level of verbosity (default is 1)
 
-    - rifts :                               followed by an ARGUS file that 
+    - rifts :                               followed by an ARGUS file that
                                             prescribes the rifts
-    - toltip :                              tolerance to move tip on an 
-                                            existing point of the domain 
+    - toltip :                              tolerance to move tip on an
+                                            existing point of the domain
                                             outline
-    - tracks :                              followed by an ARGUS file that 
-                                            prescribes the tracks that the mesh 
+    - tracks :                              followed by an ARGUS file that
+                                            prescribes the tracks that the mesh
                                             will stick to
-    - RequiredVertices :                    mesh vertices that are required. 
+    - RequiredVertices :                    mesh vertices that are required.
                                             [x, y, ref]; ref is optional
-    - tol :                                 if the distance between 2 points of 
-                                            the domain outline is less than 
+    - tol :                                 if the distance between 2 points of
+                                            the domain outline is less than
                                             tol, they will be merged
 
@@ -250,9 +250,8 @@
 
             # Flag how many edges we have now, that way we know which edges
-            # belong to the subdomain. Will be used later fo required edges 
+            # belong to the subdomain. Will be used later fo required edges
             # if NoBoundaryRefinement equals 1.
             new_edge_length = len(bamg_geometry.Edges)
-            edges_required = range((edge_length + 1), (new_edge_length + 1)) # NOTE: Upper bound of range is non-inclusive (compare to src/m/mesh/bamg.m)
-
+            edges_required = np.asarray(range((edge_length + 1), (new_edge_length + 1)))  # NOTE: Upper bound of range is non-inclusive (compare to src/m/mesh/bamg.m)
             if i: # NOTE: same as `if i > 0` (MATLAB is `if i > 1`)
                 bamg_geometry.SubDomains = np.vstack((bamg_geometry.SubDomains, [2, count + 1, 1, -subdomain_ref]))
@@ -445,5 +444,5 @@
                                     np.array([[count, count + 1, 2]]),
                                     np.hstack((
-                                        np.arange(count + 1, count + nods).reshape(-1, ), 
+                                        np.arange(count + 1, count + nods).reshape(-1, ),
                                         np.arange(count + 2, count + nods + 1).reshape(-1, ),
                                         (1 + i) * np.ones((nods - 1, 1))
@@ -455,5 +454,5 @@
                     nods = rift[i]['nods'] - 1
                     bamg_geometry.Vertices = np.vstack((
-                        bamg_geometry.Vertices, 
+                        bamg_geometry.Vertices,
                         np.hstack((
                             rift[i]['x'][:],
Index: issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.m
===================================================================
--- issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.m	(revision 27035)
+++ issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.m	(revision 27232)
@@ -15,8 +15,39 @@
 %      md.mesh=gmshplanet('radius',6000,'resolution',100);
 
+	%Find path to gmsh
+	paths = {
+		[getenv('ISSM_EXT_DIR') '/shared/gmsh/install/bin/gmsh'],...
+		[getenv('ISSM_EXT_DIR') '/static/gmsh/install/bin/gmsh'],...
+		[getenv('ISSM_EXT_DIR') '/gmsh/install/bin/gmsh'],...
+		[issmdir() 'externalpackages/gmsh/install/bin/gmsh'],...
+		[issmdir() 'bin/gmsh'],...
+		['/usr/bin/gmsh']...
+	};
+	gmshpath = '';
+	for i=paths
+		if exist(i{1},'file'),
+			gmshpath = i{1};
+			break;
+		end
+	end
+	if isempty(gmshpath),
+		error('Gmsh not found, make sure it is properly installed');
+	end
+
 	% Get Gmsh version
 	[s,r]=system(['gmsh -info 2>&1 | command grep ''Version'' | sed -e ''s/Version[[:blank:]]*:[[:blank:]]//'' | cut -d ''.'' -f1']);
 	if s~=0,
 		error(r);
+	elseif isempty(r),
+		% If this function is called from one of our distributable packages, we 
+		% need to do a bit more to find the Gmsh executable
+		[filepath,name,ext]=fileparts(which('gmsh.'));
+		setenv('PATH',[filepath ':' getenv('PATH')]);
+		[s,r]=system(['gmsh -info 2>&1 | command grep ''Version'' | sed -e ''s/Version[[:blank:]]*:[[:blank:]]//'' | cut -d ''.'' -f1']);
+		if s~=0,
+			error(r);
+		elseif isempty(r),
+			error('gmshplanet: Gmsh executable not found!');
+		end
 	end
 	gmshmajorversion=str2num(r);
@@ -40,9 +71,9 @@
 
 	% NOTE:
-	% - The default format in Gmsh 3 is "msh2". Rather than conditionally 
-	% modifying our parsing scheme for Gmsh 4, for now, we simply set the 
+	% - The default format in Gmsh 3 is "msh2". Rather than conditionally
+	% modifying our parsing scheme for Gmsh 4, for now, we simply set the
 	% 'Mesh.MshFileVersion' option.
-	% - Decreasing the value of the 'Mesh.RandomFactor' option leads to an 
-	% equal number of nodes and elements being produced under macOS and Linux 
+	% - Decreasing the value of the 'Mesh.RandomFactor' option leads to an
+	% equal number of nodes and elements being produced under macOS and Linux
 	% at certain resolutions using certain meshing algorithms.
 	%
@@ -131,4 +162,9 @@
 
 	% Call gmsh
+	%
+	% NOTE: The default format in Gmsh 3 is "msh2". Rather than conditionally
+	%		modifying our parsing scheme for Gmsh 4, for now, we simply set the
+	%		"-format" option.
+	%
 	if  exist(options,'refine'),
 		system(['gmsh -2 sphere.geo -bgm sphere.pos']);
@@ -184,9 +220,9 @@
 	%}}}
 
-	%a little technicality here. the mesh generate is not exactly on the 
-	%sphere. we create lat,long coordinates, and reproject on an exact sphere. 
+	%a little technicality here. the mesh generate is not exactly on the
+	%sphere. we create lat,long coordinates, and reproject on an exact sphere.
 	mesh.r=sqrt(mesh.x.^2+mesh.y.^2+mesh.z.^2);
 
-	%make sure we don't have south and north pole: 
+	%make sure we don't have south and north pole:
 	pos=find(mesh.x==0 & mesh.y==0);
 	mesh.lat = asind(mesh.z./mesh.r);
Index: issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.py
===================================================================
--- issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.py	(revision 27035)
+++ issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.py	(revision 27232)
@@ -1,6 +1,4 @@
 import subprocess
-
 import numpy as np
-
 from MatlabFuncs import *
 from mesh3dsurface import *
@@ -26,8 +24,11 @@
     # Get Gmsh version
     subproc_args = 'gmsh -info 2>&1 | command grep \'Version\' | sed -e \'s/Version[[:blank:]]*:[[:blank:]]//\' | cut -d \'.\' -f1'
-    subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    subproc = subprocess.Popen(subproc_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
     outs, errs = subproc.communicate()
-
-    if ((not isinstance(errs,bytes)) & (errs != '')) or (isinstance(errs,bytes) & (errs.decode() != '')):
+    try:
+        strErrs = errs.decode()
+    except AttributeError:  #this is not a byte variable, let's assume string
+        strErrs = errs
+    if strErrs != '':
         raise Exception('gmshplanet: call to gmsh failed: {}'.format(errs))
     gmshmajorversion = int(outs)
@@ -51,9 +52,9 @@
     #
     # NOTE:
-    # - The default format in Gmsh 3 is "msh2". Rather than conditionally 
-    # modifying our parsing scheme for Gmsh 4, for now, we simply set the 
+    # - The default format in Gmsh 3 is "msh2". Rather than conditionally
+    # modifying our parsing scheme for Gmsh 4, for now, we simply set the
     # 'Mesh.MshFileVersion' option.
-    # - Decreasing the value of the 'Mesh.RandomFactor' option leads to an 
-    # equal number of nodes and elements being produced under macOS and Linux 
+    # - Decreasing the value of the 'Mesh.RandomFactor' option leads to an
+    # equal number of nodes and elements being produced under macOS and Linux
     # at certain resolutions using certain meshing algorithms.
     #
@@ -126,12 +127,18 @@
         for i in range(meshini.numberofelements):
             fid.write('ST(%g,%g,%g,%g,%g,%g,%g,%g,%g){%g,%g,%g};\n'
-                % (meshini.x[meshini.elements[i, 0]-1], meshini.y[meshini.elements[i, 0]-1], meshini.z[meshini.elements[i, 0]-1],
-                meshini.x[meshini.elements[i, 1]-1], meshini.y[meshini.elements[i, 1]-1], meshini.z[meshini.elements[i, 1]-1],
-                meshini.x[meshini.elements[i, 2]-1], meshini.y[meshini.elements[i, 2]-1], meshini.z[meshini.elements[i, 2]-1],
-                metric[meshini.elements[i, 0]-1], metric[meshini.elements[i, 1]-1], metric[meshini.elements[i, 2]-1]))
+                      % (meshini.x[meshini.elements[i, 0] - 1], meshini.y[meshini.elements[i, 0] - 1], meshini.z[meshini.elements[i, 0] - 1],
+                         meshini.x[meshini.elements[i, 1] - 1], meshini.y[meshini.elements[i, 1] - 1], meshini.z[meshini.elements[i, 1] - 1],
+                         meshini.x[meshini.elements[i, 2] - 1], meshini.y[meshini.elements[i, 2] - 1], meshini.z[meshini.elements[i, 2] - 1],
+                         metric[meshini.elements[i, 0] - 1], metric[meshini.elements[i, 1] - 1], metric[meshini.elements[i, 2] - 1]))
         fid.write('};\n')
         fid.close()
         #}}}
 
+    # Call gmsh
+    #
+    # NOTE: The default format in Gmsh 3 is "msh2". Rather than conditionally
+    #       modifying our parsing scheme for Gmsh 4, for now, we simply set the
+    #       "-format" option.
+    #
     if options.exist('refine'):
         subprocess.call('gmsh -2 sphere.geo -bgm sphere.pos', shell=True)
@@ -187,5 +194,5 @@
     #}}}
 
-    # A little technicality here. The mesh is not exactly on the sphere. We 
+    # A little technicality here. The mesh is not exactly on the sphere. We
     # create lat,long coordiantes, and reproject onto an exact sphere.
     mesh.r = np.sqrt(mesh.x ** 2 + mesh.y ** 2 + mesh.z ** 2)
Index: issm/trunk/src/m/modules/CoordTransform.m
===================================================================
--- issm/trunk/src/m/modules/CoordTransform.m	(revision 27035)
+++ issm/trunk/src/m/modules/CoordTransform.m	(revision 27232)
@@ -31,4 +31,12 @@
 end
 
+% If this function is called from within one of our distributable packages, set 
+% the 'PROJ_LIB' environment variable so that the PROJ binary can find the 
+% assets it needs
+whatproj=what('share/proj');
+if ~isempty(whatproj) && isdir(whatproj.path)
+	setenv('PROJ_LIB', whatproj.path);
+end
+
 % Call mex module
 [xout, yout] = CoordTransform_matlab(xin,yin,projin,projout);
Index: issm/trunk/src/m/parameterization/setflowequation.m
===================================================================
--- issm/trunk/src/m/parameterization/setflowequation.m	(revision 27035)
+++ issm/trunk/src/m/parameterization/setflowequation.m	(revision 27232)
@@ -55,5 +55,5 @@
 %check that each element has at least one flag
 if any(SIAflag+SSAflag+HOflag+L1L2flag+MOLHOflag+FSflag==0),
-	error('elements type not assigned, supported models are ''SIA'',''SSA'',''HO'' and ''FS''')
+	error('elements type not assigned, supported models are ''SIA'',''SSA'',''HO'',''MOLHO'' and ''FS''')
 end
 
Index: issm/trunk/src/m/plot/applyoptions.py
===================================================================
--- issm/trunk/src/m/plot/applyoptions.py	(revision 27035)
+++ issm/trunk/src/m/plot/applyoptions.py	(revision 27232)
@@ -11,4 +11,5 @@
 from plot_contour import plot_contour
 from plot_streamlines import plot_streamlines
+from plot_edgeoverlay import plot_edgeoverlay
 
 
@@ -33,5 +34,5 @@
     fontsize = options.getfieldvalue('fontsize', 8)
     fontweight = options.getfieldvalue('fontweight', 'normal')
-    fontfamily = options.getfieldvalue('fontfamily', 'sans - serif')
+    fontfamily = options.getfieldvalue('fontfamily', 'sans-serif')
     font = {
         'fontsize': fontsize,
@@ -156,12 +157,9 @@
     # {{{ ShowBasins TODO
     # }}}
-    # {{{ clim
-    if options.exist('clim'):
-        lims = options.getfieldvalue('clim')
-        assert len(lims) == 2, 'error, clim should be passed as a list of length 2'
-    elif options.exist('caxis'):
+    # {{{ caxis
+    if options.exist('caxis'):
         lims = options.getfieldvalue('caxis')
         assert len(lims) == 2, 'error, caxis should be passed as a list of length 2'
-        options.addfielddefault('clim', lims)
+        options.addfielddefault('caxis', lims)
     else:
         if len(data) > 0:
@@ -188,13 +186,10 @@
     if options.exist('cmap_set_under'):
         cbar_extend += 2
-    # }}}
-    # {{{ contours
-    if options.exist('contourlevels'):
-        plot_contour(md, data, options, ax)
-    # }}}
-    # {{{ wrapping TODO
-    # }}}
-    # {{{ colorbar
-    if options.getfieldvalue('colorbar', 1) == 1:
+
+    # }}}
+    # {{{ colorbar extension
+    if options.exist('cbar_extend'):
+        extend = options.getfieldvalue('cbar_extend', 'neither')
+    else:
         if cbar_extend == 0:
             extend = 'neither'
@@ -205,5 +200,19 @@
         elif cbar_extend == 3:
             extend = 'both'
-
+        options.addfielddefault('cbar_extend', extend)
+    # }}}
+    # {{{ contours
+    if options.exist('contourlevels'):
+        plot_contour(md, data, options, ax)
+    # }}}
+    # {{{ edgeoverlay
+    if options.exist('edgeoverlay'):
+        edgedata = options.getfieldvalue('edgeoverlay')
+        plot_edgeoverlay(md, edgedata, options, ax)
+    # }}}
+    # {{{ wrapping TODO
+    # }}}
+    # {{{ colorbar
+    if options.getfieldvalue('colorbar', 1) == 1:
         cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
         if options.exist('alpha'):
Index: issm/trunk/src/m/plot/plot_BC.py
===================================================================
--- issm/trunk/src/m/plot/plot_BC.py	(revision 27035)
+++ issm/trunk/src/m/plot/plot_BC.py	(revision 27232)
@@ -4,4 +4,5 @@
 from plot_icefront import plot_icefront
 from hydrologydc import hydrologydc
+from hydrologyglads import hydrologyglads
 from mpl_toolkits.mplot3d import Axes3D
 from mpl_toolkits.axes_grid1.inset_locator import inset_axes
@@ -36,5 +37,6 @@
         #define what to plot with plot style
         spc_dict = {'spcvx': ['stressbalance', 'o', 'r', 240, 'vx Dirichlet'],
-                    'spcvy': ['stressbalance', 'o', 'b', 160, 'vy Dirichlet']}
+                    'spcvy': ['stressbalance', 'o', 'b', 160, 'vy Dirichlet'],
+                    'spcthickness': ['masstransport', 'o', 'k', 40, 'Thickness']}
         if not is2d:
             spc_dict['spcvz'] = ['stressbalance', 'o', 'y', 80, 'vy Dirichlet']
@@ -44,4 +46,7 @@
             if md.hydrology.isefficientlayer:
                 spc_dict['spcsediment_head'] = ['hydrology', '^', 'b', 240, 'IDS Head']
+
+        if isinstance(md.hydrology, hydrologyglads):
+            spc_dict['spcphi'] = ['hydrology', 'v', 'r', 240, 'phi']
 
         for key in spc_dict:
Index: issm/trunk/src/m/plot/plot_edgeoverlay.py
===================================================================
--- issm/trunk/src/m/plot/plot_edgeoverlay.py	(revision 27232)
+++ issm/trunk/src/m/plot/plot_edgeoverlay.py	(revision 27232)
@@ -0,0 +1,133 @@
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+from processmesh import processmesh
+from matplotlib import collections
+from scipy.stats import percentileofscore
+
+
+def plot_edgeoverlay(md, datain, options, ax):
+    '''
+    plot_channels - plot channels area for GLADS
+    Usage:
+        plot_channels(md, options, fig, axes)
+
+    See also: PLOTMODEL'''
+
+    # if md.mesh.numberofedges not in np.shape(datain):
+    #     raise ValueError('Data must be defined on edges to be ploted as an edge overlay')
+
+    x, y, z, elements, is2d, isplanet = processmesh(md, [], options)
+    Edges = md.mesh.edges - 1
+
+    #First we mask values under a given value define by quantiles
+    if options.exist('edgemin'):
+        minval = options.getfieldvalue('edgemin', 0)
+        minquant = percentileofscore(datain, minval, kind='weak')
+        minquant = minquant / 100
+    else:
+        minquant = 0.7
+        minval = np.quantile(datain, minquant)
+    print("For the overlay we plot values above {:.4g} wich corresponds to the {}% percentile".format(minval, minquant * 100))
+
+    flags = datain > minval  #6.7e-5  # this is appropriate for channel Area (perhaps)
+
+    edgetype = options.getfieldvalue('edgetype', 'thickness')
+
+    if edgetype == "color":
+        #create an nodewise dataset from edges
+        NodeMask = np.ones(np.shape(md.mesh.x), dtype=bool)
+        #We grab all the starts from the unmasked edges
+        Starters = Edges[np.where(flags), 0]
+        NodeMask[Starters] = False
+        Xstart = np.ma.array(x, mask=NodeMask)
+        Ystart = np.ma.array(y, mask=NodeMask)
+
+        NodeMask = np.ones(np.shape(md.mesh.x), dtype=bool)
+        Enders = Edges[np.where(flags), 1]
+        NodeMask[Enders] = False
+        Xend = np.ma.array(x, mask=NodeMask)
+        Yend = np.ma.array(y, mask=NodeMask)
+
+        #define vectors from the start and end point of the unmasked edges
+        EdgeEnd = Edges[:, 1]
+        EdgeStart = Edges[:, 0]
+        quiverU = np.ma.array(Xend[EdgeEnd] - Xstart[EdgeStart], mask=np.invert(flags))
+        quiverV = np.ma.array(Yend[EdgeEnd] - Ystart[EdgeStart], mask=np.invert(flags))
+
+        #mask out the values from the data and create colorscale
+        Masked = np.ma.masked_array(datain, mask=np.invert(flags))
+        cbar_extend = 0
+        edgemap = plt.cm.get_cmap('inferno')
+        if options.exist('cedgeaxis'):
+            lims = options.getfieldvalue('cedgeaxis', [Masked.min(), Masked.max()])
+            edgenorm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
+            if lims[0] > Masked.min():
+                edgemap.set_under('r')
+                cbar_extend += 2
+            if lims[1] < Masked.max():
+                edgemap.set_over('k')
+                cbar_extend += 1
+        else:
+            edgenorm = mpl.colors.Normalize(vmin=Masked.min(), vmax=Masked.max())
+
+        if cbar_extend == 0:
+            extend = 'neither'
+        elif cbar_extend == 1:
+            extend = 'max'
+        elif cbar_extend == 2:
+            extend = 'min'
+        elif cbar_extend == 3:
+            extend = 'both'
+
+        ax.quiver(Xstart[EdgeStart], Ystart[EdgeStart], quiverU, quiverV, datain,
+                  units="xy", angles="xy", scale_units="xy", scale=1,
+                  headwidth=0, headlength=0, width=100, headaxislength=0,
+                  norm=edgenorm, cmap=edgemap)
+
+        #plt.colorbar(plt.cm.ScalarMappable(norm=edgenorm, cmap=edgemap), ax=ax, extend=extend, orientation='horizontal', anchor=(1, 0))
+        cbarax = ax.inset_axes([0.02, 0.02, 0.96, 0.05])
+        #inset_axes(ax, width="100%", height="5%", loc='lower center', borderpad=-5)
+        mpl.colorbar.ColorbarBase(cbarax, norm=edgenorm, cmap=edgemap, extend=extend, orientation='horizontal', ticklocation='top')
+
+    elif edgetype == 'thickness':
+        #First we classify a range
+        if options.exist('edgeranges'):
+            edgeranges = options.getfieldvalue('edgeranges', 2)
+        else:
+            edgeranges = 2
+
+        quantrange = np.linspace(minquant, 1, edgeranges + 1)[:-1]
+        flags = []
+        legtext = []
+        for Qindex, quantile in enumerate(quantrange):
+            if quantile < quantrange[-1]:
+                lowquant = np.quantile(datain, quantile)
+                highquant = np.quantile(datain, quantrange[Qindex + 1])
+                flags.append(np.logical_and(datain >= lowquant, datain <= highquant))
+                legtext.append('From  {:.2g} to {:.2g}'. format(lowquant, highquant))
+            else:
+                lowquant = np.quantile(datain, quantile)
+                flags.append((datain > lowquant))
+                legtext.append('More than {:.2g}'.format(lowquant))
+
+        flags = np.asarray(np.squeeze(flags))
+        EdgeEnd = Edges[:, 1]
+        EdgeStart = Edges[:, 0]
+
+        for index in range(edgeranges):
+            linecol = []
+            #We loop on the result and aonly add to a linecollection the flaged edges.
+            for datindex, datval in enumerate(datain):
+                if flags[index, datindex]:
+                    linecol.append([(x[EdgeStart[datindex]], y[EdgeStart[datindex]]),
+                                    (x[EdgeEnd[datindex]], y[EdgeEnd[datindex]])])
+
+            lc = collections.LineCollection(linecol, color='k', linewidth=0.5 + index,
+                                            label=legtext[index])
+            ax.add_collection(lc)
+
+        ax.legend(title='Overlay')
+
+    else:
+        print("Only 'color', and 'thickness' are accepted as edgeoverlay types")
Index: issm/trunk/src/m/plot/plot_icefront.py
===================================================================
--- issm/trunk/src/m/plot/plot_icefront.py	(revision 27035)
+++ issm/trunk/src/m/plot/plot_icefront.py	(revision 27232)
@@ -1,4 +1,5 @@
 import numpy as np
 from processmesh import processmesh
+import matplotlib as mpl
 from mpl_toolkits.mplot3d.art3d import Line3DCollection
 from mpl_toolkits.axes_grid1.inset_locator import inset_axes
@@ -26,4 +27,10 @@
     icefront = np.where(np.logical_and(iceelement != nodes_per_elt, iceelement != 0))
 
+    oceannodes = md.mask.ocean_levelset < 0
+    oceanelement = np.sum(oceannodes[elements], axis=1)
+
+    #icefront check
+    groundingline = np.where(np.logical_and(oceanelement != nodes_per_elt, oceanelement != 0))
+
     #plot mesh
     if is2d:
@@ -32,6 +39,11 @@
         #highlight elements on neumann
         if len(icefront[0]) > 0:
-            colors = np.asarray([0.5 for element in elements[icefront]])
-            ax.tripcolor(x, y, elements[icefront], facecolors=colors, alpha=0.5, label='elements on ice front')
+            colors = np.ones(np.shape(elements[icefront])[0])
+            cmap = mpl.colors.ListedColormap("navy")
+            ax.tripcolor(x, y, elements[icefront], facecolors=colors, edgecolor='k', label='elements on ice front', cmap=cmap)
+        if len(groundingline[0]) > 0:
+            colors = np.ones(np.shape(elements[groundingline])[0])
+            cmap = mpl.colors.ListedColormap("limegreen")
+            ax.tripcolor(x, y, elements[groundingline], facecolors=colors, edgecolor='k', label='elements on grounding line', cmap=cmap)
     else:
         ax = inset_axes(ax, width='100%', height='100%', loc=3, borderpad=0, axes_class=Axes3D)
Index: issm/trunk/src/m/plot/plot_manager.py
===================================================================
--- issm/trunk/src/m/plot/plot_manager.py	(revision 27035)
+++ issm/trunk/src/m/plot/plot_manager.py	(revision 27232)
@@ -27,5 +27,5 @@
     currently generated using matplotlib's AxesGrid toolkit.
 
-    'gridindex' is passed through to specialized plot* functions and 
+    'gridindex' is passed through to specialized plot* functions and
     applyoptions.
 
@@ -89,5 +89,4 @@
     # }}}
 
-    #process data and model
     x, y, z, elements, is2d, isplanet = processmesh(md, data, options)
     data2, datatype = processdata(md, data, options)
Index: issm/trunk/src/m/plot/plot_mesh.py
===================================================================
--- issm/trunk/src/m/plot/plot_mesh.py	(revision 27035)
+++ issm/trunk/src/m/plot/plot_mesh.py	(revision 27232)
@@ -21,6 +21,10 @@
     fig.delaxes(axgrid.cbar_axes[gridindex])
 
+    #retrieve some options
+    edgecolor=options.getfieldvalue('edgecolor','k')
+    linewidth=options.getfieldvalue('linewidth',1)
+
     if is2d:
-        ax.triplot(x, y, elements)
+        ax.triplot(x, y, elements,color=edgecolor,linewidth=linewidth)
     else:
         ax = inset_axes(axgrid[gridindex], width='100%', height='100%', loc=3, borderpad=0, axes_class=Axes3D)
Index: issm/trunk/src/m/plot/plot_transient_movie.m
===================================================================
--- issm/trunk/src/m/plot/plot_transient_movie.m	(revision 27035)
+++ issm/trunk/src/m/plot/plot_transient_movie.m	(revision 27232)
@@ -12,5 +12,5 @@
 	if exist(options,'transient_movie_field'),
 		field=getfieldvalue(options,'transient_movie_field');
-	elseif ischar(getfieldvalue(options,'data'))
+	elseif ischar(getfieldvalue(options,'data')) && ~strcmp(getfieldvalue(options,'data'),'transient_movie')
 		field=getfieldvalue(options,'data');
 	else
@@ -43,4 +43,6 @@
 	elseif exist(options,'steps'),
 		steps = getfieldvalue(options,'steps');
+	elseif exist(options,'step'),
+		steps = getfieldvalue(options,'step');
 	else
 		steps=1:length(results);
Index: issm/trunk/src/m/plot/plot_unit.py
===================================================================
--- issm/trunk/src/m/plot/plot_unit.py	(revision 27035)
+++ issm/trunk/src/m/plot/plot_unit.py	(revision 27232)
@@ -33,13 +33,9 @@
 
     # colormap
-    # {{{ give number of colorlevels and transparency
+    # give number of colorlevels and transparency {{{
     colorlevels = options.getfieldvalue('colorlevels', 128)
     alpha = options.getfieldvalue('alpha', 1)
-    if alpha < 1:
-        antialiased = True
-    else:
-        antialiased = False
-    # }}}
-    # {{{ define wich colormap to use
+    # }}}
+    # define wich colormap to use {{{
     try:
         defaultmap = plt.cm.get_cmap('viridis', colorlevels)
@@ -51,13 +47,7 @@
     else:
         cmap = getcolormap(options)
-    if options.exist('cmap_set_over'):
-        over = options.getfieldvalue('cmap_set_over', '0.5')
-        cmap.set_over(over)
-    if options.exist('cmap_set_under'):
-        under = options.getfieldvalue('cmap_set_under', '0.5')
-        cmap.set_under(under)
     options.addfield('colormap', cmap)
     # }}}
-    # {{{ if plotting only one of several layers reduce dataset, same for surface
+    # if plotting only one of several layers reduce dataset, same for surface {{{
     if options.getfieldvalue('layer', 0) >= 1:
         plotlayer = options.getfieldvalue('layer', 0)
@@ -68,5 +58,5 @@
         data = data[(plotlayer - 1) * slicesize:plotlayer * slicesize]
     # }}}
-    # {{{ Get the colormap limits
+    # Get the colormap limits {{{
     dataspread = np.nanmax(data) - np.nanmin(data)
     if dataspread != 0.:
@@ -75,8 +65,10 @@
         limextent = 0.
 
-    if options.exist('clim'):
-        lims = options.getfieldvalue('clim', [np.nanmin(data), np.nanmax(data)])
-    elif options.exist('caxis'):
+    if options.exist('caxis'):
         lims = options.getfieldvalue('caxis', [np.nanmin(data), np.nanmax(data)])
+        if lims[0] > np.nanmin(data):
+            options.addfielddefault('cmap_set_under', 'r')
+        if lims[1] < np.nanmax(data):
+            options.addfielddefault('cmap_set_over', 'k')
     else:
         if limextent == 0.:
@@ -87,20 +79,37 @@
         else:
             lims = [np.nanmin(data), np.nanmax(data)]
-    # }}}
-    # {{{ Set the spread of the colormap (default is normal
+
+    cbar_extend = 0
+    if options.exist('cmap_set_over'):
+        over = options.getfieldvalue('cmap_set_over', 'k')
+        cmap.set_over(over)
+        cbar_extend += 1
+    if options.exist('cmap_set_under'):
+        under = options.getfieldvalue('cmap_set_under', 'r')
+        cmap.set_under(under)
+        cbar_extend += 2
+    # }}}
+
+    # colorbar extension {{{
+    if cbar_extend == 0:
+        extend = 'neither'
+    elif cbar_extend == 1:
+        extend = 'max'
+    elif cbar_extend == 2:
+        extend = 'min'
+    elif cbar_extend == 3:
+        extend = 'both'
+    options.addfielddefault('cbar_extend', extend)
+    # }}}
+    # Set the spread of the colormap (default is normal) {{{
     if options.exist('log'):
         norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1])
     else:
         norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
-    if options.exist('log'):
-        norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1])
-    else:
-        norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
     options.addfield('colornorm', norm)
     # }}}
 
     # Plot depending on the datatype
-    # {{{ data are on elements
-
+    # data are on elements {{{
     if datatype == 1:
         if is2d:
@@ -109,4 +118,5 @@
             else:
                 triangles = mpl.tri.Triangulation(x, y, elements)
+
             tri = ax.tripcolor(triangles, data, colorlevels, cmap=cmap, norm=norm, alpha=alpha, edgecolors=edgecolor)
         else:
@@ -160,6 +170,5 @@
 
     # }}}
-    # {{{ data are on nodes
-
+    # data are on nodes {{{
     elif datatype == 2:
         if is2d:
@@ -169,15 +178,8 @@
             else:
                 triangles = mpl.tri.Triangulation(x, y, elements)
-    #tri = ax.tricontourf(triangles, data, colorlevels, cmap = cmap, norm=norm, alpha = alpha)
-            if options.exist('log'):
-                if alpha < 1:  #help with antialiasing
-                    tri = ax.tricontour(triangles, data, colorlevels, cmap=cmap, norm=norm, alpha=0.1, antialiased=antialiased)
-                tri = ax.tricontourf(triangles, data, colorlevels, cmap=cmap, norm=norm, alpha=alpha, antialiased=antialiased)
+            if edgecolor == 'None':
+                tri = ax.tripcolor(triangles, data, cmap=cmap, norm=norm, alpha=alpha, shading='gouraud')
             else:
-                if alpha < 1:  #help with antialiasing
-                    tri = ax.tricontour(triangles, data, colorlevels, cmap=cmap, norm=norm, alpha=0.1, antialiased=antialiased)
-                tri = ax.tricontourf(triangles, data, colorlevels, cmap=cmap, norm=norm, alpha=alpha, extend='both', antialiased=antialiased)
-            if edgecolor != 'None':
-                ax.triplot(x, y, elements, color=edgecolor)
+                tri = ax.tripcolor(triangles, data, cmap=cmap, norm=norm, alpha=alpha, edgecolors=edgecolor)
         else:
             #first deal with the colormap
@@ -185,5 +187,4 @@
             loccmap.set_array(lims)
             loccmap.set_clim(vmin=lims[0], vmax=lims[1])
-
     #deal with prism sides
             recface = np.vstack((elements[:, 0], elements[:, 1], elements[:, 4], elements[:, 3])).T
@@ -222,5 +223,5 @@
 
     # }}}
-    # {{{ plotting quiver
+    # plotting quiver {{{
     elif datatype == 3:
         if is2d:
@@ -230,14 +231,24 @@
         return
     # }}}
-    # {{{ plotting P1 Patch (TODO)
+    # plotting P1 Patch (TODO) {{{
     elif datatype == 4:
         print('plot_unit message: P1 patch plot not implemented yet')
         return
     # }}}
-    # {{{ plotting P0 Patch (TODO)
+    # plotting P0 Patch (TODO) {{{
     elif datatype == 5:
         print('plot_unit message: P0 patch plot not implemented yet')
         return
     # }}}
+    # plotting edges  {{{
+    elif datatype == 6:
+        if is2d:
+            triangles = mpl.tri.Triangulation(x, y, elements)
+            tri = ax.tripcolor(triangles, data, cmap=cmap, norm=norm, alpha=alpha, edgecolors=edgecolor)
+
+        else:
+            print("edge plotting is not implemented for 3D")
+        return
+    # }}}
     else:
         raise ValueError('datatype = %d not supported' % datatype)
Index: issm/trunk/src/m/plot/plotmodel.py
===================================================================
--- issm/trunk/src/m/plot/plotmodel.py	(revision 27035)
+++ issm/trunk/src/m/plot/plotmodel.py	(revision 27232)
@@ -28,33 +28,27 @@
     numberofplots = options.numberofplots
 
-    #get number of subplots
-    subplotwidth = ceil(sqrt(numberofplots))
+    #get the "optimal" number of subfigures in a row/col
+    if (np.nanmax(md.mesh.x) - np.nanmin(md.mesh.x)) > (np.nanmax(md.mesh.y) - np.nanmin(md.mesh.y)):
+        maxrow = ceil(sqrt(numberofplots))
+        maxcol = ceil(numberofplots / maxrow)
+    else:
+        maxcol = ceil(sqrt(numberofplots))
+        maxrow = ceil(numberofplots / maxcol)
 
-    # TODO: Check that commenting this out is correct; we do not need a hold
-    # under matplotlib, right?
-    #
-    # #get hold
-    # hold = options.list[0].getfieldvalue('hold', False)
-
-    #if nrows and ncols specified, then bypass
+    #If any  of nrows or ncols are given we use that
     if options.list[0].exist('nrows'):
         nrows = options.list[0].getfieldvalue('nrows')
-        nr = True
+        if options.list[0].exist('ncols'):
+            ncols = options.list[0].getfieldvalue('ncols')
+        else:
+            ncols = ceil(numberofplots / nrows)
+    elif options.list[0].exist('ncols'):
+        ncols = options.list[0].getfieldvalue('ncols')
+        nrows = ceil(numberofplots / ncols)
     else:
-        nrows = np.ceil(numberofplots / subplotwidth)
-        nr = False
-
-    if options.list[0].exist('ncols'):
-        ncols = options.list[0].getfieldvalue('ncols')
-        nc = True
-    else:
-        ncols = int(subplotwidth)
-        nc = False
+        nrows = maxrow
+        ncols = maxcol
     ncols = int(ncols)
     nrows = int(nrows)
-
-    #check that nrows and ncols were given at the same time!
-    if nr != nc:
-        raise Exception('plotmodel error message: nrows and ncols need to be specified together, or not at all')
 
     # Go through plots
@@ -86,9 +80,9 @@
         #       taken from https://matplotlib.org/api/_as_gen/mpl_toolkits.axes_grid1.axes_grid.ImageGrid.html
         #
-        direction = options.list[0].getfieldvalue('direction', 'row') # {"row", "column"}, default: "row"
-        axes_pad = options.list[0].getfieldvalue('axes_pad', 0.25) # float or (float, float), default : 0.02; Padding or (horizonal padding, vertical padding) between axes, in inches
-        add_all = options.list[0].getfieldvalue('add_all', True) # bool, default: True
-        share_all = options.list[0].getfieldvalue('share_all', True) # bool, default: False
-        label_mode = options.list[0].getfieldvalue('label_mode', 'L') # {"L", "1", "all"}, default: "L"; Determines which axes will get tick labels: "L": All axes on the left column get vertical tick labels; all axes on the bottom row get horizontal tick labels;. "1": Only the bottom left axes is labelled. "all": all axes are labelled.
+        direction = options.list[0].getfieldvalue('direction', 'row')  # {"row", "column"}, default: "row"
+        axes_pad = options.list[0].getfieldvalue('axes_pad', 0.25)  # float or (float, float), default : 0.02; Padding or (horizonal padding, vertical padding) between axes, in inches
+        add_all = options.list[0].getfieldvalue('add_all', True)  # bool, default: True
+        share_all = options.list[0].getfieldvalue('share_all', True)  # bool, default: False
+        label_mode = options.list[0].getfieldvalue('label_mode', 'L')  # {"L", "1", "all"}, default: "L"; Determines which axes will get tick labels: "L": All axes on the left column get vertical tick labels; all axes on the bottom row get horizontal tick labels;. "1": Only the bottom left axes is labelled. "all": all axes are labelled.
 
         # Translate MATLAB colorbar mode to matplotlib
Index: issm/trunk/src/m/plot/processdata.py
===================================================================
--- issm/trunk/src/m/plot/processdata.py	(revision 27035)
+++ issm/trunk/src/m/plot/processdata.py	(revision 27232)
@@ -8,5 +8,7 @@
     datatype = 2 -> nodes
     datatype = 3 -> node quivers
-    datatype = 4 -> patch
+    datatype = 4 -> P1 patch
+    datatype = 5 -> P0 patch
+    datatype = 6 -> edges
 
     Usage:
@@ -24,4 +26,9 @@
     else:
         numberofvertices2d = np.nan
+
+    try:
+        numberofedges = md.mesh.numberofedges
+    except AttributeError:
+        numberofedges = np.nan
 
     if options.exist('amr'):
@@ -52,5 +59,5 @@
     # }}}
 
-    #  log {{{
+    # log {{{
     if options.exist('log'):
         cutoff = options.getfieldvalue('log', 1)
@@ -58,13 +65,27 @@
     # }}}
 
-    #  quiver plot {{{
+    # quiver plot {{{
     if datasize[1] > 1 and datasize[0] != numberofvertices + 1:
-        if datasize[0] == numberofvertices and datasize[1] == 2:
+        if datasize[0] == numberofvertices and datasize[1] in [2, 3]:
             datatype = 3
+            if md.mesh.dimension() == 3:
+                if datasize[1] == 2:
+                    data = np.hstack(data, np.zeros((datasize[0])))
+                elif datasize[1] > 3:
+                    raise ValueError('plotmodel error message: data should have two or three columns of length md.mesh.numberofvertices for a quiver plot')
         else:
-            raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot')
+            #we should have a patch
+            print("Assuming that data provided is a patch")
+            datatype = 4
+            index = md.mesh.elements
+            if np.shape(data)[1] < np.shape(index)[1]:
+                    raise ValueError('plotmodel error message: data should have more columns than vertices per elements to plot a patch')
+            procdata = np.zeros((numberofvertices))
+            procdata[md.mesh.elements -1] = data[:, 0:np.shape(index)[1]]
+            datasize = [numberofvertices, 1]
+
     # }}}
 
-    #  element data{{{
+    # element data{{{
     if datasize[0] == numberofelements and datasize[1] == 1:
         #initialize datatype if non patch
@@ -93,6 +114,6 @@
     # }}}
 
-    #  node data {{{
-    if datasize[0] in [numberofvertices, numberofvertices2d] and datasize[1] == 1:
+    # node data {{{
+    elif datasize[0] in [numberofvertices, numberofvertices2d] and datasize[1] == 1:
         datatype = 2
         # AMR {{{
@@ -101,5 +122,5 @@
             procdata = procdata[nonan]
         # }}}
-        #  Mask {{{
+        # Mask {{{
         if options.exist('mask'):
             flags = options.getfieldvalue('mask')
@@ -119,6 +140,19 @@
     # }}}
 
-    #  spc time series {{{
-    if datasize[0] == numberofvertices + 1:
+    # edge data {{{
+    elif datasize[0] in [numberofedges] and datasize[1] == 1:
+        datatype = 6
+        procdata = np.zeros((md.mesh.numberofelements))
+        repeat = np.zeros((md.mesh.numberofelements))
+        for index, edge in enumerate(md.mesh.edges[:, -2:]):
+            procdata[edge - 1] += data[index] * np.asarray(edge - 1 > -1, dtype=int)
+            repeat[edge - 1] += np.asarray(edge - 1 > -1, dtype=int)
+        procdata = procdata / repeat
+
+        # }}}
+    # }}}
+
+    # spc time series {{{
+    elif datasize[0] == numberofvertices + 1:
         datatype = 2
         spccol = options.getfieldvalue('spccol', 0)
@@ -127,12 +161,7 @@
         procdata = procdata[0:-1, spccol]
 
-        #mask?
-
-        #layer projection?
-
-        #control arrow density if quiver plot
     # }}}
 
-    # convert rank - 2 array to rank - 1 {{{
+    # convert rank -2 array to rank -1 {{{
     if np.ndim(procdata) == 2 and np.shape(procdata)[1] == 1:
         procdata = procdata.reshape(-1, )
@@ -142,16 +171,23 @@
     nanfill = options.getfieldvalue('nan', -9999)
     if np.any(np.isnan(procdata)):
-        lb = np.nanmin(procdata)
-        ub = np.nanmax(procdata)
-        if lb == ub:
-            lb = lb - 0.5
-            ub = ub + 0.5
-            nanfill = lb - 1
+        if options.exist('caxis'):
+            [lb, ub] = options.getfieldvalue('caxis')
+        else:
+            lb = np.nanmin(procdata)
+            ub = np.nanmax(procdata)
+            if lb == ub:
+                lb = lb - 0.5
+                ub = ub + 0.5
+                nanfill = lb - 1
+            options.addfielddefault('caxis', [lb, ub])
+
         procdata[np.isnan(procdata)] = nanfill
         procdata = np.ma.array(procdata, mask=np.isnan(procdata))
-        #clim looks to be deprecated and replaced by caxis
-        #options.addfielddefault('clim', [lb, ub])
-        options.addfielddefault('cmap_set_under', '1')
-        print(("WARNING: nan's treated as", nanfill, "by default.  Change using pairoption 'nan', nan_fill_value in plotmodel call"))
+        if nanfill < lb:
+            options.addfielddefault('cmap_set_under', 'r')
+        elif nanfill > ub:
+            options.addfielddefault('cmap_set_over', 'k')
+        if nanfill < ub and nanfill > lb:
+            print(("WARNING: nan's treated as", nanfill, "by default. Which is in your data interval, change it with ['nan', value] in plotmodel options"))
     # }}}
 
Index: issm/trunk/src/m/solve/waitonlock.py
===================================================================
--- issm/trunk/src/m/solve/waitonlock.py	(revision 27035)
+++ issm/trunk/src/m/solve/waitonlock.py	(revision 27232)
@@ -11,6 +11,6 @@
     """WAITONLOCK - wait for a file
 
-    This routine will return when a file named 'lockfilename' is written to 
-    disk. Also check for outlog file because it might be written several 
+    This routine will return when a file named 'lockfilename' is written to
+    disk. Also check for outlog file because it might be written several
     seconds after the lock file.
 
@@ -21,5 +21,5 @@
 
     TODO:
-    - Uncomment import of localpfe and check on cluster type once localpfe.py 
+    - Uncomment import of localpfe and check on cluster type once localpfe.py
     has been translated from localpfe.m.
     """
@@ -79,12 +79,13 @@
             sys.stdout.write('\rchecking for job completion (time: {} min {} sec)      '.format(floor(elapsedtime / 60), floor(rem(elapsedtime, 60)))) # TODO: After Python 2 is deprecated, we can change this call to print([...], end='')
             elapsedtime = elapsedtime / 60 # Converts time from sec to min
-            subproc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-            outs, errs = subproc.communicate() # NOTE: Need to consume output before checking return code
+            subproc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
+            outs, errs = subproc.communicate()  # NOTE: Need to consume output before checking return code
 
             # TODO: Debug the following check under Linux (exits after first iteration with errs = "b")
             # UPDATE: Works in testing under Debian Linux system. Leaving comment for now so that it is easier to backtrace this issue if someone else encounters it.
+            # FIXED: comunicates returns stuff in bytes in Python 3 unless you set "universal_newlines=True"
             #
-            #if errs != '':
-            #    raise Exception('waitonlock: check for existence of files failed: {}'.format(errs))
+            if errs != '':
+               raise Exception('waitonlock: check for existence of files failed: {}'.format(errs))
             ispresent = not subproc.returncode
             if ispresent:
Index: issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp
===================================================================
--- issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 27035)
+++ issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 27232)
@@ -98,4 +98,16 @@
 		#endif
 	}
+	else if(strcmp(name,"_PETSC_HAVE_CUDA_")==0){
+		value = 0.;
+		#ifdef PETSC_HAVE_CUDA
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_PETSC_HAVE_PASTIX_")==0){
+		value = 0.;
+		#ifdef PETSC_HAVE_PASTIX
+		value = 1.;
+		#endif
+	}
 	else if(strcmp(name,"_DAKOTA_VERSION_")==0){
 		#ifdef _DAKOTA_VERSION_
Index: issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- issm/trunk/src/wrappers/matlab/Makefile.am	(revision 27035)
+++ issm/trunk/src/wrappers/matlab/Makefile.am	(revision 27232)
@@ -122,5 +122,5 @@
 AM_LDFLAGS += -Wl,-rpath,'@rpath'
 else
-AM_LDFLAGS += -Wl,-static -Wl,--disable-new-dtags -Wl,-rpath,'$$ORIGIN'
+AM_LDFLAGS += -Wl,-static -Wl,-lbacktrace -Wl,--disable-new-dtags -Wl,-rpath,'$$ORIGIN'
 endif
 endif
Index: issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- issm/trunk/src/wrappers/python/Makefile.am	(revision 27035)
+++ issm/trunk/src/wrappers/python/Makefile.am	(revision 27232)
@@ -76,5 +76,5 @@
 AM_LDFLAGS += -Wl,-rpath,'@rpath'
 else
-AM_LDFLAGS += -Wl,-static -Wl,--disable-new-dtags -Wl,-rpath,'$$ORIGIN'
+AM_LDFLAGS += -Wl,-static -Wl,-lbacktrace -Wl,--disable-new-dtags -Wl,-rpath,'$$ORIGIN'
 endif
 endif
Index: issm/trunk/test/NightlyRun/IdFromString.py
===================================================================
--- issm/trunk/test/NightlyRun/IdFromString.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/IdFromString.py	(revision 27232)
@@ -2,4 +2,5 @@
 from IdToName import IdToName
 import os
+import re
 
 # use verbose = False to print output when this is called by command line
@@ -27,12 +28,11 @@
     ids = []
     idnames = []
-    for f in os.listdir('.'):
-        if f.endswith('.py') and f.startswith('test'):
-            # all tests look like: "testwxyz.py" so 5th to 3rd to last is always the full id
-            s = int(f[4:-3])
-            name = IdToName(s)
-            if (string == ' * ') or (name is not None and string in name):
-                ids.append(s)
-                idnames.append(name)
+    flist = [f for f in os.listdir('.') if re.match('test[0-9]+.py', f)] # File name must follow the format "test<integer>.py"
+    list_ids = [int(re.search(r'\d+',file.split('.')[0]).group()) for file in flist] # Retrieve test IDs
+    for i in list_ids:
+        name = IdToName(i)
+        if (string == ' * ') or (name is not None and string in name):
+            ids.append(i)
+            idnames.append(name)
 
 #Return if no test found
Index: issm/trunk/test/NightlyRun/runme.m
===================================================================
--- issm/trunk/test/NightlyRun/runme.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/runme.m	(revision 27232)
@@ -88,5 +88,5 @@
 % }}}
 %GET ids  {{{
-flist=dir;%use dir, as it seems to act OS independent
+flist=dir; %use dir, as it seems to act OS independent
 list_ids=[];
 for i=1:numel(flist),
@@ -101,5 +101,5 @@
 				disp(['WARNING: ignore file ' flist(i).name]);
 			else
-				list_ids(end+1)=id;%Keep test id only (strip 'test' and '.m')
+				list_ids(end+1)=id; %Keep test id only (strip 'test' and '.m')
 			end
 		end
@@ -217,5 +217,4 @@
 				end
 			end
-
 		%PRODUCE nc files?
 		elseif strcmpi(procedure,'ncExport'),
Index: issm/trunk/test/NightlyRun/runme.py
===================================================================
--- issm/trunk/test/NightlyRun/runme.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/runme.py	(revision 27232)
@@ -365,5 +365,5 @@
                             field = field.T
                             if np.shape(field) != np.shape(archive):
-                                raise RuntimeError("Field '{}' from test is malformed; shape is {}, should be {} or {}".format(archive_name, np.shape(field.T), np.shape(archive), np.shape(archive.T)))
+                                raise RuntimeError("Field '{}' from test {} is malformed; shape is {}, should be {} or {}".format(fieldname, archive_name[7:], np.shape(field.T), np.shape(archive), np.shape(archive.T)))
 
                         error_diff = np.amax(np.abs(archive - field), axis=0) / (np.amax(np.abs(archive), axis=0) + float_info.epsilon)
Index: issm/trunk/test/NightlyRun/test2002.py
===================================================================
--- issm/trunk/test/NightlyRun/test2002.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test2002.py	(revision 27232)
@@ -11,7 +11,12 @@
 
 
+# Mesh earth
+#
+# NOTE: In MATLAB, we currently use cached mesh to account for differences in
+# mesh generated under Linux versus under macOS
+#
 md = model()
 
-## Generate and save mesh (need to uncomment import of gmshplanet as well)
+# Generate and save mesh (need to uncomment import of gmshplanet as well)
 # md.mesh = gmshplanet('radius', 6.371012 * 1e3, 'resolution', 700.) # 700 km resolution mesh
 # with open('../Data/SlcTestMesh.pkl', 'wb') as slc_test_mesh_file:
@@ -60,5 +65,5 @@
 
 icemask = np.ones((md.mesh.numberofvertices, ))
-# NOTE: Need to be careful here: when using multidimensional array elements to 
+# NOTE: Need to be careful here: when using multidimensional array elements to
 # address a one-dimensional array in MATLAB, only first column is used
 #
Index: issm/trunk/test/NightlyRun/test2004.m
===================================================================
--- issm/trunk/test/NightlyRun/test2004.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/test2004.m	(revision 27232)
@@ -7,8 +7,8 @@
 %}}}
 
-%create sealevel model to hold our information: 
+%create sealevel model to hold our information:
 sl=sealevelmodel();
 
-%Create basins using boundaries from shapefile: 
+%Create basins using boundaries from shapefile:
 %some projections we'll rely on:  %{{{
 proj4326=epsg2proj(4326);
@@ -71,8 +71,8 @@
 %Go through basins and mesh:  %{{{
 %meshing parameters:  {{{
-hmin=500; hmax=700; hmin=hmin*1000; hmax=hmax*1000; 
+hmin=500; hmax=700; hmin=hmin*1000; hmax=hmax*1000;
 tolerance=100; %tolerance of 100m on Earth position when merging 3d meshes
 threshold=5;
-defaultoptions={'KeepVertices',0,'MaxCornerAngle',0.0000000001,'NoBoundaryRefinement',1}; 
+defaultoptions={'KeepVertices',0,'MaxCornerAngle',0.0000000001,'NoBoundaryRefinement',1};
 alreadyloaded=0;
 %}}}
@@ -82,5 +82,5 @@
 	disp(sprintf('Meshing basin %s\n',bas.name));
 
-	%recover basin domain: 
+	%recover basin domain:
 	domain=bas.contour();
 
@@ -92,9 +92,9 @@
 	%plotmodel(md,'data','mesh');pause(1);
 
-	%miscellaneous: 
+	%miscellaneous:
 	md.mesh.proj=bas.proj;
 	md.miscellaneous.name=bas.name;
 
-	%recover mask where we have land: 
+	%recover mask where we have land:
 	md.private.bamg.landmask=double(md.private.bamg.mesh.Triangles(:,4)>=1);
 
@@ -107,5 +107,5 @@
 %}}}
 
-%Parameterization: 
+%Parameterization:
 %Parameterize ice sheets : {{{
 for ind=sl.basinindx('continent',{'antarctica'}),
@@ -113,13 +113,13 @@
 
 	md=sl.icecaps{ind};
-	bas=sl.basins{ind}; 
+	bas=sl.basins{ind};
 	%masks :  %{{{
-	%ice levelset from domain outlines: 
+	%ice levelset from domain outlines:
 	md.mask.ice_levelset=-ones(md.mesh.numberofvertices,1);
-	
-	if bas.isnameany('antarctica-grounded'), 
+
+	if bas.isnameany('antarctica-grounded'),
 		md.mask.ocean_levelset=ones(md.mesh.numberofvertices,1);
 	end
-	if bas.isnameany('ronne','ross'), 
+	if bas.isnameany('ronne','ross'),
 		md.mask.ocean_levelset=-ones(md.mesh.numberofvertices,1);
 	end
@@ -161,5 +161,5 @@
 			% index=delaunayn(points);
 			index=BamgTriangulate(longAIS, latAIS);
-			lat=md.mesh.lat; 
+			lat=md.mesh.lat;
 			long=md.mesh.long+360;
 			pos=find(long>360);
@@ -195,9 +195,9 @@
 	bas=sl.basins{ind};
 
-	%recover lat,long: 
+	%recover lat,long:
 	[md.mesh.long,md.mesh.lat]=gdaltransform(md.mesh.x,md.mesh.y,md.mesh.proj,'EPSG:4326');
 
 	%mask:  %{{{
-	%Figure out mask from initial mesh: deal with land and ocean masks (land 
+	%Figure out mask from initial mesh: deal with land and ocean masks (land
 	%includes grounded ice).  %{{{
 	%first, transform land element mask into vertex-driven one
@@ -213,5 +213,5 @@
 	sumconnectedisonocean=sum(connectedisonocean,2);
 
-	%figure out which land elements are connected to the ocean: 
+	%figure out which land elements are connected to the ocean:
 	landelsconocean=landels(find(sumconnectedisonocean));
 
@@ -223,5 +223,5 @@
 	md.mesh.elements(landelsconocean,1)];
 
-	%edge ind1 and ind2: 
+	%edge ind1 and ind2:
 	for i=1:length(ind1),
 		els1=md.mesh.vertexconnectivity(ind1(i),1: md.mesh.vertexconnectivity(ind1(i),end));
@@ -230,5 +230,5 @@
 
 		if length(find(land(els)))==1,
-			%this edge is on the beach, 0 the edge: 
+			%this edge is on the beach, 0 the edge:
 			land_mask(ind1(i))=0;
 			land_mask(ind2(i))=0;
@@ -237,5 +237,5 @@
 
 	md.mask.ocean_levelset=land_mask;
-	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);   %if there are glaciers, we'll adjust 
+	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);   %if there are glaciers, we'll adjust
 
 	if testagainst2002,
@@ -251,5 +251,5 @@
 	md.masstransport.spcthickness=zeros(md.mesh.numberofvertices,1);
 
-	if testagainst2002, 
+	if testagainst2002,
 		% {{{
 		%greenland
@@ -261,5 +261,5 @@
 		%md.masstransport.spcthickness(pos)=-100*ratio;
 
-		%correct mask: 
+		%correct mask:
 		md.mask.ice_levelset(md.mesh.elements(pos,:))=-1;
 		% }}}
@@ -281,6 +281,6 @@
 		delHGLA=sum(delH(:,3:end),2);
 		index=BamgTriangulate(longGLA, latGLA);
-		lat=md.mesh.lat; 
-		long=md.mesh.long+360; 
+		lat=md.mesh.lat;
+		long=md.mesh.long+360;
 		pos=find(long>360);
 		long(pos)=long(pos)-360;
@@ -292,6 +292,6 @@
 		md.masstransport.spcthickness(pos)= md.masstransport.spcthickness(pos)-delHGLA(pos)/100;
 
-		%adjust mask accordingly: 
-		pos=find(md.masstransport.spcthickness); 
+		%adjust mask accordingly:
+		pos=find(md.masstransport.spcthickness);
 		md.mask.ice_levelset(pos)=-1;
 		md.mask.ocean_levelset(pos)=1;
@@ -322,16 +322,16 @@
 %%Assemble Earth in 3D {{{
 
-%parameters: 
+%parameters:
 plotting=0;
 tolerance=100;
-loneedgesdetect=0; 
-
-%create Earth model by concatenating all the icecaps in 3D: 
+loneedgesdetect=0;
+
+%create Earth model by concatenating all the icecaps in 3D:
 sl.caticecaps('tolerance',tolerance,'loneedgesdetect',loneedgesdetect);
 
-%figure out how each icecap's mesh connects to the larger Earth mesh: 
+%figure out how each icecap's mesh connects to the larger Earth mesh:
 sl.intersections('force',1);
 
-%figure out connectivity: 
+%figure out connectivity:
 disp('Mesh connectivity');
 sl.earth.mesh.vertexconnectivity=NodeConnectivity(sl.earth.mesh.elements,sl.earth.mesh.numberofvertices);
@@ -341,5 +341,5 @@
 sl.earth.mesh.area=averaging(sl.earth,GetAreas3DTria(sl.earth.mesh.elements,sl.earth.mesh.x,sl.earth.mesh.y,sl.earth.mesh.z),4);
 
-%transfer a list of fields from each icecap and continent back to Earth: 
+%transfer a list of fields from each icecap and continent back to Earth:
 sl.transfer('mask.ice_levelset');
 sl.transfer('mask.ocean_levelset');
@@ -355,5 +355,5 @@
 sl.transfer('dsl.sea_water_pressure_at_sea_floor');
 
-%radius: 
+%radius:
 sl.earth.mesh.r=sqrt(sl.earth.mesh.x.^2+sl.earth.mesh.y.^2+sl.earth.mesh.z.^2);
 
@@ -373,10 +373,10 @@
 md=sl.earth; %we don't do computations on ice sheets or land.
 
-%Materials: 
+%Materials:
 md.materials=materials('hydro');
 
-%elastic loading from love numbers: 
+%elastic loading from love numbers:
 md.solidearth.lovenumbers=lovenumbers('maxdeg',100);
-md.solidearth.settings.ocean_area_scaling = 0; 
+md.solidearth.settings.ocean_area_scaling = 0;
 
 %Miscellaneous
@@ -395,6 +395,6 @@
 md.timestepping.time_step=1;
 
-%Physics: 
-md.transient.issmb=0; 
+%Physics:
+md.transient.issmb=0;
 md.transient.isstressbalance=0;
 md.transient.isthermal=0;
@@ -402,5 +402,5 @@
 md.transient.isslc=1;
 
-%Initializations: 
+%Initializations:
 md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
 md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
Index: issm/trunk/test/NightlyRun/test2004.py
===================================================================
--- issm/trunk/test/NightlyRun/test2004.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test2004.py	(revision 27232)
@@ -2,7 +2,7 @@
 #
 # TODO:
-# - Save boundaries by name to some data structure with tag so that they can be 
-#   copied to basins that use identical shapefiles and projections (will need 
-#   to check if the cost of the additional structure, checks, and copying are 
+# - Save boundaries by name to some data structure with tag so that they can be
+#   copied to basins that use identical shapefiles and projections (will need
+#   to check if the cost of the additional structure, checks, and copying are
 #   greater than the cost of projecting).
 #
@@ -41,5 +41,5 @@
 #HemisphereWest #{{{
 sl.addbasin(
-    basin('continent', 'hemispherewest', 'name', 'hemispherewest', 'proj', laea(0, -90), 'boundaries', [ # Peru projection 3587
+    basin('continent', 'hemispherewest', 'name', 'hemispherewest', 'proj', laea(0, -90), 'boundaries', [  # Peru projection 3587
         boundary('shppath', shppath, 'shpfilename', 'HemisphereSplit', 'proj', proj4326, 'orientation', 'reverse'),
         boundary('shppath', shppath, 'shpfilename', 'NorthAntarctica', 'proj', proj3031),
@@ -49,6 +49,5 @@
         boundary('shppath', shppath, 'shpfilename', 'RonneWestSummit', 'proj', proj3031),
         boundary('shppath', shppath, 'shpfilename', 'WestAntarctica2', 'proj', proj3031, 'orientation', 'reverse'),
-        boundary('shppath', shppath, 'shpfilename', 'SouthAntarctica', 'proj', proj3031)
-        ]
+        boundary('shppath', shppath, 'shpfilename', 'SouthAntarctica', 'proj', proj3031)]
     )
 )
@@ -59,7 +58,6 @@
         boundary('shppath', shppath, 'shpfilename', 'SouthAntarctica', 'proj', proj3031),
         boundary('shppath', shppath, 'shpfilename', 'RossIceShelf', 'proj', proj3031),
-        boundary('shppath', shppath, 'shpfilename', 'RossWestFront','proj', proj3031),
-        boundary('shppath', shppath, 'shpfilename', 'RossFront', 'proj', proj3031, 'orientation', 'reverse')
-        ]
+        boundary('shppath', shppath, 'shpfilename', 'RossWestFront', 'proj', proj3031),
+        boundary('shppath', shppath, 'shpfilename', 'RossFront', 'proj', proj3031, 'orientation', 'reverse')]
     )
 )
@@ -67,12 +65,11 @@
 #HemisphereEast: {{{
 sl.addbasin(
-    basin('continent', 'hemisphereeast', 'name', 'hemisphereeast', 'proj', laea(0, +90), 'boundaries', [ #Australian projection lat, long
+    basin('continent', 'hemisphereeast', 'name', 'hemisphereeast', 'proj', laea(0, +90), 'boundaries', [  #Australian projection lat, long
         boundary('shppath', shppath, 'shpfilename', 'HemisphereSplit', 'proj', proj4326),
         boundary('shppath', shppath, 'shpfilename', 'SouthAntarctica', 'proj', proj3031),
-        boundary('shppath', shppath, 'shpfilename','RossFront', 'proj', proj3031),
+        boundary('shppath', shppath, 'shpfilename', 'RossFront', 'proj', proj3031),
         boundary('shppath', shppath, 'shpfilename', 'RossWestFront', 'proj', proj3031),
-        boundary('shppath', shppath, 'shpfilename', 'EastAntarctica2', 'proj', proj3031,'orientation', 'reverse'),
-        boundary('shppath', shppath, 'shpfilename', 'NorthAntarctica', 'proj', proj3031)
-        ]
+        boundary('shppath', shppath, 'shpfilename', 'EastAntarctica2', 'proj', proj3031, 'orientation', 'reverse'),
+        boundary('shppath', shppath, 'shpfilename', 'NorthAntarctica', 'proj', proj3031)]
     )
 )
@@ -90,6 +87,5 @@
         boundary('shppath', shppath, 'shpfilename', 'RonneIceShelf', 'proj', proj3031),
         boundary('shppath', shppath, 'shpfilename', 'RonneEastSummit', 'proj', proj3031),
-        boundary('shppath', shppath, 'shpfilename', 'RonneBrunt', 'proj', proj3031)
-        ]
+        boundary('shppath', shppath, 'shpfilename', 'RonneBrunt', 'proj', proj3031)]
     )
 )
@@ -101,6 +97,5 @@
         boundary('shppath', shppath, 'shpfilename', 'RonneIceShelf', 'proj', proj3031),
         boundary('shppath', shppath, 'shpfilename', 'RonneEastSummit', 'proj', proj3031),
-        boundary('shppath', shppath, 'shpfilename', 'RonneFront', 'proj', proj3031, 'orientation', 'reverse')
-        ]
+        boundary('shppath', shppath, 'shpfilename', 'RonneFront', 'proj', proj3031, 'orientation', 'reverse')]
     )
 )
@@ -114,11 +109,9 @@
 hmin = hmin * 1000
 hmax = hmax * 1000
-tolerance = 100 # tolerance of 100m on Earth position when merging 3d meshes
+tolerance = 100  # tolerance of 100m on Earth position when merging 3d meshes
 threshold = 5
-defaultoptions = [
-    'KeepVertices', 0,
-    'MaxCornerAngle', 0.0000000001,
-    'NoBoundaryRefinement', 1
-]
+defaultoptions = ['KeepVertices', 0,
+                  'MaxCornerAngle', 0.0000000001,
+                  'NoBoundaryRefinement', 1]
 alreadyloaded = 0
 #}}}
@@ -134,5 +127,5 @@
 
     # Mesh
-    md = bamg(model(), 'domain', domain, 'subdomains', coastline, 'hmin', hmin, 'hmax', hmax, *defaultoptions) # NOTE: Unpacking defaultoptions with '*'
+    md = bamg(model(), 'domain', domain, 'subdomains', coastline, 'hmin', hmin, 'hmax', hmax, *defaultoptions)  # NOTE: Unpacking defaultoptions with '*'
 
     # Miscellaneous
@@ -254,14 +247,10 @@
     landelsconocean = landels[np.nonzero(sumconnectedisonocean)[0]]
 
-    ind1 = np.hstack((
-        md.mesh.elements[landelsconocean, 0],
-        md.mesh.elements[landelsconocean, 1],
-        md.mesh.elements[landelsconocean, 2]
-    ))
-    ind2 = np.hstack((
-        md.mesh.elements[landelsconocean, 1],
-        md.mesh.elements[landelsconocean, 2],
-        md.mesh.elements[landelsconocean, 0]
-    ))
+    ind1 = np.hstack((md.mesh.elements[landelsconocean, 0],
+                      md.mesh.elements[landelsconocean, 1],
+                      md.mesh.elements[landelsconocean, 2]))
+    ind2 = np.hstack((md.mesh.elements[landelsconocean, 1],
+                      md.mesh.elements[landelsconocean, 2],
+                      md.mesh.elements[landelsconocean, 0]))
 
     # Edge ind1 and ind2
@@ -325,6 +314,6 @@
         delHGLA = InterpFromMeshToMesh2d(index, longGLA, latGLA, delHGLA, longe, late)
 
-        # NOTE: For some reason, cannot apply pos to multiple arrays in a 
-        #       singlelike we might do in MATLAB. Instead, we iterate over 
+        # NOTE: For some reason, cannot apply pos to multiple arrays in a
+        #       singlelike we might do in MATLAB. Instead, we iterate over
         #       elements of pos.
         #
@@ -461,12 +450,10 @@
 md.solidearth.settings.rotation = 0
 md.solidearth.settings.viscous = 0
-md.solidearth.requested_outputs = [
-    'default',
-    'DeltaIceThickness',
-    'Sealevel',
-    'Bed',
-    'SealevelBarystaticIceMask',
-    'SealevelBarystaticOceanMask',
-]
+md.solidearth.requested_outputs = ['default',
+                                   'DeltaIceThickness',
+                                   'Sealevel',
+                                   'Bed',
+                                   'SealevelBarystaticIceMask',
+                                   'SealevelBarystaticOceanMask']
 md = solve(md, 'Transient')
 Seustatic = md.results.TransientSolution.Sealevel
Index: issm/trunk/test/NightlyRun/test2006.py
===================================================================
--- issm/trunk/test/NightlyRun/test2006.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test2006.py	(revision 27232)
@@ -18,4 +18,5 @@
 md = model()
 md.cluster = generic('name', gethostname(), 'np', 5)
+md.mesh = gmshplanet('radius', 6.371012 * 1e3, 'resolution', 700.)  #700 km resolution mesh
 
 # Load precomputed mesh
@@ -163,31 +164,22 @@
 for i in range(len(locations)):
     if i == 0:
-        md.outputdefinition.definitions = [
-            nodalvalue(
-                'name',             'SNode',
-                'definitionstring', 'Outputdefinition1',
-                'model_string',     'Sealevel',
-                'node',             locations[i]
-            )
-        ]
+        md.outputdefinition.definitions = [nodalvalue('name', 'SNode',
+                                                      'definitionstring', 'Outputdefinition1',
+                                                      'model_string', 'Sealevel',
+                                                      'node', locations[i])]
     else:
         md.outputdefinition.definitions.append(
-            nodalvalue(
-                'name',             'SNode',
-                'definitionstring', 'Outputdefinition' + str(i + 1),
-                'model_string',     'Sealevel',
-                'node',             locations[i]
-            )
-        )
+            nodalvalue('name', 'SNode',
+                       'definitionstring', 'Outputdefinition' + str(i + 1),
+                       'model_string', 'Sealevel',
+                       'node', locations[i]))
 #}}}
 
 # Algorithm #{{{
 md.qmu.method = dakota_method.dakota_method('nond_samp')
-md.qmu.method = dmeth_params_set(
-    md.qmu.method,
-    'seed',             1234,
-    'samples',          10,
-    'sample_type',      'random'
-)
+md.qmu.method = dmeth_params_set(md.qmu.method,
+                                 'seed', 1234,
+                                 'samples', 10,
+                                 'sample_type', 'random')
 md.qmu.output = 1
 #}}}
@@ -235,5 +227,5 @@
 
 # Compare statistics with our own here
-svalues = mds.results.StatisticsSolution[-1].SealevelSamples # all values at locations
+svalues = mds.results.StatisticsSolution[-1].SealevelSamples  # all values at locations
 
 dvalues = np.zeros((md.qmu.method.params.samples, len(locations)))
Index: issm/trunk/test/NightlyRun/test2010.m
===================================================================
--- issm/trunk/test/NightlyRun/test2010.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/test2010.m	(revision 27232)
@@ -110,7 +110,7 @@
 lat=md.results.TransientSolution.SealevelBarystaticIceLatbar*pi/180;
 lon=md.results.TransientSolution.SealevelBarystaticIceLongbar*pi/180;
-moi_xz = sum(-loadice.*areaice.*rad_e^2.*sin(lat).*cos(lat).*cos(lon));
-moi_yz = sum(-loadice.*areaice.*rad_e^2.*sin(lat).*cos(lat).*sin(lon));
-moi_zz = sum(-loadice.*areaice.*rad_e^2.*(-1.0/3.0+sin(lat).^2));
+moi_xz = sum(-loadice.*rad_e^2.*sin(lat).*cos(lat).*cos(lon));
+moi_yz = sum(-loadice.*rad_e^2.*sin(lat).*cos(lat).*sin(lon));
+moi_zz = sum(-loadice.*rad_e^2.*(-1.0/3.0+sin(lat).^2));
 theoretical_value_check=[moixz/moi_xz moiyz/moi_yz moizz/moi_zz]; % should yield [1.0 1.0 1.0]
 % }}}
Index: issm/trunk/test/NightlyRun/test2013.m
===================================================================
--- issm/trunk/test/NightlyRun/test2013.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/test2013.m	(revision 27232)
@@ -99,4 +99,5 @@
 latbar=md.results.TransientSolution.SealevelBarystaticIceLatbar;
 
+loads=loads./areas;
 
 %Fields and tolerances to track changes
Index: issm/trunk/test/NightlyRun/test243.m
===================================================================
--- issm/trunk/test/NightlyRun/test243.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/test243.m	(revision 27232)
@@ -10,4 +10,5 @@
 md.smb = SMBgemb(md.mesh,md.geometry);
 md.smb.dsnowIdx = 1;
+md.smb.swIdx = 1;
 
 %load hourly surface forcing date from 1979 to 2009:
Index: issm/trunk/test/NightlyRun/test243.py
===================================================================
--- issm/trunk/test/NightlyRun/test243.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test243.py	(revision 27232)
@@ -2,7 +2,5 @@
 from socket import gethostname
 import sys
-
 import numpy as np
-
 from model import *
 from parameterize import *
@@ -23,4 +21,5 @@
 md.smb = SMBgemb(md.mesh, md.geometry)
 md.smb.dsnowIdx = 1
+md.smb.swIdx = 1
 
 #load hourly surface forcing date from 1979 to 2009:
@@ -44,12 +43,10 @@
 
 #smb settings
-md.smb.requested_outputs = [
-        'SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbEC',
-        'SmbA','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC','SmbMeanSHF','SmbMeanLHF',
-        'SmbMeanULW','SmbNetLW','SmbNetSW','SmbWAdd','SmbRunoff','SmbRefreeze','SmbMelt',
-        'SmbEC','SmbPrecipitation','SmbRain','SmbAccumulatedMassBalance','SmbAccumulatedRunoff',
-        'SmbAccumulatedMelt','SmbAccumulatedEC','SmbAccumulatedPrecipitation','SmbAccumulatedRain',
-        'SmbAccumulatedPrecipitation','SmbAccumulatedRefreeze'
-    ]
+md.smb.requested_outputs = ['SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbEC',
+                            'SmbA','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC','SmbMeanSHF','SmbMeanLHF',
+                            'SmbMeanULW','SmbNetLW','SmbNetSW','SmbWAdd','SmbRunoff','SmbRefreeze','SmbMelt',
+                            'SmbEC','SmbPrecipitation','SmbRain','SmbAccumulatedMassBalance','SmbAccumulatedRunoff',
+                            'SmbAccumulatedMelt','SmbAccumulatedEC','SmbAccumulatedPrecipitation','SmbAccumulatedRain',
+                            'SmbAccumulatedPrecipitation','SmbAccumulatedRefreeze']
 
 #only run smb core:
@@ -72,5 +69,5 @@
 
 #Fields and tolerances to track changes
-field_names = ['Layers','SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbA' ,'SmbEC','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC','SmbMeanSHF','SmbMeanLHF','SmbMeanULW','SmbNetLW','SmbNetSW','SmbAccumulatedMassBalance','SmbAccumulatedRunoff','SmbAccumulatedMelt','SmbAccumulatedEC','SmbAccumulatedPrecipitation','SmbAccumulatedRain','SmbAccumulatedRefreeze','SmbRunoff','SmbMelt','SmbEC','SmbPrecipitation','SmbRain','SmbRefreeze','SmbWAdd']
+field_names = ['Layers', 'SmbDz', 'SmbT', 'SmbD', 'SmbRe', 'SmbGdn', 'SmbGsp', 'SmbA', 'SmbEC', 'SmbMassBalance', 'SmbMAdd', 'SmbDzAdd', 'SmbFAC', 'SmbMeanSHF', 'SmbMeanLHF', 'SmbMeanULW', 'SmbNetLW', 'SmbNetSW', 'SmbAccumulatedMassBalance', 'SmbAccumulatedRunoff', 'SmbAccumulatedMelt', 'SmbAccumulatedEC', 'SmbAccumulatedPrecipitation', 'SmbAccumulatedRain', 'SmbAccumulatedRefreeze', 'SmbRunoff', 'SmbMelt', 'SmbEC', 'SmbPrecipitation', 'SmbRain', 'SmbRefreeze', 'SmbWAdd']
 field_tolerances = [1e-12, 2e-12, 1e-12, 2e-11, 1e-11, 2e-11, 1e-11, 1e-12, 1e-11, 1e-12, 1e-12, 1e-12, 1e-11, 2e-11, 2e-11, 1e-11, 9e-10, 2e-11, 1e-11, 9e-10, 2e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11, 1e-11]
 
Index: issm/trunk/test/NightlyRun/test244.m
===================================================================
--- issm/trunk/test/NightlyRun/test244.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/test244.m	(revision 27232)
@@ -11,4 +11,5 @@
 md.smb = SMBgemb(md.mesh,md.geometry);
 md.smb.dsnowIdx = 0;
+md.smb.swIdx = 1;
 
 %load hourly surface forcing date from 1979 to 2009:
Index: issm/trunk/test/NightlyRun/test244.py
===================================================================
--- issm/trunk/test/NightlyRun/test244.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test244.py	(revision 27232)
@@ -30,4 +30,5 @@
 md.smb = SMBgemb(md.mesh, md.geometry)
 md.smb.dsnowIdx = 0
+md.smb.swIdx = 1
 
 #load hourly surface forcing date from 1979 to 2009:
Index: issm/trunk/test/NightlyRun/test252.m
===================================================================
--- issm/trunk/test/NightlyRun/test252.m	(revision 27035)
+++ issm/trunk/test/NightlyRun/test252.m	(revision 27232)
@@ -10,4 +10,6 @@
 md.smb = SMBgemb(md.mesh,md.geometry);
 md.smb.dsnowIdx = 4;
+md.smb.swIdx = 1;
+md.smb.tcIdx = 2;
 
 %load hourly surface forcing date from 1979 to 2009:
Index: issm/trunk/test/NightlyRun/test252.py
===================================================================
--- issm/trunk/test/NightlyRun/test252.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test252.py	(revision 27232)
@@ -23,4 +23,6 @@
 md.smb = SMBgemb(md.mesh, md.geometry)
 md.smb.dsnowIdx = 4
+md.smb.swIdx = 1
+md.smb.tcIdx = 2
 
 #load hourly surface forcing date from 1979 to 2009:
@@ -79,60 +81,56 @@
                'SmbDz3', 'SmbT3', 'SmbD3', 'SmbRe3', 'SmbGdn3', 'SmbGsp3', 'SmbA3', 'SmbEC3', 'SmbMassBalance3', 'SmbMAdd3', 'SmbDzAdd3', 'SmbFAC3',
                'SmbDz4', 'SmbT4', 'SmbD4', 'SmbRe4', 'SmbGdn4', 'SmbGsp4', 'SmbA4', 'SmbEC4', 'SmbMassBalance4', 'SmbMAdd4', 'SmbDzAdd4', 'SmbFAC4']
-field_tolerances = [
-    1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,
-    1e-12,1e-12,1e-11,1e-10,2e-11,1e-11,1e-12,1e-11,1e-12,1e-12,1e-12,1e-11,
-    1e-12,1e-12,2e-12,2e-11,4e-11,1e-11,1e-12,1e-11,1e-11,1e-12,1e-12,1e-11,
-    1e-11,1e-11,4e-11,4e-11,1e-12,4e-11,1e-12,3e-12,1e-10,1e-12,1e-12,2e-11
-]
+field_tolerances = [1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12, 1e-12,
+                    1e-12, 1e-12, 1e-11, 1e-10, 2e-11, 1e-11, 1e-12, 1e-11, 1e-12, 1e-12, 1e-12, 1e-11,
+                    1e-12, 1e-12, 2e-12, 2e-11, 4e-11, 1e-11, 1e-12, 1e-11, 1e-11, 1e-12, 1e-12, 1e-11,
+                    1e-11, 1e-11, 4e-11, 4e-11, 1e-12, 4e-11, 1e-12, 3e-12, 1e-10, 1e-12, 1e-12, 2e-11]
 # Shape is different in python solution (fixed using reshape) which can cause test failure
-field_values = [
-    nlayers,
-    md.results.TransientSolution[0].SmbDz[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbT[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbD[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbRe[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbGdn[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbGsp[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbA[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[0].SmbEC[0],
-    md.results.TransientSolution[0].SmbMassBalance[0],
-    md.results.TransientSolution[0].SmbMAdd[0],
-    md.results.TransientSolution[0].SmbDzAdd[0],
-    md.results.TransientSolution[0].SmbFAC[0],
-    md.results.TransientSolution[145].SmbDz[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbT[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbD[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbRe[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbGdn[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbGsp[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbA[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[145].SmbEC[0],
-    md.results.TransientSolution[145].SmbMassBalance[0],
-    md.results.TransientSolution[145].SmbMAdd[0],
-    md.results.TransientSolution[145].SmbDzAdd[0],
-    md.results.TransientSolution[145].SmbFAC[0],
-    md.results.TransientSolution[146].SmbDz[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbT[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbD[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbRe[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbGdn[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbGsp[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbA[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[146].SmbEC[0],
-    md.results.TransientSolution[146].SmbMassBalance[0],
-    md.results.TransientSolution[146].SmbMAdd[0],
-    md.results.TransientSolution[146].SmbDzAdd[0],
-    md.results.TransientSolution[146].SmbFAC[0],
-    md.results.TransientSolution[-1].SmbDz[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbT[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbD[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbRe[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbGdn[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbGsp[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbA[0, 0:nlayers].reshape(1, -1),
-    md.results.TransientSolution[-1].SmbEC[0],
-    md.results.TransientSolution[-1].SmbMassBalance[0],
-    md.results.TransientSolution[-1].SmbMAdd[0],
-    md.results.TransientSolution[-1].SmbDzAdd[0],
-    md.results.TransientSolution[-1].SmbFAC[0]
-]
+field_values = [nlayers,
+                md.results.TransientSolution[0].SmbDz[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbT[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbD[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbRe[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbGdn[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbGsp[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbA[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[0].SmbEC[0],
+                md.results.TransientSolution[0].SmbMassBalance[0],
+                md.results.TransientSolution[0].SmbMAdd[0],
+                md.results.TransientSolution[0].SmbDzAdd[0],
+                md.results.TransientSolution[0].SmbFAC[0],
+                md.results.TransientSolution[145].SmbDz[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbT[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbD[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbRe[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbGdn[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbGsp[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbA[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[145].SmbEC[0],
+                md.results.TransientSolution[145].SmbMassBalance[0],
+                md.results.TransientSolution[145].SmbMAdd[0],
+                md.results.TransientSolution[145].SmbDzAdd[0],
+                md.results.TransientSolution[145].SmbFAC[0],
+                md.results.TransientSolution[146].SmbDz[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbT[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbD[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbRe[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbGdn[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbGsp[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbA[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[146].SmbEC[0],
+                md.results.TransientSolution[146].SmbMassBalance[0],
+                md.results.TransientSolution[146].SmbMAdd[0],
+                md.results.TransientSolution[146].SmbDzAdd[0],
+                md.results.TransientSolution[146].SmbFAC[0],
+                md.results.TransientSolution[-1].SmbDz[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbT[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbD[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbRe[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbGdn[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbGsp[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbA[0, 0:nlayers].reshape(1, -1),
+                md.results.TransientSolution[-1].SmbEC[0],
+                md.results.TransientSolution[-1].SmbMassBalance[0],
+                md.results.TransientSolution[-1].SmbMAdd[0],
+                md.results.TransientSolution[-1].SmbDzAdd[0],
+                md.results.TransientSolution[-1].SmbFAC[0]]
Index: issm/trunk/test/NightlyRun/test417.py
===================================================================
--- issm/trunk/test/NightlyRun/test417.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test417.py	(revision 27232)
@@ -41,17 +41,16 @@
     'mean', np.ones((npart, 1)),
     'stddev', .01 * np.ones((npart, 1)),
-    'partition', partition
-    )
+    'partition', partition)
 
 #responses
-md.qmu.responses.MaxVel = response_function.response_function('descriptor','MaxVel')
-md.qmu.responses.IceVolume = response_function.response_function('descriptor','IceVolume')
-md.qmu.responses.MassFlux1 = response_function.response_function('descriptor','indexed_MassFlux_1')
-md.qmu.responses.MassFlux2 = response_function.response_function('descriptor','indexed_MassFlux_2')
-md.qmu.responses.MassFlux3 = response_function.response_function('descriptor','indexed_MassFlux_3')
-md.qmu.responses.MassFlux4 = response_function.response_function('descriptor','indexed_MassFlux_4')
-md.qmu.responses.MassFlux5 = response_function.response_function('descriptor','indexed_MassFlux_5')
-md.qmu.responses.massFlux6 = response_function.response_function('descriptor','indexed_MassFlux_6')
-md.qmu.responses.massFlux7 = response_function.response_function('descriptor','indexed_MassFlux_7')
+md.qmu.responses.MaxVel = response_function.response_function('descriptor', 'MaxVel')
+#md.qmu.responses.IceVolume = response_function.response_function('descriptor', 'IceVolume')  #commented for matlab consistency
+md.qmu.responses.MassFlux1 = response_function.response_function('descriptor', 'indexed_MassFlux_1')
+md.qmu.responses.MassFlux2 = response_function.response_function('descriptor', 'indexed_MassFlux_2')
+md.qmu.responses.MassFlux3 = response_function.response_function('descriptor', 'indexed_MassFlux_3')
+md.qmu.responses.MassFlux4 = response_function.response_function('descriptor', 'indexed_MassFlux_4')
+md.qmu.responses.MassFlux5 = response_function.response_function('descriptor', 'indexed_MassFlux_5')
+md.qmu.responses.massFlux6 = response_function.response_function('descriptor', 'indexed_MassFlux_6')
+md.qmu.responses.massFlux7 = response_function.response_function('descriptor', 'indexed_MassFlux_7')
 
 #mass flux profiles
Index: issm/trunk/test/NightlyRun/test440.py
===================================================================
--- issm/trunk/test/NightlyRun/test440.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test440.py	(revision 27232)
@@ -30,15 +30,11 @@
 
 #variables
-md.qmu.variables.rho_ice = normal_uncertain.normal_uncertain(
-    'descriptor', 'MaterialsRhoIce',
-    'mean', 1,
-    'stddev', 0.01
-    )
+md.qmu.variables.rho_ice = normal_uncertain.normal_uncertain('descriptor', 'MaterialsRhoIce',
+                                                             'mean', 1,
+                                                             'stddev', 0.01)
 
 #responses
-md.qmu.responses.MaxVel = response_function.response_function(
-    'descriptor', 'scaled_Thickness',
-    'partition', partition
-    )
+md.qmu.responses.MaxVel = response_function.response_function('descriptor', 'scaled_Thickness',
+                                                              'partition', partition)
 
 #method
Index: issm/trunk/test/NightlyRun/test446.py
===================================================================
--- issm/trunk/test/NightlyRun/test446.py	(revision 27035)
+++ issm/trunk/test/NightlyRun/test446.py	(revision 27232)
@@ -15,5 +15,5 @@
 md.cluster = generic('name', gethostname(), 'np', 3)
 md.stressbalance.requested_outputs = ['default', 'VxSurface', 'VySurface', 'VxShear', 'VyShear', 'VxBase', 'VyBase']
-md = SetMOLHOBC(md);
+md = SetMOLHOBC(md)
 md = solve(md, 'Stressbalance')
 
Index: issm/trunk/test/NightlyRun/test906.m
===================================================================
--- issm/trunk/test/NightlyRun/test906.m	(revision 27232)
+++ issm/trunk/test/NightlyRun/test906.m	(revision 27232)
@@ -0,0 +1,92 @@
+%Test Name: SquareNoDynHydrologyDCtimeadapt
+md=triangle(model(), '../Exp/Square.exp', 200000.);
+md=setmask(md, '', '');
+md=parameterize(md, '../Par/SquareNoDyn.par');
+md.cluster=generic('name', oshostname(), 'np', 1);
+
+md.transient=deactivateall(md.transient);
+md.transient.ishydrology=1;
+md.hydrology=(hydrologydc);
+md.hydrology=initialize(md.hydrology,md);
+
+%Hydro Model Parameters
+md.hydrology.isefficientlayer=1;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=500;
+md.hydrology.rel_tol=1.0e-6;
+md.hydrology.penalty_lock=10;
+md.hydrology.max_iter=100;
+md.hydrology.transfer_flag=1;
+md.hydrology.unconfined_flag=0;
+md.hydrology.leakage_factor=5.0e-10;
+md.hydrology.mask_thawed_node=ones(md.mesh.numberofvertices,1);
+
+%Sediment Parameters
+md.hydrology.sediment_porosity=0.4;
+md.hydrology.sediment_transmitivity=3.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_thickness=10.;
+
+%Epl Parameters
+md.hydrology.mask_eplactive_node=zeros(md.mesh.numberofvertices,1);
+md.hydrology.epl_conductivity=30.;
+md.hydrology.epl_initial_thickness=1.0;
+md.hydrology.epl_colapse_thickness=1.0e-3;
+md.hydrology.epl_thick_comp=0;
+md.hydrology.epl_max_thickness=10;
+md.hydrology.eplflip_lock=0;
+
+%Initialisation
+md.initialization.sediment_head=md.geometry.base;
+md.initialization.epl_head=md.geometry.base;
+md.initialization.epl_thickness=ones(md.mesh.numberofvertices,1);
+
+%Boundary conditions
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
+
+%Forcing
+stepping=3600./md.constants.yts;
+endtime=0.3;
+times=[0.:stepping:endtime];
+input=find(abs(times-0.3) > 0.2);
+inputval=times*0+100;
+inputval(input)=0;
+
+%basal forcing inputval
+md.basalforcings.groundedice_melting_rate=repmat(inputval,md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=[[md.basalforcings.groundedice_melting_rate];[times]];
+
+%Time
+md.timestepping.final_time=endtime;
+md.settings.output_frequency=1.0;
+
+md.timestepping.average_forcing=1;
+md.hydrology.step_adapt=1;
+md.hydrology.steps_per_step=1;
+md.timestepping.time_step=0.1;
+
+
+md=solve(md, 'Transient');
+
+field_names={'SedimentWaterHead2', 'EplWaterHead2', 'SedimentHeadResidual2',...
+	     'SedimentHeadSubstep2', 'EplHeadSubstep2', 'HydrologySubsteps2', 'HydrologySubTime2',...
+	     'SedimentWaterHead3', 'EplWaterHead3', 'SedimentHeadResidual3'};
+field_tolerances={1e-13, 1e-13, 1e-13,...
+		  1e-13, 1e-13, 1e-13, 1e-13,...
+		  1e-13, 1e-13, 1e-13};
+field_values={md.results.TransientSolution(2).SedimentHead,...
+	      md.results.TransientSolution(2).EplHead,...
+	      md.results.TransientSolution(2).SedimentHeadResidual,...
+	      md.results.TransientSolution(2).SedimentHeadSubstep,...
+	      md.results.TransientSolution(2).EplHeadSubstep,...
+	      md.results.TransientSolution(2).HydrologySubsteps,...
+	      md.results.TransientSolution(2).HydrologySubTime,...
+	      md.results.TransientSolution(3).SedimentHead,...
+	      md.results.TransientSolution(3).EplHead,...
+	      md.results.TransientSolution(3).SedimentHeadResidual};
+
+for i=1:3
+	disp(md.results.TransientSolution(i).EplHead(1));
+	disp(md.results.TransientSolution(i).HydrologySubTime);
+	disp(md.results.TransientSolution(i).HydrologySubsteps);
+end
Index: issm/trunk/test/NightlyRun/test906.py
===================================================================
--- issm/trunk/test/NightlyRun/test906.py	(revision 27232)
+++ issm/trunk/test/NightlyRun/test906.py	(revision 27232)
@@ -0,0 +1,93 @@
+#Test Name: SquareNoDynHydrologyDCtimeadapt
+import numpy as np
+from model import *
+from solve import *
+from socket import gethostname
+from triangle import triangle
+from setmask import setmask
+from parameterize import parameterize
+
+md = triangle(model(), '../Exp/Square.exp', 200000.)
+md = setmask(md, '', '')
+md = parameterize(md, '../Par/SquareNoDyn.py')
+
+md.transient = transient.deactivateall(md.transient)
+md.transient.ishydrology = True
+md.hydrology = hydrologydc()
+md.hydrology = md.hydrology.initialize(md)
+
+#Hydro Model Parameters
+md.hydrology.isefficientlayer = 1
+md.hydrology.sedimentlimit_flag = 1
+md.hydrology.sedimentlimit = 500
+md.hydrology.rel_tol = 1.0e-6
+md.hydrology.penalty_lock = 10
+md.hydrology.max_iter = 100
+md.hydrology.transfer_flag = 1
+md.hydrology.unconfined_flag = 0
+md.hydrology.leakage_factor = 5.0e-10
+md.hydrology.mask_thawed_node = np.ones((md.mesh.numberofvertices))
+
+#Sediment Parameters
+md.hydrology.sediment_porosity = 0.4
+md.hydrology.sediment_transmitivity = 3.0 * np.ones((md.mesh.numberofvertices))
+md.hydrology.sediment_thickness = 10.
+
+#Epl Parameters
+md.hydrology.mask_eplactive_node = np.zeros((md.mesh.numberofvertices))
+md.hydrology.epl_conductivity = 30.
+md.hydrology.epl_initial_thickness = 1.0
+md.hydrology.epl_colapse_thickness = 1.0e-3
+md.hydrology.epl_thick_comp = 0
+md.hydrology.epl_max_thickness = 10
+md.hydrology.eplflip_lock = 0
+
+#Initialisation
+md.initialization.sediment_head = md.geometry.base
+md.initialization.epl_head = md.geometry.base
+md.initialization.epl_thickness = np.ones((md.mesh.numberofvertices))
+
+#Boundary conditions
+front = np.where(md.mesh.x == 0)[0]
+md.hydrology.spcsediment_head = np.nan * np.ones((md.mesh.numberofvertices))
+md.hydrology.spcepl_head = np.nan * np.ones((md.mesh.numberofvertices))
+
+#Forcing
+stepping = 3600. / md.constants.yts  #hourly forcing
+endtime = 0.3
+times = np.arange(0., endtime + stepping, stepping)
+inputval = np.where(np.abs(times - 0.3) > 0.2, 0, 100.0)
+
+#basal forcing inputval
+md.basalforcings.groundedice_melting_rate = np.outer(np.ones((md.mesh.numberofvertices)), inputval)
+md.basalforcings.groundedice_melting_rate = np.append(md.basalforcings.groundedice_melting_rate, [times], axis=0)
+
+#Time
+md.timestepping.final_time = endtime
+md.settings.output_frequency = 1.0
+
+md.timestepping.average_forcing = 1
+md.hydrology.step_adapt = 1
+md.hydrology.steps_per_step = 1
+md.timestepping.time_step = 0.1
+md.debug.valgrind = False
+
+md.cluster = generic('name', gethostname(), 'np', 1)
+md = solve(md, 'Transient')
+
+field_names = ['SedimentWaterHead2', 'EplWaterHead2', 'SedimentHeadResidual2',
+               'SedimentHeadSubstep2', 'EplHeadSubstep2', 'HydrologySubsteps2', 'HydrologySubTime2',
+               'SedimentWaterHead3', 'EplWaterHead3', 'SedimentHeadResidual3']
+field_tolerances = [1e-13, 1e-13, 1e-13,
+                    1e-13, 1e-13, 1e-13, 1e-13,
+                    1e-13, 1e-13, 1e-13]
+field_values = [md.results.TransientSolution[1].SedimentHead,
+                md.results.TransientSolution[1].EplHead,
+                md.results.TransientSolution[1].SedimentHeadResidual,
+                md.results.TransientSolution[1].SedimentHeadSubstep,
+                md.results.TransientSolution[1].EplHeadSubstep,
+                md.results.TransientSolution[1].HydrologySubsteps,
+                md.results.TransientSolution[1].HydrologySubTime,
+                md.results.TransientSolution[2].SedimentHead,
+                md.results.TransientSolution[2].EplHead,
+                md.results.TransientSolution[2].SedimentHeadResidual]
